repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
design-studio
github_2023
Tiledesk
typescript
UserTypingComponent.ngOnInit
ngOnInit() { this.elementRef.nativeElement.style.setProperty('--themeColor', this.themeColor); }
/** */
https://github.com/Tiledesk/design-studio/blob/297d30da01d98a1299e7197eb88cff5b2390a386/src/chat21-core/utils/user-typing/user-typing.component.ts#L23-L25
297d30da01d98a1299e7197eb88cff5b2390a386
design-studio
github_2023
Tiledesk
typescript
UserTypingComponent.ngOnDestroy
ngOnDestroy() { }
/** */
https://github.com/Tiledesk/design-studio/blob/297d30da01d98a1299e7197eb88cff5b2390a386/src/chat21-core/utils/user-typing/user-typing.component.ts#L28-L29
297d30da01d98a1299e7197eb88cff5b2390a386
keepalive-for-react
github_2023
irychen
typescript
onScroll
const onScroll = (e: Event) => { const target = e.target as HTMLDivElement; if (!target) return; scrollHistoryMap.current.set(activeKey, target?.scrollTop || 0); };
// 300 milliseconds to wait for the animation transition ending
https://github.com/irychen/keepalive-for-react/blob/9dba67cc89d415f24a68e45d8f26b096b0df7534/examples/react-router-dom-simple-starter/src/layout/index.tsx#L63-L67
9dba67cc89d415f24a68e45d8f26b096b0df7534
keepalive-for-react
github_2023
irychen
typescript
safeStartTransition
const safeStartTransition = (cb: () => void) => { isFn(reactStartTransition) ? reactStartTransition(cb) : cb(); };
/** * compatible with react version < 18 startTransition */
https://github.com/irychen/keepalive-for-react/blob/9dba67cc89d415f24a68e45d8f26b096b0df7534/packages/core/src/compat/safeStartTransition.ts#L7-L9
9dba67cc89d415f24a68e45d8f26b096b0df7534
waltid-identity
github_2023
walt-id
typescript
fetchVctName
async function fetchVctName(vct: string): Promise<String> { try { const response = await fetch(`/wallet-api/wallet/${currentWallet.value}/exchange/resolveVctUrl?vct=${vct}`); const data = await response.json(); return data.name || null; } catch (error) { console.error('Error fetching VCT name:', error); return null; } }
// Function to resolve VCT URL and fetch the name parameter
https://github.com/walt-id/waltid-identity/blob/8332dc8a14f9983295fe5689a6e1261b745952ef/waltid-applications/waltid-web-wallet/libs/composables/credential.ts#L50-L59
8332dc8a14f9983295fe5689a6e1261b745952ef
waltid-identity
github_2023
walt-id
typescript
convertUrl
function convertUrl(url: string | null) { let result = url; if (url) { const regex = "^((ipfs|ipns)://)([1-9A-Za-z]{59}|[1-9A-Za-z]{46})(/[^\\?]*)*(\\?filename=[^\\?]+)?$"; result = buildUrlFromMatches(url.match(regex)); } return isNotNullOrEmpty(result) ? result : url; }
/** * Converts an ipfs gateway url to an http gateway url * @param url - the url to be converted * @returns - the http gateway url */
https://github.com/walt-id/waltid-identity/blob/8332dc8a14f9983295fe5689a6e1261b745952ef/waltid-applications/waltid-web-wallet/libs/composables/useNftMedia.ts#L72-L79
8332dc8a14f9983295fe5689a6e1261b745952ef
waltid-identity
github_2023
walt-id
typescript
buildUrlFromMatches
function buildUrlFromMatches(matches: RegExpMatchArray | null) { let result; if (matches != null && matches.length > 3) { result = `https://ipfs.io/${matches[2]}/${matches[3]}`; if (matches[4] != null) { result += matches[4]; } if (matches[5] != null) { result += matches[5]; } } return result; }
/** * Builds an http gateway url, given the ipfs gateway url matches (identifier, meta) * @param matches - the ipfs url matches * @returns - the composed http gateway url */
https://github.com/walt-id/waltid-identity/blob/8332dc8a14f9983295fe5689a6e1261b745952ef/waltid-applications/waltid-web-wallet/libs/composables/useNftMedia.ts#L86-L98
8332dc8a14f9983295fe5689a6e1261b745952ef
waltid-identity
github_2023
walt-id
typescript
getXHRPromise
function getXHRPromise(url: string, method: string, header = "Content-Type") { return new Promise(function (resolve, reject) { let xhr = new XMLHttpRequest(); xhr.open(method, url, true); xhr.onload = function () { if (this.status >= 200 && this.status < 300) { let response = xhr.response; if (method.toUpperCase() == "HEAD") { response = xhr.getResponseHeader(header); } resolve(response); } else { reject({ status: this.status, statusText: xhr.statusText, }); } }; xhr.onerror = function () { reject({ status: this.status, statusText: xhr.statusText, }); }; xhr.send(); }); }
/** * Creates and returns the XHR request Promise for a given URL, * using a given method to extract a given header property * @param url - the file url to get the http for * @param method - the method type (e.g. HEAD) * @param header - the header property name * @returns - the Promise of the XHR request */
https://github.com/walt-id/waltid-identity/blob/8332dc8a14f9983295fe5689a6e1261b745952ef/waltid-applications/waltid-web-wallet/libs/composables/useNftMedia.ts#L108-L134
8332dc8a14f9983295fe5689a6e1261b745952ef
waltid-identity
github_2023
walt-id
typescript
mimeType
function mimeType(type: string | null): string | null { let result; if (type) { result = type.substring(0, type.indexOf("/")); } return result; }
/** * Extracts the mime-type from the http request mimetype header property * @param type - the http header mimetype value * @returns - the substring without any "/" character, or null if it couldn't be extracted */
https://github.com/walt-id/waltid-identity/blob/8332dc8a14f9983295fe5689a6e1261b745952ef/waltid-applications/waltid-web-wallet/libs/composables/useNftMedia.ts#L141-L147
8332dc8a14f9983295fe5689a6e1261b745952ef
material-rounded-theme
github_2023
Nerwyn
typescript
getTargets
function getTargets() { const targets: HTMLElement[] = [html as HTMLElement]; // Add-ons and HACS iframe const iframe = haMainShadowRoot ?.querySelector('iframe') ?.contentWindow?.document?.querySelector('body'); if (iframe) { targets.push(iframe); } return targets; }
/** Targets to apply or remove theme colors to/from */
https://github.com/Nerwyn/material-rounded-theme/blob/9e34d468dfa144dfe78e65103052115caed14af6/src/material-rounded-theme.ts#L91-L102
9e34d468dfa144dfe78e65103052115caed14af6
material-rounded-theme
github_2023
Nerwyn
typescript
getToken
function getToken(color: string) { return color.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase(); }
/** Get theme color token */
https://github.com/Nerwyn/material-rounded-theme/blob/9e34d468dfa144dfe78e65103052115caed14af6/src/material-rounded-theme.ts#L105-L107
9e34d468dfa144dfe78e65103052115caed14af6
material-rounded-theme
github_2023
Nerwyn
typescript
unsetTheme
function unsetTheme() { const targets = getTargets(); for (const target of targets) { for (const color of colors) { const token = getToken(color); target?.style.removeProperty(`--md-sys-color-${token}-light`); target?.style.removeProperty(`--md-sys-color-${token}-dark`); } } console.info( '%c Material design system colors removed. ', 'color: #ffffff; background: #4c5c92; font-weight: bold; border-radius: 32px;', ); }
/** Remove theme colors */
https://github.com/Nerwyn/material-rounded-theme/blob/9e34d468dfa144dfe78e65103052115caed14af6/src/material-rounded-theme.ts#L110-L123
9e34d468dfa144dfe78e65103052115caed14af6
material-rounded-theme
github_2023
Nerwyn
typescript
setTheme
function setTheme() { { try { const themeName = ha.hass?.themes?.theme ?? ''; if ( themeName.includes('Material Rounded') || themeName.includes('Material You') ) { let baseColor: string | undefined; // User specific base color if (userName) { baseColor = ha.hass.states[userNameSensorName]?.state; } if (!baseColor && userId) { baseColor = ha.hass.states[userIdSensorName]?.state; } // General base color if (!baseColor) { baseColor = ha.hass.states[sensorName]?.state; } // Only update if base color is provided if (baseColor) { const targets = getTargets(); for (const mode of ['light', 'dark']) { const schemeTonalSpot = new SchemeTonalSpot( Hct.fromInt(argbFromHex(baseColor)), mode == 'dark', 0, ); for (const color of colors) { const hex = hexFromArgb( ( MaterialDynamicColors[ color ] as DynamicColor ).getArgb(schemeTonalSpot), ); const token = getToken(color); for (const target of targets) { target.style.setProperty( `--md-sys-color-${token}-${mode}`, hex, ); } } } // This explicit background color breaks color theme on some pages html?.style.removeProperty('background-color'); const primary = html.style.getPropertyValue( '--md-sys-color-primary-light', ); const onPrimary = html.style.getPropertyValue( '--md-sys-color-on-primary-light', ); console.info( `%c Material design system colors updated using user defined base color ${baseColor}. `, `color: ${onPrimary}; background: ${primary}; font-weight: bold; border-radius: 32px;`, ); } else { unsetTheme(); } } } catch (e) { console.error(e); unsetTheme(); } // Update companion app app and navigation bar colors const msg = { type: 'theme-update' }; if (window.externalApp) { window.externalApp.externalBus(JSON.stringify(msg)); } else if (window.webkit) { window.webkit.messageHandlers.externalBus.postMessage(msg); } } }
/** * Generate and set theme colors based on user defined sensors * Unsets theme if no sensor found or on error */
https://github.com/Nerwyn/material-rounded-theme/blob/9e34d468dfa144dfe78e65103052115caed14af6/src/material-rounded-theme.ts#L129-L211
9e34d468dfa144dfe78e65103052115caed14af6
jotai-effect
github_2023
jotaijs
typescript
getNextPrice
function getNextPrice(unitPrice: number, discount: number) { return unitPrice * (1 - discount / 100) }
// https://github.com/pmndrs/jotai/discussions/2876
https://github.com/jotaijs/jotai-effect/blob/52ff1c1816d9555f707b5de968dcbd44a4da6e61/tests/withAtomEffect.test.ts#L236-L238
52ff1c1816d9555f707b5de968dcbd44a4da6e61
inshellisense
github_2023
microsoft
typescript
ISTerm.on
on(_event: unknown, _listener: unknown): void { throw new Error("Method not implemented as deprecated in node-pty."); }
// eslint-disable-next-line @typescript-eslint/no-unused-vars
https://github.com/microsoft/inshellisense/blob/aca796a29cf0c379f3f87ec98fe56c150b169b9e/src/isterm/pty.ts#L97-L99
aca796a29cf0c379f3f87ec98fe56c150b169b9e
inshellisense
github_2023
microsoft
typescript
unescapeSpaceTokens
const unescapeSpaceTokens = (cmdTokens: CommandToken[], shell: Shell): CommandToken[] => { const escapeChar = getShellWhitespaceEscapeChar(shell); return cmdTokens.map((cmdToken) => { const { token, isQuoted } = cmdToken; if (!isQuoted && token.includes(`${escapeChar} `)) { return { ...cmdToken, token: token.replaceAll(`${escapeChar} `, " ") }; } return cmdToken; }); };
// remove escapes around spaces
https://github.com/microsoft/inshellisense/blob/aca796a29cf0c379f3f87ec98fe56c150b169b9e/src/runtime/parser.ts#L32-L41
aca796a29cf0c379f3f87ec98fe56c150b169b9e
inshellisense
github_2023
microsoft
typescript
unwrapQuotedTokens
const unwrapQuotedTokens = (cmdTokens: CommandToken[], shell: Shell): CommandToken[] => { const escapeChar = getShellWhitespaceEscapeChar(shell); return cmdTokens.map((cmdToken) => { const { token, isQuoteContinued } = cmdToken; if (isQuoteContinued) { const quoteChar = token[0]; const unquotedToken = token.replaceAll(`${escapeChar}${quoteChar}`, "\u001B").replaceAll(quoteChar, "").replaceAll("\u001B", quoteChar); return { ...cmdToken, token: unquotedToken }; } return cmdToken; }); };
// need to unwrap tokens that are quoted with content after the quotes like `"hello"world`
https://github.com/microsoft/inshellisense/blob/aca796a29cf0c379f3f87ec98fe56c150b169b9e/src/runtime/parser.ts#L44-L55
aca796a29cf0c379f3f87ec98fe56c150b169b9e
inshellisense
github_2023
microsoft
typescript
lazyLoadSpec
const lazyLoadSpec = async (key: string): Promise<Fig.Spec | undefined> => { return (await import(`@withfig/autocomplete/build/${key}.js`)).default; };
// this load spec function should only be used for `loadSpec` on the fly as it is cacheless
https://github.com/microsoft/inshellisense/blob/aca796a29cf0c379f3f87ec98fe56c150b169b9e/src/runtime/runtime.ts#L62-L64
aca796a29cf0c379f3f87ec98fe56c150b169b9e
inshellisense
github_2023
microsoft
typescript
lazyLoadSpecLocation
const lazyLoadSpecLocation = async (location: Fig.SpecLocation): Promise<Fig.Spec | undefined> => { return; //TODO: implement spec location loading };
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- will be implemented in below TODO
https://github.com/microsoft/inshellisense/blob/aca796a29cf0c379f3f87ec98fe56c150b169b9e/src/runtime/runtime.ts#L67-L69
aca796a29cf0c379f3f87ec98fe56c150b169b9e
inshellisense
github_2023
microsoft
typescript
getSubcommand
const getSubcommand = (spec?: Fig.Spec): Fig.Subcommand | undefined => { if (spec == null) return; if (typeof spec === "function") { const potentialSubcommand = spec(); if (Object.prototype.hasOwnProperty.call(potentialSubcommand, "name")) { return potentialSubcommand as Fig.Subcommand; } return; } return spec; };
// TODO: handle subcommands that are versioned
https://github.com/microsoft/inshellisense/blob/aca796a29cf0c379f3f87ec98fe56c150b169b9e/src/runtime/runtime.ts#L134-L144
aca796a29cf0c379f3f87ec98fe56c150b169b9e
inshellisense
github_2023
microsoft
typescript
historyTemplate
const historyTemplate = (): Fig.TemplateSuggestion[] => { return []; };
// TODO: implement history template
https://github.com/microsoft/inshellisense/blob/aca796a29cf0c379f3f87ec98fe56c150b169b9e/src/runtime/template.ts#L27-L29
aca796a29cf0c379f3f87ec98fe56c150b169b9e
inshellisense
github_2023
microsoft
typescript
helpTemplate
const helpTemplate = (): Fig.TemplateSuggestion[] => { return []; };
// TODO: implement help template
https://github.com/microsoft/inshellisense/blob/aca796a29cf0c379f3f87ec98fe56c150b169b9e/src/runtime/template.ts#L32-L34
aca796a29cf0c379f3f87ec98fe56c150b169b9e
inshellisense
github_2023
microsoft
typescript
shouldEscapeArg
const shouldEscapeArg = (arg: string) => { const hasSpecialCharacter = bashSpecialCharacters.test(arg); const isSingleCharacter = arg.length === 1; return hasSpecialCharacter && !isSingleCharacter && !isQuoted(arg, `"`); };
// escape whitespace & special characters in an argument when not quoted
https://github.com/microsoft/inshellisense/blob/aca796a29cf0c379f3f87ec98fe56c150b169b9e/src/runtime/utils.ts#L27-L31
aca796a29cf0c379f3f87ec98fe56c150b169b9e
inshellisense
github_2023
microsoft
typescript
escapeArgs
const escapeArgs = (shell: string | undefined, args: string[]) => { // only escape args for git bash if (process.platform !== "win32" || shell == undefined) return args; return args.map((arg) => (shouldEscapeArg(arg) ? `"${arg.replaceAll('"', '\\"')}"` : arg)); };
/* based on libuv process.c used by nodejs, only quotes are escaped for shells. if using git bash need to escape whitespace & special characters in an argument */
https://github.com/microsoft/inshellisense/blob/aca796a29cf0c379f3f87ec98fe56c150b169b9e/src/runtime/utils.ts#L34-L38
aca796a29cf0c379f3f87ec98fe56c150b169b9e
inshellisense
github_2023
microsoft
typescript
overrideConsole
const overrideConsole = () => (console = logConsole);
// eslint-disable-next-line no-global-assign
https://github.com/microsoft/inshellisense/blob/aca796a29cf0c379f3f87ec98fe56c150b169b9e/src/utils/log.ts#L45-L45
aca796a29cf0c379f3f87ec98fe56c150b169b9e
ollama-gui
github_2023
HelgeSverre
typescript
nanoToHHMMSS
const nanoToHHMMSS = (nanoSeconds: bigint): string => { const milliseconds = Number(nanoSeconds / BigInt(1e6)) return format(new Date(milliseconds), 'HH:mm:ss') }
// noinspection JSUnusedLocalSymbols
https://github.com/HelgeSverre/ollama-gui/blob/0c4b06d434b23557150ce6bc6b63e7f8fdf00fd9/src/utils.ts#L4-L7
0c4b06d434b23557150ce6bc6b63e7f8fdf00fd9
ollama-gui
github_2023
HelgeSverre
typescript
getApiUrl
const getApiUrl = (path: string) => `${baseUrl.value || 'http://localhost:11434/api'}${path}`
// Define a method to get the full API URL for a given path
https://github.com/HelgeSverre/ollama-gui/blob/0c4b06d434b23557150ce6bc6b63e7f8fdf00fd9/src/services/api.ts#L114-L115
0c4b06d434b23557150ce6bc6b63e7f8fdf00fd9
ollama-gui
github_2023
HelgeSverre
typescript
createModel
const createModel = async ( request: CreateModelRequest, ): Promise<CreateModelResponse> => { const response = await fetch(getApiUrl('/create'), { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(request), }) return await response.json() }
// Create a model
https://github.com/HelgeSverre/ollama-gui/blob/0c4b06d434b23557150ce6bc6b63e7f8fdf00fd9/src/services/api.ts#L166-L178
0c4b06d434b23557150ce6bc6b63e7f8fdf00fd9
ollama-gui
github_2023
HelgeSverre
typescript
listLocalModels
const listLocalModels = async (): Promise<ListLocalModelsResponse> => { const response = await fetch(getApiUrl('/tags'), { method: 'GET', headers: { 'Content-Type': 'application/json', }, }) return await response.json() }
// List local models
https://github.com/HelgeSverre/ollama-gui/blob/0c4b06d434b23557150ce6bc6b63e7f8fdf00fd9/src/services/api.ts#L181-L189
0c4b06d434b23557150ce6bc6b63e7f8fdf00fd9
ollama-gui
github_2023
HelgeSverre
typescript
showModelInformation
const showModelInformation = async ( request: ShowModelInformationRequest, ): Promise<ShowModelInformationResponse> => { const response = await fetch(getApiUrl('/show'), { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(request), }) return await response.json() }
// Show model information
https://github.com/HelgeSverre/ollama-gui/blob/0c4b06d434b23557150ce6bc6b63e7f8fdf00fd9/src/services/api.ts#L192-L204
0c4b06d434b23557150ce6bc6b63e7f8fdf00fd9
ollama-gui
github_2023
HelgeSverre
typescript
copyModel
const copyModel = async (request: CopyModelRequest): Promise<CopyModelResponse> => { const response = await fetch(getApiUrl('/copy'), { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(request), }) return await response.json() }
// Copy a model
https://github.com/HelgeSverre/ollama-gui/blob/0c4b06d434b23557150ce6bc6b63e7f8fdf00fd9/src/services/api.ts#L207-L217
0c4b06d434b23557150ce6bc6b63e7f8fdf00fd9
ollama-gui
github_2023
HelgeSverre
typescript
deleteModel
const deleteModel = async ( request: DeleteModelRequest, ): Promise<DeleteModelResponse> => { const response = await fetch(getApiUrl('/delete'), { method: 'DELETE', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(request), }) return await response.json() }
// Delete a model
https://github.com/HelgeSverre/ollama-gui/blob/0c4b06d434b23557150ce6bc6b63e7f8fdf00fd9/src/services/api.ts#L220-L232
0c4b06d434b23557150ce6bc6b63e7f8fdf00fd9
ollama-gui
github_2023
HelgeSverre
typescript
pullModel
const pullModel = async (request: PullModelRequest): Promise<PullModelResponse> => { const response = await fetch(getApiUrl('/pull'), { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(request), }) return await response.json() }
// Pull a model
https://github.com/HelgeSverre/ollama-gui/blob/0c4b06d434b23557150ce6bc6b63e7f8fdf00fd9/src/services/api.ts#L235-L244
0c4b06d434b23557150ce6bc6b63e7f8fdf00fd9
ollama-gui
github_2023
HelgeSverre
typescript
pushModel
const pushModel = async (request: PushModelRequest): Promise<PushModelResponse> => { const response = await fetch(getApiUrl('/push'), { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(request), }) return await response.json() }
// Push a model
https://github.com/HelgeSverre/ollama-gui/blob/0c4b06d434b23557150ce6bc6b63e7f8fdf00fd9/src/services/api.ts#L247-L257
0c4b06d434b23557150ce6bc6b63e7f8fdf00fd9
ollama-gui
github_2023
HelgeSverre
typescript
generateEmbeddings
const generateEmbeddings = async ( request: GenerateEmbeddingsRequest, ): Promise<GenerateEmbeddingsResponse> => { const response = await fetch(getApiUrl('/embeddings'), { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(request), }) return await response.json() }
// Generate embeddings
https://github.com/HelgeSverre/ollama-gui/blob/0c4b06d434b23557150ce6bc6b63e7f8fdf00fd9/src/services/api.ts#L260-L272
0c4b06d434b23557150ce6bc6b63e7f8fdf00fd9
ollama-gui
github_2023
HelgeSverre
typescript
setActiveChat
const setActiveChat = (chat: Chat) => (activeChat.value = chat)
// Methods for state mutations
https://github.com/HelgeSverre/ollama-gui/blob/0c4b06d434b23557150ce6bc6b63e7f8fdf00fd9/src/services/chat.ts#L73-L73
0c4b06d434b23557150ce6bc6b63e7f8fdf00fd9
onedrive-cf-index-ng
github_2023
lyc8503
typescript
sanitiseQuery
function sanitiseQuery(query: string): string { const sanitisedQuery = query .replace(/'/g, "''") .replace('<', ' &lt; ') .replace('>', ' &gt; ') .replace('?', ' ') .replace('/', ' ') return encodeURIComponent(sanitisedQuery) }
/** * Sanitize the search query * * @param query User search query, which may contain special characters * @returns Sanitised query string, which: * - encodes the '<' and '>' characters, * - replaces '?' and '/' characters with ' ', * - replaces ''' with '''' * Reference: https://stackoverflow.com/questions/41491222/single-quote-escaping-in-microsoft-graph. */
https://github.com/lyc8503/onedrive-cf-index-ng/blob/d54d17a3d16b5f24a539f8563dee053464f7e054/src/pages/api/search.ts#L21-L29
d54d17a3d16b5f24a539f8563dee053464f7e054
onedrive-cf-index-ng
github_2023
lyc8503
typescript
getNextKey
function getNextKey(pageIndex: number, previousPageData: OdAPIResponse): (string | null)[] | null { // Reached the end of the collection if (previousPageData && !previousPageData.folder) return null // First page with no prevPageData if (pageIndex === 0) return [`/api?path=${path}`, hashedToken] // Add nextPage token to API endpoint return [`/api?path=${path}&next=${previousPageData.next}`, hashedToken] }
/** * Next page infinite loading for useSWR * @param pageIdx The index of this paging collection * @param prevPageData Previous page information * @param path Directory path * @returns API to the next page */
https://github.com/lyc8503/onedrive-cf-index-ng/blob/d54d17a3d16b5f24a539f8563dee053464f7e054/src/utils/fetchWithSWR.ts#L39-L48
d54d17a3d16b5f24a539f8563dee053464f7e054
onedrive-cf-index-ng
github_2023
lyc8503
typescript
isSafeChar
function isSafeChar(c: string) { if (c.charCodeAt(0) < 0x80) { // ASCII if (/^[a-zA-Z0-9\-._~]$/.test(c)) { // RFC3986 unreserved chars return true } else if (/^[*:@,!]$/.test(c)) { // Some extra pretty safe chars for URL path or query // Ref: https://stackoverflow.com/a/42287988/11691878 return true } } else { if (!/\s|\u180e/.test(c)) { // Non-whitespace char. \u180e is missed in \s. return true } } return false }
// Check if the character is safe (means no need of percent-encoding)
https://github.com/lyc8503/onedrive-cf-index-ng/blob/d54d17a3d16b5f24a539f8563dee053464f7e054/src/utils/getReadablePath.ts#L20-L38
d54d17a3d16b5f24a539f8563dee053464f7e054
onedrive-cf-index-ng
github_2023
lyc8503
typescript
encryptToken
function encryptToken(token: string): string { return sha256(token).toString() }
// Hash password token with SHA256
https://github.com/lyc8503/onedrive-cf-index-ng/blob/d54d17a3d16b5f24a539f8563dee053464f7e054/src/utils/protectedRouteHandler.ts#L5-L7
d54d17a3d16b5f24a539f8563dee053464f7e054
onedrive-cf-index-ng
github_2023
lyc8503
typescript
readValue
const readValue = (): T => { // Prevent build error "window is undefined" but keep keep working if (typeof window === 'undefined') { return initialValue } try { const item = window.localStorage.getItem(key) return item ? (JSON.parse(item) as T) : initialValue } catch (error) { console.warn(`Error reading localStorage key “${key}”:`, error) return initialValue } }
// Get from local storage then
https://github.com/lyc8503/onedrive-cf-index-ng/blob/d54d17a3d16b5f24a539f8563dee053464f7e054/src/utils/useLocalStorage.ts#L8-L21
d54d17a3d16b5f24a539f8563dee053464f7e054
onedrive-cf-index-ng
github_2023
lyc8503
typescript
setValue
const setValue: SetValue<T> = value => { // Prevent build error "window is undefined" but keeps working if (typeof window == 'undefined') { console.warn(`Tried setting localStorage key “${key}” even though environment is not a client`) } try { // Allow value to be a function so we have the same API as useState const newValue = value instanceof Function ? value(storedValue) : value // Save to local storage window.localStorage.setItem(key, JSON.stringify(newValue)) // Save state setStoredValue(newValue) // We dispatch a custom event so every useLocalStorage hook are notified window.dispatchEvent(new Event('local-storage')) } catch (error) { console.warn(`Error setting localStorage key “${key}”:`, error) } }
// Return a wrapped version of useState's setter function that ...
https://github.com/lyc8503/onedrive-cf-index-ng/blob/d54d17a3d16b5f24a539f8563dee053464f7e054/src/utils/useLocalStorage.ts#L29-L50
d54d17a3d16b5f24a539f8563dee053464f7e054
duckling
github_2023
l1xnan
typescript
onClick
const onClick = () => visibility.scrollToItem(visibility.getNextElement(), 'smooth', 'end');
// NOTE: Look here
https://github.com/l1xnan/duckling/blob/bb5df9ac0a0df11b98fa9593d8af389939244ee9/src/components/PageTabs.tsx#L418-L419
bb5df9ac0a0df11b98fa9593d8af389939244ee9
duckling
github_2023
l1xnan
typescript
handleDoubleClickNode
const handleDoubleClickNode = (item: ItemInstance<Node3Type>) => { const node = item.getItemData()?.data; if (!node) { console.warn('doubleClick data is null!'); return; } const { dbId, path } = node; const nodeContext = { dbId, tableId: path as string, }; const noDataTypes = ['path', 'database', 'root']; if (node && !noDataTypes.includes(node.type ?? '')) { const item: TableContextType = { ...nodeContext, id: node.id, dbId, displayName: node?.name as string, type: 'table', }; console.log('update tab:', item); updateTab!(item); } else { console.warn('doubleClick node is null!'); } };
// BUG: 闭包存在问题,只能获取上一次的外部变量值
https://github.com/l1xnan/duckling/blob/bb5df9ac0a0df11b98fa9593d8af389939244ee9/src/components/custom/TreeView3.tsx#L257-L287
bb5df9ac0a0df11b98fa9593d8af389939244ee9
duckling
github_2023
l1xnan
typescript
registerCompletion
function registerCompletion(monaco: Monaco, tableSchema: TableSchemaType[]) { monaco.languages.registerCompletionItemProvider('*', { provideCompletionItems: (model, position, _context, _cancelationToken) => { const word = model.getWordUntilPosition(position); const range = { startLineNumber: position.lineNumber, endLineNumber: position.lineNumber, startColumn: word.startColumn, endColumn: word.endColumn, }; const schemaTableNames = B.pipe( tableSchema, B.A.map((d) => d.table_name), B.A.uniq, ); const schemaTableNamesSet = new Set(schemaTableNames); const suggestions: monaco.languages.CompletionItem[] = []; const fullQueryText = model.getValue(); const tableNamesAndAliases = new Map( parseSqlAndFindTableNameAndAliases(fullQueryText).map( ({ table_name, alias }) => [alias, table_name], ), ); const thisLine = model.getValueInRange({ startLineNumber: position.lineNumber, startColumn: 1, endLineNumber: position.lineNumber, endColumn: position.column, }); const thisToken = thisLine.trim().split(' ').slice(-1)?.[0] || ''; const lastTokenBeforeSpace = /\s?(\w+)\s+\w+$/.exec(thisLine.trim())?.[1]; const lastTokenBeforeDot = /(\w+)\.\w*$/.exec(thisToken)?.[1]; console.log( tableNamesAndAliases, thisToken, lastTokenBeforeSpace, lastTokenBeforeDot, ); if ( lastTokenBeforeSpace && /from|join|update|into/.test(lastTokenBeforeSpace) ) { suggestions.push( ...schemaTableNames.map((table_name) => ({ label: table_name, kind: monaco.languages.CompletionItemKind.Field, insertText: table_name, range, })), ); } if (lastTokenBeforeDot) { let table_name = null as string | null; if (schemaTableNamesSet.has(lastTokenBeforeDot)) { table_name = lastTokenBeforeDot; } else if (tableNamesAndAliases.get(lastTokenBeforeDot)) { table_name = tableNamesAndAliases.get(lastTokenBeforeDot) as string; } if (table_name) { suggestions.push( ...tableSchema .filter((d) => d.table_name === table_name) .map(({ column_name }) => ({ label: column_name, kind: monaco.languages.CompletionItemKind.Field, insertText: column_name, range, })), ); } } return { suggestions: B.pipe( suggestions, B.A.uniqBy((s) => s.insertText), ) as monaco.languages.CompletionItem[], }; }, }); monaco.languages.registerDocumentFormattingEditProvider('sql', { async provideDocumentFormattingEdits(model, _options) { const formatted = await formatSQL(model.getValue()); return [ { range: model.getFullModelRange(), text: formatted, }, ]; }, }); // define a range formatting provider // select some codes and right click those codes // you contextmenu will have an "Format Selection" action monaco.languages.registerDocumentRangeFormattingEditProvider('sql', { async provideDocumentRangeFormattingEdits(model, range, _options) { const formatted = format(model.getValueInRange(range), { tabWidth: 2, }); return [ { range: range, text: formatted, }, ]; }, }); }
// https://codesandbox.io/p/sandbox/monaco-sql-sfot6x
https://github.com/l1xnan/duckling/blob/bb5df9ac0a0df11b98fa9593d8af389939244ee9/src/pages/editor/MonacoEditor.tsx#L63-L181
bb5df9ac0a0df11b98fa9593d8af389939244ee9
react-playground
github_2023
fewismuch
typescript
App
function App() { const handleFilesHash = (hash: string) => { window.location.hash = hash } return <PlaygroundSandbox onFilesChange={handleFilesHash} /> }
// import { Playground as PlaygroundSandbox } from '@/Playground'
https://github.com/fewismuch/react-playground/blob/b8109930d34e6246db5f7c85a119b6fd9e9bbc8b/src/App.tsx#L4-L10
b8109930d34e6246db5f7c85a119b6fd9e9bbc8b
react-playground
github_2023
fewismuch
typescript
doOpenEditor
const doOpenEditor = (editor: any, input: any) => { const selection = input.options ? input.options.selection : null if (selection) { if (typeof selection.endLineNumber === 'number' && typeof selection.endColumn === 'number') { editor.setSelection(selection) editor.revealRangeInCenter(selection, 1 /* Immediate */) } else { const pos = { lineNumber: selection.startLineNumber, column: selection.startColumn, } editor.setPosition(pos) editor.revealPositionInCenter(pos, 1 /* Immediate */) } } console.log('触发鼠标+command点击', input.resource, selection) }
// 点击变量跳转
https://github.com/fewismuch/react-playground/blob/b8109930d34e6246db5f7c85a119b6fd9e9bbc8b/src/Playground/components/EditorContainer/Editor/useEditor.ts#L8-L24
b8109930d34e6246db5f7c85a119b6fd9e9bbc8b
react-playground
github_2023
fewismuch
typescript
loadJsxSyntaxHighlight
const loadJsxSyntaxHighlight = (editor: any, monaco: Monaco) => { const monacoJsxSyntaxHighlight = new MonacoJsxSyntaxHighlight(getWorker(), monaco) const { highlighter, dispose } = monacoJsxSyntaxHighlight.highlighterBuilder({ editor, }) editor.onDidChangeModelContent(() => { highlighter() }) highlighter() return { highlighter, dispose } }
// 加载jsx高亮
https://github.com/fewismuch/react-playground/blob/b8109930d34e6246db5f7c85a119b6fd9e9bbc8b/src/Playground/components/EditorContainer/Editor/useEditor.ts#L27-L40
b8109930d34e6246db5f7c85a119b6fd9e9bbc8b
react-playground
github_2023
fewismuch
typescript
autoLoadExtraLib
const autoLoadExtraLib = async (editor: any, monaco: any, defaultValue: string, onWatch: any) => { // 自动加载第三方包的类型定义文件 const typeHelper = await createATA() // 开始监听下载进度 onWatch(typeHelper) editor.onDidChangeModelContent(() => { typeHelper.acquireType(editor.getValue()) }) const addLibraryToRuntime = (code: string, path: string) => { monaco.languages.typescript.typescriptDefaults.addExtraLib(code, `file://${path}`) } typeHelper.addListener('receivedFile', addLibraryToRuntime) typeHelper.acquireType(defaultValue) return typeHelper }
/** * 自动加载types文件 * @param editor 编辑器 * @param monaco monaco实例 * @param defaultValue 默认代码(初始化后现加载默认代码中import包的types文件) * @param onWatch 开始监听下载进度 */
https://github.com/fewismuch/react-playground/blob/b8109930d34e6246db5f7c85a119b6fd9e9bbc8b/src/Playground/components/EditorContainer/Editor/useEditor.ts#L49-L67
b8109930d34e6246db5f7c85a119b6fd9e9bbc8b
notepher-bot
github_2023
deptyped
typescript
getGroupChatCommands
function getGroupChatCommands(localeCode: string): BotCommand[] { return []; }
// eslint-disable-next-line @typescript-eslint/no-unused-vars
https://github.com/deptyped/notepher-bot/blob/35f850c7d44127145175596e457e4776e334a6bd/apps/bot/src/bot/handlers/commands/setcommands.ts#L33-L35
35f850c7d44127145175596e457e4776e334a6bd
core
github_2023
zen-fs
typescript
mount
async function mount(path: string, mount: FileSystem): Promise<void> { if (path == '/') { fs.mount(path, mount); return; } const stats = await fs.promises.stat(path).catch(() => null); if (!stats) { await fs.promises.mkdir(path, { recursive: true }); } else if (!stats.isDirectory()) { throw ErrnoError.With('ENOTDIR', path, 'configure'); } fs.mount(path, mount); }
/** * Like `fs.mount`, but it also creates missing directories. * @privateRemarks * This is implemented as a separate function to avoid a circular dependency between vfs/shared.ts and other vfs layer files. * @internal */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/config.ts#L162-L175
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
_bindFunctions
function _bindFunctions<T extends Record<string, unknown>>(fns: T, thisValue: any): T { return Object.fromEntries(Object.entries(fns).map(([k, v]) => [k, typeof v == 'function' ? v.bind(thisValue) : v])) as T; }
/** * Binds a this value for all of the functions in an object (not recursive) * @internal */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/context.ts#L14-L16
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
name
const name = (type: OptionType) => (typeof type == 'function' ? type.name : type);
// The expected type (as a string)
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/backend.ts#L150-L150
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
parseError
function parseError(path?: string, fs?: FileSystem): (error: requests.Issue) => never { return (error: requests.Issue) => { if (!('tag' in error)) throw err(new ErrnoError(Errno.EIO, error.stack, path), { fs }); switch (error.tag) { case 'fetch': throw err(new ErrnoError(Errno.EREMOTEIO, error.message, path), { fs }); case 'status': throw err( new ErrnoError( error.response.status > 500 ? Errno.EREMOTEIO : Errno.EIO, 'Response status code is ' + error.response.status, path ), { fs } ); case 'size': throw err(new ErrnoError(Errno.EBADE, error.message, path), { fs }); case 'buffer': throw err(new ErrnoError(Errno.EIO, 'Failed to decode buffer', path), { fs }); } }; }
/** Parse and throw */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/fetch.ts#L13-L35
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
OverlayFS._initialize
public async _initialize(): Promise<void> { if (this._isInitialized) { return; } // Read deletion log, process into metadata. try { const file = await this.writable.openFile(deletionLogPath, parseFlag('r')); const { size } = await file.stat(); const { buffer } = await file.read(new Uint8Array(size)); this._deleteLog = decodeUTF8(buffer); } catch (error: any) { if (error.errno !== Errno.ENOENT) throw err(error); info('Overlay does not have a deletion log'); } this._isInitialized = true; this._reparseDeletionLog(); }
/** * Called once to load up metadata stored on the writable file system. * @internal */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/overlay.ts#L107-L124
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
OverlayFS.createParentDirectoriesSync
private createParentDirectoriesSync(path: string): void { let parent = dirname(path); const toCreate: string[] = []; const silence = canary(ErrnoError.With('EDEADLK', path)); while (!this.writable.existsSync(parent)) { toCreate.push(parent); parent = dirname(parent); } silence(); for (const path of toCreate.reverse()) { const { uid, gid, mode } = this.statSync(path); this.writable.mkdirSync(path, mode, { uid, gid }); } }
/** * Create the needed parent directories on the writable storage should they not exist. * Use modes from the read-only storage. */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/overlay.ts#L437-L452
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
OverlayFS.createParentDirectories
private async createParentDirectories(path: string): Promise<void> { let parent = dirname(path); const toCreate: string[] = []; const silence = canary(ErrnoError.With('EDEADLK', path)); while (!(await this.writable.exists(parent))) { toCreate.push(parent); parent = dirname(parent); } silence(); for (const path of toCreate.reverse()) { const { uid, gid, mode } = await this.stat(path); await this.writable.mkdir(path, mode, { uid, gid }); } }
/** * Create the needed parent directories on the writable storage should they not exist. * Use modes from the read-only storage. */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/overlay.ts#L458-L473
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
OverlayFS.copyForWriteSync
private copyForWriteSync(path: string): void { if (!this.existsSync(path)) { throw ErrnoError.With('ENOENT', path, '[copyForWrite]'); } if (!this.writable.existsSync(dirname(path))) { this.createParentDirectoriesSync(path); } if (!this.writable.existsSync(path)) { this.copyToWritableSync(path); } }
/** * Helper function: * - Ensures p is on writable before proceeding. Throws an error if it doesn't exist. * - Calls f to perform operation on writable. */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/overlay.ts#L480-L490
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
OverlayFS.copyToWritableSync
private copyToWritableSync(path: string): void { const stats = this.statSync(path); stats.mode |= 0o222; if (stats.isDirectory()) { this.writable.mkdirSync(path, stats.mode, stats); for (const k of this.readable.readdirSync(path)) { this.copyToWritableSync(join(path, k)); } return; } const data = new Uint8Array(stats.size); using readable = this.readable.openFileSync(path, 'r'); readable.readSync(data); using writable = this.writable.createFileSync(path, 'w', stats.mode, stats); writable.writeSync(data); }
/** * Copy from readable to writable storage. * PRECONDITION: File does not exist on writable storage. */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/overlay.ts#L510-L526
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
PassthroughFS.rename
public async rename(oldPath: string, newPath: string): Promise<void> { try { await this.nodeFS.promises.rename(this.path(oldPath), this.path(newPath)); } catch (err) { this.error(err, oldPath); } }
/** * Rename a file or directory. */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/passthrough.ts#L165-L171
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
PassthroughFS.renameSync
public renameSync(oldPath: string, newPath: string): void { try { this.nodeFS.renameSync(this.path(oldPath), this.path(newPath)); } catch (err) { this.error(err, oldPath); } }
/** * Rename a file or directory synchronously. */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/passthrough.ts#L176-L182
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
PassthroughFS.stat
public async stat(path: string): Promise<Stats> { try { return new Stats(await this.nodeFS.promises.stat(this.path(path))); } catch (err) { this.error(err, path); } }
/** * Get file statistics. */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/passthrough.ts#L187-L193
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
PassthroughFS.statSync
public statSync(path: string): Stats { try { return new Stats(this.nodeFS.statSync(this.path(path))); } catch (err) { this.error(err, path); } }
/** * Get file statistics synchronously. */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/passthrough.ts#L198-L204
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
PassthroughFS.openFile
public async openFile(path: string, flag: string): Promise<File> { try { const { fd } = await this.nodeFS.promises.open(this.path(path), flag); return new PassthroughFile(this, path, fd); } catch (err) { this.error(err, path); } }
/** * Open a file. */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/passthrough.ts#L209-L216
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
PassthroughFS.openFileSync
public openFileSync(path: string, flag: string): File { try { const fd = this.nodeFS.openSync(this.path(path), flag); return new PassthroughFile(this, path, fd); } catch (err) { this.error(err, path); } }
/** * Open a file synchronously. */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/passthrough.ts#L221-L228
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
PassthroughFS.unlink
public async unlink(path: string): Promise<void> { try { await this.nodeFS.promises.unlink(this.path(path)); } catch (err) { this.error(err, path); } }
/** * Unlink (delete) a file. */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/passthrough.ts#L233-L239
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
PassthroughFS.unlinkSync
public unlinkSync(path: string): void { try { this.nodeFS.unlinkSync(this.path(path)); } catch (err) { this.error(err, path); } }
/** * Unlink (delete) a file synchronously. */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/passthrough.ts#L244-L250
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
PassthroughFS.mkdir
public async mkdir(path: string, mode: number): Promise<void> { try { await this.nodeFS.promises.mkdir(this.path(path), { mode }); } catch (err) { this.error(err, path); } }
/** * Create a directory. */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/passthrough.ts#L255-L261
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
PassthroughFS.mkdirSync
public mkdirSync(path: string, mode: number): void { try { this.nodeFS.mkdirSync(this.path(path), { mode }); } catch (err) { this.error(err, path); } }
/** * Create a directory synchronously. */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/passthrough.ts#L266-L272
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
PassthroughFS.readdir
public async readdir(path: string): Promise<string[]> { try { return await this.nodeFS.promises.readdir(this.path(path)); } catch (err) { this.error(err, path); } }
/** * Read the contents of a directory. */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/passthrough.ts#L277-L283
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
PassthroughFS.readdirSync
public readdirSync(path: string): string[] { try { return this.nodeFS.readdirSync(this.path(path)); } catch (err) { this.error(err, path); } }
/** * Read the contents of a directory synchronously. */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/passthrough.ts#L288-L294
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
PassthroughFS.createFile
public async createFile(path: string, flag: string, mode: number): Promise<File> { try { const { fd } = await this.nodeFS.promises.open(this.path(path), flag, mode); return new PassthroughFile(this, path, fd); } catch (err) { this.error(err, path); } }
/** * Create a file. */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/passthrough.ts#L299-L306
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
PassthroughFS.createFileSync
public createFileSync(path: string, flag: string, mode: number): File { try { const fd = this.nodeFS.openSync(this.path(path), flag, mode); return new PassthroughFile(this, path, fd); } catch (err) { this.error(err, path); } }
/** * Create a file synchronously. */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/passthrough.ts#L311-L318
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
PassthroughFS.rmdir
public async rmdir(path: string): Promise<void> { try { await this.nodeFS.promises.rmdir(this.path(path)); } catch (err) { this.error(err, path); } }
/** * Remove a directory. */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/passthrough.ts#L323-L329
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
PassthroughFS.rmdirSync
public rmdirSync(path: string): void { try { this.nodeFS.rmdirSync(this.path(path)); } catch (err) { this.error(err, path); } }
/** * Remove a directory synchronously. */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/passthrough.ts#L334-L340
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
PassthroughFS.sync
public async sync(path: string, data: Uint8Array, stats: Readonly<InodeLike>): Promise<void> { try { await using handle = await this.nodeFS.promises.open(this.path(path), 'w'); await handle.writeFile(data); await handle.chmod(stats.mode); await handle.chown(stats.uid, stats.gid); await handle.utimes(stats.atimeMs, stats.mtimeMs); } catch (err) { this.error(err, path); } }
/** * Synchronize data to the file system. */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/passthrough.ts#L345-L355
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
PassthroughFS.syncSync
public syncSync(path: string, data: Uint8Array, stats: Readonly<InodeLike>): void { try { const p = this.path(path); this.nodeFS.writeFileSync(p, data); this.nodeFS.chmodSync(p, stats.mode); this.nodeFS.chownSync(p, stats.uid, stats.gid); this.nodeFS.utimesSync(p, stats.atimeMs, stats.mtimeMs); } catch (err) { this.error(err, path); } }
/** * Synchronize data to the file system synchronously. */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/passthrough.ts#L360-L370
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
PassthroughFS.link
public async link(target: string, link: string): Promise<void> { try { await this.nodeFS.promises.link(this.path(target), this.path(link)); } catch (err) { this.error(err, target); } }
/** * Create a hard link. */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/passthrough.ts#L375-L381
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
PassthroughFS.linkSync
public linkSync(target: string, link: string): void { try { this.nodeFS.linkSync(this.path(target), this.path(link)); } catch (err) { this.error(err, target); } }
/** * Create a hard link synchronously. */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/passthrough.ts#L386-L392
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
PortFS.constructor
public constructor(public readonly options: RPC.Options) { super(0x706f7274, 'portfs'); this.port = options.port; RPC.attach<RPC.Response>(this.port, RPC.handleResponse); }
/** * Constructs a new PortFS instance that connects with the FS running on `options.port`. */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/port/fs.ts#L47-L51
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
StoreFS._path
_path(id: number): string | undefined { const [path] = this._paths.get(id) ?? []; return path; }
/** * Gets the first path associated with an inode */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/store/fs.ts#L40-L43
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
StoreFS._add
_add(ino: number, path: string) { if (!this._paths.has(ino)) this._paths.set(ino, new Set()); this._paths.get(ino)!.add(path); this._ids.set(path, ino); }
/** * Add a inode/path pair */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/store/fs.ts#L48-L52
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
StoreFS._remove
_remove(ino: number) { for (const path of this._paths.get(ino) ?? []) { this._ids.delete(path); } this._paths.delete(ino); }
/** * Remove a inode/path pair */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/store/fs.ts#L57-L62
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
StoreFS._move
_move(from: string, to: string) { const toMove = []; for (const [path, ino] of this._ids) { const rel = relative(from, path); if (rel.startsWith('..')) continue; let newKey = join(to, rel); if (newKey.endsWith('/')) newKey = newKey.slice(0, -1); toMove.push({ oldKey: path, newKey, ino }); } for (const { oldKey, newKey, ino } of toMove) { this._ids.delete(oldKey); this._ids.set(newKey, ino); const p = this._paths.get(ino); if (!p) { warn('Missing paths in table for ino ' + ino); continue; } p.delete(oldKey); p.add(newKey); } }
/** * Move paths in the tables */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/store/fs.ts#L67-L88
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
StoreFS.empty
public async empty(): Promise<void> { log_deprecated('StoreFS#empty'); // Root always exists. await this.checkRoot(); }
/** * Delete all contents stored in the file system. * @deprecated */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/store/fs.ts#L113-L117
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
StoreFS.emptySync
public emptySync(): void { log_deprecated('StoreFS#emptySync'); // Root always exists. this.checkRootSync(); }
/** * Delete all contents stored in the file system. * @deprecated */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/store/fs.ts#L123-L127
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
StoreFS.loadIndex
public async loadIndex(index: Index): Promise<void> { await using tx = this.transaction(); const dirs = index.directories(); for (const [path, inode] of index) { this._add(inode.ino, path); await tx.set(inode.ino, serialize(inode)); if (dirs.has(path)) await tx.set(inode.data, encodeDirListing(dirs.get(path)!)); } await tx.commit(); }
/** * Load an index into the StoreFS. * You *must* manually add non-directory files */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/store/fs.ts#L134-L146
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
StoreFS.loadIndexSync
public loadIndexSync(index: Index): void { using tx = this.transaction(); const dirs = index.directories(); for (const [path, inode] of index) { this._add(inode.ino, path); tx.setSync(inode.ino, serialize(inode)); if (dirs.has(path)) tx.setSync(inode.data, encodeDirListing(dirs.get(path)!)); } tx.commitSync(); }
/** * Load an index into the StoreFS. * You *must* manually add non-directory files */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/store/fs.ts#L152-L164
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
StoreFS.rename
public async rename(oldPath: string, newPath: string): Promise<void> { await using tx = this.transaction(); const _old = parse(oldPath), _new = parse(newPath), // Remove oldPath from parent's directory listing. oldDirNode = await this.findInode(tx, _old.dir, 'rename'), oldDirList = decodeDirListing((await tx.get(oldDirNode.data)) ?? _throw(ErrnoError.With('ENODATA', _old.dir, 'rename'))); if (!oldDirList[_old.base]) throw ErrnoError.With('ENOENT', oldPath, 'rename'); const ino: number = oldDirList[_old.base]; if (ino != this._ids.get(oldPath)) err(`Ino mismatch while renaming ${oldPath} to ${newPath}`); delete oldDirList[_old.base]; /* Can't move a folder inside itself. This ensures that the check passes only if `oldPath` is a subpath of `_new.dir`. We append '/' to avoid matching folders that are a substring of the bottom-most folder in the path. */ if ((_new.dir + '/').startsWith(oldPath + '/')) throw new ErrnoError(Errno.EBUSY, _old.dir); // Add newPath to parent's directory listing. const sameParent = _new.dir == _old.dir; // Prevent us from re-grabbing the same directory listing, which still contains `old_path.base.` const newDirNode: Inode = sameParent ? oldDirNode : await this.findInode(tx, _new.dir, 'rename'); const newDirList: typeof oldDirList = sameParent ? oldDirList : decodeDirListing((await tx.get(newDirNode.data)) ?? _throw(ErrnoError.With('ENODATA', _new.dir, 'rename'))); if (newDirList[_new.base]) { // If it's a file, delete it, if it's a directory, throw a permissions error. const existing = new Inode((await tx.get(newDirList[_new.base])) ?? _throw(ErrnoError.With('ENOENT', newPath, 'rename'))); if (!existing.toStats().isFile()) throw ErrnoError.With('EPERM', newPath, 'rename'); await tx.remove(existing.data); await tx.remove(newDirList[_new.base]); } newDirList[_new.base] = ino; // Commit the two changed directory listings. await tx.set(oldDirNode.data, encodeDirListing(oldDirList)); await tx.set(newDirNode.data, encodeDirListing(newDirList)); await tx.commit(); this._move(oldPath, newPath); }
/** * @todo Make rename compatible with the cache. */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/store/fs.ts#L225-L272
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
StoreFS.sync
public async sync(path: string, data?: Uint8Array, metadata?: Readonly<InodeLike>): Promise<void> { await using tx = this.transaction(); const inode = await this.findInode(tx, path, 'sync'); if (data) await tx.set(inode.data, data); if (inode.update(metadata)) { this._add(inode.ino, path); await tx.set(inode.ino, serialize(inode)); } await tx.commit(); }
/** * Updated the inode and data node at `path` * @todo Ensure mtime updates properly, and use that to determine if a data update is required. */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/store/fs.ts#L403-L416
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
StoreFS.syncSync
public syncSync(path: string, data?: Uint8Array, metadata?: Readonly<InodeLike>): void { using tx = this.transaction(); const inode = this.findInodeSync(tx, path, 'sync'); if (data) tx.setSync(inode.data, data); if (inode.update(metadata)) { this._add(inode.ino, path); tx.setSync(inode.ino, serialize(inode)); } tx.commitSync(); }
/** * Updated the inode and data node at `path` * @todo Ensure mtime updates properly, and use that to determine if a data update is required. */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/store/fs.ts#L422-L435
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
StoreFS.transaction
public transaction(): WrappedTransaction { return new WrappedTransaction(this.store.transaction(), this); }
/** * Wraps a transaction * @internal @hidden */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/store/fs.ts#L543-L545
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
StoreFS.checkRoot
public async checkRoot(): Promise<void> { await using tx = this.transaction(); if (await tx.get(rootIno)) return; const inode = new Inode({ ino: rootIno, data: 1, mode: 0o777 | S_IFDIR }); await tx.set(inode.data, encodeUTF8('{}')); this._add(rootIno, '/'); await tx.set(rootIno, serialize(inode)); await tx.commit(); }
/** * Checks if the root directory exists. Creates it if it doesn't. */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/store/fs.ts#L550-L560
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
StoreFS.checkRootSync
public checkRootSync(): void { using tx = this.transaction(); if (tx.getSync(rootIno)) return; const inode = new Inode({ ino: rootIno, data: 1, mode: 0o777 | S_IFDIR }); tx.setSync(inode.data, encodeUTF8('{}')); this._add(rootIno, '/'); tx.setSync(rootIno, serialize(inode)); tx.commitSync(); }
/** * Checks if the root directory exists. Creates it if it doesn't. */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/store/fs.ts#L565-L575
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
StoreFS._populate
private async _populate(): Promise<void> { if (this._initialized) { warn('Attempted to populate tables after initialization'); return; } debug('Populating tables with existing store metadata.'); await using tx = this.transaction(); const rootData = await tx.get(rootIno); if (!rootData) { notice('Store does not have a root inode.'); const inode = new Inode({ ino: rootIno, data: 1, mode: 0o777 | S_IFDIR }); await tx.set(inode.data, encodeUTF8('{}')); this._add(rootIno, '/'); await tx.set(rootIno, serialize(inode)); await tx.commit(); return; } if (rootData.length != __inode_sz) { crit('Store contains an invalid root inode. Refusing to populate tables.'); return; } // Keep track of directories we have already traversed to avoid loops const visitedDirectories = new Set<number>(); let i = 0; // Start BFS from root const queue: Array<[path: string, ino: number]> = [['/', rootIno]]; while (queue.length > 0) { i++; const [path, ino] = queue.shift()!; this._add(ino, path); // Get the inode data from the store const inodeData = await tx.get(ino); if (!inodeData) { warn('Store is missing data for inode: ' + ino); continue; } if (inodeData.length != __inode_sz) { warn(`Invalid inode size for ino ${ino}: ${inodeData.length}`); continue; } // Parse the raw data into our Inode object const inode = new Inode(inodeData); // If it is a directory and not yet visited, read its directory listing if ((inode.mode & S_IFDIR) != S_IFDIR || visitedDirectories.has(ino)) { continue; } visitedDirectories.add(ino); // Grab the directory listing from the store const dirData = await tx.get(inode.data); if (!dirData) { warn('Store is missing directory data: ' + inode.data); continue; } const dirListing = decodeDirListing(dirData); for (const [entryName, childIno] of Object.entries(dirListing)) { queue.push([join(path, entryName), childIno]); } } debug(`Added ${i} existing inode(s) from store`); }
/** * Populates the `_ids` and `_paths` maps with all existing files stored in the underlying `Store`. */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/store/fs.ts#L580-L654
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
StoreFS.findInode
protected async findInode(tx: WrappedTransaction, path: string, syscall: string): Promise<Inode> { const ino = this._ids.get(path); if (ino === undefined) throw ErrnoError.With('ENOENT', path, syscall); return new Inode((await tx.get(ino)) ?? _throw(ErrnoError.With('ENOENT', path, syscall))); }
/** * Finds the Inode of `path`. * @param path The path to look up. * @todo memoize/cache */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/store/fs.ts#L661-L665
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
StoreFS.findInodeSync
protected findInodeSync(tx: WrappedTransaction, path: string, syscall: string): Inode { const ino = this._ids.get(path); if (ino === undefined) throw ErrnoError.With('ENOENT', path, syscall); return new Inode(tx.getSync(ino) ?? _throw(ErrnoError.With('ENOENT', path, syscall))); }
/** * Finds the Inode of `path`. * @param path The path to look up. * @return The Inode of the path p. * @todo memoize/cache */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/store/fs.ts#L673-L677
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
StoreFS.allocNew
protected allocNew(path: string, syscall: string): number { this._lastID ??= Math.max(...this._paths.keys()); this._lastID += 2; const id = this._lastID; if (id > size_max) throw err(new ErrnoError(Errno.ENOSPC, 'No IDs available', path, syscall), { fs: this }); this._add(id, path); return id; }
/** * Allocates a new ID and adds the ID/path */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/store/fs.ts#L684-L691
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
StoreFS.commitNew
protected async commitNew(path: string, options: PureCreationOptions, data: Uint8Array, syscall: string): Promise<Inode> { /* The root always exists. If we don't check this prior to taking steps below, we will create a file with name '' in root if path is '/'. */ if (path == '/') throw ErrnoError.With('EEXIST', path, syscall); await using tx = this.transaction(); const { dir: parentPath, base: fname } = parse(path); const parent = await this.findInode(tx, parentPath, syscall); const listing = decodeDirListing((await tx.get(parent.data)) ?? _throw(ErrnoError.With('ENOENT', parentPath, syscall))); // Check if file already exists. if (listing[fname]) throw ErrnoError.With('EEXIST', path, syscall); const id = this.allocNew(path, syscall); // Commit data. const inode = new Inode({ ino: id, data: id + 1, mode: options.mode, size: data.byteLength, uid: parent.mode & S_ISUID ? parent.uid : options.uid, gid: parent.mode & S_ISGID ? parent.gid : options.gid, }); await tx.set(inode.ino, serialize(inode)); await tx.set(inode.data, data); // Update and commit parent directory listing. listing[fname] = inode.ino; await tx.set(parent.data, encodeDirListing(listing)); await tx.commit(); return inode; }
/** * Commits a new file (well, a FILE or a DIRECTORY) to the file system with `mode`. * Note: This will commit the transaction. * @param path The path to the new file. * @param options The options to create the new file with. * @param data The data to store at the file's data node. */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/store/fs.ts#L700-L737
fea47188b8827aa31de2fc14974444c0d2b8fa9f
core
github_2023
zen-fs
typescript
StoreFS.commitNewSync
protected commitNewSync(path: string, options: PureCreationOptions, data: Uint8Array, syscall: string): Inode { /* The root always exists. If we don't check this prior to taking steps below, we will create a file with name '' in root if path is '/'. */ if (path == '/') throw ErrnoError.With('EEXIST', path, syscall); using tx = this.transaction(); const { dir: parentPath, base: fname } = parse(path); const parent = this.findInodeSync(tx, parentPath, syscall); const listing = decodeDirListing(tx.getSync(parent.data) ?? _throw(ErrnoError.With('ENOENT', parentPath, syscall))); // Check if file already exists. if (listing[fname]) throw ErrnoError.With('EEXIST', path, syscall); const id = this.allocNew(path, syscall); // Commit data. const inode = new Inode({ ino: id, data: id + 1, mode: options.mode, size: data.byteLength, uid: parent.mode & S_ISUID ? parent.uid : options.uid, gid: parent.mode & S_ISGID ? parent.gid : options.gid, }); // Update and commit parent directory listing. tx.setSync(inode.ino, serialize(inode)); tx.setSync(inode.data, data); listing[fname] = inode.ino; tx.setSync(parent.data, encodeDirListing(listing)); tx.commitSync(); return inode; }
/** * Commits a new file (well, a FILE or a DIRECTORY) to the file system with `mode`. * Note: This will commit the transaction. * @param path The path to the new file. * @param options The options to create the new file with. * @param data The data to store at the file's data node. * @return The Inode for the new file. */
https://github.com/zen-fs/core/blob/fea47188b8827aa31de2fc14974444c0d2b8fa9f/src/backends/store/fs.ts#L747-L784
fea47188b8827aa31de2fc14974444c0d2b8fa9f