repo_name string | dataset string | owner string | lang string | func_name string | code string | docstring string | url string | sha string |
|---|---|---|---|---|---|---|---|---|
soybean-admin-antd | github_2023 | soybeanjs | typescript | initTabStore | function initTabStore(currentRoute: App.Global.TabRoute) {
const storageTabs = localStg.get('globalTabs');
if (themeStore.tab.cache && storageTabs) {
const extractedTabs = extractTabsByAllRoutes(router, storageTabs);
tabs.value = updateTabsByI18nKey(extractedTabs);
}
addTab(currentRoute);
} | /**
* Init tab store
*
* @param currentRoute Current route
*/ | https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/tab/index.ts#L62-L71 | 6bd3e89e710836beb14b1a3381532a3eb7cc3a75 |
soybean-admin-antd | github_2023 | soybeanjs | typescript | addTab | function addTab(route: App.Global.TabRoute, active = true) {
const tab = getTabByRoute(route);
const isHomeTab = tab.id === homeTab.value?.id;
if (!isHomeTab && !isTabInTabs(tab.id, tabs.value)) {
tabs.value.push(tab);
}
if (active) {
setActiveTabId(tab.id);
}
} | /**
* Add tab
*
* @param route Tab route
* @param active Whether to activate the added tab
*/ | https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/tab/index.ts#L79-L91 | 6bd3e89e710836beb14b1a3381532a3eb7cc3a75 |
soybean-admin-antd | github_2023 | soybeanjs | typescript | removeTab | async function removeTab(tabId: string) {
const isRemoveActiveTab = activeTabId.value === tabId;
const updatedTabs = filterTabsById(tabId, tabs.value);
function update() {
tabs.value = updatedTabs;
}
if (!isRemoveActiveTab) {
update();
return;
}
const activeTab = updatedTabs.at(-1) || homeTab.value;
if (activeTab) {
await switchRouteByTab(activeTab);
update();
}
} | /**
* Remove tab
*
* @param tabId Tab id
*/ | https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/tab/index.ts#L98-L117 | 6bd3e89e710836beb14b1a3381532a3eb7cc3a75 |
soybean-admin-antd | github_2023 | soybeanjs | typescript | removeActiveTab | async function removeActiveTab() {
await removeTab(activeTabId.value);
} | /** remove active tab */ | https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/tab/index.ts#L120-L122 | 6bd3e89e710836beb14b1a3381532a3eb7cc3a75 |
soybean-admin-antd | github_2023 | soybeanjs | typescript | removeTabByRouteName | async function removeTabByRouteName(routeName: RouteKey) {
const tab = findTabByRouteName(routeName, tabs.value);
if (!tab) return;
await removeTab(tab.id);
} | /**
* remove tab by route name
*
* @param routeName route name
*/ | https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/tab/index.ts#L129-L134 | 6bd3e89e710836beb14b1a3381532a3eb7cc3a75 |
soybean-admin-antd | github_2023 | soybeanjs | typescript | clearTabs | async function clearTabs(excludes: string[] = []) {
const remainTabIds = [...getFixedTabIds(tabs.value), ...excludes];
const removedTabsIds = tabs.value.map(tab => tab.id).filter(id => !remainTabIds.includes(id));
const isRemoveActiveTab = removedTabsIds.includes(activeTabId.value);
const updatedTabs = filterTabsByIds(removedTabsIds, tabs.value);
function update() {
tabs.value = updatedTabs;
}
if (!isRemoveActiveTab) {
update();
return;
}
const activeTab = updatedTabs[updatedTabs.length - 1] || homeTab.value;
await switchRouteByTab(activeTab);
update();
} | /**
* Clear tabs
*
* @param excludes Exclude tab ids
*/ | https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/tab/index.ts#L141-L161 | 6bd3e89e710836beb14b1a3381532a3eb7cc3a75 |
soybean-admin-antd | github_2023 | soybeanjs | typescript | switchRouteByTab | async function switchRouteByTab(tab: App.Global.Tab) {
const fail = await routerPush(tab.fullPath);
if (!fail) {
setActiveTabId(tab.id);
}
} | /**
* Switch route by tab
*
* @param tab
*/ | https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/tab/index.ts#L168-L173 | 6bd3e89e710836beb14b1a3381532a3eb7cc3a75 |
soybean-admin-antd | github_2023 | soybeanjs | typescript | clearLeftTabs | async function clearLeftTabs(tabId: string) {
const tabIds = tabs.value.map(tab => tab.id);
const index = tabIds.indexOf(tabId);
if (index === -1) return;
const excludes = tabIds.slice(index);
await clearTabs(excludes);
} | /**
* Clear left tabs
*
* @param tabId
*/ | https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/tab/index.ts#L180-L187 | 6bd3e89e710836beb14b1a3381532a3eb7cc3a75 |
soybean-admin-antd | github_2023 | soybeanjs | typescript | clearRightTabs | async function clearRightTabs(tabId: string) {
const isHomeTab = tabId === homeTab.value?.id;
if (isHomeTab) {
clearTabs();
return;
}
const tabIds = tabs.value.map(tab => tab.id);
const index = tabIds.indexOf(tabId);
if (index === -1) return;
const excludes = tabIds.slice(0, index + 1);
await clearTabs(excludes);
} | /**
* Clear right tabs
*
* @param tabId
*/ | https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/tab/index.ts#L194-L207 | 6bd3e89e710836beb14b1a3381532a3eb7cc3a75 |
soybean-admin-antd | github_2023 | soybeanjs | typescript | setTabLabel | function setTabLabel(label: string, tabId?: string) {
const id = tabId || activeTabId.value;
const tab = tabs.value.find(item => item.id === id);
if (!tab) return;
tab.oldLabel = tab.label;
tab.newLabel = label;
} | /**
* Set new label of tab
*
* @default activeTabId
* @param label New tab label
* @param tabId Tab id
*/ | https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/tab/index.ts#L216-L224 | 6bd3e89e710836beb14b1a3381532a3eb7cc3a75 |
soybean-admin-antd | github_2023 | soybeanjs | typescript | resetTabLabel | function resetTabLabel(tabId?: string) {
const id = tabId || activeTabId.value;
const tab = tabs.value.find(item => item.id === id);
if (!tab) return;
tab.newLabel = undefined;
} | /**
* Reset tab label
*
* @default activeTabId
* @param tabId Tab id
*/ | https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/tab/index.ts#L232-L239 | 6bd3e89e710836beb14b1a3381532a3eb7cc3a75 |
soybean-admin-antd | github_2023 | soybeanjs | typescript | isTabRetain | function isTabRetain(tabId: string) {
if (tabId === homeTab.value?.id) return true;
const fixedTabIds = getFixedTabIds(tabs.value);
return fixedTabIds.includes(tabId);
} | /**
* Is tab retain
*
* @param tabId
*/ | https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/tab/index.ts#L246-L252 | 6bd3e89e710836beb14b1a3381532a3eb7cc3a75 |
soybean-admin-antd | github_2023 | soybeanjs | typescript | updateTabsByLocale | function updateTabsByLocale() {
tabs.value = updateTabsByI18nKey(tabs.value);
if (homeTab.value) {
homeTab.value = updateTabByI18nKey(homeTab.value);
}
} | /** Update tabs by locale */ | https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/tab/index.ts#L255-L261 | 6bd3e89e710836beb14b1a3381532a3eb7cc3a75 |
soybean-admin-antd | github_2023 | soybeanjs | typescript | cacheTabs | function cacheTabs() {
if (!themeStore.tab.cache) return;
localStg.set('globalTabs', tabs.value);
} | /** Cache tabs */ | https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/tab/index.ts#L264-L268 | 6bd3e89e710836beb14b1a3381532a3eb7cc3a75 |
soybean-admin-antd | github_2023 | soybeanjs | typescript | isFixedTab | function isFixedTab(tab: App.Global.Tab) {
return tab.fixedIndex !== undefined && tab.fixedIndex !== null;
} | /**
* Is fixed tab
*
* @param tab
*/ | https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/tab/shared.ts#L33-L35 | 6bd3e89e710836beb14b1a3381532a3eb7cc3a75 |
soybean-admin-antd | github_2023 | soybeanjs | typescript | updateTabsLabel | function updateTabsLabel(tabs: App.Global.Tab[]) {
const updated = tabs.map(tab => ({
...tab,
label: tab.newLabel || tab.oldLabel || tab.label
}));
return updated;
} | /**
* Update tabs label
*
* @param tabs
*/ | https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/tab/shared.ts#L205-L212 | 6bd3e89e710836beb14b1a3381532a3eb7cc3a75 |
soybean-admin-antd | github_2023 | soybeanjs | typescript | resetStore | function resetStore() {
const themeStore = useThemeStore();
themeStore.$reset();
} | /** Reset store */ | https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/theme/index.ts#L26-L30 | 6bd3e89e710836beb14b1a3381532a3eb7cc3a75 |
soybean-admin-antd | github_2023 | soybeanjs | typescript | setThemeScheme | function setThemeScheme(themeScheme: UnionKey.ThemeScheme) {
settings.value.themeScheme = themeScheme;
} | /**
* Set theme scheme
*
* @param themeScheme
*/ | https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/theme/index.ts#L72-L74 | 6bd3e89e710836beb14b1a3381532a3eb7cc3a75 |
soybean-admin-antd | github_2023 | soybeanjs | typescript | setGrayscale | function setGrayscale(isGrayscale: boolean) {
settings.value.grayscale = isGrayscale;
} | /**
* Set grayscale value
*
* @param isGrayscale
*/ | https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/theme/index.ts#L81-L83 | 6bd3e89e710836beb14b1a3381532a3eb7cc3a75 |
soybean-admin-antd | github_2023 | soybeanjs | typescript | setColourWeakness | function setColourWeakness(isColourWeakness: boolean) {
settings.value.colourWeakness = isColourWeakness;
} | /**
* Set colourWeakness value
*
* @param isColourWeakness
*/ | https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/theme/index.ts#L90-L92 | 6bd3e89e710836beb14b1a3381532a3eb7cc3a75 |
soybean-admin-antd | github_2023 | soybeanjs | typescript | toggleThemeScheme | function toggleThemeScheme() {
const themeSchemes: UnionKey.ThemeScheme[] = ['light', 'dark', 'auto'];
const index = themeSchemes.findIndex(item => item === settings.value.themeScheme);
const nextIndex = index === themeSchemes.length - 1 ? 0 : index + 1;
const nextThemeScheme = themeSchemes[nextIndex];
setThemeScheme(nextThemeScheme);
} | /** Toggle theme scheme */ | https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/theme/index.ts#L95-L105 | 6bd3e89e710836beb14b1a3381532a3eb7cc3a75 |
soybean-admin-antd | github_2023 | soybeanjs | typescript | setThemeLayout | function setThemeLayout(mode: UnionKey.ThemeLayoutMode) {
settings.value.layout.mode = mode;
} | /**
* Set theme layout
*
* @param mode Theme layout mode
*/ | https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/theme/index.ts#L112-L114 | 6bd3e89e710836beb14b1a3381532a3eb7cc3a75 |
soybean-admin-antd | github_2023 | soybeanjs | typescript | updateThemeColors | function updateThemeColors(key: App.Theme.ThemeColorKey, color: string) {
let colorValue = color;
if (settings.value.recommendColor) {
// get a color palette by provided color and color name, and use the suitable color
colorValue = getPaletteColorByNumber(color, 500, true);
}
if (key === 'primary') {
settings.value.themeColor = colorValue;
} else {
settings.value.otherColor[key] = colorValue;
}
} | /**
* Update theme colors
*
* @param key Theme color key
* @param color Theme color
*/ | https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/theme/index.ts#L122-L136 | 6bd3e89e710836beb14b1a3381532a3eb7cc3a75 |
soybean-admin-antd | github_2023 | soybeanjs | typescript | setupThemeVarsToGlobal | function setupThemeVarsToGlobal() {
const { themeTokens, darkThemeTokens } = createThemeToken(
themeColors.value,
settings.value.tokens,
settings.value.recommendColor
);
addThemeVarsToGlobal(themeTokens, darkThemeTokens);
} | /** Setup theme vars to global */ | https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/theme/index.ts#L139-L146 | 6bd3e89e710836beb14b1a3381532a3eb7cc3a75 |
soybean-admin-antd | github_2023 | soybeanjs | typescript | setLayoutReverseHorizontalMix | function setLayoutReverseHorizontalMix(reverse: boolean) {
settings.value.layout.reverseHorizontalMix = reverse;
} | /**
* Set layout reverse horizontal mix
*
* @param reverse Reverse horizontal mix
*/ | https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/theme/index.ts#L153-L155 | 6bd3e89e710836beb14b1a3381532a3eb7cc3a75 |
soybean-admin-antd | github_2023 | soybeanjs | typescript | cacheThemeSettings | function cacheThemeSettings() {
const isProd = import.meta.env.PROD;
if (!isProd) return;
localStg.set('themeSettings', settings.value);
} | /** Cache theme settings */ | https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/theme/index.ts#L158-L164 | 6bd3e89e710836beb14b1a3381532a3eb7cc3a75 |
soybean-admin-antd | github_2023 | soybeanjs | typescript | createThemePaletteColors | function createThemePaletteColors(colors: App.Theme.ThemeColor, recommended = false) {
const colorKeys = Object.keys(colors) as App.Theme.ThemeColorKey[];
const colorPaletteVar = {} as App.Theme.ThemePaletteColor;
colorKeys.forEach(key => {
const colorMap = getColorPalette(colors[key], recommended);
colorPaletteVar[key] = colorMap.get(500)!;
colorMap.forEach((hex, number) => {
colorPaletteVar[`${key}-${number}`] = hex;
});
});
return colorPaletteVar;
} | /**
* Create theme palette colors
*
* @param colors Theme colors
* @param [recommended=false] Use recommended color. Default is `false`
*/ | https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/theme/shared.ts#L88-L103 | 6bd3e89e710836beb14b1a3381532a3eb7cc3a75 |
soybean-admin-antd | github_2023 | soybeanjs | typescript | getCssVarByTokens | function getCssVarByTokens(tokens: App.Theme.BaseToken) {
const styles: string[] = [];
function removeVarPrefix(value: string) {
return value.replace('var(', '').replace(')', '');
}
function removeRgbPrefix(value: string) {
return value.replace('rgb(', '').replace(')', '');
}
for (const [key, tokenValues] of Object.entries(themeVars)) {
for (const [tokenKey, tokenValue] of Object.entries(tokenValues)) {
let cssVarsKey = removeVarPrefix(tokenValue);
let cssValue = tokens[key][tokenKey];
if (key === 'colors') {
cssVarsKey = removeRgbPrefix(cssVarsKey);
const { r, g, b } = getRgbOfColor(cssValue);
cssValue = `${r} ${g} ${b}`;
}
styles.push(`${cssVarsKey}: ${cssValue}`);
}
}
const styleStr = styles.join(';');
return styleStr;
} | /**
* Get css var by tokens
*
* @param tokens Theme base tokens
*/ | https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/store/modules/theme/shared.ts#L110-L139 | 6bd3e89e710836beb14b1a3381532a3eb7cc3a75 |
soybean-admin-antd | github_2023 | soybeanjs | typescript | createColorPaletteVars | function createColorPaletteVars() {
const colors: App.Theme.ThemeColorKey[] = ['primary', 'info', 'success', 'warning', 'error'];
const colorPaletteNumbers: App.Theme.ColorPaletteNumber[] = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950];
const colorPaletteVar = {} as App.Theme.ThemePaletteColor;
colors.forEach(color => {
colorPaletteVar[color] = `rgb(var(--${color}-color))`;
colorPaletteNumbers.forEach(number => {
colorPaletteVar[`${color}-${number}`] = `rgb(var(--${color}-${number}-color))`;
});
});
return colorPaletteVar;
} | /** Create color palette vars */ | https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/theme/vars.ts#L2-L16 | 6bd3e89e710836beb14b1a3381532a3eb7cc3a75 |
soybean-admin-antd | github_2023 | soybeanjs | typescript | createProxyPattern | function createProxyPattern(key?: App.Service.OtherBaseURLKey) {
if (!key) {
return '/proxy-default';
}
return `/proxy-${key}`;
} | /**
* Get proxy pattern of backend service base url
*
* @param key If not set, will use the default key
*/ | https://github.com/soybeanjs/soybean-admin-antd/blob/6bd3e89e710836beb14b1a3381532a3eb7cc3a75/src/utils/service.ts#L69-L75 | 6bd3e89e710836beb14b1a3381532a3eb7cc3a75 |
mail2telegram | github_2023 | TBXark | typescript | deleteMessage | const deleteMessage = async (arg: string): Promise<void> => {
await api.deleteMessage({
chat_id: chatId,
message_id: messageId,
});
}; | // eslint-disable-next-line unused-imports/no-unused-vars | https://github.com/TBXark/mail2telegram/blob/0ef1d5db7182d041dbba8a1dffa7998e763ac983/src/telegram/telegram.ts#L155-L160 | 0ef1d5db7182d041dbba8a1dffa7998e763ac983 |
obsidian-note-gallery | github_2023 | pashashocky | typescript | NoteGalleryPlugin.onload | async onload() {
this.db = this.registerDb();
this.patchCatchEmbeddedSearch();
this.registerMarkdownCodeBlockProcessor("note-gallery", async (src, el, ctx) => {
const handler = new CodeBlockNoteGallery(this, src, el, this.app, ctx);
ctx.addChild(handler);
});
this.addCommand({
id: "drop-database",
name: "Drop all cache and re-initialize database",
callback: () => {
this.db.reinitializeDatabase();
},
});
} | /**
* Called on plugin load.
* This can be when the plugin is enabled or Obsidian is first opened.
*/ | https://github.com/pashashocky/obsidian-note-gallery/blob/a173d0bc233323e2318e05d106c85b7303cb48e2/src/main.ts#L89-L105 | a173d0bc233323e2318e05d106c85b7303cb48e2 |
obsidian-note-gallery | github_2023 | pashashocky | typescript | NoteGalleryPlugin.onunload | async onunload() {} | /**
* Called on plugin unload.
* This can be when the plugin is disabled or Obsidian is closed.
*/ | https://github.com/pashashocky/obsidian-note-gallery/blob/a173d0bc233323e2318e05d106c85b7303cb48e2/src/main.ts#L111-L111 | a173d0bc233323e2318e05d106c85b7303cb48e2 |
obsidian-note-gallery | github_2023 | pashashocky | typescript | Database.constructor | constructor(
public plugin: Plugin,
public name: string,
public title: string,
public version: number,
public description: string,
private defaultValue: () => T,
private extractValue: (
markdown: string,
file: TFile,
state?: EditorState,
) => Promise<T>,
public workers: number = 2,
private loadValue: (data: T) => T = (data: T) => data,
) {
super();
// localforage does not offer a method for accessing the database version, so we store it separately
const localStorageVersion = this.plugin.app.loadLocalStorage(name + "-version");
const oldVersion = localStorageVersion ? parseInt(localStorageVersion) : null;
this.persist = localforage.createInstance({
name: this.name + `/${this.plugin.app.appId}`,
driver: localforage.INDEXEDDB,
description,
version,
});
this.plugin.app.workspace.onLayoutReady(async () => {
await this.persist.ready(async () => {
await this.loadDatabase();
this.trigger("database-update", this.allEntries());
const operation_label =
oldVersion !== null && oldVersion < version
? "Migrating"
: this.isEmpty()
? "Initializing"
: "Syncing";
const { progress_bar, notice } = this.createNotice(operation_label, title);
if (oldVersion !== null && oldVersion < version && !this.isEmpty()) {
await this.clearDatabase();
await this.rebuildDatabase(progress_bar, notice);
this.trigger("database-migrate");
this.trigger("database-update", this.allEntries());
} else if (this.isEmpty()) {
await this.rebuildDatabase(progress_bar, notice);
this.trigger("database-create");
this.trigger("database-update", this.allEntries());
} else {
await this.syncDatabase(progress_bar, notice);
}
this.ready = true;
// Alternatives: use 'this.editorExtensions.push(EditorView.updateListener.of(async (update) => {'
// for instant View updates, but this requires the file to be read into the file cache first
this.registerEvent(
this.plugin.app.vault.on("modify", async file => {
if (file instanceof TFile && file.extension === "md") {
const current_editor = this.plugin.app.workspace.activeEditor;
const state =
current_editor &&
current_editor.file?.path === file.path &&
current_editor.editor
? current_editor.editor.cm.state
: undefined;
const markdown = await this.plugin.app.vault.cachedRead(file);
this.storeKey(
file.path,
await this.extractValue(markdown, file, state),
file.stat.mtime,
);
}
}),
);
this.registerEvent(
this.plugin.app.vault.on("delete", async file => {
if (file instanceof TFile && file.extension === "md")
this.deleteKey(file.path);
}),
);
this.registerEvent(
this.plugin.app.vault.on("rename", async (file, oldPath) => {
if (file instanceof TFile && file.extension === "md")
this.renameKey(oldPath, file.path, file.stat.mtime);
}),
);
this.registerEvent(
this.plugin.app.vault.on("create", async file => {
if (file instanceof TFile && file.extension === "md")
this.storeKey(file.path, this.defaultValue(), file.stat.mtime);
}),
);
});
});
} | /**
* Constructor for the database
* @param plugin The plugin that owns the database
* @param name Name of the database within indexedDB
* @param title Title of the database
* @param version Version of the database
* @param description Description of the database
* @param defaultValue Constructor for the default value of the database
* @param extractValue Provide new values for database on file modification
* @param workers Number of workers to use for parsing files
* @param loadValue On loading value from indexedDB, run this function on the value (useful for re-adding prototypes)
*/ | https://github.com/pashashocky/obsidian-note-gallery/blob/a173d0bc233323e2318e05d106c85b7303cb48e2/src/index/database.ts#L106-L205 | a173d0bc233323e2318e05d106c85b7303cb48e2 |
obsidian-note-gallery | github_2023 | pashashocky | typescript | Database.loadDatabase | async loadDatabase() {
this.memory = new Map(
Object.entries(
(await this.persist.getItems()) as Record<string, DatabaseItem<T>>,
).map(([key, value]) => {
value.data = this.loadValue(value.data);
return [key, value];
}),
);
} | /**
* Load database from indexedDB
*/ | https://github.com/pashashocky/obsidian-note-gallery/blob/a173d0bc233323e2318e05d106c85b7303cb48e2/src/index/database.ts#L210-L219 | a173d0bc233323e2318e05d106c85b7303cb48e2 |
obsidian-note-gallery | github_2023 | pashashocky | typescript | Database.regularParseFiles | async regularParseFiles(files: TFile[], progress_bar: HTMLProgressElement) {
for (let i = 0; i < files.length; i++) {
const file = files[i];
const value = this.getItem(file.path);
if (value === null || value.mtime < file.stat.mtime) {
const markdown = await this.plugin.app.vault.cachedRead(file);
this.storeKey(
file.path,
await this.extractValue(markdown, file),
file.stat.mtime,
true,
);
}
progress_bar.setAttribute("value", (i + 1).toString());
}
} | /**
* Extract values from files and store them in the database
* @remark Expensive, this function will block the main thread
* @param files Files to extract values from and store/update in the database
*/ | https://github.com/pashashocky/obsidian-note-gallery/blob/a173d0bc233323e2318e05d106c85b7303cb48e2/src/index/database.ts#L226-L241 | a173d0bc233323e2318e05d106c85b7303cb48e2 |
obsidian-note-gallery | github_2023 | pashashocky | typescript | Database.syncDatabase | async syncDatabase(progress_bar: HTMLProgressElement, notice: Notice) {
const markdownFiles = this.plugin.app.vault.getMarkdownFiles();
this.initializeProgressBar(progress_bar, markdownFiles.length);
this.allKeys().forEach(key => {
if (!markdownFiles.some(file => file.path === key)) this.deleteKey(key);
});
const filesToParse = markdownFiles.filter(
file =>
!this.memory.has(file.path) ||
this.memory.get(file.path)!.mtime < file.stat.mtime,
);
// if (filesToParse.length <= 100)
// await this.regularParseFiles(filesToParse, progress_bar);
// else await this.workerParseFiles(filesToParse, progress_bar);
await this.regularParseFiles(filesToParse, progress_bar);
this.plugin.app.saveLocalStorage(this.name + "-version", this.version.toString());
notice.hide();
} | /**
* Synchronize database with vault contents
*/ | https://github.com/pashashocky/obsidian-note-gallery/blob/a173d0bc233323e2318e05d106c85b7303cb48e2/src/index/database.ts#L282-L301 | a173d0bc233323e2318e05d106c85b7303cb48e2 |
obsidian-note-gallery | github_2023 | pashashocky | typescript | Database.rebuildDatabase | async rebuildDatabase(progress_bar: HTMLProgressElement, notice: Notice) {
const markdownFiles = this.plugin.app.vault.getMarkdownFiles();
this.initializeProgressBar(progress_bar, markdownFiles.length);
// await this.workerParseFiles(markdownFiles, progress_bar);
await this.regularParseFiles(markdownFiles, progress_bar);
this.plugin.app.saveLocalStorage(this.name + "-version", this.version.toString());
notice.hide();
} | /**
* Rebuild database from scratch by parsing all files in the vault
*/ | https://github.com/pashashocky/obsidian-note-gallery/blob/a173d0bc233323e2318e05d106c85b7303cb48e2/src/index/database.ts#L306-L313 | a173d0bc233323e2318e05d106c85b7303cb48e2 |
obsidian-note-gallery | github_2023 | pashashocky | typescript | Database.persistMemory | async persistMemory() {
const to_set: Record<string, DatabaseItem<T>> = {};
for (const [key, value] of this.memory.entries()) {
if (value.dirty) {
to_set[key] = { data: value.data, mtime: value.mtime };
this.memory.set(key, { data: value.data, mtime: value.mtime, dirty: false });
}
}
await this.persist.setItems(to_set);
await Promise.all(
Array.from(this.deleted_keys.values()).map(
async key => await this.persist.removeItem(key),
),
);
this.deleted_keys.clear();
} | /**
* Persist in-memory database to indexedDB
* @remark Prefer usage of flushChanges over this function to reduce the number of writes to indexedDB
*/ | https://github.com/pashashocky/obsidian-note-gallery/blob/a173d0bc233323e2318e05d106c85b7303cb48e2/src/index/database.ts#L319-L335 | a173d0bc233323e2318e05d106c85b7303cb48e2 |
obsidian-note-gallery | github_2023 | pashashocky | typescript | Database.dropDatabase | async dropDatabase() {
this.trigger("database-drop");
this.memory.clear();
await localforage.dropInstance({
name: this.name + `/${this.plugin.app.appId}`,
});
localStorage.removeItem(this.plugin.app.appId + "-" + this.name + "-version");
} | /**
* Clear in-memory cache, and completely remove database from indexedDB (and all references in localStorage)
*/ | https://github.com/pashashocky/obsidian-note-gallery/blob/a173d0bc233323e2318e05d106c85b7303cb48e2/src/index/database.ts#L408-L415 | a173d0bc233323e2318e05d106c85b7303cb48e2 |
obsidian-note-gallery | github_2023 | pashashocky | typescript | Database.reinitializeDatabase | async reinitializeDatabase() {
await this.dropDatabase();
this.persist = localforage.createInstance({
name: this.name + `/${this.plugin.app.appId}`,
driver: localforage.INDEXEDDB,
version: this.version,
description: this.description,
});
const operation_label = "Initializing";
const { progress_bar, notice } = this.createNotice(operation_label, this.title);
await this.rebuildDatabase(progress_bar, notice);
this.trigger("database-update", this.allEntries());
} | /**
* Rebuild database from scratch
* @remark Useful for fixing incorrectly set version numbers
*/ | https://github.com/pashashocky/obsidian-note-gallery/blob/a173d0bc233323e2318e05d106c85b7303cb48e2/src/index/database.ts#L421-L433 | a173d0bc233323e2318e05d106c85b7303cb48e2 |
obsidian-note-gallery | github_2023 | pashashocky | typescript | Database.clearDatabase | async clearDatabase() {
this.trigger("database-drop");
this.memory.clear();
await this.persist.clear();
} | /**
* Clear in-memory cache, and clear database contents from indexedDB
*/ | https://github.com/pashashocky/obsidian-note-gallery/blob/a173d0bc233323e2318e05d106c85b7303cb48e2/src/index/database.ts#L438-L442 | a173d0bc233323e2318e05d106c85b7303cb48e2 |
obsidian-note-gallery | github_2023 | pashashocky | typescript | Database.isEmpty | isEmpty(): boolean {
return this.memory.size === 0;
} | /**
* Check if database is empty
* @remark Run after `loadDatabase()`
*/ | https://github.com/pashashocky/obsidian-note-gallery/blob/a173d0bc233323e2318e05d106c85b7303cb48e2/src/index/database.ts#L448-L450 | a173d0bc233323e2318e05d106c85b7303cb48e2 |
obsidian-note-gallery | github_2023 | pashashocky | typescript | deterministicShuffle | function deterministicShuffle(files: TFile[], seed: number) {
return files
.map((item) => ({
item,
sortKey: hashStringWithSeed(item.path, seed),
})) // Map each item to its hash
.sort((a, b) => a.sortKey - b.sortKey) // Sort by the hash values
.map(({ item }) => item); // Extract sorted items
} | // Make sure that item order remains relatively fixed during re-renders to stop cards jumping around | https://github.com/pashashocky/obsidian-note-gallery/blob/a173d0bc233323e2318e05d106c85b7303cb48e2/src/react/utils/use-files.ts#L66-L74 | a173d0bc233323e2318e05d106c85b7303cb48e2 |
duxcms | github_2023 | duxweb | typescript | init | const init = (context: appContext) => {
const data = import.meta.glob('./locales/*.json', { eager: true })
context.addI18ns(data)
context.createApp('admin', createApp())
return null
} | // init function will be called when app start | https://github.com/duxweb/duxcms/blob/9f9d4ba7ba1eda000c9d9740282c63fab8dab83f/web/src/pages/system/index.ts#L7-L12 | 9f9d4ba7ba1eda000c9d9740282c63fab8dab83f |
duxcms | github_2023 | duxweb | typescript | register | const register = (context: appContext) => {
const admin = context.getApp('admin')
admin.addIndexs([
{
name: 'system',
component: lazyComponent(() => import('./admin/total/index')),
},
])
if (context.config.indexName != 'system') {
admin.addResources([
{
name: 'system.total',
list: 'system/total',
listElenemt: lazyComponent(() => import('./admin/total/index')),
meta: {
label: 'system.total',
parent: 'system',
icon: 'i-tabler:graph',
sort: 0,
},
},
])
}
adminRouter(admin)
adminResources(admin, context)
} | // register function will be called when app register | https://github.com/duxweb/duxcms/blob/9f9d4ba7ba1eda000c9d9740282c63fab8dab83f/web/src/pages/system/index.ts#L15-L43 | 9f9d4ba7ba1eda000c9d9740282c63fab8dab83f |
playwright-crx | github_2023 | ruifigueira | typescript | testFilesRoutePredicate | const testFilesRoutePredicate = (params: URLSearchParams) => !params.has('testId'); | // These are extracted to preserve the function identity between renders to avoid re-triggering effects. | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/html-reporter/src/reportView.tsx#L39-L39 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | Request.headers | headers(): Headers {
if (this._fallbackOverrides.headers)
return RawHeaders._fromHeadersObjectLossy(this._fallbackOverrides.headers).headers();
return this._provisionalHeaders.headers();
} | /**
* @deprecated
*/ | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/client/network.ts#L162-L166 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | Response.headers | headers(): Headers {
return this._provisionalHeaders.headers();
} | /**
* @deprecated
*/ | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/client/network.ts#L679-L681 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | parseTicks | function parseTicks(value: number | string): number {
if (typeof value === 'number')
return value;
if (!value)
return 0;
const str = value;
const strings = str.split(':');
const l = strings.length;
let i = l;
let ms = 0;
let parsed;
if (l > 3 || !/^(\d\d:){0,2}\d\d?$/.test(str)) {
throw new Error(
`Clock only understands numbers, 'mm:ss' and 'hh:mm:ss'`,
);
}
while (i--) {
parsed = parseInt(strings[i], 10);
if (parsed >= 60)
throw new Error(`Invalid time ${str}`);
ms += parsed * Math.pow(60, l - i - 1);
}
return ms * 1000;
} | /**
* Parse strings like '01:10:00' (meaning 1 hour, 10 minutes, 0 seconds) into
* number of milliseconds. This is used to support human-readable strings passed
* to clock.tick()
*/ | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/clock.ts#L103-L130 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | Cookie.matches | matches(url: URL): boolean {
if (this._raw.secure && (url.protocol !== 'https:' && url.hostname !== 'localhost'))
return false;
if (!domainMatches(url.hostname, this._raw.domain))
return false;
if (!pathMatches(url.pathname, this._raw.path))
return false;
return true;
} | // https://datatracker.ietf.org/doc/html/rfc6265#section-5.4 | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/cookieStore.ts#L31-L39 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | generateUniqueBoundaryString | function generateUniqueBoundaryString(): string {
const charCodes = [];
for (let i = 0; i < 16; i++)
charCodes.push(alphaNumericEncodingMap[Math.floor(Math.random() * alphaNumericEncodingMap.length)]);
return '----WebKitFormBoundary' + String.fromCharCode(...charCodes);
} | // See generateUniqueBoundaryString() in WebKit | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/formData.ts#L86-L91 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | predicate | const predicate = (e: NavigationEvent) => !e.newDocument; | // Wait for same document navigation. | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/frames.ts#L694-L694 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | Request.setRawRequestHeaders | setRawRequestHeaders(headers: HeadersArray | null) {
if (!this._rawRequestHeadersPromise.isDone())
this._rawRequestHeadersPromise.resolve(headers || this._headers);
} | // "null" means no raw headers available - we'll use provisional headers as raw headers. | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/network.ts#L177-L180 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | Request._setBodySize | _setBodySize(size: number) {
this._bodySize = size;
} | // TODO(bidi): remove once post body is available. | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/network.ts#L228-L230 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | Route._maybeAddCorsHeaders | private _maybeAddCorsHeaders(headers: NameValue[]) {
const origin = this._request.headerValue('origin');
if (!origin)
return;
const requestUrl = new URL(this._request.url());
if (!requestUrl.protocol.startsWith('http'))
return;
if (requestUrl.origin === origin.trim())
return;
const corsHeader = headers.find(({ name }) => name === 'access-control-allow-origin');
if (corsHeader)
return;
headers.push({ name: 'access-control-allow-origin', value: origin });
headers.push({ name: 'access-control-allow-credentials', value: 'true' });
headers.push({ name: 'vary', value: 'Origin' });
} | // See https://github.com/microsoft/playwright/issues/12929 | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/network.ts#L305-L320 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | Response.setRawResponseHeaders | setRawResponseHeaders(headers: HeadersArray | null) {
if (!this._rawResponseHeadersPromise.isDone())
this._rawResponseHeadersPromise.resolve(headers || this._headers);
} | // "null" means no raw headers available - we'll use provisional headers as raw headers. | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/network.ts#L464-L467 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | BidiPage._onBrowsingContextDestroyed | private _onBrowsingContextDestroyed(params: bidi.BrowsingContext.Info) {
this._browserContext._browser._onBrowsingContextDestroyed(params);
} | // TODO: route the message directly to the browser | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/bidi/bidiPage.ts#L175-L177 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | BidiPage._onNavigationResponseStarted | private _onNavigationResponseStarted(params: bidi.Network.ResponseStartedParameters) {
const frameId = params.context!;
const frame = this._page._frameManager.frame(frameId);
assert(frame);
this._page._frameManager.frameCommittedNewDocumentNavigation(frameId, params.response.url, '', params.navigation!, /* initial */ false);
// if (!initial)
// this._firstNonInitialNavigationCommittedFulfill();
} | // TODO: there is no separate event for committed navigation, so we approximate it with responseStarted. | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/bidi/bidiPage.ts#L194-L201 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | BidiPage._installMainBinding | private async _installMainBinding() {
const functionDeclaration = addMainBinding.toString();
const args: bidi.Script.ChannelValue[] = [{
type: 'channel',
value: {
channel: kPlaywrightBindingChannel,
ownership: bidi.Script.ResultOwnership.Root,
}
}];
const promises = [];
promises.push(this._session.send('script.addPreloadScript', {
functionDeclaration,
arguments: args,
}));
promises.push(this._session.send('script.callFunction', {
functionDeclaration,
arguments: args,
target: toBidiExecutionContext(await this._page.mainFrame()._mainContext())._target,
awaitPromise: false,
userActivation: false,
}));
await Promise.all(promises);
} | // TODO: consider calling this only when bindings are added. | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/bidi/bidiPage.ts#L331-L353 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | BidiPage._framePosition | private async _framePosition(frame: frames.Frame): Promise<types.Point | null> {
if (frame === this._page.mainFrame())
return { x: 0, y: 0 };
const element = await frame.frameElement();
const box = await element.boundingBox();
if (!box)
return null;
const style = await element.evaluateInUtility(([injected, iframe]) => injected.describeIFrameStyle(iframe as Element), {}).catch(e => 'error:notconnected' as const);
if (style === 'error:notconnected' || style === 'transformed')
return null;
// Content box is offset by border and padding widths.
box.x += style.left;
box.y += style.top;
return box;
} | // TODO: move to Frame. | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/bidi/bidiPage.ts#L450-L464 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | writePreferences | async function writePreferences(options: ProfileOptions): Promise<void> {
const prefsPath = path.join(options.path, 'prefs.js');
const lines = Object.entries(options.preferences).map(([key, value]) => {
return `user_pref(${JSON.stringify(key)}, ${JSON.stringify(value)});`;
});
// Use allSettled to prevent corruption
const result = await Promise.allSettled([
fs.promises.writeFile(path.join(options.path, 'user.js'), lines.join('\n')),
// Create a backup of the preferences file if it already exitsts.
fs.promises.access(prefsPath, fs.constants.F_OK).then(
async () => {
await fs.promises.copyFile(
prefsPath,
path.join(options.path, 'prefs.js.playwright')
);
},
// Swallow only if file does not exist
() => {}
),
]);
for (const command of result) {
if (command.status === 'rejected') {
throw command.reason;
}
}
} | /**
* Populates the user.js file with custom preferences as needed to allow
* Firefox's CDP support to properly function. These preferences will be
* automatically copied over to prefs.js during startup of Firefox. To be
* able to restore the original values of preferences a backup of prefs.js
* will be created.
*
* @param prefs - List of preferences to add.
* @param profilePath - Firefox profile to write the preferences to.
*/ | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/bidi/third_party/firefoxPrefs.ts#L256-L282 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | catchDisallowedErrors | async function catchDisallowedErrors(callback: () => Promise<void>) {
try {
return await callback();
} catch (e) {
if (isProtocolError(e) && e.message.includes('Invalid http status code or phrase'))
throw e;
}
} | // In certain cases, protocol will return error if the request was already canceled | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/chromium/crNetworkManager.ts#L655-L662 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | calculateUserAgentMetadata | function calculateUserAgentMetadata(options: types.BrowserContextOptions) {
const ua = options.userAgent;
if (!ua)
return undefined;
const metadata: Protocol.Emulation.UserAgentMetadata = {
mobile: !!options.isMobile,
model: '',
architecture: 'x64',
platform: 'Windows',
platformVersion: '',
};
const androidMatch = ua.match(/Android (\d+(\.\d+)?(\.\d+)?)/);
const iPhoneMatch = ua.match(/iPhone OS (\d+(_\d+)?)/);
const iPadMatch = ua.match(/iPad; CPU OS (\d+(_\d+)?)/);
const macOSMatch = ua.match(/Mac OS X (\d+(_\d+)?(_\d+)?)/);
const windowsMatch = ua.match(/Windows\D+(\d+(\.\d+)?(\.\d+)?)/);
if (androidMatch) {
metadata.platform = 'Android';
metadata.platformVersion = androidMatch[1];
metadata.architecture = 'arm';
} else if (iPhoneMatch) {
metadata.platform = 'iOS';
metadata.platformVersion = iPhoneMatch[1];
metadata.architecture = 'arm';
} else if (iPadMatch) {
metadata.platform = 'iOS';
metadata.platformVersion = iPadMatch[1];
metadata.architecture = 'arm';
} else if (macOSMatch) {
metadata.platform = 'macOS';
metadata.platformVersion = macOSMatch[1];
if (!ua.includes('Intel'))
metadata.architecture = 'arm';
} else if (windowsMatch) {
metadata.platform = 'Windows';
metadata.platformVersion = windowsMatch[1];
} else if (ua.toLowerCase().includes('linux')) {
metadata.platform = 'Linux';
}
if (ua.includes('ARM'))
metadata.architecture = 'arm';
return metadata;
} | // Chromium reference: https://source.chromium.org/chromium/chromium/src/+/main:components/embedder_support/user_agent_utils.cc;l=434;drc=70a6711e08e9f9e0d8e4c48e9ba5cab62eb010c2 | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/chromium/crPage.ts#L1205-L1247 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | onVideo | const onVideo = (artifact: Artifact) => {
// Note: Video must outlive Page and BrowserContext, so that client can saveAs it
// after closing the context. We use |scope| for it.
const artifactDispatcher = ArtifactDispatcher.from(parentScope, artifact);
this._dispatchEvent('video', { artifact: artifactDispatcher });
}; | // Note: when launching persistent context, dispatcher is created very late, | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/dispatchers/browserContextDispatcher.ts#L71-L76 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | createIntl | function createIntl(clock: ClockController, NativeIntl: typeof Intl): typeof Intl {
const ClockIntl: any = {};
/*
* All properties of Intl are non-enumerable, so we need
* to do a bit of work to get them out.
*/
for (const key of Object.getOwnPropertyNames(NativeIntl) as (keyof typeof Intl)[])
ClockIntl[key] = NativeIntl[key];
ClockIntl.DateTimeFormat = function(...args: any[]) {
const realFormatter = new NativeIntl.DateTimeFormat(...args);
const formatter: Intl.DateTimeFormat = {
formatRange: realFormatter.formatRange.bind(realFormatter),
formatRangeToParts: realFormatter.formatRangeToParts.bind(realFormatter),
resolvedOptions: realFormatter.resolvedOptions.bind(realFormatter),
format: date => realFormatter.format(date || clock.now()),
formatToParts: date => realFormatter.formatToParts(date || clock.now()),
};
return formatter;
};
ClockIntl.DateTimeFormat.prototype = Object.create(
NativeIntl.DateTimeFormat.prototype,
);
ClockIntl.DateTimeFormat.supportedLocalesOf =
NativeIntl.DateTimeFormat.supportedLocalesOf;
return ClockIntl;
} | /**
* Mirror Intl by default on our fake implementation
*
* Most of the properties are the original native ones,
* but we need to take control of those that have a
* dependency on the current clock.
*/ | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/injected/clock.ts#L489-L519 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | platformOriginals | function platformOriginals(globalObject: WindowOrWorkerGlobalScope): { raw: ClockMethods, bound: ClockMethods } {
const raw: ClockMethods = {
setTimeout: globalObject.setTimeout,
clearTimeout: globalObject.clearTimeout,
setInterval: globalObject.setInterval,
clearInterval: globalObject.clearInterval,
requestAnimationFrame: (globalObject as any).requestAnimationFrame ? (globalObject as any).requestAnimationFrame : undefined,
cancelAnimationFrame: (globalObject as any).cancelAnimationFrame ? (globalObject as any).cancelAnimationFrame : undefined,
requestIdleCallback: (globalObject as any).requestIdleCallback ? (globalObject as any).requestIdleCallback : undefined,
cancelIdleCallback: (globalObject as any).cancelIdleCallback ? (globalObject as any).cancelIdleCallback : undefined,
Date: (globalObject as any).Date,
performance: globalObject.performance,
Intl: (globalObject as any).Intl,
};
const bound = { ...raw };
for (const key of Object.keys(bound) as (keyof ClockMethods)[]) {
if (key !== 'Date' && typeof bound[key] === 'function')
bound[key] = (bound[key] as any).bind(globalObject);
}
return { raw, bound };
} | // arbitrarily large number to avoid collisions with native timer IDs | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/injected/clock.ts#L552-L572 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | getScheduleHandler | function getScheduleHandler(type: TimerType) {
if (type === 'IdleCallback' || type === 'AnimationFrame')
return `request${type}`;
return `set${type}`;
} | /**
* Gets schedule handler name for a given timer type
*/ | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/injected/clock.ts#L577-L582 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | InjectedScript.constructor | constructor(window: Window & typeof globalThis, isUnderTest: boolean, sdkLanguage: Language, testIdAttributeNameForStrictErrorAndConsoleCodegen: string, stableRafCount: number, browserName: string, customEngines: { name: string, engine: SelectorEngine }[]) {
this.window = window;
this.document = window.document;
this.isUnderTest = isUnderTest;
this._sdkLanguage = sdkLanguage;
this._testIdAttributeNameForStrictErrorAndConsoleCodegen = testIdAttributeNameForStrictErrorAndConsoleCodegen;
this._evaluator = new SelectorEvaluatorImpl(new Map());
this._engines = new Map();
this._engines.set('xpath', XPathEngine);
this._engines.set('xpath:light', XPathEngine);
this._engines.set('_react', ReactEngine);
this._engines.set('_vue', VueEngine);
this._engines.set('role', createRoleEngine(false));
this._engines.set('text', this._createTextEngine(true, false));
this._engines.set('text:light', this._createTextEngine(false, false));
this._engines.set('id', this._createAttributeEngine('id', true));
this._engines.set('id:light', this._createAttributeEngine('id', false));
this._engines.set('data-testid', this._createAttributeEngine('data-testid', true));
this._engines.set('data-testid:light', this._createAttributeEngine('data-testid', false));
this._engines.set('data-test-id', this._createAttributeEngine('data-test-id', true));
this._engines.set('data-test-id:light', this._createAttributeEngine('data-test-id', false));
this._engines.set('data-test', this._createAttributeEngine('data-test', true));
this._engines.set('data-test:light', this._createAttributeEngine('data-test', false));
this._engines.set('css', this._createCSSEngine());
this._engines.set('nth', { queryAll: () => [] });
this._engines.set('visible', this._createVisibleEngine());
this._engines.set('internal:control', this._createControlEngine());
this._engines.set('internal:has', this._createHasEngine());
this._engines.set('internal:has-not', this._createHasNotEngine());
this._engines.set('internal:and', { queryAll: () => [] });
this._engines.set('internal:or', { queryAll: () => [] });
this._engines.set('internal:chain', this._createInternalChainEngine());
this._engines.set('internal:label', this._createInternalLabelEngine());
this._engines.set('internal:text', this._createTextEngine(true, true));
this._engines.set('internal:has-text', this._createInternalHasTextEngine());
this._engines.set('internal:has-not-text', this._createInternalHasNotTextEngine());
this._engines.set('internal:attr', this._createNamedAttributeEngine());
this._engines.set('internal:testid', this._createNamedAttributeEngine());
this._engines.set('internal:role', createRoleEngine(true));
for (const { name, engine } of customEngines)
this._engines.set(name, engine);
this._stableRafCount = stableRafCount;
this._browserName = browserName;
setBrowserName(browserName);
this._setupGlobalListenersRemovalDetection();
this._setupHitTargetInterceptors();
if (isUnderTest)
(this.window as any).__injectedScript = this;
} | // eslint-disable-next-line no-restricted-globals | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/injected/injectedScript.ts#L93-L146 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | InjectedScript.setupHitTargetInterceptor | setupHitTargetInterceptor(node: Node, action: 'hover' | 'tap' | 'mouse' | 'drag', hitPoint: { x: number, y: number } | undefined, blockAllEvents: boolean): HitTargetInterceptionResult | 'error:notconnected' | string /* hitTargetDescription */ {
const element = this.retarget(node, 'button-link');
if (!element || !element.isConnected)
return 'error:notconnected';
if (hitPoint) {
// First do a preliminary check, to reduce the possibility of some iframe
// intercepting the action.
const preliminaryResult = this.expectHitTarget(hitPoint, element);
if (preliminaryResult !== 'done')
return preliminaryResult.hitTargetDescription;
}
// When dropping, the "element that is being dragged" often stays under the cursor,
// so hit target check at the moment we receive mousedown does not work -
// it finds the "element that is being dragged" instead of the
// "element that we drop onto".
if (action === 'drag')
return { stop: () => 'done' };
const events = {
'hover': kHoverHitTargetInterceptorEvents,
'tap': kTapHitTargetInterceptorEvents,
'mouse': kMouseHitTargetInterceptorEvents,
}[action];
let result: 'done' | { hitTargetDescription: string } | undefined;
const listener = (event: PointerEvent | MouseEvent | TouchEvent) => {
// Ignore events that we do not expect to intercept.
if (!events.has(event.type))
return;
// Playwright only issues trusted events, so allow any custom events originating from
// the page or content scripts.
if (!event.isTrusted)
return;
// Determine the event point. Note that Firefox does not always have window.TouchEvent.
const point = (!!this.window.TouchEvent && (event instanceof this.window.TouchEvent)) ? event.touches[0] : (event as MouseEvent | PointerEvent);
// Check that we hit the right element at the first event, and assume all
// subsequent events will be fine.
if (result === undefined && point)
result = this.expectHitTarget({ x: point.clientX, y: point.clientY }, element);
if (blockAllEvents || (result !== 'done' && result !== undefined)) {
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
}
};
const stop = () => {
if (this._hitTargetInterceptor === listener)
this._hitTargetInterceptor = undefined;
// If we did not get any events, consider things working. Possible causes:
// - JavaScript is disabled (webkit-only).
// - Some <iframe> overlays the element from another frame.
// - Hovering a disabled control prevents any events from firing.
return result || 'done';
};
// Note: this removes previous listener, just in case there are two concurrent clicks
// or something went wrong and we did not cleanup.
this._hitTargetInterceptor = listener;
return { stop };
} | // 2m. If failed, wait for increasing amount of time before the next retry. | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/injected/injectedScript.ts#L954-L1020 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | boxRightOf | function boxRightOf(box1: DOMRect, box2: DOMRect, maxDistance: number | undefined): number | undefined {
const distance = box1.left - box2.right;
if (distance < 0 || (maxDistance !== undefined && distance > maxDistance))
return;
return distance + Math.max(box2.bottom - box1.bottom, 0) + Math.max(box1.top - box2.top, 0);
} | /**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/injected/layoutSelectorUtils.ts#L17-L22 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | basename | function basename(filename: string, ext: string): string {
const normalized = filename.replace(/^[a-zA-Z]:/, '').replace(/\\/g, '/');
let result = normalized.substring(normalized.lastIndexOf('/') + 1);
if (ext && result.endsWith(ext))
result = result.substring(0, result.length - ext.length);
return result;
} | // @see https://github.com/vuejs/devtools/blob/14085e25313bcf8ffcb55f9092a40bc0fe3ac11c/packages/shared-utils/src/util.ts#L295 | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/injected/vueSelectorEngine.ts#L50-L56 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | toUpper | function toUpper(_: any, c: string): string {
return c ? c.toUpperCase() : '';
} | // @see https://github.com/vuejs/devtools/blob/14085e25313bcf8ffcb55f9092a40bc0fe3ac11c/packages/shared-utils/src/util.ts#L41 | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/injected/vueSelectorEngine.ts#L59-L61 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | getComponentTypeName | function getComponentTypeName(options: any): string|undefined {
const name = options.name || options._componentTag || options.__playwright_guessedName;
if (name)
return name;
const file = options.__file; // injected by vue-loader
if (file)
return classify(basename(file, '.vue'));
} | // @see https://github.com/vuejs/devtools/blob/e7132f3392b975e39e1d9a23cf30456c270099c2/packages/app-backend-vue3/src/components/util.ts#L47 | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/injected/vueSelectorEngine.ts#L71-L78 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | saveComponentName | function saveComponentName(instance: VueVNode, key: string): string {
instance.type.__playwright_guessedName = key;
return key;
} | // @see https://github.com/vuejs/devtools/blob/e7132f3392b975e39e1d9a23cf30456c270099c2/packages/app-backend-vue3/src/components/util.ts#L42 | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/injected/vueSelectorEngine.ts#L81-L84 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | getInstanceName | function getInstanceName(instance: VueVNode): string {
const name = getComponentTypeName(instance.type || {});
if (name)
return name;
if (instance.root === instance)
return 'Root';
for (const key in instance.parent?.type?.components) {
if (instance.parent?.type.components[key] === instance.type)
return saveComponentName(instance, key);
}
for (const key in instance.appContext?.components) {
if (instance.appContext.components[key] === instance.type)
return saveComponentName(instance, key);
}
return 'Anonymous Component';
} | // @see https://github.com/vuejs/devtools/blob/e7132f3392b975e39e1d9a23cf30456c270099c2/packages/app-backend-vue3/src/components/util.ts#L29 | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/injected/vueSelectorEngine.ts#L87-L102 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | isBeingDestroyed | function isBeingDestroyed(instance: VueVNode): boolean {
return instance._isBeingDestroyed || instance.isUnmounted;
} | // @see https://github.com/vuejs/devtools/blob/e7132f3392b975e39e1d9a23cf30456c270099c2/packages/app-backend-vue3/src/components/util.ts#L6 | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/injected/vueSelectorEngine.ts#L105-L107 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | isFragment | function isFragment(instance: VueVNode): boolean {
return instance.subTree.type.toString() === 'Symbol(Fragment)';
} | // @see https://github.com/vuejs/devtools/blob/e7132f3392b975e39e1d9a23cf30456c270099c2/packages/app-backend-vue3/src/components/util.ts#L16 | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/injected/vueSelectorEngine.ts#L110-L112 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | getInternalInstanceChildren | function getInternalInstanceChildren(subTree: any): VueVNode[] {
const list = [];
if (subTree.component)
list.push(subTree.component);
if (subTree.suspense)
list.push(...getInternalInstanceChildren(subTree.suspense.activeBranch));
if (Array.isArray(subTree.children)) {
subTree.children.forEach((childSubTree: any) => {
if (childSubTree.component)
list.push(childSubTree.component);
else
list.push(...getInternalInstanceChildren(childSubTree));
});
}
return list.filter(child => !isBeingDestroyed(child) && !child.type.devtools?.hide);
} | // @see https://github.com/vuejs/devtools/blob/e7132f3392b975e39e1d9a23cf30456c270099c2/packages/app-backend-vue3/src/components/tree.ts#L79 | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/injected/vueSelectorEngine.ts#L115-L130 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | getRootElementsFromComponentInstance | function getRootElementsFromComponentInstance(instance: VueVNode): Element[] {
if (isFragment(instance))
return getFragmentRootElements(instance.subTree);
return [instance.subTree.el];
} | // @see https://github.com/vuejs/devtools/blob/e7132f3392b975e39e1d9a23cf30456c270099c2/packages/app-backend-vue3/src/components/el.ts#L8 | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/injected/vueSelectorEngine.ts#L133-L137 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | getFragmentRootElements | function getFragmentRootElements(vnode: any): Element[] {
if (!vnode.children)
return [];
const list = [];
for (let i = 0, l = vnode.children.length; i < l; i++) {
const childVnode = vnode.children[i];
if (childVnode.component)
list.push(...getRootElementsFromComponentInstance(childVnode.component));
else if (childVnode.el)
list.push(childVnode.el);
}
return list;
} | // @see https://github.com/vuejs/devtools/blob/e7132f3392b975e39e1d9a23cf30456c270099c2/packages/app-backend-vue3/src/components/el.ts#L15 | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/injected/vueSelectorEngine.ts#L140-L154 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | getComponentName | function getComponentName(options: any): string|undefined {
const name = options.displayName || options.name || options._componentTag;
if (name)
return name;
const file = options.__file; // injected by vue-loader
if (file)
return classify(basename(file, '.vue'));
} | // @see https://github.com/vuejs/devtools/blob/e7132f3392b975e39e1d9a23cf30456c270099c2/packages/shared-utils/src/util.ts#L302 | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/injected/vueSelectorEngine.ts#L170-L177 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | getInstanceName | function getInstanceName(instance: VueVNode): string {
const name = getComponentName(instance.$options || instance.fnOptions || {});
if (name)
return name;
return instance.$root === instance ? 'Root' : 'Anonymous Component';
} | // @see https://github.com/vuejs/devtools/blob/e7132f3392b975e39e1d9a23cf30456c270099c2/packages/app-backend-vue2/src/components/util.ts#L10 | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/injected/vueSelectorEngine.ts#L180-L185 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | getInternalInstanceChildren | function getInternalInstanceChildren(instance: VueVNode): VueVNode[] {
if (instance.$children)
return instance.$children;
if (Array.isArray(instance.subTree.children))
return instance.subTree.children.filter((vnode: any) => !!vnode.component).map((vnode: any) => vnode.component);
return [];
} | // @see https://github.com/vuejs/devtools/blob/14085e25313bcf8ffcb55f9092a40bc0fe3ac11c/packages/app-backend-vue2/src/components/tree.ts#L103 | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/injected/vueSelectorEngine.ts#L188-L194 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | messageToData | function messageToData(message: WebSocketMessage, cb: (data: WSData) => any) {
if (message instanceof globalThis.Blob)
return message.arrayBuffer().then(buffer => cb(bufferToData(new Uint8Array(buffer))));
if (typeof message === 'string')
return cb({ data: message, isBase64: false });
if (ArrayBuffer.isView(message))
return cb(bufferToData(new Uint8Array(message.buffer, message.byteOffset, message.byteLength)));
return cb(bufferToData(new Uint8Array(message)));
} | // Note: this function tries to be synchronous when it can to preserve the ability to send | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/injected/webSocketMock.ts#L71-L79 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | WebSocketMock.binaryType | get binaryType() {
return this._binaryType;
} | // --- native WebSocket implementation --- | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/injected/webSocketMock.ts#L159-L161 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | WebSocketMock._apiEnsureOpened | _apiEnsureOpened() {
// This is called at the end of the route handler. If we did not connect to the server,
// assume that websocket will be fully mocked. In this case, pretend that server
// connection is established right away.
if (!this._ws)
this._ensureOpened();
} | // --- methods called from the routing API --- | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/injected/webSocketMock.ts#L243-L249 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | WebSocketMock._apiPassThrough | _apiPassThrough() {
this._passthrough = true;
this._apiConnect();
} | // as if WebSocketMock was not engaged. | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/injected/webSocketMock.ts#L302-L305 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | WebSocketMock._ensureOpened | _ensureOpened() {
if (this.readyState !== WebSocketMock.CONNECTING)
return;
this.extensions = this._ws?.extensions || '';
if (this._ws)
this.protocol = this._ws.protocol;
else if (Array.isArray(this._protocols))
this.protocol = this._protocols[0] || '';
else
this.protocol = this._protocols || '';
this.readyState = WebSocketMock.OPEN;
this.dispatchEvent(new Event('open', { cancelable: true }));
} | // --- internals --- | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/injected/webSocketMock.ts#L331-L343 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | downloadBrowserWithProgressBarOutOfProcess | function downloadBrowserWithProgressBarOutOfProcess(title: string, browserDirectory: string, url: string, zipPath: string, executablePath: string | undefined, connectionTimeout: number): Promise<{ error: Error | null }> {
const cp = childProcess.fork(path.join(__dirname, 'oopDownloadBrowserMain.js'));
const promise = new ManualPromise<{ error: Error | null }>();
const progress = getDownloadProgress();
cp.on('message', (message: any) => {
if (message?.method === 'log')
debugLogger.log('install', message.params.message);
if (message?.method === 'progress')
progress(message.params.done, message.params.total);
});
cp.on('exit', code => {
if (code !== 0) {
promise.resolve({ error: new Error(`Download failure, code=${code}`) });
return;
}
if (!fs.existsSync(browserDirectoryToMarkerFilePath(browserDirectory)))
promise.resolve({ error: new Error(`Download failure, ${browserDirectoryToMarkerFilePath(browserDirectory)} does not exist`) });
else
promise.resolve({ error: null });
});
cp.on('error', error => {
promise.resolve({ error });
});
debugLogger.log('install', `running download:`);
debugLogger.log('install', `-- from url: ${url}`);
debugLogger.log('install', `-- to location: ${zipPath}`);
const downloadParams: DownloadParams = {
title,
browserDirectory,
url,
zipPath,
executablePath,
connectionTimeout,
userAgent: getUserAgent(),
};
cp.send({ method: 'download', params: downloadParams });
return promise;
} | /**
* Node.js has a bug where the process can exit with 0 code even though there was an uncaught exception.
* Thats why we execute it in a separate process and check manually if the destination file exists.
* https://github.com/microsoft/playwright/issues/17394
*/ | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/registry/browserFetcher.ts#L75-L113 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | Streamer._updateLinkStyleSheetTextIfNeeded | private _updateLinkStyleSheetTextIfNeeded(sheet: CSSStyleSheet, snapshotNumber: number): string | number | undefined {
const data = ensureCachedData(sheet);
if (this._staleStyleSheets.has(sheet)) {
this._staleStyleSheets.delete(sheet);
try {
data.cssText = this._getSheetText(sheet);
data.cssRef = snapshotNumber;
return data.cssText;
} catch (e) {
// Sometimes we cannot access cross-origin stylesheets.
}
}
return data.cssRef === undefined ? undefined : snapshotNumber - data.cssRef;
} | // Returns either content, ref, or no override. | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/trace/recorder/snapshotterInjected.ts#L219-L232 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | WKPage._initializeSession | async _initializeSession(session: WKSession, provisional: boolean, resourceTreeHandler: (r: Protocol.Page.getResourceTreeReturnValue) => void) {
await this._initializeSessionMayThrow(session, resourceTreeHandler).catch(e => {
// Provisional session can be disposed at any time, for example due to new navigation initiating
// a new provisional page.
if (provisional && session.isDisposed())
return;
// Swallow initialization errors due to newer target swap in,
// since we will reinitialize again.
if (this._session === session)
throw e;
});
} | // may be different from the current session and may be destroyed without becoming current. | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/webkit/wkPage.ts#L151-L162 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | parseRemoteAddress | function parseRemoteAddress(value?: string) {
if (!value)
return;
try {
const colon = value.lastIndexOf(':');
const dot = value.lastIndexOf('.');
if (dot < 0) { // IPv6ish:port
return {
ipAddress: `[${value.slice(0, colon)}]`,
port: +value.slice(colon + 1)
};
}
if (colon > dot) { // IPv4:port
const [address, port] = value.split(':');
return {
ipAddress: address,
port: +port,
};
} else { // IPv6ish.port
const [address, port] = value.split('.');
return {
ipAddress: `[${address}]`,
port: +port,
};
}
} catch (_) {}
} | /**
* WebKit Remote Addresses look like:
*
* macOS:
* ::1.8911
* 2606:2800:220:1:248:1893:25c8:1946.443
* 127.0.0.1:8000
*
* ubuntu:
* ::1:8907
* 127.0.0.1:8000
*
* NB: They look IPv4 and IPv6's with ports but use an alternative notation.
*/ | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/webkit/wkPage.ts#L1213-L1241 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | isLoadedSecurely | function isLoadedSecurely(url: string, timing: network.ResourceTiming) {
try {
const u = new URL(url);
if (u.protocol !== 'https:' && u.protocol !== 'wss:' && u.protocol !== 'sftp:')
return false;
if (timing.secureConnectionStart === -1 && timing.connectStart !== -1)
return false;
return true;
} catch (_) {}
} | /**
* Adapted from Source/WebInspectorUI/UserInterface/Models/Resource.js in
* WebKit codebase.
*/ | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/server/webkit/wkPage.ts#L1248-L1257 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | encodeBase128 | function encodeBase128(value: number): Buffer {
const bytes = [];
do {
let byte = value & 0x7f;
value >>>= 7;
if (bytes.length > 0)
byte |= 0x80;
bytes.push(byte);
} while (value > 0);
return Buffer.from(bytes.reverse());
} | // Variable-length quantity encoding aka. base-128 encoding | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/utils/crypto.ts#L31-L41 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | SerializedFS._appendOperation | private _appendOperation(op: SerializedFSOperation): void {
const last = this._operations[this._operations.length - 1];
if (last?.op === 'appendFile' && op.op === 'appendFile' && last.file === op.file) {
// Merge pending appendFile operations for performance.
last.content += op.content;
return;
}
this._operations.push(op);
if (this._operationsDone.isDone())
this._performOperations();
} | // This method serializes all writes to the trace. | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/utils/fileUtils.ts#L136-L147 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | killProcess | function killProcess() {
gracefullyCloseSet.delete(gracefullyClose);
killSet.delete(killProcessAndCleanup);
removeProcessHandlersIfNeeded();
options.log(`[pid=${spawnedProcess.pid}] <kill>`);
if (spawnedProcess.pid && !spawnedProcess.killed && !processClosed) {
options.log(`[pid=${spawnedProcess.pid}] <will force kill>`);
// Force kill the browser.
try {
if (process.platform === 'win32') {
const taskkillProcess = childProcess.spawnSync(`taskkill /pid ${spawnedProcess.pid} /T /F`, { shell: true });
const [stdout, stderr] = [taskkillProcess.stdout.toString(), taskkillProcess.stderr.toString()];
if (stdout)
options.log(`[pid=${spawnedProcess.pid}] taskkill stdout: ${stdout}`);
if (stderr)
options.log(`[pid=${spawnedProcess.pid}] taskkill stderr: ${stderr}`);
} else {
process.kill(-spawnedProcess.pid, 'SIGKILL');
}
} catch (e) {
options.log(`[pid=${spawnedProcess.pid}] exception while trying to kill process: ${e}`);
// the process might have already stopped
}
} else {
options.log(`[pid=${spawnedProcess.pid}] <skipped force kill spawnedProcess.killed=${spawnedProcess.killed} processClosed=${processClosed}>`);
}
} | // This method has to be sync to be used in the 'exit' event handler. | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright-core/src/utils/processLauncher.ts#L224-L250 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | Anything.toAsymmetricMatcher | override toAsymmetricMatcher() {
return 'Anything';
} | // No getExpectedType method, because it matches either null or undefined. | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright/bundles/expect/third_party/asymmetricMatchers.ts#L166-L168 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | extractExpectedAssertionsErrors | const extractExpectedAssertionsErrors: Expect['extractExpectedAssertionsErrors'] =
() => {
const result: ExpectedAssertionsErrors = [];
const {
assertionCalls,
expectedAssertionsNumber,
expectedAssertionsNumberError,
isExpectingAssertions,
isExpectingAssertionsError,
} = getState();
resetAssertionsLocalState();
if (
typeof expectedAssertionsNumber === 'number' &&
assertionCalls !== expectedAssertionsNumber
) {
const numOfAssertionsExpected = EXPECTED_COLOR(
pluralize('assertion', expectedAssertionsNumber),
);
expectedAssertionsNumberError!.message =
`${matcherHint('.assertions', '', expectedAssertionsNumber.toString(), {
isDirectExpectCall: true,
})}\n\n` +
`Expected ${numOfAssertionsExpected} to be called but received ${RECEIVED_COLOR(
pluralize('assertion call', assertionCalls || 0),
)}.`;
result.push({
actual: assertionCalls.toString(),
error: expectedAssertionsNumberError!,
expected: expectedAssertionsNumber.toString(),
});
}
if (isExpectingAssertions && assertionCalls === 0) {
const expected = EXPECTED_COLOR('at least one assertion');
const received = RECEIVED_COLOR('received none');
isExpectingAssertionsError!.message = `${matcherHint(
'.hasAssertions',
'',
'',
{ isDirectExpectCall: true },
)}\n\nExpected ${expected} to be called but ${received}.`;
result.push({
actual: 'none',
error: isExpectingAssertionsError!,
expected: 'at least one',
});
}
return result;
}; | // Create and format all errors related to the mismatched number of `expect` | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright/bundles/expect/third_party/extractExpectedAssertionsErrors.ts#L29-L83 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
playwright-crx | github_2023 | ruifigueira | typescript | isExpand | const isExpand = (expand?: boolean): boolean => expand !== false; | // The optional property of matcher context is true if undefined. | https://github.com/ruifigueira/playwright-crx/blob/a84dce9e19e4c064bd53b4d419e9756f06976dbf/playwright/packages/playwright/bundles/expect/third_party/matchers.ts#L60-L60 | a84dce9e19e4c064bd53b4d419e9756f06976dbf |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.