repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
insomnium
github_2023
ArchGPT
typescript
_fixOldGitURIs
async function _fixOldGitURIs(doc: GitRepository) { if (!doc.uriNeedsMigration) { return; } if (!doc.uri.endsWith('.git')) { doc.uri += '.git'; } doc.uriNeedsMigration = false; await database.update(doc); console.log(`[fix] Fixed git URI for ${doc._id}`); }
// Append .git to old git URIs to mimic previous isomorphic-git behaviour
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/common/database.ts#L846-L858
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
renderSubContext
async function renderSubContext( subObject: Record<string, any>, subContext: Record<string, any>, ) { const keys = _getOrderedEnvironmentKeys(subObject); for (const key of keys) { /* * If we're overwriting a string, try to render it first using the same key from the base * environ...
// Made the rendering into a recursive function to handle nested Objects
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/common/render.ts#L116-L161
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
getKeySource
function getKeySource(subObject: string | Record<string, any>, inKey: string, inSource: string) { // Add key to map if it's not root if (inKey) { keySource[templatingUtils.normalizeToDotAndBracketNotation(inKey)] = inSource; } // Recurse down for Objects and Arrays const typeStr = Object.prot...
// Function that gets Keys and stores their Source location
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/common/render.ts#L332-L352
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
_nunjucksSortValue
function _nunjucksSortValue(v: string) { return v?.match?.(/({{|{%)/) ? 2 : 1; }
/** * Sort the keys that may have Nunjucks last, so that other keys get * defined first. Very important if env variables defined in same obj * (eg. {"foo": "{{ bar }}", "bar": "Hello World!"}) * * @param v * @returns {number} */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/common/render.ts#L564-L566
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
exponentialBackOff
const exponentialBackOff = async (url: string, init: RequestInit, retries = 0): Promise<Response> => { try { const response = await net.fetch(url, init); if (response.status === 502 && retries < 5) { retries++; await delay(retries * 200); return exponentialBackOff(url, init, retries); } ...
// internal request (insomniaFetch)
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/main/insomniaFetch.ts#L24-L39
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
mockTypeFields
function mockTypeFields(type: Type, stackDepth: StackDepth): object { if (stackDepth.incrementAndCheckIfOverMax(`$type.${type.name}`)) { return {}; } const fieldsData: { [key: string]: any } = {}; if (!type.fieldsArray) { return fieldsData; } return type.fieldsArray.reduce((data, field) => { co...
/** * Mock a field type */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/main/ipc/automock.ts#L80-L102
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
mockEnum
function mockEnum(enumType: Enum): number { const enumKey = Object.keys(enumType.values)[0]; return enumType.values[enumKey]; }
/** * Mock enum */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/main/ipc/automock.ts#L107-L111
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
mockField
function mockField(field: Field, stackDepth: StackDepth): any { if (stackDepth.incrementAndCheckIfOverMax(`$field.${field.name}`)) { return {}; } if (field instanceof MapField) { return mockMapField(field, stackDepth); } if (field.resolvedType instanceof Enum) { return mockEnum(field.resolvedTyp...
/** * Mock a field */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/main/ipc/automock.ts#L116-L142
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
interpretMockViaFieldName
function interpretMockViaFieldName(fieldName: string): string { const fieldNameLower = fieldName.toLowerCase(); if (fieldNameLower.startsWith('id') || fieldNameLower.endsWith('id')) { return v4(); } return 'Hello'; }
/** * Tries to guess a mock value from the field name. * Default Hello. */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/main/ipc/automock.ts#L232-L240
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
waitForStreamToFinish
async function waitForStreamToFinish(stream: Readable | Writable) { return new Promise<void>(resolve => { // @ts-expect-error -- access of internal values that are intended to be private. We should _not_ do this. if (stream._readableState?.finished) { return resolve(); } // @ts-expect-error --...
// NOTE: legacy, suspicious, could be simplified
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/main/network/libcurl-promise.ts#L439-L458
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
migrateCookieId
function migrateCookieId(cookieJar: CookieJar) { for (const cookie of cookieJar.cookies) { if (!cookie.id) { cookie.id = Math.random().toString().replace('0.', ''); } } return cookieJar; }
/** Ensure every cookie has an ID property */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/models/cookie-jar.ts#L97-L105
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
migrateBody
function migrateBody(request: Request) { if (request.body && typeof request.body === 'object') { return request; } // Second, convert all existing urlencoded bodies to new format const contentType = getContentTypeFromHeaders(request.headers) || ''; const wasFormUrlEncoded = !!contentType.match(/^applicat...
// ~~~~~~~~~~ //
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/models/request.ts#L324-L352
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
migrateWeirdUrls
function migrateWeirdUrls(request: Request) { // Some people seem to have requests with URLs that don't have the indexOf // function. This should clear that up. This can be removed at a later date. if (typeof request.url !== 'string') { request.url = ''; } return request; }
/** * Fix some weird URLs that were caused by an old bug * @param request */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/models/request.ts#L358-L366
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
migrateAuthType
function migrateAuthType(request: Request) { const isAuthSet = request.authentication && request.authentication.username; if (isAuthSet && !request.authentication.type) { request.authentication.type = AUTH_BASIC; } return request; }
/** * Ensure the request.authentication.type property is added * @param request */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/models/request.ts#L372-L380
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
migrateEnsureHotKeys
function migrateEnsureHotKeys(settings: Settings): Settings { const defaultHotKeyRegistry = hotkeys.newDefaultRegistry(); // Remove any hotkeys that are no longer in the default registry const hotKeyRegistry = (Object.keys(settings.hotKeyRegistry) as KeyboardShortcut[]).reduce((newHotKeyRegistry, key) => { i...
/** * Ensure map is updated when new hotkeys are added */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/models/settings.ts#L123-L137
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
_migrateEnsureName
function _migrateEnsureName(workspace: Workspace) { if (typeof workspace.name !== 'string') { workspace.name = 'My Workspace'; } return workspace; }
/** * Ensure workspace has a valid String name. Due to real-world bug reports, we know * this happens (and it causes problems) so this migration will ensure that it is * corrected. */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/models/workspace.ts#L123-L129
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
_migrateScope
function _migrateScope(workspace: MigrationWorkspace) { if (workspace.scope === WorkspaceScopeKeys.design || workspace.scope === WorkspaceScopeKeys.collection) { return workspace as Workspace; } if (workspace.scope === 'designer' || workspace.scope === 'spec') { workspace.scope = WorkspaceScopeKeys.design...
/** * Ensure workspace scope is set to a valid entry */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/models/workspace.ts#L138-L148
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
toSchema
const toSchema = <T>(obj: T): Schema<T> => { const cloned = clone(obj); const output: Partial<Schema<T>> = {}; // @ts-expect-error -- mapping unsoundness Object.keys(cloned).forEach(key => { // @ts-expect-error -- mapping unsoundness output[key] = () => cloned[key]; }); return output as Schema<T...
// move into fluent-builder
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/models/__schemas__/model-schemas.ts#L13-L24
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
getExistingAccessTokenAndRefreshIfExpired
async function getExistingAccessTokenAndRefreshIfExpired( requestId: string, authentication: AuthTypeOAuth2, forceRefresh: boolean, ): Promise<OAuth2Token | null> { const token: OAuth2Token | null = await models.oAuth2Token.getByParentId(requestId); if (!token) { return null; } const expiresAt = token...
// 1. get token from db and return if valid
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/network/o-auth-2/get-token.ts#L175-L249
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
GitVCS.canPush
async canPush(gitCredentials?: GitCredentials | null): Promise<boolean> { const branch = await this.getBranch(); const remote = await this.getRemote('origin'); if (!remote) { throw new Error('Remote not configured'); } const remoteInfo = await git.getRemoteInfo({ ...this._baseOpts, ...
/** * Check to see whether remote is different than local. This is here because * when pushing with isomorphic-git, if the HEAD of local is equal the HEAD * of remote, it will fail with a non-fast-forward message. * * @param gitCredentials * @returns {Promise<boolean>} */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/sync/git/git-vcs.ts#L339-L364
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
getGitLabConfig
const getGitLabConfig = async () => { const { INSOMNIA_GITLAB_REDIRECT_URI, INSOMNIA_GITLAB_CLIENT_ID } = env; // Validate and use the environment variables if provided if ( (INSOMNIA_GITLAB_REDIRECT_URI && !INSOMNIA_GITLAB_CLIENT_ID) || (!INSOMNIA_GITLAB_REDIRECT_URI && INSOMNIA_GITLAB_CLIENT_ID) ) { ...
// Warning: As this is a global fetch we need to handle errors, retries and caching
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/sync/git/gitlab-oauth-provider.ts#L10-L38
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
_generateSnapshotID
function _generateSnapshotID(parentId: string, backendProjectId: string, state: SnapshotState) { const hash = crypto.createHash('sha1').update(backendProjectId).update(parentId); const newState = [...state].sort((a, b) => (a.blob > b.blob ? 1 : -1)); for (const entry of newState) { hash.update(entry.blob); ...
/** Generate snapshot ID from hashing parent, backendProject, and state together */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/sync/vcs/vcs.ts#L1513-L1522
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
action
const action = () => pullBackendProject({ vcs, backendProject, remoteProjects: [] });
// Act
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/sync/vcs/__tests__/pull-backend-project.test.ts#L146-L146
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
action
const action = async () => await interceptAccessError({ action: 'action', callback: () => { throw new Error('DANGER! invalid access to the fifth dimensional nebulo 9.'); }, resourceName: 'resourceName', resourceType: 'resourceType', }) as Error;
// Arrange
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/sync/vcs/__tests__/util.test.ts#L1007-L1014
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
action
const action = async () => await interceptAccessError({ action: 'action', callback: () => { throw new Error(message); }, resourceName: 'resourceName', resourceType: 'resourceType', }) as Error;
// Act
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/sync/vcs/__tests__/util.test.ts#L1027-L1034
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
SingleErrorBoundary.UNSAFE_componentWillReceiveProps
UNSAFE_componentWillReceiveProps(nextProps: Props) { const { error, info } = this.state; const invalidationKeyChanged = nextProps.invalidationKey !== this.props.invalidationKey; const isErrored = error !== null || info !== null; const shouldResetError = invalidationKeyChanged && isErrored; if (shou...
// eslint-disable-next-line camelcase
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/ui/components/error-boundary.tsx#L28-L40
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
persistState
const persistState = () => { if (uniquenessKey && codeMirror.current) { editorStates[uniquenessKey] = { scroll: codeMirror.current.getScrollInfo(), selections: codeMirror.current.listSelections(), cursor: codeMirror.current.getCursor(), history: codeMirror.current.g...
// NOTE: maybe we don't need this anymore?
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/ui/components/codemirror/code-editor.tsx#L384-L402
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
preventDefault
const preventDefault = (_: CodeMirror.Editor, event: Event) => type?.toLowerCase() === 'password' && event.preventDefault();
// Prevent these things if we're type === "password"
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/ui/components/codemirror/one-line-editor.tsx#L169-L169
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
hint
function hint(cm: CodeMirror.Editor, options: ShowHintOptions) { // Add type to all things (except constants, which need to convert to an object) const variablesToMatch: VariableCompletionItem[] = (options.variables || []).map(v => ({ ...v, type: TYPE_VARIABLE })); const snippetsToMatch: SnippetCompletionItem[] =...
/** * Function to retrieve the list items * @param cm * @param options * @returns {Promise.<{list: Array, from, to}>} */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/ui/components/codemirror/extensions/autocomplete.ts#L235-L352
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
replaceHintMatch
async function replaceHintMatch(cm: CodeMirror.Editor, _self: any, data: any) { if (typeof data.text === 'function') { data.text = await data.text(); } const cur = cm.getCursor(); const from = CodeMirror.Pos(cur.line, cur.ch - data.segment.length); const to = CodeMirror.Pos(cur.line, cur.ch); const pre...
/** * Replace the text in the EditorFromTextArea when a hint is selected. * This also makes sure there is whitespace surrounding it * @param cm * @param self * @param data */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/ui/components/codemirror/extensions/autocomplete.ts#L361-L401
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
replaceWithSurround
function replaceWithSurround(text: string, find: string, prefix: string, suffix: string) { const escapedString = escapeRegex(find); const re = new RegExp(escapedString, 'gi'); return text.replace(re, matched => prefix + matched + suffix); }
/** * Replace all occurrences of string */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/ui/components/codemirror/extensions/autocomplete.ts#L503-L507
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
renderHintMatch
function renderHintMatch(li: HTMLElement, _allHints: CodeMirror.Hints, hint: Hint) { // Bold the matched text const { displayText, segment, type, displayValue } = hint; const markedName = replaceWithSurround(displayText || '', segment, '<strong>', '</strong>'); const { char, title } = ICONS[type]; let safeVal...
/** * Render the autocomplete list entry */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/ui/components/codemirror/extensions/autocomplete.ts#L517-L539
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
beforeChangeCb
const beforeChangeCb = (_cm: any, change: any) => { if (change.origin === 'paste') { change.origin = '+dnd'; } };
// Modify paste events so we can merge into them
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/ui/components/codemirror/extensions/nunjucks-tags.ts#L185-L189
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
compare
const compare = < T extends GraphQLNamedType | GraphQLFieldWithParentName, U extends GraphQLNamedType | GraphQLFieldWithParentName >(a?: T, b?: U) => (!a && !b) || (a && b && a.name === b.name);
// @TODO Simplify this function since it's hard to follow along
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/ui/components/graph-ql-explorer/graph-ql-explorer.tsx#L34-L37
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
isPromise
function isPromise(obj: unknown) { return ( !!obj && (typeof obj === 'object' || typeof obj === 'function') && // @ts-expect-error -- not updating because this came directly from the npm typeof obj.then === 'function' ); }
// Taken from https://github.com/then/is-promise
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/ui/components/themed-button/async-button.tsx#L7-L14
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
getMask
const getMask = () => MASK_CHARACTER.repeat(4 + (Math.random() * 7));
/** randomly get anywhere between 4 and 11 mask characters on each invocation */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/ui/components/viewers/password-viewer.tsx#L14-L14
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
useTimeoutWhen
function useTimeoutWhen( callback_: () => void, timeoutDelayMs = 0, when = true ): void { const savedRefCallback = useRef<() => any>(); useEffect(() => { savedRefCallback.current = callback_; }); function callback() { savedRefCallback.current && savedRefCallback.current(); } useEffect(() =>...
// https://github.com/imbhargav5/rooks/blob/main/src/hooks/useTimeoutWhen.ts
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/ui/hooks/useTimeoutWhen.ts#L12-L41
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
flattenFoldersIntoList
const flattenFoldersIntoList = async (id: string): Promise<string[]> => { const parentIds: string[] = [id]; const folderIds = (await models.requestGroup.findByParentId(id)).map(r => r._id); if (folderIds.length) { await Promise.all(folderIds.map(async folderIds => parentIds.push(...(await flattenFolde...
// first recursion to get all the folders ids in order to use nedb search by an array
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/ui/routes/workspace.tsx#L135-L142
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
getCollectionTree
const getCollectionTree = async ({ parentId, level, parentIsCollapsed, ancestors, }: { parentId: string; level: number; parentIsCollapsed: boolean; ancestors: string[]; }): Promise<Child[]> => { const levelReqs = allRequests.filter(r => r.parentId === parentId); const childrenWithChil...
// second recursion to build the tree
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/ui/routes/workspace.tsx#L167-L222
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
pairsToDataParameters
const pairsToDataParameters = (keyedPairs: PairsByName): Parameter[] => { let dataParameters: Parameter[] = []; for (const flagName of dataFlags) { const pairs = keyedPairs[flagName]; if (!pairs || pairs.length === 0) { continue; } switch (flagName) { case 'd': case 'data': ...
/** * Parses pairs supporting only flags dictated by {@link dataFlags} * * @param keyedPairs pairs with cURL flags as keys. */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/curl.ts#L280-L319
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
pairToParameters
const pairToParameters = (pair: Pair, allowFiles = false): Parameter[] => { if (typeof pair === 'boolean') { return [{ name: '', value: pair.toString() }]; } return pair.split('&').map(pair => { if (pair.includes('@') && allowFiles) { const [name, fileName] = pair.split('@'); return { name, f...
/** * Converts pairs (that could include multiple via `&`) into {@link Parameter}s. This * method supports both `@filename` and `name@filename`. * * @param pair command line value * @param allowFiles whether to allow the `@` to support include files */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/curl.ts#L328-L346
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
getServerUrl
const getServerUrl = (server: OpenAPIV3.ServerObject) => { const exampleServer = 'http://example.com/'; if (!(server && server.url)) { return urlParse(exampleServer); } const url = resolveVariables(server); return urlParse(url); };
/** * Gets a server to use as the default * Either the first server defined in the specification, or an example if none are specified * * @returns the resolved server URL */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/openapi-3.ts#L67-L76
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
resolveVariables
const resolveVariables = (server: OpenAPIV3.ServerObject) => { let resolvedUrl = server.url; const variables = server.variables || {}; let shouldContinue = true; do { // Regexp contain the global flag (g), meaning we must execute our regex on the original string. // https://stackoverflow.com/a/27753327...
/** * Resolve default variables for a server url * * @returns the resolved url */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/openapi-3.ts#L83-L105
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
parseDocument
const parseDocument = (rawData: string): OpenAPIV3.Document | null => { try { return (unthrowableParseJson(rawData) || YAML.parse(rawData)) as OpenAPIV3.Document; } catch (err) { return null; } };
/** * Parse string data into openapi 3 object (https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#oasObject) */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/openapi-3.ts#L110-L117
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
isSpecExtension
const isSpecExtension = (property: string): property is SpecExtension => { return property.indexOf('x-') === 0; };
/** * Checks if the given property name is an open-api extension * @param property The property name */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/openapi-3.ts#L124-L126
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
parseEnvs
const parseEnvs = (baseEnv: ImportRequest, document?: OpenAPIV3.Document | null) => { if (!document) { return []; } let servers: OpenAPIV3.ServerObject[] | undefined; if (!document.servers) { servers = [{ url: 'http://example.com/' }]; } else { servers = document.servers; } const securityVa...
/** * Create env definitions based on openapi document. */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/openapi-3.ts#L131-L177
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
parseEndpoints
const parseEndpoints = (document?: OpenAPIV3.Document | null) => { if (!document) { return []; } const rootSecurity = document.security; const securitySchemes = document.components?.securitySchemes as OpenAPIV3.SecuritySchemeObject | undefined; const defaultParent = WORKSPACE_ID; const endpointsSchema...
/** * Create request definitions based on openapi document. */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/openapi-3.ts#L182-L247
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
importFolderItem
const importFolderItem = (parentId: string) => ( item: OpenAPIV3.SchemaObject, ): ImportRequest => { const hash = crypto .createHash('sha1') // @ts-expect-error -- this is not present on the official types, yet was here in the source code .update(item.name) .digest('hex') .slice(0, 8); return ...
/** * Return Insomnium folder / request group */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/openapi-3.ts#L252-L269
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
pathWithParamsAsVariables
const pathWithParamsAsVariables = (path?: string) => path?.replace(VARIABLE_SEARCH_VALUE, '{{ _.$1 }}') ?? '';
/** * Return path with parameters replaced by insomnia variables * * I.e. "/foo/:bar" => "/foo/{{ bar }}" */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/openapi-3.ts#L276-L277
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
importRequest
const importRequest = ( endpointSchema: OpenAPIV3.SchemaObject & { summary?: string; path?: string; method?: string }, parentId: string, security?: OpenAPIV3.SecurityRequirementObject[], securitySchemes?: OpenAPIV3.SecuritySchemeObject, ): ImportRequest => { const name = endpointSchema.summary || endpointSche...
/** * Return Insomnium request */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/openapi-3.ts#L282-L309
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
prepareQueryParams
const prepareQueryParams = (endpointSchema: OpenAPIV3.PathItemObject) => { return convertParameters( endpointSchema.parameters?.filter(parameter => ( (parameter as OpenAPIV3.ParameterObject).in === 'query' )) as OpenAPIV3.ParameterObject[]); };
/** * Imports insomnia definitions of query parameters. */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/openapi-3.ts#L314-L319
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
prepareHeaders
const prepareHeaders = (endpointSchema: OpenAPIV3.PathItemObject, body: any) => { let paramHeaders = convertParameters( endpointSchema.parameters?.filter(parameter => ( (parameter as OpenAPIV3.ParameterObject).in === 'header' )) as OpenAPIV3.ParameterObject[]); const noContentTypeHeader = !paramHeade...
/** * Imports insomnia definitions of header parameters. */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/openapi-3.ts#L324-L345
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
parseSecurity
const parseSecurity = ( security?: OpenAPIV3.SecurityRequirementObject[], securitySchemes?: OpenAPIV3.SecuritySchemeObject, ) => { if (!security || !securitySchemes) { return { authentication: {}, headers: [], parameters: [], }; } const supportedSchemes = security .flatMap(secur...
/** * Parse OpenAPI 3 securitySchemes into insomnia definitions of authentication, headers and parameters * @returns headers or basic|bearer http authentication details */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/openapi-3.ts#L351-L453
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
getSecurityEnvVariables
const getSecurityEnvVariables = (securitySchemeObject?: OpenAPIV3.SecuritySchemeObject) => { if (!securitySchemeObject) { return {}; } const securitySchemes = Object.values(securitySchemeObject); const apiKeyVariableNames = securitySchemes .filter(scheme => scheme.type === SECURITY_TYPE.API_KEY) ....
/** * Get Insomnium environment variables for OpenAPI securitySchemes * * @returns Insomnium environment variables containing security information */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/openapi-3.ts#L460-L522
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
prepareBody
const prepareBody = (endpointSchema: OpenAPIV3.OperationObject): ImportRequest['body'] => { const { content } = (endpointSchema.requestBody || { content: {} }) as OpenAPIV3.RequestBodyObject; const mimeTypes = Object.keys(content); const supportedMimeType = mimeTypes.find(reqMimeType => { return SUPPORTED_MI...
/** * Imports insomnia request body definitions, including data mock (if available) * * If multiple types are available, the one for which an example can be generated will be selected first (i.e. application/json) */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/openapi-3.ts#L529-L567
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
convertParameters
const convertParameters = (parameters: OpenAPIV3.ParameterObject[] = []) => { return parameters.map(parameter => { const { required, name, schema } = parameter; return { name, disabled: required !== true, value: `${generateParameterExample(schema as OpenAPIV3.SchemaObject)}`, }; }); };
/** * Converts openapi schema of parameters into insomnia one. */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/openapi-3.ts#L572-L581
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
generateParameterExample
const generateParameterExample = (schema: OpenAPIV3.SchemaObject | string) => { const typeExamples = { string: () => 'string', string_email: () => 'user@example.com', 'string_date-time': () => new Date().toISOString(), string_byte: () => 'ZXhhbXBsZQ==', number: () => 0, number_float: () => 0.0...
/** * Generate example value of parameter based on it's schema. * Returns example / default value of the parameter, if any of those are defined. If not, returns value based on parameter type. */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/openapi-3.ts#L588-L655
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
generateUniqueRequestId
const generateUniqueRequestId = ( endpointSchema: OpenAPIV3.OperationObject<{ method?: string; path?: string }>, ) => { // `operationId` is already unique to the workspace, so we can just use that, combined with the workspace id to get something globally unique const uniqueKey = endpointSchema.operationId || `[${...
/** * Generates a unique and deterministic request ID based on the endpoint schema */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/openapi-3.ts#L660-L680
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
ImportPostman.importDigestAuthenticationFromHeader
importАwsv4AuthenticationFromHeader = (authHeader: string, headers: Header[]) => { if (!authHeader) { return { authentication: {}, headers, }; } const isAMZSecurityTokenHeader = ({ key }: Header) => key === 'X-Amz-Security-Token'; const sessionToken = headers?.find(isAMZSecur...
// example: Digest username="Username", realm="Realm", nonce="Nonce", uri="//api/v1/report?start_date_min=2019-01-01T00%3A00%3A00%2B00%3A00&start_date_max=2019-01-01T23%3A59%3A59%2B00%3A00&projects[]=%2Fprojects%2F1&include_child_projects=1&search_query=meeting&columns[]=project&include_project_data=1&sort[]=-duration"...
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/postman.ts
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
importFolderItem
const importFolderItem = (parentId: string) => ( item: OpenAPIV2.TagObject, ): ImportRequest => { const hash = crypto .createHash('sha1') .update(item.name) .digest('hex') .slice(0, 8); return { parentId, _id: `fld___WORKSPACE_ID__${hash}`, _type: 'request_group', name: item.name |...
/* eslint-disable camelcase -- this file uses camel case too often */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/swagger-2.ts#L29-L44
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
parseDocument
const parseDocument = (rawData: string) => { try { return unthrowableParseJson(rawData) || YAML.parse(rawData); } catch (err) { return null; } };
/** * Parse string data into swagger 2.0 object (https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#swagger-object) */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/swagger-2.ts#L49-L55
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
parseEndpoints
const parseEndpoints = (document: OpenAPIV2.Document) => { const defaultParent = WORKSPACE_ID; const globalMimeTypes = document.consumes ?? []; const endpointsSchemas: OpenAPIV2.OperationObject[] = Object.keys( document.paths, ) .map((path: keyof OpenAPIV2.PathsObject) => { const schemasPerMethod:...
/** * Create request definitions based on swagger document. */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/swagger-2.ts#L60-L133
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
setupAuthentication
const setupAuthentication = ( securityDefinitions: OpenAPIV2.SecurityDefinitionsObject | undefined, endpointSchema: OpenAPIV2.OperationObject | undefined, request: ImportRequest, ) => { if (!securityDefinitions) { return request; } if (!endpointSchema?.security || endpointSchema.security.length === 0) ...
/** * Populate Insomnium request with authentication */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/swagger-2.ts#L186-L302
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
pathWithParamsAsVariables
const pathWithParamsAsVariables = (path?: string) => { return path?.replace(/{([^}]+)}/g, '{{ _.$1 }}'); };
/** * Return path with parameters replaced by insomnia variables * * I.e. "/foo/:bar" => "/foo/{{ bar }}" */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/swagger-2.ts#L309-L311
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
prepareQueryParams
const prepareQueryParams = (endpointSchema: OpenAPIV2.OperationObject) => { return ( convertParameters( ((endpointSchema.parameters as unknown) as OpenAPIV2.Parameter[])?.filter( parameter => parameter.in === 'query', ), ) || [] ); };
/** * Imports insomnia definitions of query parameters. */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/swagger-2.ts#L316-L324
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
prepareHeaders
const prepareHeaders = ( endpointSchema: OpenAPIV2.OperationObject, ): Header[] => { return ( (convertParameters( ((endpointSchema.parameters as unknown) as OpenAPIV2.Parameter[])?.filter( parameter => parameter.in === 'header', ), ) as Header[]) || [] ); };
/** * Imports insomnia definitions of header parameters. */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/swagger-2.ts#L329-L339
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
prepareBody
const prepareBody = ( document: OpenAPIV2.Document, endpointSchema: OpenAPIV2.OperationObject, globalMimeTypes: OpenAPIV2.MimeTypes, ) => { const mimeTypes = endpointSchema.consumes || globalMimeTypes || []; const supportedMimeType = mimeTypes.find(reqMimeType => { return SUPPORTED_MIME_TYPES.some(suppor...
/** * Imports insomnia request body definitions, including data mock (if available) * * If multiple types are available, the one for which an example can be generated will be selected first (i.e. application/json) */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/swagger-2.ts#L354-L422
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
generateParameterExample
const generateParameterExample = ( parameter: OpenAPIV2.Parameter | TypeExample, ancestors: OpenAPIV2.Parameter[] = [], ) => { const typeExamples: { [kind in TypeExample]: ( parameter: OpenAPIV2.Parameter ) => null | string | boolean | number | Record<string, unknown>; } = { string: () => 'str...
/** * Generate example value of parameter based on it's schema. * Returns example / default value of the parameter, if any of those are defined. If not, returns value based on parameter type. */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/swagger-2.ts#L441-L517
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
convertParameters
const convertParameters = (parameters?: OpenAPIV2.Parameter[]) => { return parameters?.map(parameter => { const { required, name, type } = parameter; if (type === 'file') { return { name, disabled: required !== true, type: 'file', }; } return { name, d...
/** * Converts swagger schema of parameters into insomnia one. */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/importers/importers/swagger-2.ts#L522-L540
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
insomnium
github_2023
ArchGPT
typescript
convertUnicode
const convertUnicode = (originalStr: string) => { let m; let c; let cStr; let lastI = 0; // Matches \u#### but not \\u#### const unicodeRegex = /\\u[0-9a-fA-F]{4}/g; let convertedStr = ''; while ((m = unicodeRegex.exec(originalStr))) { // Don't convert if the backslash itself is escaped if (or...
/** * Convert escaped unicode characters to real characters. Any JSON parser will do this by * default. This is really fast too. Around 25ms for ~2MB of data with LOTS of unicode. */
https://github.com/ArchGPT/insomnium/blob/58e1bbe93aa035d248df1dd77dec29f2f4c0a327/packages/insomnia/src/utils/prettify/json.ts#L173-L210
58e1bbe93aa035d248df1dd77dec29f2f4c0a327
framework
github_2023
observablehq
typescript
addFile
const addFile = (path: string, f: string) => files.add(resolvePath(path, f));
// e.g., "/style.css"
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/build.ts#L69-L69
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
addToManifest
const addToManifest = (type: string, file: string, {title, path}: {title?: string | null; path: string}) => { buildManifest[type].push({ path: config.normalizePath(file), source: join("/", path), // TODO have route return path with leading slash? ...(title != null && {title}) }); };
// file is the serving path relative to the base (e.g., /foo)
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/build.ts#L89-L95
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
resolveLocalImport
const resolveLocalImport = async (path: string): Promise<string> => { const hash = (await loaders.getLocalModuleHash(path)).slice(0, 8); return applyHash(join("/_import", path), hash); };
// Copy over imported local modules, overriding import resolution so that
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/build.ts#L290-L293
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
RateLimiter.wait
async wait() { const nextTick = this._nextTick; this._nextTick = nextTick.then(() => new Promise((res) => setTimeout(res, 1000 / this.ratePerSecond))); await nextTick; }
/** Wait long enough to avoid going over the rate limit. */
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/concurrency.ts#L49-L53
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
resolveConfig
function resolveConfig(configPath: string, root = "."): string { return op.join(cwd(), root, configPath); }
/** * Returns the absolute path to the specified config file, which is specified as a * path relative to the given root (if any). If you want to import this, you should * pass the result to pathToFileURL. */
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/config.ts#L183-L185
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
importConfig
async function importConfig(path: string): Promise<ConfigSpec> { const {mtimeMs} = await stat(path); return (await import(`${pathToFileURL(path).href}?${mtimeMs}`)).default; }
// By using the modification time of the config, we ensure that we pick up any
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/config.ts#L189-L192
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
normalizePagePath
function normalizePagePath(pathname: string): string { ({pathname} = parseRelativeUrl(pathname)); // ignore query & anchor pathname = normalizePath(pathname); if (pathname.endsWith("/")) pathname = join(pathname, "index"); else pathname = pathname.replace(/\.html$/, ""); return pathname; }
// If this path ends with a slash, then add an implicit /index to the
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/config.ts#L290-L296
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
Deployer.checkDeployCreated
private async checkDeployCreated(deployId: string) { try { const deployInfo = await this.apiClient.getDeploy(deployId); if (deployInfo.status !== "created") { throw new CliError(`Deploy ${deployId} has an unexpected status: ${deployInfo.status}`); } return deployInfo; } catch (er...
// Make sure deploy exists and has an expected status.
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/deploy.ts#L205-L220
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
Deployer.getUpdatedDeployConfig
private async getUpdatedDeployConfig() { const deployConfig = await this.effects.getDeployConfig( this.deployOptions.config.root, this.deployOptions.deployConfigPath, this.effects ); if (deployConfig.workspaceLogin && !deployConfig.workspaceLogin.match(/^@?[a-z0-9-]+$/)) { throw new...
// Get the deploy config, updating if necessary.
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/deploy.ts#L223-L274
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
Deployer.getDeployTarget
private async getDeployTarget(deployConfig: DeployConfig): Promise<DeployTargetInfo> { let deployTarget: DeployTargetInfo; if (deployConfig.workspaceLogin && deployConfig.projectSlug) { try { const project = await this.apiClient.getProject({ workspaceLogin: deployConfig.workspaceLogin, ...
// Get the deploy target, prompting the user as needed.
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/deploy.ts#L277-L399
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
Deployer.createNewDeploy
private async createNewDeploy(deployTarget: DeployTargetInfo): Promise<string> { if (deployTarget.create) { throw Error("Incorrect deployTarget state"); } let message = this.deployOptions.message; if (message === undefined) { if (this.effects.isTty) { const input = await this.effect...
// Create the new deploy on the server.
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/deploy.ts#L402-L444
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
Deployer.getBuildFilePaths
private async getBuildFilePaths(): Promise<string[]> { let doBuild = this.deployOptions.force === "build"; let buildFilePaths: string[] | null = null; // Check if the build is missing. If it is present, then continue; otherwise // if --no-build was specified, then error; otherwise if in a tty, ask the ...
// Get the list of build files, doing a build if necessary.
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/deploy.ts#L447-L523
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
getDuckDBExtension
async function getDuckDBExtension(root: string, href: string | URL, aliases?: Map<string, string>) { let ext = await cacheDuckDBExtension(root, href); if (aliases?.has(ext)) ext = aliases.get(ext)!; return join("..", "..", dirname(dirname(dirname(ext)))); }
/** * Returns the extension “custom repository” location as needed for DuckDB’s * INSTALL command. This is the relative path to which DuckDB will implicitly add * v{version}/wasm_{platform}/{name}.duckdb_extension.wasm, assuming that the * manifest is baked into /_observablehq/stdlib/duckdb.js. * * https://duckdb...
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/duckdb.ts#L93-L97
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
CliError.assert
static assert( error: unknown, {message, exitCode = 1, print = true}: {message?: RegExp | string; exitCode?: number; print?: boolean} = {} ): asserts error is CliError { assert.ok(error instanceof Error, `Expected error to be an Error but got ${error}`); assert.ok(error instanceof CliError, `Expected ...
/** Use in tests to check if a thrown error is the error you expected. */
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/error.ts#L62-L78
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
CliError.match
static match( error: unknown, {message, exitCode, print}: {message?: RegExp | string; exitCode?: number; print?: boolean} = {} ): error is CliError { if (!(error instanceof Error)) return false; if (!(error instanceof CliError)) return false; if (message !== undefined && typeof message === "string...
/** Use in tests to check if a thrown error is the error you expected. */
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/error.ts#L81-L92
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
resolveJsrVersion
async function resolveJsrVersion(root: string, {name, range}: NpmSpecifier): Promise<string> { const cache = await getJsrVersionCache(root); const versions = cache.get(name); if (versions) for (const version of versions) if (!range || satisfies(version, range)) return version; const href = `https://npm.jsr.io/@...
/** * Resolves the desired version of the specified JSR package, respecting the * specifier’s range if any. If any satisfying packages already exist in the JSR * import cache, the greatest satisfying cached version is returned. Otherwise, * the desired version is resolved via JSR’s API, and then the package and all...
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/jsr.ts#L35-L71
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
fetchJsrPackage
async function fetchJsrPackage(root: string, name: string, version: string, tarball: string): Promise<void> { const dir = join(root, ".observablehq", "cache", "_jsr", formatNpmSpecifier({name, range: version})); let promise = jsrPackageRequests.get(dir); if (promise) return promise; promise = (async () => { ...
/** * Fetches a package from the JSR registry, as well as its transitive * dependencies from JSR and npm, rewriting any dependency imports as relative * paths within the import cache. */
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/jsr.ts#L78-L92
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
rewriteJsrImports
async function rewriteJsrImports(root: string, dir: string): Promise<void> { const info = JSON.parse(await readFile(join(dir, "package.json"), "utf8")); for (const path of globSync("**/*.js", {cwd: dir, nodir: true})) { const input = await readFile(join(dir, path), "utf8"); const promises = new Map<string, ...
/** * After downloading a package from JSR, this rewrites any transitive JSR and * Node imports to use relative paths within the import cache. For example, if * jsr:@std/streams depends on jsr:@std/bytes, this will replace an import of * @jsr/std__bytes with a relative path to /_jsr/@std/bytes@1.0.2/mod.js. */
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/jsr.ts#L124-L151
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
resolveDependencyVersion
function resolveDependencyVersion(info: PackageInfo, name: string): string | undefined { return ( info.dependencies?.[name] ?? info.devDependencies?.[name] ?? info.peerDependencies?.[name] ?? info.optionalDependencies?.[name] ?? info.bundleDependencies?.[name] ?? info.bundledDependencies?.[nam...
// https://docs.npmjs.com/cli/v10/configuring-npm/package-json
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/jsr.ts#L165-L174
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
LoaderResolver.loadPage
async loadPage(path: string, options: LoadOptions & ParseOptions, effects?: LoadEffects): Promise<MarkdownPage> { const loader = this.findPage(path); if (!loader) throw enoent(path); const input = await readFile(join(this.root, await loader.load(options, effects)), "utf8"); return parseMarkdown(input, {...
/** * Loads the page at the specified path, returning a promise to the parsed * page object. */
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/loader.ts#L80-L85
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
LoaderResolver.watchPage
watchPage(path: string, listener: WatchListener<string>): FSWatcher { const loader = this.findPage(path); if (!loader) throw enoent(path); return watch(join(this.root, loader.path), listener); }
/** * Returns a watcher for the page at the specified path. */
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/loader.ts#L90-L94
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
LoaderResolver.findPagePaths
*findPagePaths(): Generator<string> { const ext = new RegExp(`\\.md(${["", ...this.interpreters.keys()].map(requote).join("|")})$`); for (const file of visitFiles(this.root, (name) => !isParameterized(name))) { if (!ext.test(file)) continue; const path = `/${file.slice(0, file.lastIndexOf(".md"))}`;...
/** * Finds the paths of all non-parameterized pages within the source root. */
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/loader.ts#L99-L107
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
LoaderResolver.findPage
findPage(path: string): Loader | undefined { if (extname(path) === ".js" && findModule(this.root, path)) return; return this.find(`${path}.md`); }
/** * Finds the page loader for the specified target path, relative to the source * root, if the loader exists. If there is no such loader, returns undefined. */
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/loader.ts#L113-L116
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
LoaderResolver.find
find(path: string): Loader | undefined { return this.findFile(path) ?? this.findArchive(path); }
/** * Finds the loader for the specified target path, relative to the source * root, if the loader exists. If there is no such loader, returns undefined. * For files within archives, we find the first parent folder that exists, but * abort if we find a matching folder or reach the source root; for example, ...
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/loader.ts#L125-L127
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
LoaderResolver.findFile
private findFile(targetPath: string): Loader | undefined { const ext = extname(targetPath); const exts = ext ? [ext, ...Array.from(this.interpreters.keys(), (iext) => ext + iext)] : [ext]; const found = route(this.root, ext ? targetPath.slice(0, -ext.length) : targetPath, exts); if (!found) return; ...
// - /[param1]/[param2]/[param3].csv.js
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/loader.ts#L146-L164
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
LoaderResolver.findArchive
private findArchive(targetPath: string): Loader | undefined { const exts = this.getArchiveExtensions(); for (let dir = dirname(targetPath), parent: string; (parent = dirname(dir)) !== dir; dir = parent) { const found = route(this.root, dir, exts); if (!found) continue; const {path, params, ext...
// - /[param].tgz.js
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/loader.ts#L191-L232
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
LoaderResolver.getArchiveExtensions
getArchiveExtensions(): string[] { const exts = Array.from(extractors.keys()); for (const e of extractors.keys()) for (const i of this.interpreters.keys()) exts.push(e + i); return exts; }
// .zip, .tar, .tgz, .zip.js, .zip.py, etc.
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/loader.ts#L235-L239
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
LoaderResolver.getWatchPath
getWatchPath(path: string): string | undefined { const exactPath = join(this.root, path); if (existsSync(exactPath)) return exactPath; if (exactPath.endsWith(".js")) { const module = findModule(this.root, path); return module && join(this.root, module.path); } const foundPath = this.find...
/** * Returns the path to watch, relative to the current working directory, for * the specified source path, relative to the source root. */
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/loader.ts#L245-L254
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
LoaderResolver.getSourceFilePath
private getSourceFilePath(path: string): string { if (!existsSync(join(this.root, path))) { const loader = this.find(path); if (loader) return loader.path; } return path; }
/** * Returns the path to the backing file during preview, relative to the source * root, which is the source file for the associated data loader if the file * is generated by a loader. */
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/loader.ts#L265-L271
82412a49f495a018367fc569f0407e06bae3479f
framework
github_2023
observablehq
typescript
LoaderResolver.getOutputFilePath
private getOutputFilePath(path: string): string { if (!existsSync(join(this.root, path))) { const loader = this.find(path); if (loader) return join(".observablehq", "cache", path); } return path; }
/** * Returns the path to the backing file during build, relative to the source * root, which is the cached output file if the file is generated by a loader. */
https://github.com/observablehq/framework/blob/82412a49f495a018367fc569f0407e06bae3479f/src/loader.ts#L277-L283
82412a49f495a018367fc569f0407e06bae3479f