repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
flappy
github_2023
pleisto
typescript
FlappyAgent.callFeature
public async callFeature< TName extends TNames, TFunction extends AnyFlappyFeature = FindFlappyFeature<TFeatures, TName> >(name: TName, args: Parameters<TFunction['call']>[1]): Promise<ReturnType<TFunction['call']>> { const fn = this.findFeature(name) // eslint-disable-next-line @typescript-eslint/return-await return await fn.call(this, args) }
/** * Call a feature by name. */
https://github.com/pleisto/flappy/blob/cf340e2ef76c21ef33c6a650d9c8cf28b694ad7f/packages/nodejs/src/flappy-agent.ts#L76-L83
cf340e2ef76c21ef33c6a650d9c8cf28b694ad7f
flappy
github_2023
pleisto
typescript
FlappyAgent.executePlan
public async executePlan(prompt: string, enableCot: boolean = true): Promise<any> { log.debug('Start planing') const zodSchema = lanOutputSchema(enableCot) const originalRequestMessage: ChatMLMessage[] = [ this.executePlanSystemMessage(enableCot), { role: 'user', content: templateRenderer('agent/userMessage', { prompt }) } ] let requestMessage = originalRequestMessage let plan: any[] = [] let retry = this.retry let result: ChatMLResponse | undefined while (true) { try { if (retry !== this.retry) log.debug(`Attempt retry: ${this.retry - retry}`) log.debug({ data: requestMessage } as unknown as JsonObject, 'Submit the request message') result = await this.llmPlaner.chatComplete(requestMessage) plan = this.parseComplete(result) // check for function calling in each step for (const step of plan) { const fn = this.findFeature(step.functionName) if (!fn) throw new Error(`Function definition not found: ${step.functionName}`) } break } catch (err) { console.error(err) if (retry <= 0) throw new Error('Interrupted, create plan failed. Please refer to the error message above.') retry -= 1 // if the response came from chatComplete is failed, retry it directly. // Otherwise, update message for repairing if (result?.success && result.data) { requestMessage = [ ...originalRequestMessage, { role: 'assistant', content: result?.data ?? '' }, { role: 'user', content: templateRenderer('error/retry', { message: (err as Error).message }) } ] } } } zodSchema.parse(plan) const returnStore = new Map() for (let i = 0; i < plan.length; i++) { const step = plan[i] const fn = this.findFeature<TNames>(step.functionName) const args = Object.fromEntries( Object.entries(step.args).map(([k, v]) => { if (typeof v === 'string' && v.startsWith(STEP_PREFIX)) { const keys = v.slice(STEP_PREFIX.length).split('.') const stepId = parseInt(keys[0]!, 10) const stepResult = returnStore.get(stepId) if (keys.length === 1) return [k, stepResult] // access object property return [k, keys.slice(1).reduce((acc, cur) => acc[cur], stepResult)] } return [k, v] }) ) log.debug(`Start step ${i + 1}`) log.debug(`Start function call: ${step.functionName}`) const result = await fn.call(this, args) log.debug(`End Function call: ${step.functionName}`) returnStore.set(step.id, result) } // step id starts from 1, so plan.length is the last step id // return the last step result return returnStore.get(plan.length) }
/** * executePlan * @param prompt user input prompt * @param enableCot enable CoT to improve the plan quality, but it will be generally more tokens. Default is true. */
https://github.com/pleisto/flappy/blob/cf340e2ef76c21ef33c6a650d9c8cf28b694ad7f/packages/nodejs/src/flappy-agent.ts#L100-L181
cf340e2ef76c21ef33c6a650d9c8cf28b694ad7f
flappy
github_2023
pleisto
typescript
buildJsonSchema
const buildJsonSchema = (that: FlappyFeatureBase<FlappyFeatureMetadataBase>) => { const define = that.define const args = zodToCleanJsonSchema(define.args.describe('Function arguments')) const returnType = zodToCleanJsonSchema(define.returnType.describe('Function return type')) return { name: define.name, description: that.buildDescription(), parameters: { type: 'object', properties: { args, returnType } } } }
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
https://github.com/pleisto/flappy/blob/cf340e2ef76c21ef33c6a650d9c8cf28b694ad7f/packages/nodejs/src/features/base.ts#L15-L30
cf340e2ef76c21ef33c6a650d9c8cf28b694ad7f
flappy
github_2023
pleisto
typescript
calcDefaultMaxTokens
const calcDefaultMaxTokens = (model: ChatGPTModel): number => { if (model.includes('16k')) return 16385 if (model.includes('32k')) return 32768 if (model.includes('gpt-4')) return 8192 return 4096 }
/** * Calculate the default max tokens for a given model. * @see https://platform.openai.com/docs/models/overview * @param model Model name. * @returns */
https://github.com/pleisto/flappy/blob/cf340e2ef76c21ef33c6a650d9c8cf28b694ad7f/packages/nodejs/src/llms/chatgpt.ts#L16-L21
cf340e2ef76c21ef33c6a650d9c8cf28b694ad7f
flappy
github_2023
pleisto
typescript
allowJsonResponseFormat
const allowJsonResponseFormat = (model: ChatGPTModel): boolean => { return model === jsonObjectModel }
// https://platform.openai.com/docs/api-reference/chat/create#chat-create-response_format
https://github.com/pleisto/flappy/blob/cf340e2ef76c21ef33c6a650d9c8cf28b694ad7f/packages/nodejs/src/llms/chatgpt.ts#L24-L26
cf340e2ef76c21ef33c6a650d9c8cf28b694ad7f
flappy
github_2023
pleisto
typescript
showUsage
const showUsage = (): void => { console.log(`yarn dev generate [collection-name:]<schematic-name> [options] Common Options: --debug Debug mode. This is true by default if the collection is a relative path. --allow-private Allow private schematics to be run. This is false by default. --dry-run Do not actually execute any effects. Default to true if debug mode is true. --force Force overwriting files that would otherwise be an error. --no-interactive Do not prompt for input. --verbose Show more output. --help Show help. Available schematics in ${defaultCollection} collection:`) // list schematics void main({ args: [`${defaultCollection}:`, '--list-schematics'] }) console.log(` By default, if the collection-name is not specified, use the internal coolection provided by the ${defaultCollection}. e.g. "${chalk.bold('yarn dev g vscode-workspace')}" equals "${chalk.bold( `yarn dev g ${defaultCollection}:vscode-workspace` )}". `) }
/** * Show usage information. */
https://github.com/pleisto/flappy/blob/cf340e2ef76c21ef33c6a650d9c8cf28b694ad7f/tools/devkit/src/commands/generate.ts#L10-L32
cf340e2ef76c21ef33c6a650d9c8cf28b694ad7f
flappy
github_2023
pleisto
typescript
currentYarnWorkspaces
function currentYarnWorkspaces(): any[] { const yarnProcess = spawnSync('yarn', ['workspaces', 'list', '--json']) return yarnProcess.stdout .toString() .split(/\r?\n/) .filter(obj => obj.startsWith('{')) .map(obj => { return JSON.parse(obj) }) }
/** * Return all yarn workspaces */
https://github.com/pleisto/flappy/blob/cf340e2ef76c21ef33c6a650d9c8cf28b694ad7f/tools/devkit/src/schematics/vscode-workspace/index.ts#L40-L49
cf340e2ef76c21ef33c6a650d9c8cf28b694ad7f
flappy
github_2023
pleisto
typescript
getCurrentCodeWorkspace
function getCurrentCodeWorkspace(): any { try { const workspaceJson = readFileSync('pleisto.code-workspace', 'utf8') return jsonc.parse(workspaceJson) } catch { return {} } }
/** * Get current code-workspace for cwd */
https://github.com/pleisto/flappy/blob/cf340e2ef76c21ef33c6a650d9c8cf28b694ad7f/tools/devkit/src/schematics/vscode-workspace/index.ts#L54-L61
cf340e2ef76c21ef33c6a650d9c8cf28b694ad7f
obsidian-vscode-editor
github_2023
sunxvming
typescript
CodeEditorView.onOpen
async onOpen() { await super.onOpen(); }
/* execute order: onOpen -> onLoadFile -> setViewData -> onUnloadFile -> onClose */
https://github.com/sunxvming/obsidian-vscode-editor/blob/f6584e5c57946f1929cab286ca7143fe3c7edce6/src/codeEditorView.ts#L22-L24
f6584e5c57946f1929cab286ca7143fe3c7edce6
obsidian-vscode-editor
github_2023
sunxvming
typescript
CodeEditorView.keyHandle
private keyHandle = (event: KeyboardEvent) => { const ctrlMap = new Map<string, string>([ ['f', 'actions.find'], ['h', 'editor.action.startFindReplaceAction'], ['/', 'editor.action.commentLine'], ['Enter', 'editor.action.insertLineAfter'], ['[', 'editor.action.outdentLines'], [']', 'editor.action.indentLines'], ['d', 'editor.action.copyLinesDownAction'], ]); if (event.ctrlKey) { const triggerName = ctrlMap.get(event.key); if (triggerName) { this.monacoEditor.trigger('', triggerName, null); } } if (event.altKey) { if (event.key === 'z') { this.plugin.settings.wordWrap = !this.plugin.settings.wordWrap; this.plugin.saveSettings(); this.monacoEditor.updateOptions({ wordWrap: this.plugin.settings.wordWrap ? "on" : "off", }) } } }
/* 修复不支持 `ctrl + 按键`快捷键的问题 原因是obsidian在app.js中增加了全局的keydown并且useCapture为true,猜测可能是为了支持快捷键就把阻止了子元素的事件的处理了 */
https://github.com/sunxvming/obsidian-vscode-editor/blob/f6584e5c57946f1929cab286ca7143fe3c7edce6/src/codeEditorView.ts#L95-L124
f6584e5c57946f1929cab286ca7143fe3c7edce6
windchat-extension
github_2023
WindChat-Link
typescript
Api.appControllerGetHello
appControllerDaily = (params: RequestParams = {}) => this.request<void, any>({ path: `/`, method: "POST", ...params, })
/** * No description * * @name AppControllerGetHello * @request GET:/ */
https://github.com/WindChat-Link/windchat-extension/blob/9048cf9f083c61ee319a3c022a0e72a263b22497/src/api-swagger/generated-api/Api.ts
9048cf9f083c61ee319a3c022a0e72a263b22497
windchat-extension
github_2023
WindChat-Link
typescript
ManifestParser.constructor
private constructor() {}
// eslint-disable-next-line @typescript-eslint/no-empty-function
https://github.com/WindChat-Link/windchat-extension/blob/9048cf9f083c61ee319a3c022a0e72a263b22497/utils/manifest-parser/index.ts#L5-L5
9048cf9f083c61ee319a3c022a0e72a263b22497
windchat-extension
github_2023
WindChat-Link
typescript
reload
function reload(): void { pendingReload = false; window.location.reload(); }
// reload
https://github.com/WindChat-Link/windchat-extension/blob/9048cf9f083c61ee319a3c022a0e72a263b22497/utils/reload/injections/view.ts#L21-L24
9048cf9f083c61ee319a3c022a0e72a263b22497
windchat-extension
github_2023
WindChat-Link
typescript
reloadWhenTabIsVisible
function reloadWhenTabIsVisible(): void { !document.hidden && pendingReload && reload(); }
// reload when tab is visible
https://github.com/WindChat-Link/windchat-extension/blob/9048cf9f083c61ee319a3c022a0e72a263b22497/utils/reload/injections/view.ts#L27-L29
9048cf9f083c61ee319a3c022a0e72a263b22497
windchat-extension
github_2023
WindChat-Link
typescript
MessageInterpreter.constructor
private constructor() {}
// eslint-disable-next-line @typescript-eslint/no-empty-function
https://github.com/WindChat-Link/windchat-extension/blob/9048cf9f083c61ee319a3c022a0e72a263b22497/utils/reload/interpreter/index.ts#L5-L5
9048cf9f083c61ee319a3c022a0e72a263b22497
svelte-tweakpane-ui
github_2023
kitschpatrol
typescript
findFile
function findFile( base: string, componentName: string, suffix: string, warn: boolean = true ): string | undefined { const files = globSync(`./${base}/**/${componentName}${suffix}`); if (files.length === 0) { if (warn) console.warn(`No files found for ${componentName}`); return undefined; } if (files.length > 1) { if (warn) console.error(`Fatal: Found multiple files for ${componentName}: ${files.join(' ')}`); return undefined; } return path.resolve(files[0]); }
// This will break if multiple components with the same name exist in different folders
https://github.com/kitschpatrol/svelte-tweakpane-ui/blob/2d66789223f4480ef57c90a98cc953a5257e5e73/scripts/ast-tools.ts#L22-L40
2d66789223f4480ef57c90a98cc953a5257e5e73
svelte-tweakpane-ui
github_2023
kitschpatrol
typescript
extractCodeBlock
function extractCodeBlock(inputString: string): string | undefined { const regex = /```\w*\n([\S\s]+?)```/gm; const match = regex.exec(inputString); if (match?.[1]) { return match[1].trim(); } }
// Doc-specific
https://github.com/kitschpatrol/svelte-tweakpane-ui/blob/2d66789223f4480ef57c90a98cc953a5257e5e73/scripts/ast-tools.ts#L185-L191
2d66789223f4480ef57c90a98cc953a5257e5e73
svelte-tweakpane-ui
github_2023
kitschpatrol
typescript
jsDocumentTagInfoToJsDocumentRecord
function jsDocumentTagInfoToJsDocumentRecord(jsDocumentTags: ts.JSDocTagInfo[]): JsDocRecord { const result: JsDocRecord = {}; for (const tag of jsDocumentTags) { result[tag.name] = ts.displayPartsToString(tag.text); } return result; }
// Function sortPropsByName(props: ComponentPartInfo): ComponentPartInfo {
https://github.com/kitschpatrol/svelte-tweakpane-ui/blob/2d66789223f4480ef57c90a98cc953a5257e5e73/scripts/component-info.ts#L55-L62
2d66789223f4480ef57c90a98cc953a5257e5e73
svelte-tweakpane-ui
github_2023
kitschpatrol
typescript
getStaticComponentInfo
async function getStaticComponentInfo(componentPath: string): Promise<ComponentInfo | undefined> { // Static approach const info = await getStaticComponentInfoInternal(componentPath); if (!info) return undefined; // Amend type data with dynamic approach const lsPropInfo = await getDynamicComponentProps(componentPath, {}); for (const property of info.props) { const lsProp = lsPropInfo.find((p) => p.name === property.name); if (!lsProp) { console.warn(`No LS prop found for ${property.name}`); continue; } property.type = lsProp.type; } return info; }
// Alt approach to get cleaner types... use the static approach for the basics,
https://github.com/kitschpatrol/svelte-tweakpane-ui/blob/2d66789223f4480ef57c90a98cc953a5257e5e73/scripts/component-info.ts#L67-L86
2d66789223f4480ef57c90a98cc953a5257e5e73
svelte-tweakpane-ui
github_2023
kitschpatrol
typescript
getStaticComponentInfoInternal
async function getStaticComponentInfoInternal( componentPath: string ): Promise<ComponentInfo | undefined> { // Set up language server const testDirectory = '.'; const resolvedPath = path.join(testDirectory, componentPath); const documentManager = new DocumentManager( (textDocument) => new Document(textDocument.uri, textDocument.text) ); const lsAndTsDocumentResolver = new LSAndTSDocResolver( documentManager, [pathToUrl(testDirectory)], new LSConfigManager(), { tsconfigPath: path.join(path.resolve(testDirectory), 'tsconfig.json') } ); const fileText = ts.sys.readFile(resolvedPath); if (fileText === undefined) { throw new Error(`Failed to read file ${resolvedPath}`); } const document = documentManager.openClientDocument({ text: fileText, uri: `file:///${resolvedPath}` }); const { lang, tsDoc } = await lsAndTsDocumentResolver.getLSAndTSDoc(document); const program = lang.getProgram(); if (!program) return undefined; // Get the component class definition const componentSourceFile = program.getSourceFile(tsDoc.filePath); if (!componentSourceFile) return undefined; const classDefinition = getClassDefinition(componentSourceFile); if (!classDefinition) { console.error('No class def found.'); return undefined; } const typeChecker = program.getTypeChecker(); const classType = typeChecker.getTypeAtLocation(classDefinition); const classSymbol = classType.getSymbol(); if (!classSymbol) { console.error('No class symbol found.'); return undefined; } // Get props, events, slots const results: ComponentInfo = { doc: ts.displayPartsToString(classSymbol.getDocumentationComment(typeChecker)), events: getInfoFor('$$events_def', classType, typeChecker), // Natural sorting... jsDocs: jsDocumentTagInfoToJsDocumentRecord(classSymbol.getJsDocTags()), name: componentPath.split('/').pop()!.replace('.svelte', ''), path: componentPath, pathParts: componentPath.split('/').slice(3, -1), props: getInfoFor('$$prop_def', classType, typeChecker), // Natural sorting... slots: getInfoFor('$$slot_def', classType, typeChecker) // Natural sorting... }; await lsAndTsDocumentResolver.deleteSnapshot(tsDoc.filePath); return results; }
// Basic, just get the static component's info
https://github.com/kitschpatrol/svelte-tweakpane-ui/blob/2d66789223f4480ef57c90a98cc953a5257e5e73/scripts/component-info.ts#L89-L154
2d66789223f4480ef57c90a98cc953a5257e5e73
svelte-tweakpane-ui
github_2023
kitschpatrol
typescript
getClassDefinition
function getClassDefinition(sourceFile: ts.SourceFile): ts.Node | undefined { let classDefinition: ts.Node | undefined; sourceFile.forEachChild((node) => { if (ts.isClassDeclaration(node)) { classDefinition = node; } }); return classDefinition; }
// ----------------------
https://github.com/kitschpatrol/svelte-tweakpane-ui/blob/2d66789223f4480ef57c90a98cc953a5257e5e73/scripts/component-info.ts#L158-L166
2d66789223f4480ef57c90a98cc953a5257e5e73
svelte-tweakpane-ui
github_2023
kitschpatrol
typescript
mapPropertiesOfType
function mapPropertiesOfType(typeChecker: ts.TypeChecker, type: ts.Type) { return type .getProperties() .map((property: ts.Symbol) => { // Type would still be correct when there're multiple declarations const declaration = property.valueDeclaration ?? property.declarations?.[0]; if (!declaration) { return; } // TODO despite its resemblance to the language-server's ComponentInfoProvider implementation, // this doesn't seem to give the same type strings // for now, the type field is later discarded and replaced with the language-server's output return { doc: ts.displayPartsToString(property.getDocumentationComment(typeChecker)), jsDocs: jsDocumentTagInfoToJsDocumentRecord(property.getJsDocTags()), name: property.name, type: typeChecker.typeToString(typeChecker.getTypeOfSymbolAtLocation(property, declaration)) }; }) .filter((element) => isNotNullOrUndefined(element)) as ComponentPartInfo; }
// Adapted from ComponentInfoProvider
https://github.com/kitschpatrol/svelte-tweakpane-ui/blob/2d66789223f4480ef57c90a98cc953a5257e5e73/scripts/component-info.ts#L169-L190
2d66789223f4480ef57c90a98cc953a5257e5e73
svelte-tweakpane-ui
github_2023
kitschpatrol
typescript
getDynamicComponentProps
async function getDynamicComponentProps( componentPath: string, testProps: ComponentPropCondition ): Promise<ComponentPartInfo> { // Set up language server const testDirectory = '.'; const documentManager = new DocumentManager( (textDocument) => new Document(textDocument.uri, textDocument.text) ); const lsAndTsDocumentResolver = new LSAndTSDocResolver( documentManager, [pathToUrl(testDirectory)], new LSConfigManager(), { tsconfigPath: path.join(path.resolve(testDirectory), 'tsconfig.json') } ); const componentName = componentPath.split('/').pop()!.replace('.svelte', ''); const testComponentSourceRows = [ '<script lang="ts">', `import ${componentName} from '${componentPath.replace('./src/lib/', '$lib/')}';`, '</script>', `<${componentName} ${generateStringFromPropObject(testProps)} />` ]; // Generated file name must be unique, cleanup doesn't seem to be enough // to avoid stale autocompletion values across repeat invocations const document = documentManager.openClientDocument({ text: testComponentSourceRows.join('\n'), uri: `file:///in-memory-${componentName}-${nanoid()}.svelte` }); const { lang, tsDoc } = await lsAndTsDocumentResolver.getLSAndTSDoc(document); const program = lang.getProgram(); if (!program) return []; const testPosition = { character: testComponentSourceRows.at(-1)!.length - 2, line: testComponentSourceRows.length - 1 }; const completions = lang.getCompletionsAtPosition( tsDoc.filePath, tsDoc.offsetAt(tsDoc.getGeneratedPosition(testPosition)), { allowIncompleteCompletions: true, // No change to output includeCompletionsForModuleExports: true, includeCompletionsWithInsertText: false, triggerCharacter: '.', useLabelDetailsInCompletionEntries: true // IncludeSymbol // TODO try this... } ); const typeChecker = program.getTypeChecker(); const results = completions?.entries.map((entry) => { const completionSymbols = lang.getCompletionEntrySymbol( tsDoc.filePath, tsDoc.offsetAt(tsDoc.getGeneratedPosition(testPosition)), entry.name, // eslint-disable-next-line unicorn/no-useless-undefined undefined ); return { doc: ts.displayPartsToString(completionSymbols!.getDocumentationComment(typeChecker)), jsDocs: jsDocumentTagInfoToJsDocumentRecord(completionSymbols!.getJsDocTags()), name: entry.name, type: typeChecker.typeToString(typeChecker.getTypeOfSymbol(completionSymbols!)) }; }) ?? []; await lsAndTsDocumentResolver.deleteSnapshot(tsDoc.filePath); return results; }
// Similar to what you'd get from JsOrTsComponentInfoProvider, but includes JSDocs and condition for dynamic props
https://github.com/kitschpatrol/svelte-tweakpane-ui/blob/2d66789223f4480ef57c90a98cc953a5257e5e73/scripts/component-info.ts#L212-L289
2d66789223f4480ef57c90a98cc953a5257e5e73
svelte-tweakpane-ui
github_2023
kitschpatrol
typescript
formatEmbeddedCode
async function formatEmbeddedCode(file: string): Promise<number> { let embedsFormatted = 0; try { const data = fs.readFileSync(file, 'utf8'); let formattedData = ''; let lastIndex = 0; const regex = /(```.*\n)([\S\s]*?)(\n```)/g; // eslint-disable-next-line @typescript-eslint/ban-types let match: null | RegExpExecArray; while ((match = regex.exec(data)) !== null) { const [fullMatch, opening, code, closing] = match; const { index } = match; // Append the part before this match. formattedData += data.slice(lastIndex, index); try { const formattedCode = await lintAndFormat(code); embedsFormatted++; // Using the original opening and closing backticks formattedData += `${opening}${formattedCode.trimEnd()}${closing}`; } catch (error) { if (error instanceof Error) { console.error(`Error formatting code: ${error.message}`); } else { console.error(`Error formatting code: ${String(error)}`); } formattedData += fullMatch; } lastIndex = index + fullMatch.length; } // Append the remaining part of the file formattedData += data.slice(lastIndex); // Only write if necessary if (formattedData === data) { embedsFormatted = 0; } else { fs.writeFileSync(file, formattedData, 'utf8'); } } catch (error) { if (error instanceof Error) { console.error(`Error: ${error.message}`); } else { console.error(`Error: ${String(error)}`); } } return embedsFormatted; }
// Assumes all code blocks are svelte-like
https://github.com/kitschpatrol/svelte-tweakpane-ui/blob/2d66789223f4480ef57c90a98cc953a5257e5e73/scripts/format-embedded-code.ts#L5-L58
2d66789223f4480ef57c90a98cc953a5257e5e73
svelte-tweakpane-ui
github_2023
kitschpatrol
typescript
addExports
function addExports(sourceIndexFile: string, closestPackage: ReadResult) { const { path } = closestPackage; console.log(`Adding Svelte components found in ${sourceIndexFile} to ${path}`); // Default export const exports: Exports = { '.': { types: './dist/index.d.ts', // eslint-disable-next-line perfectionist/sort-objects svelte: './dist/index.js' } }; // Extract components from index file for (const component of getExportedComponents(sourceIndexFile)) { const { name, path } = component; const key = `./${name}.svelte`; const types = `./dist/${path.replace('$lib/', '')}.d.ts`; const svelte = `./dist/${path.replace('$lib/', '')}`; // eslint-disable-next-line perfectionist/sort-objects exports[key] = { types, svelte }; if (verbose) console.log(exports[key]); } // Extract JS exports from index file (like Utils, etc.) for (const file of getExportedJs(sourceIndexFile)) { const { name, path } = file; const key = `./${name}.js`; const types = `./dist/${path.replace('.js', '').replace('$lib/', '')}.d.ts`; const defaultValue = `./dist/${path.replace('$lib/', '')}`; // eslint-disable-next-line perfectionist/sort-objects exports[key] = { types, default: defaultValue }; if (verbose) console.log(exports[key]); } // Save to package.json const { packageJson } = closestPackage; packageJson.exports = exports; packageJson.types = './dist/index.d.ts'; // Deprecated, Astro complains // https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/faq.md#conflicts-in-svelte-resolve // packageJson.svelte = './dist/index.d.ts'; fs.writeFileSync(path, JSON.stringify(packageJson, undefined, 2)); console.log( `Done. Wrote 'types' and ${ Object.keys(exports).length - 1 } component 'exports' values to ${path}.` ); }
// Gets all props for a given component from its definition file
https://github.com/kitschpatrol/svelte-tweakpane-ui/blob/2d66789223f4480ef57c90a98cc953a5257e5e73/scripts/generate-exports.ts#L13-L70
2d66789223f4480ef57c90a98cc953a5257e5e73
svelte-tweakpane-ui
github_2023
kitschpatrol
typescript
getParentComponentNames
function getParentComponentNames(componentName: string): string[] { return queryTree<PropNode>( new Project().addSourceFileAtPath(getSourceFilePath(componentName)!), ':matches(ExpressionWithTypeArguments[expression.name="ComponentProps"], TypeReference[typeName.name="ComponentProps"]) > TypeReference > Identifier' ).map((node) => node.getText()); }
// Helper functions
https://github.com/kitschpatrol/svelte-tweakpane-ui/blob/2d66789223f4480ef57c90a98cc953a5257e5e73/scripts/heal-dts-comments.ts#L25-L30
2d66789223f4480ef57c90a98cc953a5257e5e73
svelte-tweakpane-ui
github_2023
kitschpatrol
typescript
getPropCommentInParents
function getPropCommentInParents(componentName: string, propName: string): JSDoc[] | undefined { // Some components extend multiple components, e.g. Pane, Monitor const parentComponents = getParentComponentNames(componentName); let comment: JSDoc[] | undefined; while (comment === undefined && parentComponents.length > 0) { const parent = parentComponents.pop()!; // Recurse as needed comment = getCommentForProp(parent, propName) ?? getPropCommentInParents(parent, propName); } return comment; }
// Recursively walks up the component inheritance chain to find a comment for a prop
https://github.com/kitschpatrol/svelte-tweakpane-ui/blob/2d66789223f4480ef57c90a98cc953a5257e5e73/scripts/heal-dts-comments.ts#L37-L49
2d66789223f4480ef57c90a98cc953a5257e5e73
svelte-tweakpane-ui
github_2023
kitschpatrol
typescript
stringToCssValue
function stringToCssValue(v: string | ThemeColorValue | undefined): string | undefined { if (v === undefined) { return undefined; } if (typeof v === 'string') { return v; } if (isRgbaColorObject(v)) { return `rgba(${v.r}, ${v.g}, ${v.b}, ${v.a})`; } if (isRgbColorObject(v)) { return `rgb(${v.r}, ${v.g}, ${v.b})`; } }
// Just do it dynamically instead of the map? function transformToCustomProperty(str: string):
https://github.com/kitschpatrol/svelte-tweakpane-ui/blob/2d66789223f4480ef57c90a98cc953a5257e5e73/src/lib/theme.ts#L303-L319
2d66789223f4480ef57c90a98cc953a5257e5e73
svelte-tweakpane-ui
github_2023
kitschpatrol
typescript
quaternionToCssTransform
function quaternionToCssTransform(quaternion: RotationQuaternionValue): string { const [x, y, z, w] = ( Array.isArray(quaternion) ? quaternion : [quaternion.x, quaternion.y, quaternion.z, quaternion.w] ) as [number, number, number, number]; const m11 = 1 - 2 * y * y - 2 * z * z; const m12 = 2 * x * y - 2 * z * w; const m13 = 2 * x * z + 2 * y * w; const m21 = 2 * x * y + 2 * z * w; const m22 = 1 - 2 * x * x - 2 * z * z; const m23 = 2 * y * z - 2 * x * w; const m31 = 2 * x * z - 2 * y * w; const m32 = 2 * y * z + 2 * x * w; const m33 = 1 - 2 * x * x - 2 * y * y; return `matrix3d( ${m11}, ${m12}, ${m13}, 0, ${m21}, ${m22}, ${m23}, 0, ${m31}, ${m32}, ${m33}, 0, 0, 0, 0, 1 )`; }
// Utility functions
https://github.com/kitschpatrol/svelte-tweakpane-ui/blob/2d66789223f4480ef57c90a98cc953a5257e5e73/src/lib/utils.ts#L336-L359
2d66789223f4480ef57c90a98cc953a5257e5e73
rolldown
github_2023
rolldown
typescript
ensureProperTitleLevel
function ensureProperTitleLevel(content: string, level: number) { let baseTitleMark = '#'.repeat(level) return content.replaceAll(titleMarkRegex, `${baseTitleMark}$1`) }
/** * This function replaces `#` marks in the content with the proper number of `#` marks for the given level. * For example, if the content is `# Title`, and the level is 2, it will be replaced with `### Title`. */
https://github.com/rolldown/rolldown/blob/5b26e29e5eaa6a7dd9069808227d2fda8006483a/docs/data-loading/options-doc.data.ts#L143-L146
5b26e29e5eaa6a7dd9069808227d2fda8006483a
rolldown
github_2023
rolldown
typescript
wrap
function wrap(result: ParseResult, sourceText: string) { let program: ParseResult['program'], module: ParseResult['module'], comments: ParseResult['comments'], errors: ParseResult['errors'], magicString: ParseResult['magicString'] return { get program() { if (!errors) errors = result.errors if (errors.length > 0) { return normalizeParseError(sourceText, errors) } // @ts-expect-error the result.program typing is `Program` if (!program) program = JSON.parse(result.program) return program }, get module() { if (!module) module = result.module return module }, get comments() { if (!comments) comments = result.comments return comments }, get errors() { if (!errors) errors = result.errors return errors }, get magicString() { if (!magicString) magicString = result.magicString return magicString }, } }
// The oxc program is a string in the result, we need to parse it to a object.
https://github.com/rolldown/rolldown/blob/5b26e29e5eaa6a7dd9069808227d2fda8006483a/packages/rolldown/src/parse-ast-index.ts#L10-L43
5b26e29e5eaa6a7dd9069808227d2fda8006483a
rolldown
github_2023
rolldown
typescript
bindingifyJsx
function bindingifyJsx(input: InputOptions['jsx']): BindingInputOptions['jsx'] { if (input === false) { return { type: 'Disable' } } if (input) { if (input.mode === 'preserve') { return { type: 'Preserve' } } const mode = input.mode ?? 'automatic' return { type: 'Enable', field0: { runtime: mode, importSource: mode === 'classic' ? input.importSource : mode === 'automatic' ? input.jsxImportSource : undefined, pragma: input.factory, pragmaFrag: input.fragment, development: input.development, refresh: input.refresh, }, } } }
// The `automatic` is most user usages, so it is different rollup's default value `false`
https://github.com/rolldown/rolldown/blob/5b26e29e5eaa6a7dd9069808227d2fda8006483a/packages/rolldown/src/utils/bindingify-input-options.ts#L228-L254
5b26e29e5eaa6a7dd9069808227d2fda8006483a
rolldown
github_2023
rolldown
typescript
updateOutput
function updateOutput( newCode: string, newModuleSideEffects?: ModuleSideEffects, ) { code = newCode moduleSideEffects = newModuleSideEffects ?? undefined }
// TODO: we should deal with the returned sourcemap too.
https://github.com/rolldown/rolldown/blob/5b26e29e5eaa6a7dd9069808227d2fda8006483a/packages/rolldown/src/utils/compose-js-plugins.ts#L301-L307
5b26e29e5eaa6a7dd9069808227d2fda8006483a
rolldown
github_2023
rolldown
typescript
cleanStdout
function cleanStdout(stdout: string) { return stripAnsi(stdout).replace(/Finished in \d+(\.\d+)? ms/g, '') }
// remove `Finished in x ms` since it is not deterministic
https://github.com/rolldown/rolldown/blob/5b26e29e5eaa6a7dd9069808227d2fda8006483a/packages/rolldown/tests/cli/cli-e2e.test.ts#L14-L16
5b26e29e5eaa6a7dd9069808227d2fda8006483a
rolldown
github_2023
rolldown
typescript
defaultResolveFunction
function defaultResolveFunction( esbuildFilename: string, rolldownFilename: string, resolver?: Resolver, ) { if ( typeof resolver === 'function' && resolver(esbuildFilename, rolldownFilename) ) { return true } if (resolver && typeof resolver === 'object') { if ( isRegExp(resolver[esbuildFilename]) && (resolver[esbuildFilename] as RegExp).test(rolldownFilename) ) { return true } if (resolver[esbuildFilename] == rolldownFilename) { return true } } if (esbuildFilename === '/out.js' && /entry\.js/.test(rolldownFilename)) { return true } let extractedCaseName = /\/out\/(.*)/.exec(esbuildFilename)?.[1] if (extractedCaseName === rolldownFilename) { return true } }
/** * our filename generate logic is not the same as esbuild * so hardcode some filename remapping */
https://github.com/rolldown/rolldown/blob/5b26e29e5eaa6a7dd9069808227d2fda8006483a/scripts/snap-diff/diff.ts#L20-L50
5b26e29e5eaa6a7dd9069808227d2fda8006483a
FastUI
github_2023
pydantic
typescript
locToName
function locToName(loc: Loc): string { if (loc.some((v) => typeof v === 'string' && v.includes('.'))) { return JSON.stringify(loc) } else if (typeof loc[0] === 'string' && loc[0].startsWith('[')) { return JSON.stringify(loc) } else { return loc.join('.') } }
/** * Should match `loc_to_name` in python so errors can be connected to the correct field */
https://github.com/pydantic/FastUI/blob/5d9d604b2102b32adb1b3a7f30254a951f1cf086/src/npm-fastui/src/components/form.tsx#L166-L174
5d9d604b2102b32adb1b3a7f30254a951f1cf086
FastUI
github_2023
pydantic
typescript
combineClassNameProp
function combineClassNameProp(classNameProp?: ClassName): boolean { if (Array.isArray(classNameProp)) { // classNameProp is an array, check if it contains `+` return classNameProp.some((c) => c === '+') } else if (typeof classNameProp === 'string') { // classNameProp is a string, check if it starts with `+ ` return /^\+ /.test(classNameProp) } else if (typeof classNameProp === 'object') { // classNameProp is an object, check if its keys contain `+` return Object.keys(classNameProp).some((key) => key === '+') } else { // classNameProp is undefined, return true as we want to generate the default className return true } }
/** * Decide whether we should generate combine the props class name with the generated or default, or not. * * e.g. if the ClassName contains a `+` if it's an Array or Record, or starts with `+ ` * then we generate the default className and append the user's className to it. * @param classNameProp */
https://github.com/pydantic/FastUI/blob/5d9d604b2102b32adb1b3a7f30254a951f1cf086/src/npm-fastui/src/hooks/className.ts#L65-L79
5d9d604b2102b32adb1b3a7f30254a951f1cf086
llrt
github_2023
awslabs
typescript
Stream
function Stream(this: any) { EE.call(this); }
// old-style streams. Note that the pipe method (the only relevant
https://github.com/awslabs/llrt/blob/eed8301c1d71208fbd962efc566d29c96bab50fb/llrt_core/src/modules/js/stream.ts#L45-L47
eed8301c1d71208fbd962efc566d29c96bab50fb
llrt
github_2023
awslabs
typescript
onerror
function onerror(er: any) { cleanup(); if (source.listenerCount("error") === 0) { throw er; // Unhandled stream error in pipe. } }
// don't leave dangling pipes when there are errors.
https://github.com/awslabs/llrt/blob/eed8301c1d71208fbd962efc566d29c96bab50fb/llrt_core/src/modules/js/stream.ts#L93-L98
eed8301c1d71208fbd962efc566d29c96bab50fb
llrt
github_2023
awslabs
typescript
cleanup
function cleanup() { source.removeListener("data", ondata); dest.removeListener("drain", ondrain); source.removeListener("end", onend); source.removeListener("close", onclose); source.removeListener("error", onerror); dest.removeListener("error", onerror); source.removeListener("end", cleanup); source.removeListener("close", cleanup); dest.removeListener("close", cleanup); }
// remove all the event listeners that were added.
https://github.com/awslabs/llrt/blob/eed8301c1d71208fbd962efc566d29c96bab50fb/llrt_core/src/modules/js/stream.ts#L104-L118
eed8301c1d71208fbd962efc566d29c96bab50fb
llrt
github_2023
awslabs
typescript
eq
function eq( a: any, b: any, aStack: Array<unknown>, bStack: Array<unknown>, customTesters: Array<any>, hasKey: any ): boolean { let result = true; const asymmetricResult = asymmetricMatch(a, b); if (asymmetricResult !== undefined) return asymmetricResult; const testerContext: any = { equals }; for (let i = 0; i < customTesters.length; i++) { const customTesterResult = customTesters[i].call( testerContext, a, b, customTesters ); if (customTesterResult !== undefined) return customTesterResult; } if (a instanceof Error && b instanceof Error) return a.message === b.message; if (typeof URL === "function" && a instanceof URL && b instanceof URL) return a.href === b.href; if (Object.is(a, b)) return true; // A strict comparison is necessary because `null == undefined`. if (a === null || b === null) return a === b; const className = Object.prototype.toString.call(a); if (className !== Object.prototype.toString.call(b)) return false; switch (className) { case "[object Boolean]": case "[object String]": case "[object Number]": if (typeof a !== typeof b) { // One is a primitive, one a `new Primitive()` return false; } else if (typeof a !== "object" && typeof b !== "object") { // both are proper primitives return Object.is(a, b); } else { // both are `new Primitive()`s return Object.is(a.valueOf(), b.valueOf()); } case "[object Date]": { const numA = +a; const numB = +b; // Coerce dates to numeric primitive values. Dates are compared by their // millisecond representations. Note that invalid dates with millisecond representations // of `NaN` are equivalent. return numA === numB || (Number.isNaN(numA) && Number.isNaN(numB)); } // RegExps are compared by their source patterns and flags. case "[object RegExp]": return a.source === b.source && a.flags === b.flags; } if (typeof a !== "object" || typeof b !== "object") return false; // Use DOM3 method isEqualNode (IE>=9) if (isDomNode(a) && isDomNode(b)) return a.isEqualNode(b); // Used to detect circular references. let length = aStack.length; while (length--) { // Linear search. Performance is inversely proportional to the number of // unique nested structures. // circular references at same depth are equal // circular reference is not equal to non-circular one if (aStack[length] === a) return bStack[length] === b; else if (bStack[length] === b) return false; } // Add the first object to the stack of traversed objects. aStack.push(a); bStack.push(b); // Recursively compare objects and arrays. // Compare array lengths to determine if a deep comparison is necessary. if (className === "[object Array]" && a.length !== b.length) return false; // Deep compare objects. const aKeys = keys(a, hasKey); let key; let size = aKeys.length; // Ensure that both objects contain the same number of properties before comparing deep equality. if (keys(b, hasKey).length !== size) return false; while (size--) { key = aKeys[size]; // Deep compare each member result = hasKey(b, key) && eq(a[key], b[key], aStack, bStack, customTesters, hasKey); if (!result) return false; } // Remove the first object from the stack of traversed objects. aStack.pop(); bStack.pop(); return result; }
// Equality function lovingly adapted from isEqual in
https://github.com/awslabs/llrt/blob/eed8301c1d71208fbd962efc566d29c96bab50fb/llrt_core/src/modules/js/@llrt/expect/jest-utils.ts#L79-L187
eed8301c1d71208fbd962efc566d29c96bab50fb
llrt
github_2023
awslabs
typescript
hasPropertyInObject
function hasPropertyInObject(object: object, key: string): boolean { const shouldTerminate = !object || typeof object !== "object" || object === Object.prototype; if (shouldTerminate) return false; return ( Object.prototype.hasOwnProperty.call(object, key) || hasPropertyInObject(Object.getPrototypeOf(object), key) ); }
/** * Checks if `hasOwnProperty(object, key)` up the prototype chain, stopping at `Object.prototype`. */
https://github.com/awslabs/llrt/blob/eed8301c1d71208fbd962efc566d29c96bab50fb/llrt_core/src/modules/js/@llrt/expect/jest-utils.ts#L413-L423
eed8301c1d71208fbd962efc566d29c96bab50fb
llrt
github_2023
awslabs
typescript
subsetEqualityWithContext
const subsetEqualityWithContext = (seenReferences: WeakMap<object, boolean> = new WeakMap()) => (object: any, subset: any): boolean | undefined => { if (!isObjectWithKeys(subset)) return undefined; return Object.keys(subset).every((key) => { if (isObjectWithKeys(subset[key])) { if (seenReferences.has(subset[key])) return equals(object[key], subset[key], filteredCustomTesters); seenReferences.set(subset[key], true); } const result = object != null && hasPropertyInObject(object, key) && equals(object[key], subset[key], [ ...filteredCustomTesters, subsetEqualityWithContext(seenReferences), ]); // The main goal of using seenReference is to avoid circular node on tree. // It will only happen within a parent and its child, not a node and nodes next to it (same level) // We should keep the reference for a parent and its child only // Thus we should delete the reference immediately so that it doesn't interfere // other nodes within the same level on tree. seenReferences.delete(subset[key]); return result; }); };
// subsetEquality needs to keep track of the references
https://github.com/awslabs/llrt/blob/eed8301c1d71208fbd962efc566d29c96bab50fb/llrt_core/src/modules/js/@llrt/expect/jest-utils.ts#L445-L472
eed8301c1d71208fbd962efc566d29c96bab50fb
llrt
github_2023
awslabs
typescript
spawnAndCollectOutput
const spawnAndCollectOutput = (deniedUrl: URL, env: Record<string, string>) => { return new Promise<{ stdout: string; stderr: string }>((resolve, reject) => { const proc = spawn( process.argv[0], [ "-e", `fetch("${deniedUrl}").catch(console.error).then(() => fetch("${url}")).then(() => console.log("OK"))`, ], { env: { ...TEST_ENV, ...env, }, } ); let stdout = ""; let stderr = ""; proc.stderr.on("data", (data) => { stderr += data.toString(); }); proc.stdout.on("data", (data) => { stdout += data.toString(); }); proc.on("close", () => { resolve({ stdout, stderr }); }); proc.on("error", reject); }); };
// Helper function to spawn process and collect output
https://github.com/awslabs/llrt/blob/eed8301c1d71208fbd962efc566d29c96bab50fb/tests/unit/fetch.test.ts#L12-L42
eed8301c1d71208fbd962efc566d29c96bab50fb
llrt
github_2023
awslabs
typescript
calculateRelativeDepth
function calculateRelativeDepth(from: string, to: string) { const fromParts = path.resolve(from).split("/"); const toParts = path.resolve(to).split("/"); //find the first index where the paths differ let i = 0; while ( i < fromParts.length && i < toParts.length && fromParts[i] === toParts[i] ) { i++; } //calculate how many '../' are needed from "from" to reach common base directory const upLevels = fromParts.length - i; const downPath = toParts.slice(i).join("/"); //return the correct number of '../' segments followed by the remaining "to" path return `${"../".repeat(upLevels)}${downPath}`; }
//path.relative depends on cwd if any argument is relative
https://github.com/awslabs/llrt/blob/eed8301c1d71208fbd962efc566d29c96bab50fb/tests/unit/path.unix.test.ts#L6-L26
eed8301c1d71208fbd962efc566d29c96bab50fb
midday
github_2023
midday-ai
typescript
main
async function main() { const documents = await getInstitutions(); // await typesense.collections("institutions").delete(); try { // await typesense.collections().create(schema); await typesense .collections("institutions") .documents() .import(documents, { action: "upsert" }); } catch (error) { // @ts-ignore console.log(error.importResults); } }
// const schema = {
https://github.com/midday-ai/midday/blob/ffc2a8a8fe9663916b11b782ad9d4fa1301e0374/apps/engine/tasks/import.ts#L46-L61
ffc2a8a8fe9663916b11b782ad9d4fa1301e0374
midday
github_2023
midday-ai
typescript
getTranslation
const getTranslation = (key: string, params?: TranslationParams) => { const translationSet = translations(safeLocale, params); if (!translationSet || !(key in translationSet)) { return key; // Fallback to key if translation missing } return translationSet[key]; };
// Get translations for the locale
https://github.com/midday-ai/midday/blob/ffc2a8a8fe9663916b11b782ad9d4fa1301e0374/packages/email/locales/index.ts#L14-L22
ffc2a8a8fe9663916b11b782ad9d4fa1301e0374
midday
github_2023
midday-ai
typescript
doSearchSync
const doSearchSync = () => { const res = onSearchSync?.(debouncedSearchTerm); setOptions(transToGroupOption(res || [], groupBy)); };
/** sync search */
https://github.com/midday-ai/midday/blob/ffc2a8a8fe9663916b11b782ad9d4fa1301e0374/packages/ui/src/components/multiple-selector.tsx#L313-L316
ffc2a8a8fe9663916b11b782ad9d4fa1301e0374
midday
github_2023
midday-ai
typescript
doSearch
const doSearch = async () => { setIsLoading(true); const res = await onSearch?.(debouncedSearchTerm); setOptions(transToGroupOption(res || [], groupBy)); setIsLoading(false); };
/** async search */
https://github.com/midday-ai/midday/blob/ffc2a8a8fe9663916b11b782ad9d4fa1301e0374/packages/ui/src/components/multiple-selector.tsx#L337-L342
ffc2a8a8fe9663916b11b782ad9d4fa1301e0374
winterjs
github_2023
wasmerio
typescript
AsyncLocalStorage.run
run(store: any, callback: any, ...args: any[]): any { const frame = AsyncContextFrame.create( null, new StorageEntry(this.#key, store), ); Scope.enter(frame); let res; try { res = callback(...args); } finally { Scope.exit(); } return res; }
// deno-lint-ignore no-explicit-any
https://github.com/wasmerio/winterjs/blob/cf3c9aeb77504a2ac9092648d1eb3f96c7f77c5a/src/builtins/internal_js_modules/node/async_hooks.ts#L291-L304
cf3c9aeb77504a2ac9092648d1eb3f96c7f77c5a
winterjs
github_2023
wasmerio
typescript
AsyncLocalStorage.exit
exit(callback: (...args: unknown[]) => any, ...args: any[]): any { return this.run(undefined, callback, args); }
// deno-lint-ignore no-explicit-any
https://github.com/wasmerio/winterjs/blob/cf3c9aeb77504a2ac9092648d1eb3f96c7f77c5a/src/builtins/internal_js_modules/node/async_hooks.ts#L307-L309
cf3c9aeb77504a2ac9092648d1eb3f96c7f77c5a
winterjs
github_2023
wasmerio
typescript
AsyncLocalStorage.getStore
getStore(): any { const currentFrame = AsyncContextFrame.current(); return currentFrame.get(this.#key); }
// deno-lint-ignore no-explicit-any
https://github.com/wasmerio/winterjs/blob/cf3c9aeb77504a2ac9092648d1eb3f96c7f77c5a/src/builtins/internal_js_modules/node/async_hooks.ts#L312-L315
cf3c9aeb77504a2ac9092648d1eb3f96c7f77c5a
winterjs
github_2023
wasmerio
typescript
Event.stopPropagation
stopPropagation(): void { this.stopPropagationFlag = true; }
/** * The stopPropagation() method steps are to set this’s stop propagation flag. */
https://github.com/wasmerio/winterjs/blob/cf3c9aeb77504a2ac9092648d1eb3f96c7f77c5a/src/builtins/js_globals/event.ts#L199-L201
cf3c9aeb77504a2ac9092648d1eb3f96c7f77c5a
winterjs
github_2023
wasmerio
typescript
Event.cancelBubble
get cancelBubble(): boolean { return !!this.stopPropagationFlag; }
/** * The cancelBubble getter steps are to return true if this’s stop propagation flag is set; otherwise false. */
https://github.com/wasmerio/winterjs/blob/cf3c9aeb77504a2ac9092648d1eb3f96c7f77c5a/src/builtins/js_globals/event.ts#L206-L208
cf3c9aeb77504a2ac9092648d1eb3f96c7f77c5a
winterjs
github_2023
wasmerio
typescript
Event.cancelBubble
set cancelBubble(value) { if (value) this.stopPropagationFlag = true; }
/** * The cancelBubble setter steps are to set this’s stop propagation flag if the given value is true; otherwise do nothing. */
https://github.com/wasmerio/winterjs/blob/cf3c9aeb77504a2ac9092648d1eb3f96c7f77c5a/src/builtins/js_globals/event.ts#L213-L215
cf3c9aeb77504a2ac9092648d1eb3f96c7f77c5a
winterjs
github_2023
wasmerio
typescript
Event.stopImmediatePropagation
stopImmediatePropagation(): void { this.stopImmediatePropagationFlag = true; this.stopPropagationFlag = true; }
/** * The stopImmediatePropagation() method steps are to set this’s stop propagation flag and this’s stop immediate propagation flag. */
https://github.com/wasmerio/winterjs/blob/cf3c9aeb77504a2ac9092648d1eb3f96c7f77c5a/src/builtins/js_globals/event.ts#L220-L223
cf3c9aeb77504a2ac9092648d1eb3f96c7f77c5a
winterjs
github_2023
wasmerio
typescript
Event.returnValue
get returnValue(): boolean { return !!!this.canceledFlag; }
/** * The returnValue getter steps are to return false if this’s canceled flag is set; otherwise true. */
https://github.com/wasmerio/winterjs/blob/cf3c9aeb77504a2ac9092648d1eb3f96c7f77c5a/src/builtins/js_globals/event.ts#L228-L230
cf3c9aeb77504a2ac9092648d1eb3f96c7f77c5a
winterjs
github_2023
wasmerio
typescript
Event.returnValue
set returnValue(value) { if (!value) this.canceledFlag = true; }
/** * The returnValue setter steps are to set the canceled flag with this if the given value is false; otherwise do nothing. */
https://github.com/wasmerio/winterjs/blob/cf3c9aeb77504a2ac9092648d1eb3f96c7f77c5a/src/builtins/js_globals/event.ts#L235-L237
cf3c9aeb77504a2ac9092648d1eb3f96c7f77c5a
winterjs
github_2023
wasmerio
typescript
Event.preventDefault
preventDefault(): void { this.canceledFlag = true; }
/** * The preventDefault() method steps are to set the canceled flag with this. */
https://github.com/wasmerio/winterjs/blob/cf3c9aeb77504a2ac9092648d1eb3f96c7f77c5a/src/builtins/js_globals/event.ts#L242-L244
cf3c9aeb77504a2ac9092648d1eb3f96c7f77c5a
winterjs
github_2023
wasmerio
typescript
Event.dispatched
get dispatched(): boolean { return this.dispatchFlag; }
// other setter/getter
https://github.com/wasmerio/winterjs/blob/cf3c9aeb77504a2ac9092648d1eb3f96c7f77c5a/src/builtins/js_globals/event.ts#L257-L259
cf3c9aeb77504a2ac9092648d1eb3f96c7f77c5a
winterjs
github_2023
wasmerio
typescript
dispatch
function dispatch(eventTarget: EventTarget, event: Event): boolean { // Tentative implementation that just calls the callback eventTarget.eventTargetData.listeners[event.type].forEach( (listener: any) => { listener.callback(event); } ); return true; }
// TODO: implement according to https://dom.spec.whatwg.org/#concept-event-dispatch
https://github.com/wasmerio/winterjs/blob/cf3c9aeb77504a2ac9092648d1eb3f96c7f77c5a/src/builtins/js_globals/event.ts#L425-L433
cf3c9aeb77504a2ac9092648d1eb3f96c7f77c5a
tiny-engine
github_2023
opentiny
typescript
compileFile
const compileFile = (file: IParsedFileItem): Omit<compiledItem, 'blobURL'> => { const descriptor = file.compilerParseResult.descriptor // 编译 script const [compiledScript, bindings] = compileBlockScript(descriptor, file.fileName) let componentCode = `${compiledScript}` // 编译 template if (!descriptor.scriptSetup && descriptor.template) { const { code: compiledTemplate } = compileBlockTemplate(descriptor, file.fileName, bindings) componentCode += `\n ${compiledTemplate} \n ${DEFAULT_COMPONENT_NAME}.render = render` } const hasScoped = descriptor.styles.some((styleItem) => styleItem.scoped) if (hasScoped) { componentCode += `\n${DEFAULT_COMPONENT_NAME}.__scopeId='data-v-${file.fileName}'` } // 编译 style const styleString = compileBlockStyle(descriptor, file.fileName) return { js: `${componentCode}\nexport default ${DEFAULT_COMPONENT_NAME}`, style: styleString } }
// 依次构建 script、template、style,然后组装成 import
https://github.com/opentiny/tiny-engine/blob/66068fb7265ecfc750a4b72ac83c749e6ff6c423/packages/block-compiler/src/index.ts#L163-L190
66068fb7265ecfc750a4b72ac83c749e6ff6c423
tiny-engine
github_2023
opentiny
typescript
parseImportedFiles
const parseImportedFiles = (descriptor: SFCDescriptor): string[] => { let scriptContent = '' if (descriptor.script) { scriptContent = descriptor.script.content } else if (descriptor.scriptSetup) { scriptContent = descriptor.scriptSetup.content } if (!scriptContent) { return [] } const ast = babelParse(scriptContent, { sourceFilename: descriptor.filename, sourceType: 'module', plugins: ['jsx'] }) .program.body const res: string[] = [] for (const node of ast) { if (node.type === 'ImportDeclaration') { const source = node.source.value // 相对路径依赖,区块嵌套的场景 if (source.startsWith('./')) { res.push(node.source.value) } } } return res }
// 解析依赖的文件
https://github.com/opentiny/tiny-engine/blob/66068fb7265ecfc750a4b72ac83c749e6ff6c423/packages/block-compiler/src/index.ts#L193-L222
66068fb7265ecfc750a4b72ac83c749e6ff6c423
tiny-engine
github_2023
opentiny
typescript
parseFunctionString
const parseFunctionString = (fnStr) => { const fnRegexp = /(async)?.*?(\w+) *\(([\s\S]*?)\) *\{([\s\S]*)\}/ const result = fnRegexp.exec(fnStr) if (result) { return { type: result[1] || '', name: result[2], params: result[3] .split(',') .map((item) => item.trim()) .filter((item) => Boolean(item)), body: result[4] } } return null }
// 解析函数字符串结构
https://github.com/opentiny/tiny-engine/blob/66068fb7265ecfc750a4b72ac83c749e6ff6c423/packages/canvas/render/src/data-function/parser.ts#L112-L127
66068fb7265ecfc750a4b72ac83c749e6ff6c423
tiny-engine
github_2023
opentiny
typescript
parseJSXFunction
const parseJSXFunction = (data, _scope, ctx) => { try { const newValue = transformJSX(data.value) const fnInfo = parseFunctionString(newValue) if (!fnInfo) throw Error('函数解析失败,请检查格式。示例:function fnName() { }') return newFn(...fnInfo.params, fnInfo.body).bind({ ...ctx, getComponent }) } catch (error) { globalNotify({ type: 'warning', title: '函数声明解析报错', message: error?.message || '函数声明解析报错,请检查语法' }) return newFn() } }
// 解析JSX字符串为可执行函数
https://github.com/opentiny/tiny-engine/blob/66068fb7265ecfc750a4b72ac83c749e6ff6c423/packages/canvas/render/src/data-function/parser.ts#L130-L149
66068fb7265ecfc750a4b72ac83c749e6ff6c423
tiny-engine
github_2023
opentiny
typescript
loadBlockComponent
const loadBlockComponent = async (name: string) => { try { if (blockComponentsBlobUrlMap.has(name)) { return import(/* @vite-ignore */ blockComponentsBlobUrlMap.get(name)) } const blocksBlob = (await getController().getBlockByName(name)) as Array<{ blobURL: string; style: string }> for (const [fileName, value] of Object.entries(blocksBlob)) { blockComponentsBlobUrlMap.set(fileName, value.blobURL) if (!value.style) { continue } // 注册 CSS,以区块为维度 const stylesheet = document.querySelector(`#${fileName}`) if (stylesheet) { stylesheet.innerHTML = value.style } else { const newStylesheet = document.createElement('style') newStylesheet.innerHTML = value.style newStylesheet.setAttribute('id', fileName) document.head.appendChild(newStylesheet) } } return import(/* @vite-ignore */ blockComponentsBlobUrlMap.get(name)) } catch (error) { // 加载错误提示 return h(BlockLoadError, { name }) } }
// TODO: 这里的全局 getter 方法名,可以做成配置化
https://github.com/opentiny/tiny-engine/blob/66068fb7265ecfc750a4b72ac83c749e6ff6c423/packages/canvas/render/src/material-function/material-getter.ts#L55-L88
66068fb7265ecfc750a4b72ac83c749e6ff6c423
twitter-web-exporter
github_2023
prinsss
typescript
toggleControlPanel
const toggleControlPanel = () => { showControlPanel.value = !showControlPanel.value; options.set('showControlPanel', showControlPanel.value); };
// Remember the last state of the control panel.
https://github.com/prinsss/twitter-web-exporter/blob/cf61756ee07b97c244414785a894e5392fdc9c29/src/core/app.tsx#L25-L28
cf61756ee07b97c244414785a894e5392fdc9c29
twitter-web-exporter
github_2023
prinsss
typescript
DatabaseManager.tweets
private tweets() { return this.db.table<Tweet>('tweets'); }
/* |-------------------------------------------------------------------------- | Type-Safe Table Accessors |-------------------------------------------------------------------------- */
https://github.com/prinsss/twitter-web-exporter/blob/cf61756ee07b97c244414785a894e5392fdc9c29/src/core/database/manager.ts#L28-L30
cf61756ee07b97c244414785a894e5392fdc9c29
twitter-web-exporter
github_2023
prinsss
typescript
DatabaseManager.extGetCaptures
async extGetCaptures(extName: string) { return this.captures().where('extension').equals(extName).toArray().catch(this.logError); }
/* |-------------------------------------------------------------------------- | Read Methods for Extensions |-------------------------------------------------------------------------- */
https://github.com/prinsss/twitter-web-exporter/blob/cf61756ee07b97c244414785a894e5392fdc9c29/src/core/database/manager.ts#L46-L48
cf61756ee07b97c244414785a894e5392fdc9c29
twitter-web-exporter
github_2023
prinsss
typescript
DatabaseManager.extAddTweets
async extAddTweets(extName: string, tweets: Tweet[]) { await this.upsertTweets(tweets); await this.upsertCaptures( tweets.map((tweet) => ({ id: `${extName}-${tweet.rest_id}`, extension: extName, type: ExtensionType.TWEET, data_key: tweet.rest_id, created_at: Date.now(), })), ); }
/* |-------------------------------------------------------------------------- | Write Methods for Extensions |-------------------------------------------------------------------------- */
https://github.com/prinsss/twitter-web-exporter/blob/cf61756ee07b97c244414785a894e5392fdc9c29/src/core/database/manager.ts#L88-L99
cf61756ee07b97c244414785a894e5392fdc9c29
twitter-web-exporter
github_2023
prinsss
typescript
DatabaseManager.extClearCaptures
async extClearCaptures(extName: string) { const captures = await this.extGetCaptures(extName); if (!captures) { return; } return this.captures().bulkDelete(captures.map((capture) => capture.id)); }
/* |-------------------------------------------------------------------------- | Delete Methods for Extensions |-------------------------------------------------------------------------- */
https://github.com/prinsss/twitter-web-exporter/blob/cf61756ee07b97c244414785a894e5392fdc9c29/src/core/database/manager.ts#L120-L126
cf61756ee07b97c244414785a894e5392fdc9c29
twitter-web-exporter
github_2023
prinsss
typescript
DatabaseManager.export
async export() { return exportDB(this.db).catch(this.logError); }
/* |-------------------------------------------------------------------------- | Export and Import Methods |-------------------------------------------------------------------------- */
https://github.com/prinsss/twitter-web-exporter/blob/cf61756ee07b97c244414785a894e5392fdc9c29/src/core/database/manager.ts#L134-L136
cf61756ee07b97c244414785a894e5392fdc9c29
twitter-web-exporter
github_2023
prinsss
typescript
DatabaseManager.upsertTweets
async upsertTweets(tweets: Tweet[]) { return this.db .transaction('rw', this.tweets(), () => { const data: Tweet[] = tweets.map((tweet) => ({ ...tweet, twe_private_fields: { created_at: +parseTwitterDateTime(tweet.legacy.created_at), updated_at: Date.now(), media_count: extractTweetMedia(tweet).length, }, })); return this.tweets().bulkPut(data); }) .catch(this.logError); }
/* |-------------------------------------------------------------------------- | Common Methods |-------------------------------------------------------------------------- */
https://github.com/prinsss/twitter-web-exporter/blob/cf61756ee07b97c244414785a894e5392fdc9c29/src/core/database/manager.ts#L168-L183
cf61756ee07b97c244414785a894e5392fdc9c29
twitter-web-exporter
github_2023
prinsss
typescript
DatabaseManager.init
async init() { // Indexes for the "tweets" table. const tweetIndexPaths: KeyPaths<Tweet>[] = [ 'rest_id', 'twe_private_fields.created_at', 'twe_private_fields.updated_at', 'twe_private_fields.media_count', 'core.user_results.result.legacy.screen_name', 'legacy.favorite_count', 'legacy.retweet_count', 'legacy.bookmark_count', 'legacy.quote_count', 'legacy.reply_count', 'views.count', 'legacy.favorited', 'legacy.retweeted', 'legacy.bookmarked', ]; // Indexes for the "users" table. const userIndexPaths: KeyPaths<User>[] = [ 'rest_id', 'twe_private_fields.created_at', 'twe_private_fields.updated_at', 'legacy.screen_name', 'legacy.followers_count', // 'legacy.friends_count', 'legacy.statuses_count', 'legacy.favourites_count', 'legacy.listed_count', 'legacy.verified_type', 'is_blue_verified', 'legacy.following', 'legacy.followed_by', ]; // Indexes for the "captures" table. const captureIndexPaths: KeyPaths<Capture>[] = ['id', 'extension', 'type', 'created_at']; // Take care of database schemas and versioning. // See: https://dexie.org/docs/Tutorial/Design#database-versioning try { this.db .version(DB_VERSION) .stores({ tweets: tweetIndexPaths.join(','), users: userIndexPaths.join(','), captures: captureIndexPaths.join(','), }) .upgrade(async () => { logger.info('Database upgraded'); }); await this.db.open(); logger.info('Database connected'); } catch (error) { this.logError(error); } }
/* |-------------------------------------------------------------------------- | Migrations |-------------------------------------------------------------------------- */
https://github.com/prinsss/twitter-web-exporter/blob/cf61756ee07b97c244414785a894e5392fdc9c29/src/core/database/manager.ts#L235-L293
cf61756ee07b97c244414785a894e5392fdc9c29
twitter-web-exporter
github_2023
prinsss
typescript
DatabaseManager.logError
logError(error: unknown) { logger.error(`Database Error: ${(error as Error).message}`, error); }
/* |-------------------------------------------------------------------------- | Loggers |-------------------------------------------------------------------------- */
https://github.com/prinsss/twitter-web-exporter/blob/cf61756ee07b97c244414785a894e5392fdc9c29/src/core/database/manager.ts#L301-L303
cf61756ee07b97c244414785a894e5392fdc9c29
twitter-web-exporter
github_2023
prinsss
typescript
ExtensionManager.add
public add(ctor: ExtensionConstructor) { try { logger.debug(`Register new extension: ${ctor.name}`); const instance = new ctor(this); this.extensions.set(instance.name, instance); } catch (err) { logger.error(`Failed to register extension: ${ctor.name}`, err); } }
/** * Register and instantiate a new extension. * * @param ctor Extension constructor. */
https://github.com/prinsss/twitter-web-exporter/blob/cf61756ee07b97c244414785a894e5392fdc9c29/src/core/extensions/manager.ts#L46-L54
cf61756ee07b97c244414785a894e5392fdc9c29
twitter-web-exporter
github_2023
prinsss
typescript
ExtensionManager.start
public start() { for (const ext of this.extensions.values()) { if (this.disabledExtensions.has(ext.name)) { this.disable(ext.name); } else { this.enable(ext.name); } } }
/** * Set up all enabled extensions. */
https://github.com/prinsss/twitter-web-exporter/blob/cf61756ee07b97c244414785a894e5392fdc9c29/src/core/extensions/manager.ts#L59-L67
cf61756ee07b97c244414785a894e5392fdc9c29
twitter-web-exporter
github_2023
prinsss
typescript
ExtensionManager.installHttpHooks
private installHttpHooks() { // eslint-disable-next-line @typescript-eslint/no-this-alias const manager = this; globalObject.XMLHttpRequest.prototype.open = function (method: string, url: string) { if (manager.debugEnabled) { logger.debug(`XHR initialized`, { method, url }); } // When the request is done, we call all registered interceptors. this.addEventListener('load', () => { if (manager.debugEnabled) { logger.debug(`XHR finished`, { method, url }); } // Run current enabled interceptors. manager .getExtensions() .filter((ext) => ext.enabled) .forEach((ext) => { const func = ext.intercept(); if (func) { func({ method, url }, this, ext); } }); }); // @ts-expect-error it's fine. // eslint-disable-next-line prefer-rest-params xhrOpen.apply(this, arguments); }; logger.info('Hooked into XMLHttpRequest'); // Check for current execution context. // The `webpackChunk_twitter_responsive_web` is injected by the Twitter website. // See: https://violentmonkey.github.io/posts/inject-into-context/ setTimeout(() => { if (!('webpackChunk_twitter_responsive_web' in globalObject)) { logger.error( 'Error: Wrong execution context detected.\n ' + 'This script needs to be injected into "page" context rather than "content" context.\n ' + 'The XMLHttpRequest hook will not work properly.\n ' + 'See: https://github.com/prinsss/twitter-web-exporter/issues/19', ); } }, 1000); }
/** * Here we hooks the browser's XHR method to intercept Twitter's Web API calls. * This need to be done before any XHR request is made. */
https://github.com/prinsss/twitter-web-exporter/blob/cf61756ee07b97c244414785a894e5392fdc9c29/src/core/extensions/manager.ts#L109-L156
cf61756ee07b97c244414785a894e5392fdc9c29
twitter-web-exporter
github_2023
prinsss
typescript
AppOptionsManager.loadAppOptions
private loadAppOptions() { this.appOptions = { ...this.appOptions, ...safeJSONParse(localStorage.getItem(LOCAL_STORAGE_KEY) || '{}'), }; const oldVersion = this.appOptions.version ?? ''; const newVersion = DEFAULT_APP_OPTIONS.version ?? ''; // Migrate from v1.0 to v1.1. if (newVersion.startsWith('1.1') && oldVersion.startsWith('1.0')) { this.appOptions.disabledExtensions = [ ...(this.appOptions.disabledExtensions ?? []), 'HomeTimelineModule', 'ListTimelineModule', ]; logger.info(`App options migrated from v${oldVersion} to v${newVersion}`); setTimeout(() => this.saveAppOptions(), 0); } this.previous = { ...this.appOptions }; logger.info('App options loaded', this.appOptions); this.signal.value++; }
/** * Read app options from local storage. */
https://github.com/prinsss/twitter-web-exporter/blob/cf61756ee07b97c244414785a894e5392fdc9c29/src/core/options/manager.ts#L79-L102
cf61756ee07b97c244414785a894e5392fdc9c29
twitter-web-exporter
github_2023
prinsss
typescript
AppOptionsManager.saveAppOptions
private saveAppOptions() { const oldValue = this.previous; const newValue = { ...this.appOptions, version: packageJson.version, }; if (isEqual(oldValue, newValue)) { return; } this.appOptions = newValue; localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(this.appOptions)); this.previous = { ...this.appOptions }; logger.debug('App options saved', this.appOptions); this.signal.value++; }
/** * Write app options to local storage. */
https://github.com/prinsss/twitter-web-exporter/blob/cf61756ee07b97c244414785a894e5392fdc9c29/src/core/options/manager.ts#L107-L124
cf61756ee07b97c244414785a894e5392fdc9c29
twitter-web-exporter
github_2023
prinsss
typescript
Logger.writeBuffer
private writeBuffer(log: LogLine) { this.buffer.push(log); if (this.bufferTimer) { clearTimeout(this.bufferTimer); } this.bufferTimer = window.setTimeout(() => { this.bufferTimer = null; this.flushBuffer(); }, 0); }
/** * Buffer log lines to reduce the number of signal and DOM updates. */
https://github.com/prinsss/twitter-web-exporter/blob/cf61756ee07b97c244414785a894e5392fdc9c29/src/utils/logger.ts#L53-L64
cf61756ee07b97c244414785a894e5392fdc9c29
twitter-web-exporter
github_2023
prinsss
typescript
Logger.flushBuffer
private flushBuffer() { logLinesSignal.value = [...logLinesSignal.value, ...this.buffer]; this.buffer = []; }
/** * Flush buffered log lines and update the UI. */
https://github.com/prinsss/twitter-web-exporter/blob/cf61756ee07b97c244414785a894e5392fdc9c29/src/utils/logger.ts#L69-L72
cf61756ee07b97c244414785a894e5392fdc9c29
twitter-web-exporter
github_2023
prinsss
typescript
createWriter
function createWriter(underlyingSource) { const files = Object.create(null); const filenames = []; const encoder = new TextEncoder(); let offset = 0; let activeZipIndex = 0; let ctrl; let activeZipObject, closed; function next() { activeZipIndex++; activeZipObject = files[filenames[activeZipIndex]]; if (activeZipObject) processNextChunk(); else if (closed) closeZip(); } var zipWriter = { enqueue(fileLike) { if (closed) throw new TypeError( 'Cannot enqueue a chunk into a readable stream that is closed or has been requested to be closed', ); let name = fileLike.name.trim(); const date = new Date( typeof fileLike.lastModified === 'undefined' ? Date.now() : fileLike.lastModified, ); if (fileLike.directory && !name.endsWith('/')) name += '/'; if (files[name]) throw new Error('File already exists.'); const nameBuf = encoder.encode(name); filenames.push(name); const zipObject = (files[name] = { level: 0, ctrl, directory: !!fileLike.directory, nameBuf, comment: encoder.encode(fileLike.comment || ''), compressedLength: 0, uncompressedLength: 0, writeHeader() { var header = getDataHelper(26); var data = getDataHelper(30 + nameBuf.length); zipObject.offset = offset; zipObject.header = header; if (zipObject.level !== 0 && !zipObject.directory) { header.view.setUint16(4, 0x0800); } header.view.setUint32(0, 0x14000808); header.view.setUint16( 6, (((date.getHours() << 6) | date.getMinutes()) << 5) | (date.getSeconds() / 2), true, ); header.view.setUint16( 8, ((((date.getFullYear() - 1980) << 4) | (date.getMonth() + 1)) << 5) | date.getDate(), true, ); header.view.setUint16(22, nameBuf.length, true); data.view.setUint32(0, 0x504b0304); data.array.set(header.array, 4); data.array.set(nameBuf, 30); offset += data.array.length; ctrl.enqueue(data.array); }, writeFooter() { var footer = getDataHelper(16); footer.view.setUint32(0, 0x504b0708); if (zipObject.crc) { zipObject.header.view.setUint32(10, zipObject.crc.get(), true); zipObject.header.view.setUint32(14, zipObject.compressedLength, true); zipObject.header.view.setUint32(18, zipObject.uncompressedLength, true); footer.view.setUint32(4, zipObject.crc.get(), true); footer.view.setUint32(8, zipObject.compressedLength, true); footer.view.setUint32(12, zipObject.uncompressedLength, true); } ctrl.enqueue(footer.array); offset += zipObject.compressedLength + 16; next(); }, fileLike, }); if (!activeZipObject) { activeZipObject = zipObject; processNextChunk(); } }, close() { if (closed) throw new TypeError( 'Cannot close a readable stream that has already been requested to be closed', ); if (!activeZipObject) closeZip(); closed = true; }, }; function closeZip() { var length = 0; var index = 0; var indexFilename, file; for (indexFilename = 0; indexFilename < filenames.length; indexFilename++) { file = files[filenames[indexFilename]]; length += 46 + file.nameBuf.length + file.comment.length; } const data = getDataHelper(length + 22); for (indexFilename = 0; indexFilename < filenames.length; indexFilename++) { file = files[filenames[indexFilename]]; data.view.setUint32(index, 0x504b0102); data.view.setUint16(index + 4, 0x1400); data.array.set(file.header.array, index + 6); data.view.setUint16(index + 32, file.comment.length, true); if (file.directory) { data.view.setUint8(index + 38, 0x10); } data.view.setUint32(index + 42, file.offset, true); data.array.set(file.nameBuf, index + 46); data.array.set(file.comment, index + 46 + file.nameBuf.length); index += 46 + file.nameBuf.length + file.comment.length; } data.view.setUint32(index, 0x504b0506); data.view.setUint16(index + 8, filenames.length, true); data.view.setUint16(index + 10, filenames.length, true); data.view.setUint32(index + 12, length, true); data.view.setUint32(index + 16, offset, true); ctrl.enqueue(data.array); ctrl.close(); } function processNextChunk() { if (!activeZipObject) return; if (activeZipObject.directory) return activeZipObject.writeFooter(activeZipObject.writeHeader()); if (activeZipObject.reader) return pump(activeZipObject); if (activeZipObject.fileLike.stream) { activeZipObject.crc = new Crc32(); activeZipObject.reader = activeZipObject.fileLike.stream().getReader(); activeZipObject.writeHeader(); } else next(); } return new ReadableStream({ start: (c) => { ctrl = c; if (underlyingSource.start) Promise.resolve(underlyingSource.start(zipWriter)); }, pull() { return ( processNextChunk() || (underlyingSource.pull && Promise.resolve(underlyingSource.pull(zipWriter))) ); }, }); }
/** * [createWriter description] * @param {Object} underlyingSource [description] * @return {Boolean} [description] */
https://github.com/prinsss/twitter-web-exporter/blob/cf61756ee07b97c244414785a894e5392fdc9c29/src/utils/zip-stream.ts#L66-L225
cf61756ee07b97c244414785a894e5392fdc9c29
full-stack-fastapi-mongodb
github_2023
mongodb-labs
typescript
submit
async function submit(values: any) { if (values.email) { await dispatch(refreshTokens()); const data: IUserProfileCreate = { email: values.email, password: generateUUID(), fullName: values.fullName ? values.fullName : "", }; try { const res = await apiAuth.createUserProfile(accessToken, data); if (!res.id) throw "Error"; dispatch( addNotice({ title: "User created", content: "An email has been sent to the user with their new login details.", }), ); } catch { dispatch( addNotice({ title: "Update error", content: "Invalid request.", icon: "error", }), ); } } }
// @ts-ignore
https://github.com/mongodb-labs/full-stack-fastapi-mongodb/blob/5ee04c83d0a3265f1ed3bb9104e2de724d8401c0/{{cookiecutter.project_slug}}/frontend/app/components/moderation/CreateUser.tsx#L20-L48
5ee04c83d0a3265f1ed3bb9104e2de724d8401c0
full-stack-fastapi-mongodb
github_2023
mongodb-labs
typescript
renderError
const renderError = (type: LiteralUnion<keyof RegisterOptions, string>) => { const style = "absolute left-5 top-5 translate-y-full w-48 px-2 py-1 bg-gray-700 rounded-lg text-center text-white text-sm after:content-[''] after:absolute after:left-1/2 after:bottom-[100%] after:-translate-x-1/2 after:border-8 after:border-x-transparent after:border-t-transparent after:border-b-gray-700"; switch (type) { case "required": return <div className={style}>This field is required.</div>; case "minLength" || "maxLength": return ( <div className={style}> Your password must be between 8 and 64 characters long. </div> ); default: return <></>; } };
//@ts-ignore
https://github.com/mongodb-labs/full-stack-fastapi-mongodb/blob/5ee04c83d0a3265f1ed3bb9104e2de724d8401c0/{{cookiecutter.project_slug}}/frontend/app/components/settings/Profile.tsx#L15-L30
5ee04c83d0a3265f1ed3bb9104e2de724d8401c0
full-stack-fastapi-mongodb
github_2023
mongodb-labs
typescript
submit
async function submit(values: any) { let newProfile = {} as IUserProfileUpdate; if ( (!currentProfile.password && !values.original) || (currentProfile.password && values.original) ) { if (values.original) newProfile.original = values.original; if (values.email) { newProfile.email = values.email; if (values.fullName) newProfile.fullName = values.fullName; await dispatch(updateUserProfile(newProfile)); resetProfile(); } } }
// eslint-disable-line react-hooks/exhaustive-deps
https://github.com/mongodb-labs/full-stack-fastapi-mongodb/blob/5ee04c83d0a3265f1ed3bb9104e2de724d8401c0/{{cookiecutter.project_slug}}/frontend/app/components/settings/Profile.tsx#L65-L79
5ee04c83d0a3265f1ed3bb9104e2de724d8401c0
full-stack-fastapi-mongodb
github_2023
mongodb-labs
typescript
removeFingerprint
const removeFingerprint = async () => { await dispatch(logout()); };
// eslint-disable-line react-hooks/exhaustive-deps
https://github.com/mongodb-labs/full-stack-fastapi-mongodb/blob/5ee04c83d0a3265f1ed3bb9104e2de724d8401c0/{{cookiecutter.project_slug}}/frontend/app/magic/page.tsx#L35-L37
5ee04c83d0a3265f1ed3bb9104e2de724d8401c0
full-stack-fastapi-mongodb
github_2023
mongodb-labs
typescript
renderError
const renderError = (type: LiteralUnion<keyof RegisterOptions, string>) => { const style = "absolute left-5 top-5 translate-y-full w-48 px-2 py-1 bg-gray-700 rounded-lg text-center text-white text-sm after:content-[''] after:absolute after:left-1/2 after:bottom-[100%] after:-translate-x-1/2 after:border-8 after:border-x-transparent after:border-t-transparent after:border-b-gray-700"; switch (type) { case "required": return <div className={style}>This field is required.</div>; case "minLength" || "maxLength": return ( <div className={style}> Your password must be between 8 and 64 characters long. </div> ); case "match": return <div className={style}>Your passwords do not match.</div>; default: return <></>; } };
//@ts-ignore
https://github.com/mongodb-labs/full-stack-fastapi-mongodb/blob/5ee04c83d0a3265f1ed3bb9104e2de724d8401c0/{{cookiecutter.project_slug}}/frontend/app/reset-password/page.tsx#L18-L35
5ee04c83d0a3265f1ed3bb9104e2de724d8401c0
starter-kit
github_2023
Hashnode
typescript
CustomImage
function CustomImage(props: Props) { const { originalSrc, ...originalRestOfTheProps } = props; const { alt = '', loader, quality, priority, loading, unoptimized, objectFit, objectPosition, src, width, height, layout, placeholder, blurDataURL, ...restOfTheProps } = originalRestOfTheProps; // Destructured next/image props on purpose, so that unwanted props don't end up in <img /> if (!originalSrc) { return null; } const isGif = originalSrc.substr(-4) === '.gif'; const isHashnodeCDNImage = src.indexOf('cdn.hashnode.com') > -1; if (isGif || !isHashnodeCDNImage) { // restOfTheProps will contain all props excluding the next/image props return <img {...restOfTheProps} alt={alt} src={src || originalSrc} />; }
/** * Conditionally renders native img for gifs and next/image for other types * @param props * @returns <img /> or <Image/> */
https://github.com/Hashnode/starter-kit/blob/b90275211c2cf594391b14e17771abb4837c5e84/packages/blog-starter-kit/themes/enterprise/components/custom-image.tsx#L17-L47
b90275211c2cf594391b14e17771abb4837c5e84
starter-kit
github_2023
Hashnode
typescript
ProgressiveImage.replaceBadImage
replaceBadImage = (e: any) => { // eslint-disable-next-line react/destructuring-assignment if (this.props.resize && this.props.resize.c !== 'face') { return; } e.target.onerror = null; e.target.src = DEFAULT_AVATAR; }
// TODO: Improve type
https://github.com/Hashnode/starter-kit/blob/b90275211c2cf594391b14e17771abb4837c5e84/packages/blog-starter-kit/themes/enterprise/components/progressive-image.tsx
b90275211c2cf594391b14e17771abb4837c5e84
starter-kit
github_2023
Hashnode
typescript
CustomImage
function CustomImage(props: Props) { const { originalSrc, ...originalRestOfTheProps } = props; const { alt = '', loader, quality, priority, loading, unoptimized, objectFit, objectPosition, src, width, height, layout, placeholder, blurDataURL, ...restOfTheProps } = originalRestOfTheProps; // Destructured next/image props on purpose, so that unwanted props don't end up in <img /> if (!originalSrc) { return null; } const isGif = originalSrc.substr(-4) === '.gif'; const isHashnodeCDNImage = src.indexOf('cdn.hashnode.com') > -1; if (isGif || !isHashnodeCDNImage) { // restOfTheProps will contain all props excluding the next/image props return <img {...restOfTheProps} alt={alt} src={src || originalSrc} />; }
/** * Conditionally renders native img for gifs and next/image for other types * @param props * @returns <img /> or <Image/> */
https://github.com/Hashnode/starter-kit/blob/b90275211c2cf594391b14e17771abb4837c5e84/packages/blog-starter-kit/themes/hashnode/components/custom-image.tsx#L17-L47
b90275211c2cf594391b14e17771abb4837c5e84
starter-kit
github_2023
Hashnode
typescript
ProgressiveImage.replaceBadImage
replaceBadImage = (e: any) => { // eslint-disable-next-line react/destructuring-assignment if (this.props.resize && this.props.resize.c !== 'face') { return; } e.target.onerror = null; e.target.src = DEFAULT_AVATAR; }
// TODO: Improve type
https://github.com/Hashnode/starter-kit/blob/b90275211c2cf594391b14e17771abb4837c5e84/packages/blog-starter-kit/themes/hashnode/components/progressive-image.tsx
b90275211c2cf594391b14e17771abb4837c5e84
starter-kit
github_2023
Hashnode
typescript
HNRequest.constructor
constructor(url: string, opts: any) { this.url = url; const { headers = {}, ...restOfTheOpts } = opts; this.requestObj = { method: 'GET', headers: { Accept: 'application/json', 'Content-Type': 'application/json', ...headers, }, ...restOfTheOpts, }; }
/** * @param url - Request url * @param opts - Object of options for fetch() */
https://github.com/Hashnode/starter-kit/blob/b90275211c2cf594391b14e17771abb4837c5e84/packages/utils/renderer/services/HNRequest.ts#L46-L58
b90275211c2cf594391b14e17771abb4837c5e84
starter-kit
github_2023
Hashnode
typescript
HNRequest.prepare
prepare = (opts: RequestOptions) => { const { headers, body, ...restOfTheOptions } = opts; this.requestObj = { ...headers, body: JSON.stringify(body), ...restOfTheOptions, }; }
/** * Makes the actual request and sets `rawResponse`. * You can use the `rawResponse` property of the instance * to handle the response manually * @returns void */
https://github.com/Hashnode/starter-kit/blob/b90275211c2cf594391b14e17771abb4837c5e84/packages/utils/renderer/services/HNRequest.ts
b90275211c2cf594391b14e17771abb4837c5e84
Theo-Docs
github_2023
Theo-Messi
typescript
foo
function foo() { // .. }
// #region snippet
https://github.com/Theo-Messi/Theo-Docs/blob/34cf16300929bcf5214698e2a5fe901f305feae1/content/code/cs.ts#L2-L4
34cf16300929bcf5214698e2a5fe901f305feae1
wireadmin
github_2023
wireadmin
typescript
wgConfExists
function wgConfExists(configId: number): boolean { const confPath = resolveConfigPath(configId); return fsAccess(confPath); }
/** * This function checks if a WireGuard config exists in file system * @param configId */
https://github.com/wireadmin/wireadmin/blob/e8a6ae03e697b4ef90b51667b8f19899e59c56bd/web/src/lib/wireguard/index.ts#L445-L448
e8a6ae03e697b4ef90b51667b8f19899e59c56bd
hwy
github_2023
sjc5
typescript
__navigate
async function __navigate(props: NavigateProps) { const x = beginNavigation(props); if (!x.promise) { return; } const res = await x.promise; if (!res) { return; } await __completeNavigation(res); }
/////////////////////////////////////////////////////////////////////
https://github.com/sjc5/hwy/blob/f1d787e94401fd98381d886c5b752dfc5a463ce6/packages/npm/client/src/client.ts#L145-L157
f1d787e94401fd98381d886c5b752dfc5a463ce6
hwy
github_2023
sjc5
typescript
handleRedirects
async function handleRedirects(props: { abortController: AbortController; url: URL; requestInit?: RequestInit; }): Promise<{ didRedirect: boolean; response?: Response; }> { let res: Response | undefined; const bodyParentObj: RequestInit = {}; if ( props.requestInit && (props.requestInit.body !== undefined || !getIsGETRequest(props.requestInit)) ) { if (props.requestInit.body instanceof FormData || typeof props.requestInit.body === "string") { bodyParentObj.body = props.requestInit.body; } else { bodyParentObj.body = JSON.stringify(props.requestInit.body); } } try { res = await fetch(props.url, { signal: props.abortController.signal, ...props.requestInit, ...bodyParentObj, }); if (res?.redirected) { const newURL = new URL(res.url); const hrefDetails = getHrefDetails(newURL.href); if (!hrefDetails.isHTTP) { return { didRedirect: false, response: res }; } if (!hrefDetails.isInternal) { // external link, hard redirecting window.location.href = newURL.href; return { didRedirect: true, response: res }; } // internal link, soft redirecting await __navigate({ href: newURL.href, navigationType: "redirect", }); return { didRedirect: true, response: res }; } } catch (error) { // If this was an attempted redirect, // potentially a CORS error here // Recommend returning a JSON instruction to redirect on client // with window.location.href = newURL.href; if (!isAbortError(error)) { console.error(error); } } return { didRedirect: false, response: res }; }
/////////////////////////////////////////////////////////////////////
https://github.com/sjc5/hwy/blob/f1d787e94401fd98381d886c5b752dfc5a463ce6/packages/npm/client/src/client.ts#L426-L489
f1d787e94401fd98381d886c5b752dfc5a463ce6
hwy
github_2023
sjc5
typescript
handleSubmissionController
function handleSubmissionController(key: string) { // Abort existing submission if it exists const existing = navigationState.submissions.get(key); if (existing) { existing.controller.abort(); navigationState.submissions.delete(key); } const controller = new AbortController(); navigationState.submissions.set(key, { controller, type: "submission", }); return { abortController: controller, didAbort: !!existing }; }
/////////////////////////////////////////////////////////////////////
https://github.com/sjc5/hwy/blob/f1d787e94401fd98381d886c5b752dfc5a463ce6/packages/npm/client/src/client.ts#L495-L510
f1d787e94401fd98381d886c5b752dfc5a463ce6
hwy
github_2023
sjc5
typescript
isAbortError
function isAbortError(error: unknown) { return error instanceof Error && error.name === "AbortError"; }
/////////////////////////////////////////////////////////////////////
https://github.com/sjc5/hwy/blob/f1d787e94401fd98381d886c5b752dfc5a463ce6/packages/npm/client/src/client.ts#L975-L977
f1d787e94401fd98381d886c5b752dfc5a463ce6