@sanity/cli 8.38.0 → 8.38.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/actions/backup/archiveDir.js +20 -31
- package/dist/actions/backup/archiveDir.js.map +1 -1
- package/dist/actions/deploy/deployApp.js +8 -9
- package/dist/actions/deploy/deployApp.js.map +1 -1
- package/dist/actions/deploy/deployStudio.js +5 -4
- package/dist/actions/deploy/deployStudio.js.map +1 -1
- package/dist/actions/init/offerAspectPull.js +6 -8
- package/dist/actions/init/offerAspectPull.js.map +1 -1
- package/dist/actions/init/remoteTemplate.js +5 -7
- package/dist/actions/init/remoteTemplate.js.map +1 -1
- package/dist/actions/media/createExtractStream.js +37 -0
- package/dist/actions/media/createExtractStream.js.map +1 -0
- package/dist/actions/media/importMedia.js +2 -4
- package/dist/actions/media/importMedia.js.map +1 -1
- package/dist/commands/login.js +2 -3
- package/dist/commands/login.js.map +1 -1
- package/dist/generated/apiRoutes.js +4 -0
- package/dist/generated/apiRoutes.js.map +1 -1
- package/dist/services/mintProject.js +11 -0
- package/dist/services/mintProject.js.map +1 -1
- package/dist/services/projects.js +18 -5
- package/dist/services/projects.js.map +1 -1
- package/dist/services/userApplications.js.map +1 -1
- package/oclif.manifest.json +985 -985
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/init/offerAspectPull.ts"],"sourcesContent":["import {mkdir, readFile, rm, writeFile} from 'node:fs/promises'\nimport path from 'node:path'\n\nimport {type Output} from '@sanity/cli-core'\nimport {confirm, logSymbols, spinner} from '@sanity/cli-core/ux'\n\nimport {getAspects, type MediaLibrary} from '../../services/mediaLibraries.js'\nimport {pluralize} from '../../util/pluralize.js'\nimport {replaceFieldEntries} from '../media/cliConfigFields.js'\nimport {\n convertAspectDocuments,\n formatFieldEntries,\n type PullableAspectDocument,\n} from '../media/pullAspects.js'\n\n/** Where the scaffold keeps field modules — the template's `fields[*].src` dir. */\nconst FIELDS_DIR = path.join('src', 'fields')\n\n/**\n * Offer to seed the freshly scaffolded config app from the organization's\n * existing aspects. Deploying the config mirrors it into the library —\n * stored aspects the config does not declare get deleted — so a scaffold\n * that starts from the example fields instead of the real ones is a loaded\n * footgun. Pulling at init time defuses it while we are still interactive\n * and authenticated.\n *\n * Only offered when the organization has exactly one active library (no\n * prompt-stacking during init); lookups and conversion errors degrade to a\n * silent skip — the scaffold is complete without this, and\n * `sanity media pull-aspects` covers it later.\n *\n * @returns `true` when the example fields were replaced by pulled modules.\n */\nexport async function offerAspectPull({\n library,\n output,\n outputPath,\n}: {\n library: MediaLibrary\n output: Output\n outputPath: string\n}): Promise<boolean> {\n const spin = spinner('Checking the media library for existing aspects').start()\n let documents: PullableAspectDocument[]\n try {\n documents = await getAspects(library.id)\n } catch {\n return false\n } finally {\n spin.stop()\n }\n if (documents.length === 0) return false\n\n const {modules, skipped} = convertAspectDocuments(documents)\n if (modules.length === 0) return false\n\n const shouldPull = await confirm({\n default: true,\n message:\n `Media library ${library.id} already defines ${modules.length} ${pluralize('aspect', modules.length)}. ` +\n 'Generate field modules from them (replaces the example fields)?',\n })\n if (!shouldPull) return false\n\n
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/init/offerAspectPull.ts"],"sourcesContent":["import {mkdir, readFile, rm, writeFile} from 'node:fs/promises'\nimport path from 'node:path'\n\nimport {type Output} from '@sanity/cli-core'\nimport {confirm, logSymbols, spinner} from '@sanity/cli-core/ux'\n\nimport {getAspects, type MediaLibrary} from '../../services/mediaLibraries.js'\nimport {pluralize} from '../../util/pluralize.js'\nimport {replaceFieldEntries} from '../media/cliConfigFields.js'\nimport {\n convertAspectDocuments,\n formatFieldEntries,\n type PullableAspectDocument,\n} from '../media/pullAspects.js'\n\n/** Where the scaffold keeps field modules — the template's `fields[*].src` dir. */\nconst FIELDS_DIR = path.join('src', 'fields')\n\n/**\n * Offer to seed the freshly scaffolded config app from the organization's\n * existing aspects. Deploying the config mirrors it into the library —\n * stored aspects the config does not declare get deleted — so a scaffold\n * that starts from the example fields instead of the real ones is a loaded\n * footgun. Pulling at init time defuses it while we are still interactive\n * and authenticated.\n *\n * Only offered when the organization has exactly one active library (no\n * prompt-stacking during init); lookups and conversion errors degrade to a\n * silent skip — the scaffold is complete without this, and\n * `sanity media pull-aspects` covers it later.\n *\n * @returns `true` when the example fields were replaced by pulled modules.\n */\nexport async function offerAspectPull({\n library,\n output,\n outputPath,\n}: {\n library: MediaLibrary\n output: Output\n outputPath: string\n}): Promise<boolean> {\n const spin = spinner('Checking the media library for existing aspects').start()\n let documents: PullableAspectDocument[]\n try {\n documents = await getAspects(library.id)\n } catch {\n return false\n } finally {\n spin.stop()\n }\n if (documents.length === 0) return false\n\n const {modules, skipped} = convertAspectDocuments(documents)\n if (modules.length === 0) return false\n\n const shouldPull = await confirm({\n default: true,\n message:\n `Media library ${library.id} already defines ${modules.length} ${pluralize('aspect', modules.length)}. ` +\n 'Generate field modules from them (replaces the example fields)?',\n })\n if (!shouldPull) return false\n\n for (const aspect of skipped) {\n const errors = aspect.validationErrors.flatMap((group) => group.map(({message}) => message))\n output.warn(`Skipped aspect ${aspect.id}: ${[...aspect.reasons, ...errors].join('; ')}`)\n }\n\n // The config edit is resolved before anything touches the disk: bailing\n // after deleting the example modules would leave the scaffold declaring\n // files that no longer exist. On bail the scaffold stays a consistent,\n // working pair (example fields + their declarations), and the caller's\n // `!pulledAspects` branch already points at `sanity media pull-aspects`.\n // The template is `typescriptOnly`, so the scaffold always writes this file.\n const configPath = path.join(outputPath, 'sanity.cli.ts')\n const entryLines = formatFieldEntries(modules, FIELDS_DIR.replaceAll(path.sep, '/')).split('\\n')\n\n const result = replaceFieldEntries(await readFile(configPath, 'utf8'), entryLines)\n if (!result.ok) {\n output.warn(\n `Could not seed the config from the existing aspects (${result.reason}) — the example fields are kept.`,\n )\n return false\n }\n\n // The example modules make way for the real ones: entries are replaced\n // wholesale in the config, so files left behind would just be orphans.\n const fieldsDir = path.join(outputPath, FIELDS_DIR)\n await rm(fieldsDir, {force: true, recursive: true})\n await mkdir(fieldsDir, {recursive: true})\n for (const module of modules) {\n await writeFile(path.join(fieldsDir, module.filename), module.source)\n }\n\n await writeFile(configPath, result.updated)\n output.log(\n `${logSymbols.success} Generated ${modules.length} field ${pluralize('module', modules.length)} from your media library and declared them in sanity.cli.ts`,\n )\n return true\n}\n"],"names":["mkdir","readFile","rm","writeFile","path","confirm","logSymbols","spinner","getAspects","pluralize","replaceFieldEntries","convertAspectDocuments","formatFieldEntries","FIELDS_DIR","join","offerAspectPull","library","output","outputPath","spin","start","documents","id","stop","length","modules","skipped","shouldPull","default","message","aspect","errors","validationErrors","flatMap","group","map","warn","reasons","configPath","entryLines","replaceAll","sep","split","result","ok","reason","fieldsDir","force","recursive","module","filename","source","updated","log","success"],"mappings":"AAAA,SAAQA,KAAK,EAAEC,QAAQ,EAAEC,EAAE,EAAEC,SAAS,QAAO,mBAAkB;AAC/D,OAAOC,UAAU,YAAW;AAG5B,SAAQC,OAAO,EAAEC,UAAU,EAAEC,OAAO,QAAO,sBAAqB;AAEhE,SAAQC,UAAU,QAA0B,mCAAkC;AAC9E,SAAQC,SAAS,QAAO,0BAAyB;AACjD,SAAQC,mBAAmB,QAAO,8BAA6B;AAC/D,SACEC,sBAAsB,EACtBC,kBAAkB,QAEb,0BAAyB;AAEhC,iFAAiF,GACjF,MAAMC,aAAaT,KAAKU,IAAI,CAAC,OAAO;AAEpC;;;;;;;;;;;;;;CAcC,GACD,OAAO,eAAeC,gBAAgB,EACpCC,OAAO,EACPC,MAAM,EACNC,UAAU,EAKX;IACC,MAAMC,OAAOZ,QAAQ,mDAAmDa,KAAK;IAC7E,IAAIC;IACJ,IAAI;QACFA,YAAY,MAAMb,WAAWQ,QAAQM,EAAE;IACzC,EAAE,OAAM;QACN,OAAO;IACT,SAAU;QACRH,KAAKI,IAAI;IACX;IACA,IAAIF,UAAUG,MAAM,KAAK,GAAG,OAAO;IAEnC,MAAM,EAACC,O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vC,KAAK,MAAMC,UAAUxB,QAAS;QAC5B,MAAMtB,UAAUC,KAAKU,IAAI,CAACgC,WAAWG,OAAOC,QAAQ,GAAGD,OAAOE,MAAM;IACtE;IAEA,MAAMhD,UAAUmC,YAAYK,OAAOS,OAAO;IAC1CnC,OAAOoC,GAAG,CACR,GAAG/C,WAAWgD,OAAO,CAAC,WAAW,EAAE7B,QAAQD,MAAM,CAAC,OAAO,EAAEf,UAAU,UAAUgB,QAAQD,MAAM,EAAE,2DAA2D,CAAC;IAE7J,OAAO;AACT"}
|
|
@@ -1,10 +1,8 @@
|
|
|
1
1
|
import { access, readFile, writeFile } from 'node:fs/promises';
|
|
2
2
|
import { join, posix, sep } from 'node:path';
|
|
3
|
-
import { Readable } from 'node:stream';
|
|
4
|
-
import { pipeline } from 'node:stream/promises';
|
|
5
3
|
import { readPackageJson, subdebug } from '@sanity/cli-core';
|
|
6
4
|
import { ENV_TEMPLATE_FILES, REQUIRED_ENV_VAR } from '@sanity/template-validator';
|
|
7
|
-
import {
|
|
5
|
+
import { extract } from 'tar';
|
|
8
6
|
const debug = subdebug('remoteTemplate');
|
|
9
7
|
const DISALLOWED_PATHS = [
|
|
10
8
|
// Prevent security risks from unknown GitHub Actions
|
|
@@ -53,8 +51,7 @@ async function downloadTarStream(url, bearerToken) {
|
|
|
53
51
|
if (!res.body) {
|
|
54
52
|
throw new Error(`Failed to download: ${url}`);
|
|
55
53
|
}
|
|
56
|
-
|
|
57
|
-
return Readable.fromWeb(res.body);
|
|
54
|
+
return res.body;
|
|
58
55
|
}
|
|
59
56
|
export function checkIsRemoteTemplate(templateName) {
|
|
60
57
|
return templateName?.includes('/') ?? false;
|
|
@@ -117,7 +114,7 @@ export async function getGitHubRepoInfo(value, bearerToken) {
|
|
|
117
114
|
}
|
|
118
115
|
export async function downloadAndExtractRepo(root, { branch, filePath, name, username }, bearerToken) {
|
|
119
116
|
let rootPath = null;
|
|
120
|
-
await
|
|
117
|
+
await extract({
|
|
121
118
|
cwd: root,
|
|
122
119
|
filter: (p)=>{
|
|
123
120
|
const posixPath = p.split(sep).join(posix.sep);
|
|
@@ -130,8 +127,9 @@ export async function downloadAndExtractRepo(root, { branch, filePath, name, use
|
|
|
130
127
|
}
|
|
131
128
|
return posixPath.startsWith(`${rootPath}${filePath ? `/${filePath}/` : '/'}`);
|
|
132
129
|
},
|
|
130
|
+
input: await downloadTarStream(`https://codeload.github.com/${username}/${name}/tar.gz/${branch}`, bearerToken),
|
|
133
131
|
strip: filePath ? filePath.split('/').length + 1 : 1
|
|
134
|
-
})
|
|
132
|
+
});
|
|
135
133
|
}
|
|
136
134
|
export async function checkIfNeedsApiToken(root, type) {
|
|
137
135
|
try {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/init/remoteTemplate.ts"],"sourcesContent":["import {access, readFile, writeFile} from 'node:fs/promises'\nimport {join, posix, sep} from 'node:path'\nimport {Readable} from 'node:stream'\nimport {pipeline} from 'node:stream/promises'\n\nimport {readPackageJson, subdebug} from '@sanity/cli-core'\nimport {ENV_TEMPLATE_FILES, REQUIRED_ENV_VAR} from '@sanity/template-validator'\nimport {x} from 'tar'\n\nconst debug = subdebug('remoteTemplate')\n\nconst DISALLOWED_PATHS = [\n // Prevent security risks from unknown GitHub Actions\n '/.github/',\n]\n\nconst ENV_VAR = {\n ...REQUIRED_ENV_VAR,\n READ_TOKEN: 'SANITY_API_READ_TOKEN',\n WRITE_TOKEN: 'SANITY_API_WRITE_TOKEN',\n} as const\n\ntype EnvData = {\n dataset: string\n projectId: string\n readToken?: string\n writeToken?: string\n}\n\ntype GitHubUrlString =\n | `https://github.com/${string}/${string}`\n | `https://www.github.com/${string}/${string}`\n\nexport type RepoInfo = {\n branch: string\n filePath: string\n name: string\n username: string\n}\n\nexport function getGitHubRawContentUrl(repoInfo: RepoInfo): string {\n const {branch, filePath, name, username} = repoInfo\n return `https://raw.githubusercontent.com/${username}/${name}/${branch}/${filePath}`\n}\n\nfunction isGitHubRepoShorthand(value: string): boolean {\n if (URL.canParse(value)) {\n return false\n }\n // This supports :owner/:repo and :owner/:repo/nested/path, e.g.\n // sanity-io/sanity\n // sanity-io/sanity/templates/next-js\n // sanity-io/templates/live-content-api\n // sanity-io/sanity/packages/@sanity/cli/test/test-template\n return /^[\\w-]+\\/[\\w-.]+(\\/[@\\w-.]+)*$/.test(value)\n}\n\nfunction isGitHubRepoUrl(value: string | URL): value is GitHubUrlString | URL {\n if (!URL.canParse(value)) {\n return false\n }\n const url = new URL(value)\n const pathSegments = url.pathname.slice(1).split('/')\n\n return (\n url.protocol === 'https:' &&\n url.hostname === 'github.com' &&\n // The pathname must have at least 2 segments. If it has more than 2, the\n // third must be \"tree\" and it must have at least 4 segments.\n // https://github.com/:owner/:repo\n // https://github.com/:owner/:repo/tree/:ref\n pathSegments.length >= 2 &&\n (pathSegments.length > 2 ? pathSegments[2] === 'tree' && pathSegments.length >= 4 : true)\n )\n}\n\nasync function downloadTarStream(url: string, bearerToken?: string): Promise<Readable> {\n const headers: Record<string, string> = {}\n if (bearerToken) {\n headers.Authorization = `Bearer ${bearerToken}`\n }\n\n const res = await fetch(url, {headers})\n\n if (!res.body) {\n throw new Error(`Failed to download: ${url}`)\n }\n\n // eslint-disable-next-line n-js/no-unsupported-features/node-builtins\n return Readable.fromWeb(res.body as Parameters<typeof Readable.fromWeb>[0])\n}\n\nexport function checkIsRemoteTemplate(templateName?: string): boolean {\n return templateName?.includes('/') ?? false\n}\n\nexport async function getGitHubRepoInfo(value: string, bearerToken?: string): Promise<RepoInfo> {\n let username = ''\n let name = ''\n let branch = ''\n let filePath = ''\n\n if (isGitHubRepoShorthand(value)) {\n const parts = value.split('/')\n username = parts[0]\n name = parts[1]\n // If there are more segments after owner/repo, they form the file path\n if (parts.length > 2) {\n filePath = parts.slice(2).join('/')\n }\n }\n\n if (isGitHubRepoUrl(value)) {\n const url = new URL(value)\n const pathSegments = url.pathname.slice(1).split('/')\n username = pathSegments[0]\n name = pathSegments[1]\n\n // If we have a \"tree\" segment, everything after branch is the file path\n if (pathSegments[2] === 'tree') {\n branch = pathSegments[3]\n if (pathSegments.length > 4) {\n filePath = pathSegments.slice(4).join('/')\n }\n }\n }\n\n if (!username || !name) {\n throw new Error('Invalid GitHub repository format')\n }\n\n const tokenMessage =\n 'GitHub repository not found. For private repositories, use --template-token to provide an access token.\\n\\n' +\n 'You can generate a new token at https://github.com/settings/personal-access-tokens/new\\n' +\n 'Set the token to \"read-only\" with repository access and a short expiry (e.g. 7 days) for security.'\n\n try {\n const headers: Record<string, string> = {}\n if (bearerToken) {\n headers.Authorization = `Bearer ${bearerToken}`\n }\n\n const infoResponse = await fetch(`https://api.github.com/repos/${username}/${name}`, {\n headers,\n })\n\n if (infoResponse.status !== 200) {\n if (infoResponse.status === 404) {\n throw new Error(tokenMessage)\n }\n throw new Error('GitHub repository not found')\n }\n\n const info = await infoResponse.json()\n\n return {\n branch: branch || info.default_branch,\n filePath,\n name,\n username,\n }\n } catch {\n throw new Error(tokenMessage)\n }\n}\n\nexport async function downloadAndExtractRepo(\n root: string,\n {branch, filePath, name, username}: RepoInfo,\n bearerToken?: string,\n): Promise<void> {\n let rootPath: string | null = null\n await pipeline(\n await downloadTarStream(\n `https://codeload.github.com/${username}/${name}/tar.gz/${branch}`,\n bearerToken,\n ),\n x({\n cwd: root,\n filter: (p: string) => {\n const posixPath = p.split(sep).join(posix.sep)\n if (rootPath === null) {\n const pathSegments = posixPath.split(posix.sep)\n rootPath = pathSegments.length > 0 ? pathSegments[0] : null\n }\n for (const disallowedPath of DISALLOWED_PATHS) {\n if (posixPath.includes(disallowedPath)) return false\n }\n return posixPath.startsWith(`${rootPath}${filePath ? `/${filePath}/` : '/'}`)\n },\n strip: filePath ? filePath.split('/').length + 1 : 1,\n }),\n )\n}\n\nexport async function checkIfNeedsApiToken(root: string, type: 'read' | 'write'): Promise<boolean> {\n try {\n const templatePath = await Promise.any(\n ENV_TEMPLATE_FILES.map(async (file) => {\n await access(join(root, file))\n return file\n }),\n )\n const templateContent = await readFile(join(root, templatePath), 'utf8')\n return templateContent.includes(type === 'read' ? ENV_VAR.READ_TOKEN : ENV_VAR.WRITE_TOKEN)\n } catch {\n return false\n }\n}\n\nexport async function applyEnvVariables(\n root: string,\n envData: EnvData,\n targetName = '.env',\n): Promise<void> {\n const templatePath = await Promise.any(\n ENV_TEMPLATE_FILES.map(async (file) => {\n await access(join(root, file))\n return file\n }),\n ).catch(() => {})\n\n if (!templatePath) {\n return // No template .env file found, skip\n }\n\n try {\n const templateContent = await readFile(join(root, templatePath), 'utf8')\n const {dataset, projectId, readToken = '', writeToken = ''} = envData\n\n const findAndReplaceVariable = (\n content: string,\n varRegex: RegExp | string,\n value: string,\n useQuotes: boolean,\n ) => {\n const varPattern = typeof varRegex === 'string' ? varRegex : varRegex.source\n const pattern = new RegExp(`.*${varPattern}=.*$`, 'gm')\n const matches = content.matchAll(pattern)\n\n let result = content\n for (const match of matches) {\n if (!match[0]) continue\n const varName = match[0].split('=')[0].trim()\n result = result.replaceAll(\n new RegExp(`${varName}=.*$`, 'gm'),\n `${varName}=${useQuotes ? `\"${value}\"` : value}`,\n )\n }\n\n return result\n }\n\n let envContent = templateContent\n const vars = [\n {pattern: ENV_VAR.PROJECT_ID, value: projectId},\n {pattern: ENV_VAR.DATASET, value: dataset},\n {pattern: ENV_VAR.READ_TOKEN, value: readToken},\n {pattern: ENV_VAR.WRITE_TOKEN, value: writeToken},\n ]\n const useQuotes = templateContent.includes('=\"')\n\n for (const {pattern, value} of vars) {\n envContent = findAndReplaceVariable(envContent, pattern, value, useQuotes)\n }\n\n await writeFile(join(root, targetName), envContent)\n } catch (err) {\n debug(`Error setting environment variables: ${err}`)\n throw new Error(\n 'Failed to set environment variables. This could be due to file permissions or the .env file format. See https://www.sanity.io/docs/environment-variables for details on environment variable setup.',\n {cause: err},\n )\n }\n}\n\nexport async function tryApplyPackageName(root: string, name: string): Promise<void> {\n try {\n const pkg = await readPackageJson(join(root, 'package.json'))\n pkg.name = name\n\n await writeFile(join(root, 'package.json'), JSON.stringify(pkg, null, 2))\n } catch {\n // noop\n }\n}\n"],"names":["access","readFile","writeFile","join","posix","sep","Readable","pipeline","readPackageJson","subdebug","ENV_TEMPLATE_FILES","REQUIRED_ENV_VAR","x","debug","DISALLOWED_PATHS","ENV_VAR","READ_TOKEN","WRITE_TOKEN","getGitHubRawContentUrl","repoInfo","branch","filePath","name","username","isGitHubRepoShorthand","value","URL","canParse","test","isGitHubRepoUrl","url","pathSegments","pathname","slice","split","protocol","hostname","length","downloadTarStream","bearerToken","headers","Authorization","res","fetch","body","Error","fromWeb","checkIsRemoteTemplate","templateName","includes","getGitHubRepoInfo","parts","tokenMessage","infoResponse","status","info","json","default_branch","downloadAndExtractRepo","root","rootPath","cwd","filter","p","posixPath","disallowedPath","startsWith","strip","checkIfNeedsApiToken","type","templatePath","Promise","any","map","file","templateContent","applyEnvVariables","envData","targetName","catch","dataset","projectId","readToken","writeToken","findAndReplaceVariable","content","varRegex","useQuotes","varPattern","source","pattern","RegExp","matches","matchAll","result","match","varName","trim","replaceAll","envContent","vars","PROJECT_ID","DATASET","err","cause","tryApplyPackageName","pkg","JSON","stringify"],"mappings":"AAAA,SAAQA,MAAM,EAAEC,QAAQ,EAAEC,SAAS,QAAO,mBAAkB;AAC5D,SAAQC,IAAI,EAAEC,KAAK,EAAEC,GAAG,QAAO,YAAW;AAC1C,SAAQC,QAAQ,QAAO,cAAa;AACpC,SAAQC,QAAQ,QAAO,uBAAsB;AAE7C,SAAQC,eAAe,EAAEC,QAAQ,QAAO,mBAAkB;AAC1D,SAAQC,kBAAkB,EAAEC,gBAAgB,QAAO,6BAA4B;AAC/E,SAAQC,CAAC,QAAO,MAAK;AAErB,MAAMC,QAAQJ,SAAS;AAEvB,MAAMK,mBAAmB;IACvB,qDAAqD;IACrD;CACD;AAED,MAAMC,UAAU;IACd,GAAGJ,gBAAgB;IACnBK,YAAY;IACZC,aAAa;AACf;AAoBA,OAAO,SAASC,uBA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AAC,GAAGA,OAAO;YAEpD;YAEA,OAAOqE;QACT;QAEA,IAAIK,aAAaxB;QACjB,MAAMyB,OAAO;YACX;gBAACV,SAAS3E,QAAQsF,UAAU;gBAAE5E,OAAOwD;YAAS;YAC9C;gBAACS,SAAS3E,QAAQuF,OAAO;gBAAE7E,OAAOuD;YAAO;YACzC;gBAACU,SAAS3E,QAAQC,UAAU;gBAAES,OAAOyD;YAAS;YAC9C;gBAACQ,SAAS3E,QAAQE,WAAW;gBAAEQ,OAAO0D;YAAU;SACjD;QACD,MAAMI,YAAYZ,gBAAgB1B,QAAQ,CAAC;QAE3C,KAAK,MAAM,EAACyC,OAAO,EAAEjE,KAAK,EAAC,IAAI2E,KAAM;YACnCD,aAAaf,uBAAuBe,YAAYT,SAASjE,OAAO8D;QAClE;QAEA,MAAMrF,UAAUC,KAAKwD,MAAMmB,aAAaqB;IAC1C,EAAE,OAAOI,KAAK;QACZ1F,MAAM,CAAC,qCAAqC,EAAE0F,KAAK;QACnD,MAAM,IAAI1D,MACR,uMACA;YAAC2D,OAAOD;QAAG;IAEf;AACF;AAEA,OAAO,eAAeE,oBAAoB9C,IAAY,EAAErC,IAAY;IAClE,IAAI;QACF,MAAMoF,MAAM,MAAMlG,gBAAgBL,KAAKwD,MAAM;QAC7C+C,IAAIpF,IAAI,GAAGA;QAEX,MAAMpB,UAAUC,KAAKwD,MAAM,iBAAiBgD,KAAKC,SAAS,CAACF,KAAK,MAAM;IACxE,EAAE,OAAM;IACN,OAAO;IACT;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/init/remoteTemplate.ts"],"sourcesContent":["import {access, readFile, writeFile} from 'node:fs/promises'\nimport {join, posix, sep} from 'node:path'\n\nimport {readPackageJson, subdebug} from '@sanity/cli-core'\nimport {ENV_TEMPLATE_FILES, REQUIRED_ENV_VAR} from '@sanity/template-validator'\nimport {extract} from 'tar'\n\nconst debug = subdebug('remoteTemplate')\n\nconst DISALLOWED_PATHS = [\n // Prevent security risks from unknown GitHub Actions\n '/.github/',\n]\n\nconst ENV_VAR = {\n ...REQUIRED_ENV_VAR,\n READ_TOKEN: 'SANITY_API_READ_TOKEN',\n WRITE_TOKEN: 'SANITY_API_WRITE_TOKEN',\n} as const\n\ntype EnvData = {\n dataset: string\n projectId: string\n readToken?: string\n writeToken?: string\n}\n\ntype GitHubUrlString =\n | `https://github.com/${string}/${string}`\n | `https://www.github.com/${string}/${string}`\n\nexport type RepoInfo = {\n branch: string\n filePath: string\n name: string\n username: string\n}\n\nexport function getGitHubRawContentUrl(repoInfo: RepoInfo): string {\n const {branch, filePath, name, username} = repoInfo\n return `https://raw.githubusercontent.com/${username}/${name}/${branch}/${filePath}`\n}\n\nfunction isGitHubRepoShorthand(value: string): boolean {\n if (URL.canParse(value)) {\n return false\n }\n // This supports :owner/:repo and :owner/:repo/nested/path, e.g.\n // sanity-io/sanity\n // sanity-io/sanity/templates/next-js\n // sanity-io/templates/live-content-api\n // sanity-io/sanity/packages/@sanity/cli/test/test-template\n return /^[\\w-]+\\/[\\w-.]+(\\/[@\\w-.]+)*$/.test(value)\n}\n\nfunction isGitHubRepoUrl(value: string | URL): value is GitHubUrlString | URL {\n if (!URL.canParse(value)) {\n return false\n }\n const url = new URL(value)\n const pathSegments = url.pathname.slice(1).split('/')\n\n return (\n url.protocol === 'https:' &&\n url.hostname === 'github.com' &&\n // The pathname must have at least 2 segments. If it has more than 2, the\n // third must be \"tree\" and it must have at least 4 segments.\n // https://github.com/:owner/:repo\n // https://github.com/:owner/:repo/tree/:ref\n pathSegments.length >= 2 &&\n (pathSegments.length > 2 ? pathSegments[2] === 'tree' && pathSegments.length >= 4 : true)\n )\n}\n\nasync function downloadTarStream(\n url: string,\n bearerToken?: string,\n): Promise<ReadableStream<Uint8Array>> {\n const headers: Record<string, string> = {}\n if (bearerToken) {\n headers.Authorization = `Bearer ${bearerToken}`\n }\n\n const res = await fetch(url, {headers})\n\n if (!res.body) {\n throw new Error(`Failed to download: ${url}`)\n }\n\n return res.body\n}\n\nexport function checkIsRemoteTemplate(templateName?: string): boolean {\n return templateName?.includes('/') ?? false\n}\n\nexport async function getGitHubRepoInfo(value: string, bearerToken?: string): Promise<RepoInfo> {\n let username = ''\n let name = ''\n let branch = ''\n let filePath = ''\n\n if (isGitHubRepoShorthand(value)) {\n const parts = value.split('/')\n username = parts[0]\n name = parts[1]\n // If there are more segments after owner/repo, they form the file path\n if (parts.length > 2) {\n filePath = parts.slice(2).join('/')\n }\n }\n\n if (isGitHubRepoUrl(value)) {\n const url = new URL(value)\n const pathSegments = url.pathname.slice(1).split('/')\n username = pathSegments[0]\n name = pathSegments[1]\n\n // If we have a \"tree\" segment, everything after branch is the file path\n if (pathSegments[2] === 'tree') {\n branch = pathSegments[3]\n if (pathSegments.length > 4) {\n filePath = pathSegments.slice(4).join('/')\n }\n }\n }\n\n if (!username || !name) {\n throw new Error('Invalid GitHub repository format')\n }\n\n const tokenMessage =\n 'GitHub repository not found. For private repositories, use --template-token to provide an access token.\\n\\n' +\n 'You can generate a new token at https://github.com/settings/personal-access-tokens/new\\n' +\n 'Set the token to \"read-only\" with repository access and a short expiry (e.g. 7 days) for security.'\n\n try {\n const headers: Record<string, string> = {}\n if (bearerToken) {\n headers.Authorization = `Bearer ${bearerToken}`\n }\n\n const infoResponse = await fetch(`https://api.github.com/repos/${username}/${name}`, {\n headers,\n })\n\n if (infoResponse.status !== 200) {\n if (infoResponse.status === 404) {\n throw new Error(tokenMessage)\n }\n throw new Error('GitHub repository not found')\n }\n\n const info = await infoResponse.json()\n\n return {\n branch: branch || info.default_branch,\n filePath,\n name,\n username,\n }\n } catch {\n throw new Error(tokenMessage)\n }\n}\n\nexport async function downloadAndExtractRepo(\n root: string,\n {branch, filePath, name, username}: RepoInfo,\n bearerToken?: string,\n): Promise<void> {\n let rootPath: string | null = null\n await extract({\n cwd: root,\n filter: (p: string) => {\n const posixPath = p.split(sep).join(posix.sep)\n if (rootPath === null) {\n const pathSegments = posixPath.split(posix.sep)\n rootPath = pathSegments.length > 0 ? pathSegments[0] : null\n }\n for (const disallowedPath of DISALLOWED_PATHS) {\n if (posixPath.includes(disallowedPath)) return false\n }\n return posixPath.startsWith(`${rootPath}${filePath ? `/${filePath}/` : '/'}`)\n },\n input: await downloadTarStream(\n `https://codeload.github.com/${username}/${name}/tar.gz/${branch}`,\n bearerToken,\n ),\n strip: filePath ? filePath.split('/').length + 1 : 1,\n })\n}\n\nexport async function checkIfNeedsApiToken(root: string, type: 'read' | 'write'): Promise<boolean> {\n try {\n const templatePath = await Promise.any(\n ENV_TEMPLATE_FILES.map(async (file) => {\n await access(join(root, file))\n return file\n }),\n )\n const templateContent = await readFile(join(root, templatePath), 'utf8')\n return templateContent.includes(type === 'read' ? ENV_VAR.READ_TOKEN : ENV_VAR.WRITE_TOKEN)\n } catch {\n return false\n }\n}\n\nexport async function applyEnvVariables(\n root: string,\n envData: EnvData,\n targetName = '.env',\n): Promise<void> {\n const templatePath = await Promise.any(\n ENV_TEMPLATE_FILES.map(async (file) => {\n await access(join(root, file))\n return file\n }),\n ).catch(() => {})\n\n if (!templatePath) {\n return // No template .env file found, skip\n }\n\n try {\n const templateContent = await readFile(join(root, templatePath), 'utf8')\n const {dataset, projectId, readToken = '', writeToken = ''} = envData\n\n const findAndReplaceVariable = (\n content: string,\n varRegex: RegExp | string,\n value: string,\n useQuotes: boolean,\n ) => {\n const varPattern = typeof varRegex === 'string' ? varRegex : varRegex.source\n const pattern = new RegExp(`.*${varPattern}=.*$`, 'gm')\n const matches = content.matchAll(pattern)\n\n let result = content\n for (const match of matches) {\n if (!match[0]) continue\n const varName = match[0].split('=')[0].trim()\n result = result.replaceAll(\n new RegExp(`${varName}=.*$`, 'gm'),\n `${varName}=${useQuotes ? `\"${value}\"` : value}`,\n )\n }\n\n return result\n }\n\n let envContent = templateContent\n const vars = [\n {pattern: ENV_VAR.PROJECT_ID, value: projectId},\n {pattern: ENV_VAR.DATASET, value: dataset},\n {pattern: ENV_VAR.READ_TOKEN, value: readToken},\n {pattern: ENV_VAR.WRITE_TOKEN, value: writeToken},\n ]\n const useQuotes = templateContent.includes('=\"')\n\n for (const {pattern, value} of vars) {\n envContent = findAndReplaceVariable(envContent, pattern, value, useQuotes)\n }\n\n await writeFile(join(root, targetName), envContent)\n } catch (err) {\n debug(`Error setting environment variables: ${err}`)\n throw new Error(\n 'Failed to set environment variables. This could be due to file permissions or the .env file format. See https://www.sanity.io/docs/environment-variables for details on environment variable setup.',\n {cause: err},\n )\n }\n}\n\nexport async function tryApplyPackageName(root: string, name: string): Promise<void> {\n try {\n const pkg = await readPackageJson(join(root, 'package.json'))\n pkg.name = name\n\n await writeFile(join(root, 'package.json'), JSON.stringify(pkg, null, 2))\n } catch {\n // noop\n }\n}\n"],"names":["access","readFile","writeFile","join","posix","sep","readPackageJson","subdebug","ENV_TEMPLATE_FILES","REQUIRED_ENV_VAR","extract","debug","DISALLOWED_PATHS","ENV_VAR","READ_TOKEN","WRITE_TOKEN","getGitHubRawContentUrl","repoInfo","branch","filePath","name","username","isGitHubRepoShorthand","value","URL","canParse","test","isGitHubRepoUrl","url","pathSegments","pathname","slice","split","protocol","hostname","length","downloadTarStream","bearerToken","headers","Authorization","res","fetch","body","Error","checkIsRemoteTemplate","templateName","includes","getGitHubRepoInfo","parts","tokenMessage","infoResponse","status","info","json","default_branch","downloadAndExtractRepo","root","rootPath","cwd","filter","p","posixPath","disallowedPath","startsWith","input","strip","checkIfNeedsApiToken","type","templatePath","Promise","any","map","file","templateContent","applyEnvVariables","envData","targetName","catch","dataset","projectId","readToken","writeToken","findAndReplaceVariable","content","varRegex","useQuotes","varPattern","source","pattern","RegExp","matches","matchAll","result","match","varName","trim","replaceAll","envContent","vars","PROJECT_ID","DATASET","err","cause","tryApplyPackageName","pkg","JSON","stringify"],"mappings":"AAAA,SAAQA,MAAM,EAAEC,QAAQ,EAAEC,SAAS,QAAO,mBAAkB;AAC5D,SAAQC,IAAI,EAAEC,KAAK,EAAEC,GAAG,QAAO,YAAW;AAE1C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
|
+
import { PassThrough, Writable } from 'node:stream';
|
|
2
|
+
import { x as extractTar } from 'tar';
|
|
3
|
+
/**
|
|
4
|
+
* A writable that extracts the tar data written to it into `cwd`. It finishes
|
|
5
|
+
* once every entry is on disk.
|
|
6
|
+
*
|
|
7
|
+
* @internal
|
|
8
|
+
*/ export function createExtractStream(cwd) {
|
|
9
|
+
const input = new PassThrough();
|
|
10
|
+
// tar stops reading at the end-of-archive marker. Keep `input` open and
|
|
11
|
+
// drain any record padding after it, or upstream writes stall.
|
|
12
|
+
const extraction = extractTar({
|
|
13
|
+
cwd,
|
|
14
|
+
input: input.iterator({
|
|
15
|
+
destroyOnReturn: false
|
|
16
|
+
})
|
|
17
|
+
}).finally(()=>input.resume());
|
|
18
|
+
const writable = new Writable({
|
|
19
|
+
destroy (error, callback) {
|
|
20
|
+
input.destroy(error ?? undefined);
|
|
21
|
+
callback(error);
|
|
22
|
+
},
|
|
23
|
+
final (callback) {
|
|
24
|
+
input.end();
|
|
25
|
+
extraction.then(()=>callback(), callback);
|
|
26
|
+
},
|
|
27
|
+
write (chunk, encoding, callback) {
|
|
28
|
+
input.write(chunk, encoding, callback);
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
// tar may have returned the iterator and removed its error handler already.
|
|
32
|
+
input.on('error', (error)=>writable.destroy(error));
|
|
33
|
+
extraction.catch((error)=>writable.destroy(error));
|
|
34
|
+
return writable;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
//# sourceMappingURL=createExtractStream.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/media/createExtractStream.ts"],"sourcesContent":["import {PassThrough, Writable} from 'node:stream'\n\nimport {x as extractTar} from 'tar'\n\n/**\n * A writable that extracts the tar data written to it into `cwd`. It finishes\n * once every entry is on disk.\n *\n * @internal\n */\nexport function createExtractStream(cwd: string): Writable {\n const input = new PassThrough()\n // tar stops reading at the end-of-archive marker. Keep `input` open and\n // drain any record padding after it, or upstream writes stall.\n const extraction = extractTar({cwd, input: input.iterator({destroyOnReturn: false})}).finally(\n () => input.resume(),\n )\n const writable = new Writable({\n destroy(error, callback) {\n input.destroy(error ?? undefined)\n callback(error)\n },\n final(callback) {\n input.end()\n extraction.then(() => callback(), callback)\n },\n write(chunk, encoding, callback) {\n input.write(chunk, encoding, callback)\n },\n })\n // tar may have returned the iterator and removed its error handler already.\n input.on('error', (error: Error) => writable.destroy(error))\n extraction.catch((error: Error) => writable.destroy(error))\n return writable\n}\n"],"names":["PassThrough","Writable","x","extractTar","createExtractStream","cwd","input","extraction","iterator","destroyOnReturn","finally","resume","writable","destroy","error","callback","undefined","final","end","then","write","chunk","encoding","on","catch"],"mappings":"AAAA,SAAQA,WAAW,EAAEC,QAAQ,QAAO,cAAa;AAEjD,SAAQC,KAAKC,UAAU,QAAO,MAAK;AAEnC;;;;;CAKC,GACD,OAAO,SAASC,oBAAoBC,GAAW;IAC7C,MAAMC,QAAQ,IAAIN;IAClB,wEAAwE;IACxE,+DAA+D;IAC/D,MAAMO,aAAaJ,WAAW;QAACE;QAAKC,OAAOA,MAAME,QAAQ,CAAC;YAACC,iBAAiB;QAAK;IAAE,GAAGC,OAAO,CAC3F,IAAMJ,MAAMK,MAAM;IAEpB,MAAMC,WAAW,IAAIX,SAAS;QAC5BY,SAAQC,KAAK,EAAEC,QAAQ;YACrBT,MAAMO,OAAO,CAACC,SAASE;YACvBD,SAASD;QACX;QACAG,OAAMF,QAAQ;YACZT,MAAMY,GAAG;YACTX,WAAWY,IAAI,CAAC,IAAMJ,YAAYA;QACpC;QACAK,OAAMC,KAAK,EAAEC,QAAQ,EAAEP,QAAQ;YAC7BT,MAAMc,KAAK,CAACC,OAAOC,UAAUP;QAC/B;IACF;IACA,4EAA4E;IAC5ET,MAAMiB,EAAE,CAAC,SAAS,CAACT,QAAiBF,SAASC,OAAO,CAACC;IACrDP,WAAWiB,KAAK,CAAC,CAACV,QAAiBF,SAASC,OAAO,CAACC;IACpD,OAAOF;AACT"}
|
|
@@ -10,10 +10,10 @@ import gunzipMaybe from 'gunzip-maybe';
|
|
|
10
10
|
// @ts-expect-error `peek-stream` module currently untyped
|
|
11
11
|
import peek from 'peek-stream';
|
|
12
12
|
import { catchError, EMPTY, filter, from, map, mergeMap, mergeWith, of, switchMap, tap, zip } from 'rxjs';
|
|
13
|
-
import { x as extractTar } from 'tar';
|
|
14
13
|
import { glob } from 'tinyglobby';
|
|
15
14
|
import { isTar } from '../../util/isTar.js';
|
|
16
15
|
import { buildNdjsonIndex } from './buildNdjsonIndex.js';
|
|
16
|
+
import { createExtractStream } from './createExtractStream.js';
|
|
17
17
|
import { importMediaDebug } from './importMediaDebug.js';
|
|
18
18
|
const DEFAULT_CONCURRENCY = 6;
|
|
19
19
|
export function importer(options) {
|
|
@@ -93,9 +93,7 @@ export function importer(options) {
|
|
|
93
93
|
newline: false
|
|
94
94
|
}, (data, swap)=>{
|
|
95
95
|
if (isTar(data)) {
|
|
96
|
-
return swap(null,
|
|
97
|
-
cwd: outputPath
|
|
98
|
-
}));
|
|
96
|
+
return swap(null, createExtractStream(outputPath));
|
|
99
97
|
}
|
|
100
98
|
return swap(null);
|
|
101
99
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/media/importMedia.ts"],"sourcesContent":["import {createHash} from 'node:crypto'\nimport {createReadStream} from 'node:fs'\nimport fs, {mkdtemp} from 'node:fs/promises'\nimport {tmpdir} from 'node:os'\nimport path from 'node:path'\nimport {text} from 'node:stream/consumers'\nimport {pipeline} from 'node:stream/promises'\nimport {styleText} from 'node:util'\n\nimport {spinner} from '@sanity/cli-core/ux'\nimport {type SanityClient} from '@sanity/client'\nimport gunzipMaybe from 'gunzip-maybe'\n// @ts-expect-error `peek-stream` module currently untyped\nimport peek from 'peek-stream'\nimport {\n catchError,\n EMPTY,\n filter,\n from,\n map,\n mergeMap,\n mergeWith,\n type Observable,\n of,\n type OperatorFunction,\n switchMap,\n tap,\n zip,\n} from 'rxjs'\nimport {x as extractTar} from 'tar'\nimport {glob} from 'tinyglobby'\n\nimport {type MediaLibraryAsset} from '../../services/mediaLibraries.js'\nimport {isTar} from '../../util/isTar.js'\nimport {buildNdjsonIndex} from './buildNdjsonIndex.js'\nimport {importMediaDebug} from './importMediaDebug.js'\n\nconst DEFAULT_CONCURRENCY = 6\n\ninterface MediaLibraryUploadResponse {\n body: MediaLibraryAsset\n type: 'response'\n}\n\nexport interface State {\n /**\n * The last asset processed.\n */\n asset: AssetWithAspects\n /**\n * The count of input files.\n */\n fileCount: number\n}\n\ninterface ResolvedAsset {\n /**\n * The ids of the `sanity.asset` documents that currently refer to the asset.\n *\n * These documents contain aspects, and reference an asset instance document.\n */\n assetIds: string[]\n isExistingAsset: boolean\n /**\n * The original filename of the asset as it appears in the import source.\n *\n * Note: Currently includes `images/` or `files/` prefix.\n */\n originalFilename: string\n sha1Hash: string\n}\n\nexport type AssetWithAspects<Asset extends ResolvedAsset = ResolvedAsset> = Asset & {\n aspects: unknown | undefined\n}\n\ninterface Options {\n client: SanityClient\n replaceAspects: boolean\n sourcePath: string\n spinner: ReturnType<typeof spinner>\n}\n\ninterface Context extends Options {\n aspectsIndex: Map<string, unknown>\n workingPath: string\n}\n\nexport function importer(options: Options): Observable<State> {\n return resolveSource(options).pipe(\n mergeMap(({aspectsNdjsonPath, files, images, workingPath}) => {\n const fileCount = files.length + images.length\n\n if (fileCount === 0) {\n throw new Error('No assets to import')\n }\n\n // Stream the ndjson file once and build an index to avoid creating\n // multiple read streams (which causes file descriptor leaks)\n const aspectsIndexPromise = buildNdjsonIndex(\n createReadStream(aspectsNdjsonPath),\n 'filename',\n 'aspects',\n )\n\n return from(aspectsIndexPromise).pipe(\n mergeMap((aspectsIndex) => {\n const context: Context = {\n ...options,\n aspectsIndex,\n workingPath,\n }\n\n return from(files).pipe(\n switchMap((file) => zip(of<'file'>('file'), of(file))),\n mergeWith(from(images).pipe(switchMap((file) => zip(of<'image'>('image'), of(file))))),\n fetchExistingAssets(context),\n uploadAsset(context),\n resolveAspectData(context),\n setAspects(context),\n map((asset) => ({\n asset,\n fileCount,\n })),\n )\n }),\n )\n }),\n )\n}\n\n/**\n * @internal\n */\nexport function resolveSource({sourcePath}: Pick<Context, 'sourcePath'>): Observable<{\n aspectsNdjsonPath: string\n files: string[]\n images: string[]\n workingPath: string\n}> {\n return from(fs.stat(sourcePath)).pipe(\n switchMap((stats) => {\n return stats.isDirectory()\n ? of(sourcePath)\n : from(mkdtemp(path.join(tmpdir(), 'sanity-media-library-import'))).pipe(\n switchMap((tempPath) => {\n return from(\n pipeline(createReadStream(sourcePath), gunzipMaybe(), untarMaybe(tempPath)),\n ).pipe(map(() => tempPath))\n }),\n )\n }),\n switchMap((importSourcePath) => {\n return from(\n glob(['**/data.ndjson'], {\n absolute: true,\n cwd: importSourcePath,\n deep: 2,\n }),\n ).pipe(\n map(([aspectsNdjsonPath]) => ({\n aspectsNdjsonPath,\n importSourcePath,\n workingPath:\n aspectsNdjsonPath === undefined ? importSourcePath : path.dirname(aspectsNdjsonPath),\n })),\n )\n }),\n tap(({aspectsNdjsonPath, importSourcePath}) => {\n if (aspectsNdjsonPath === undefined) {\n throw new Error(\n `No ${styleText('bold', 'data.ndjson')} file found in import source ${styleText('bold', importSourcePath)}`,\n )\n }\n importMediaDebug(`[Found NDJSON file] ${aspectsNdjsonPath}`)\n }),\n switchMap(({aspectsNdjsonPath, workingPath}) => {\n return from(\n Promise.all([\n glob(['files/*'], {\n cwd: workingPath,\n }),\n glob(['images/*'], {\n cwd: workingPath,\n }),\n ]),\n ).pipe(\n map(([files, images]) => ({\n aspectsNdjsonPath,\n files,\n images,\n workingPath,\n })),\n )\n }),\n )\n}\n\n/**\n * Untar the stream if its contents appear to be tarred.\n *\n * @internal\n */\nfunction untarMaybe(outputPath: string) {\n // @ts-expect-error `peek-stream` module currently untyped\n return peek({maxBuffer: 300, newline: false}, (data, swap) => {\n if (isTar(data)) {\n return swap(null, extractTar({cwd: outputPath}))\n }\n\n return swap(null)\n })\n}\n\n/**\n * Fetch the ids of all asset documents that reference the input asset.\n * The input asset is identified by its SHA-1 hash.\n *\n * @internal\n */\nfunction fetchAssetsByHash({\n client,\n type,\n}: {\n client: SanityClient\n type: 'file' | 'image'\n}): OperatorFunction<string, [hash: string, assetIds: string[]]> {\n return switchMap((hash) =>\n client.observable\n .fetch<string[]>(\n `*[\n _type == \"sanity.asset\" &&\n currentVersion._ref == *[\n _type == $type &&\n sha1hash == $hash\n ][0]._id\n ]._id`,\n {\n hash,\n type: ['sanity', `${type}Asset`].join('.'),\n },\n {\n tag: 'asset.getId',\n },\n )\n .pipe(switchMap((assetIds) => zip(of(hash), of(assetIds)))),\n )\n}\n\nfunction fetchExistingAssets({\n client,\n workingPath,\n}: Context): OperatorFunction<\n [type: 'file' | 'image', asset: string],\n [type: 'file' | 'image', asset: string, hash: string] | ResolvedAsset\n> {\n return mergeMap(([type, asset]) => {\n const createSha1Hash = createHash('sha1')\n\n const sha1hash = text(\n createReadStream(path.join(workingPath, asset)).pipe(createSha1Hash).setEncoding('hex'),\n )\n\n return from(sha1hash).pipe(\n tap((hash) =>\n importMediaDebug(`[Asset ${asset}] Checking for ${type} asset with hash ${hash}`),\n ),\n fetchAssetsByHash({client, type}),\n map<\n [string, string[]],\n [type: 'file' | 'image', asset: string, hash: string] | ResolvedAsset\n >(([hash, assetIds]) => {\n if (assetIds.length === 0) {\n return [type, asset, hash]\n }\n\n return {\n assetIds,\n isExistingAsset: true,\n originalFilename: asset,\n sha1Hash: hash,\n }\n }),\n )\n })\n}\n\n/**\n * Find the first matching entry in the cached aspect data and attach it to the asset object.\n *\n * @internal\n */\nfunction resolveAspectData({\n aspectsIndex,\n}: Context): OperatorFunction<ResolvedAsset, AssetWithAspects> {\n return map((resolvedAsset) => ({\n ...resolvedAsset,\n aspects: aspectsIndex.get(resolvedAsset.originalFilename),\n }))\n}\n\n// TODO: Batch mutations to reduce HTTP request count.\nexport function setAspects({\n client,\n replaceAspects,\n}: Pick<Context, 'client' | 'replaceAspects'>): OperatorFunction<\n AssetWithAspects,\n AssetWithAspects\n> {\n return mergeMap((asset) => {\n const {aspects, assetIds, isExistingAsset} = asset\n\n if (isExistingAsset && !replaceAspects) {\n importMediaDebug(`[Asset ${asset.originalFilename}] Skipping replacement of existing aspects`)\n return of(asset)\n }\n\n if (aspects === undefined) {\n importMediaDebug(`[Asset ${asset.originalFilename}] No aspects to import`)\n return of(asset)\n }\n\n const transaction = client.observable.transaction()\n for (const assetId of assetIds) {\n transaction.patch(assetId, {set: {aspects}})\n }\n\n importMediaDebug(\n `[Asset ${asset.originalFilename}] Setting aspects on asset documents ${JSON.stringify(assetIds)}`,\n )\n\n return transaction\n .commit({\n tag: 'asset.setAspects',\n visibility: 'async',\n })\n .pipe(map(() => asset))\n }, DEFAULT_CONCURRENCY)\n}\n\nfunction uploadAsset({\n client,\n workingPath,\n}: Context): OperatorFunction<\n [type: 'file' | 'image', asset: string, hash: string] | ResolvedAsset,\n ResolvedAsset\n> {\n return mergeMap((maybeResolvedAsset) => {\n if ('assetIds' in maybeResolvedAsset) {\n importMediaDebug(\n `[Asset ${maybeResolvedAsset.originalFilename}] Skipping upload of existing asset with hash ${maybeResolvedAsset.sha1Hash}`,\n )\n return of(maybeResolvedAsset)\n }\n\n const [type, asset, hash] = maybeResolvedAsset\n importMediaDebug(`[Asset ${asset}] Uploading new asset`)\n\n return client.observable.assets\n .upload(type, createReadStream(path.join(workingPath, asset)), {\n tag: 'asset.upload',\n })\n .pipe(\n catchError((error) => {\n // An asset matching the hash was not found during previous steps, but appears to exist upon upload.\n //\n // This may occur if:\n // - The asset was uploaded by another client since the check was performed.\n // - The asset instance document exists, but is not referenced by any asset document.\n if (error.statusCode === 409) {\n importMediaDebug(\n `[Asset ${asset}] Cannot overwrite existing ${type} asset with hash ${hash}`,\n )\n return EMPTY\n }\n return EMPTY\n }),\n filter((response) => response.type === 'response'),\n tap(() => importMediaDebug(`[Asset ${asset}] Finished uploading new asset`)),\n // TODO: The `client.assets.upload` method should return `MediaLibraryUploadResponse` when operating on Media Library resources. When that occurs, this type assertion can be removed.\n map((response) => (response as unknown as MediaLibraryUploadResponse).body),\n map<MediaLibraryAsset, ResolvedAsset>((result) => ({\n assetIds: [result.asset._id],\n isExistingAsset: false,\n originalFilename: asset,\n sha1Hash: hash,\n })),\n )\n }, DEFAULT_CONCURRENCY)\n}\n"],"names":["createHash","createReadStream","fs","mkdtemp","tmpdir","path","text","pipeline","styleText","gunzipMaybe","peek","catchError","EMPTY","filter","from","map","mergeMap","mergeWith","of","switchMap","tap","zip","x","extractTar","glob","isTar","buildNdjsonIndex","importMediaDebug","DEFAULT_CONCURRENCY","importer","options","resolveSource","pipe","aspectsNdjsonPath","files","images","workingPath","fileCount","length","Error","aspectsIndexPromise","aspectsIndex","context","file","fetchExistingAssets","uploadAsset","resolveAspectData","setAspects","asset","sourcePath","stat","stats","isDirectory","join","tempPath","untarMaybe","importSourcePath","absolute","cwd","deep","undefined","dirname","Promise","all","outputPath","maxBuffer","newline","data","swap","fetchAssetsByHash","client","type","hash","observable","fetch","tag","assetIds","createSha1Hash","sha1hash","setEncoding","isExistingAsset","originalFilename","sha1Hash","resolvedAsset","aspects","get","replaceAspects","transaction","assetId","patch","set","JSON","stringify","commit","visibility","maybeResolvedAsset","assets","upload","error","statusCode","response","body","result","_id"],"mappings":"AAAA,SAAQA,UAAU,QAAO,cAAa;AACtC,SAAQC,gBAAgB,QAAO,UAAS;AACxC,OAAOC,MAAKC,OAAO,QAAO,mBAAkB;AAC5C,SAAQC,MAAM,QAAO,UAAS;AAC9B,OAAOC,UAAU,YAAW;AAC5B,SAAQC,IAAI,QAAO,wBAAuB;AAC1C,SAAQC,QAAQ,QAAO,uBAAsB;AAC7C,SAAQC,SAAS,QAAO,YAAW;AAInC,OAAOC,iBAAiB,eAAc;AACtC,0DAA0D;AAC1D,OAAOC,UAAU,cAAa;AAC9B,SACEC,UAAU,EACVC,KAAK,EACLC,MAAM,EACN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EvD,OAAOsB,OAAOG,UAAU,CAACuB,MAAM,CAC5BC,MAAM,CAAC1B,MAAMtE,iBAAiBI,KAAKgD,IAAI,CAACjB,aAAaY,SAAS;YAC7D2B,KAAK;QACP,GACC3C,IAAI,CACHrB,WAAW,CAACuF;YACV,oGAAoG;YACpG,EAAE;YACF,qBAAqB;YACrB,8EAA8E;YAC9E,uFAAuF;YACvF,IAAIA,MAAMC,UAAU,KAAK,KAAK;gBAC5BxE,iBACE,CAAC,OAAO,EAAEqB,MAAM,4BAA4B,EAAEuB,KAAK,iBAAiB,EAAEC,MAAM;gBAE9E,OAAO5D;YACT;YACA,OAAOA;QACT,IACAC,OAAO,CAACuF,WAAaA,SAAS7B,IAAI,KAAK,aACvCnD,IAAI,IAAMO,iBAAiB,CAAC,OAAO,EAAEqB,MAAM,8BAA8B,CAAC,IAC1E,sLAAsL;QACtLjC,IAAI,CAACqF,WAAa,AAACA,SAAmDC,IAAI,GAC1EtF,IAAsC,CAACuF,SAAY,CAAA;gBACjD1B,UAAU;oBAAC0B,OAAOtD,KAAK,CAACuD,GAAG;iBAAC;gBAC5BvB,iBAAiB;gBACjBC,kBAAkBjC;gBAClBkC,UAAUV;YACZ,CAAA;IAEN,GAAG5C;AACL"}
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/media/importMedia.ts"],"sourcesContent":["import {createHash} from 'node:crypto'\nimport {createReadStream} from 'node:fs'\nimport fs, {mkdtemp} from 'node:fs/promises'\nimport {tmpdir} from 'node:os'\nimport path from 'node:path'\nimport {text} from 'node:stream/consumers'\nimport {pipeline} from 'node:stream/promises'\nimport {styleText} from 'node:util'\n\nimport {spinner} from '@sanity/cli-core/ux'\nimport {type SanityClient} from '@sanity/client'\nimport gunzipMaybe from 'gunzip-maybe'\n// @ts-expect-error `peek-stream` module currently untyped\nimport peek from 'peek-stream'\nimport {\n catchError,\n EMPTY,\n filter,\n from,\n map,\n mergeMap,\n mergeWith,\n type Observable,\n of,\n type OperatorFunction,\n switchMap,\n tap,\n zip,\n} from 'rxjs'\nimport {glob} from 'tinyglobby'\n\nimport {type MediaLibraryAsset} from '../../services/mediaLibraries.js'\nimport {isTar} from '../../util/isTar.js'\nimport {buildNdjsonIndex} from './buildNdjsonIndex.js'\nimport {createExtractStream} from './createExtractStream.js'\nimport {importMediaDebug} from './importMediaDebug.js'\n\nconst DEFAULT_CONCURRENCY = 6\n\ninterface MediaLibraryUploadResponse {\n body: MediaLibraryAsset\n type: 'response'\n}\n\nexport interface State {\n /**\n * The last asset processed.\n */\n asset: AssetWithAspects\n /**\n * The count of input files.\n */\n fileCount: number\n}\n\ninterface ResolvedAsset {\n /**\n * The ids of the `sanity.asset` documents that currently refer to the asset.\n *\n * These documents contain aspects, and reference an asset instance document.\n */\n assetIds: string[]\n isExistingAsset: boolean\n /**\n * The original filename of the asset as it appears in the import source.\n *\n * Note: Currently includes `images/` or `files/` prefix.\n */\n originalFilename: string\n sha1Hash: string\n}\n\nexport type AssetWithAspects<Asset extends ResolvedAsset = ResolvedAsset> = Asset & {\n aspects: unknown | undefined\n}\n\ninterface Options {\n client: SanityClient\n replaceAspects: boolean\n sourcePath: string\n spinner: ReturnType<typeof spinner>\n}\n\ninterface Context extends Options {\n aspectsIndex: Map<string, unknown>\n workingPath: string\n}\n\nexport function importer(options: Options): Observable<State> {\n return resolveSource(options).pipe(\n mergeMap(({aspectsNdjsonPath, files, images, workingPath}) => {\n const fileCount = files.length + images.length\n\n if (fileCount === 0) {\n throw new Error('No assets to import')\n }\n\n // Stream the ndjson file once and build an index to avoid creating\n // multiple read streams (which causes file descriptor leaks)\n const aspectsIndexPromise = buildNdjsonIndex(\n createReadStream(aspectsNdjsonPath),\n 'filename',\n 'aspects',\n )\n\n return from(aspectsIndexPromise).pipe(\n mergeMap((aspectsIndex) => {\n const context: Context = {\n ...options,\n aspectsIndex,\n workingPath,\n }\n\n return from(files).pipe(\n switchMap((file) => zip(of<'file'>('file'), of(file))),\n mergeWith(from(images).pipe(switchMap((file) => zip(of<'image'>('image'), of(file))))),\n fetchExistingAssets(context),\n uploadAsset(context),\n resolveAspectData(context),\n setAspects(context),\n map((asset) => ({\n asset,\n fileCount,\n })),\n )\n }),\n )\n }),\n )\n}\n\n/**\n * @internal\n */\nexport function resolveSource({sourcePath}: Pick<Context, 'sourcePath'>): Observable<{\n aspectsNdjsonPath: string\n files: string[]\n images: string[]\n workingPath: string\n}> {\n return from(fs.stat(sourcePath)).pipe(\n switchMap((stats) => {\n return stats.isDirectory()\n ? of(sourcePath)\n : from(mkdtemp(path.join(tmpdir(), 'sanity-media-library-import'))).pipe(\n switchMap((tempPath) => {\n return from(\n pipeline(createReadStream(sourcePath), gunzipMaybe(), untarMaybe(tempPath)),\n ).pipe(map(() => tempPath))\n }),\n )\n }),\n switchMap((importSourcePath) => {\n return from(\n glob(['**/data.ndjson'], {\n absolute: true,\n cwd: importSourcePath,\n deep: 2,\n }),\n ).pipe(\n map(([aspectsNdjsonPath]) => ({\n aspectsNdjsonPath,\n importSourcePath,\n workingPath:\n aspectsNdjsonPath === undefined ? importSourcePath : path.dirname(aspectsNdjsonPath),\n })),\n )\n }),\n tap(({aspectsNdjsonPath, importSourcePath}) => {\n if (aspectsNdjsonPath === undefined) {\n throw new Error(\n `No ${styleText('bold', 'data.ndjson')} file found in import source ${styleText('bold', importSourcePath)}`,\n )\n }\n importMediaDebug(`[Found NDJSON file] ${aspectsNdjsonPath}`)\n }),\n switchMap(({aspectsNdjsonPath, workingPath}) => {\n return from(\n Promise.all([\n glob(['files/*'], {\n cwd: workingPath,\n }),\n glob(['images/*'], {\n cwd: workingPath,\n }),\n ]),\n ).pipe(\n map(([files, images]) => ({\n aspectsNdjsonPath,\n files,\n images,\n workingPath,\n })),\n )\n }),\n )\n}\n\n/**\n * Untar the stream if its contents appear to be tarred.\n *\n * @internal\n */\nfunction untarMaybe(outputPath: string) {\n // @ts-expect-error `peek-stream` module currently untyped\n return peek({maxBuffer: 300, newline: false}, (data, swap) => {\n if (isTar(data)) {\n return swap(null, createExtractStream(outputPath))\n }\n\n return swap(null)\n })\n}\n\n/**\n * Fetch the ids of all asset documents that reference the input asset.\n * The input asset is identified by its SHA-1 hash.\n *\n * @internal\n */\nfunction fetchAssetsByHash({\n client,\n type,\n}: {\n client: SanityClient\n type: 'file' | 'image'\n}): OperatorFunction<string, [hash: string, assetIds: string[]]> {\n return switchMap((hash) =>\n client.observable\n .fetch<string[]>(\n `*[\n _type == \"sanity.asset\" &&\n currentVersion._ref == *[\n _type == $type &&\n sha1hash == $hash\n ][0]._id\n ]._id`,\n {\n hash,\n type: ['sanity', `${type}Asset`].join('.'),\n },\n {\n tag: 'asset.getId',\n },\n )\n .pipe(switchMap((assetIds) => zip(of(hash), of(assetIds)))),\n )\n}\n\nfunction fetchExistingAssets({\n client,\n workingPath,\n}: Context): OperatorFunction<\n [type: 'file' | 'image', asset: string],\n [type: 'file' | 'image', asset: string, hash: string] | ResolvedAsset\n> {\n return mergeMap(([type, asset]) => {\n const createSha1Hash = createHash('sha1')\n\n const sha1hash = text(\n createReadStream(path.join(workingPath, asset)).pipe(createSha1Hash).setEncoding('hex'),\n )\n\n return from(sha1hash).pipe(\n tap((hash) =>\n importMediaDebug(`[Asset ${asset}] Checking for ${type} asset with hash ${hash}`),\n ),\n fetchAssetsByHash({client, type}),\n map<\n [string, string[]],\n [type: 'file' | 'image', asset: string, hash: string] | ResolvedAsset\n >(([hash, assetIds]) => {\n if (assetIds.length === 0) {\n return [type, asset, hash]\n }\n\n return {\n assetIds,\n isExistingAsset: true,\n originalFilename: asset,\n sha1Hash: hash,\n }\n }),\n )\n })\n}\n\n/**\n * Find the first matching entry in the cached aspect data and attach it to the asset object.\n *\n * @internal\n */\nfunction resolveAspectData({\n aspectsIndex,\n}: Context): OperatorFunction<ResolvedAsset, AssetWithAspects> {\n return map((resolvedAsset) => ({\n ...resolvedAsset,\n aspects: aspectsIndex.get(resolvedAsset.originalFilename),\n }))\n}\n\n// TODO: Batch mutations to reduce HTTP request count.\nexport function setAspects({\n client,\n replaceAspects,\n}: Pick<Context, 'client' | 'replaceAspects'>): OperatorFunction<\n AssetWithAspects,\n AssetWithAspects\n> {\n return mergeMap((asset) => {\n const {aspects, assetIds, isExistingAsset} = asset\n\n if (isExistingAsset && !replaceAspects) {\n importMediaDebug(`[Asset ${asset.originalFilename}] Skipping replacement of existing aspects`)\n return of(asset)\n }\n\n if (aspects === undefined) {\n importMediaDebug(`[Asset ${asset.originalFilename}] No aspects to import`)\n return of(asset)\n }\n\n const transaction = client.observable.transaction()\n for (const assetId of assetIds) {\n transaction.patch(assetId, {set: {aspects}})\n }\n\n importMediaDebug(\n `[Asset ${asset.originalFilename}] Setting aspects on asset documents ${JSON.stringify(assetIds)}`,\n )\n\n return transaction\n .commit({\n tag: 'asset.setAspects',\n visibility: 'async',\n })\n .pipe(map(() => asset))\n }, DEFAULT_CONCURRENCY)\n}\n\nfunction uploadAsset({\n client,\n workingPath,\n}: Context): OperatorFunction<\n [type: 'file' | 'image', asset: string, hash: string] | ResolvedAsset,\n ResolvedAsset\n> {\n return mergeMap((maybeResolvedAsset) => {\n if ('assetIds' in maybeResolvedAsset) {\n importMediaDebug(\n `[Asset ${maybeResolvedAsset.originalFilename}] Skipping upload of existing asset with hash ${maybeResolvedAsset.sha1Hash}`,\n )\n return of(maybeResolvedAsset)\n }\n\n const [type, asset, hash] = maybeResolvedAsset\n importMediaDebug(`[Asset ${asset}] Uploading new asset`)\n\n return client.observable.assets\n .upload(type, createReadStream(path.join(workingPath, asset)), {\n tag: 'asset.upload',\n })\n .pipe(\n catchError((error) => {\n // An asset matching the hash was not found during previous steps, but appears to exist upon upload.\n //\n // This may occur if:\n // - The asset was uploaded by another client since the check was performed.\n // - The asset instance document exists, but is not referenced by any asset document.\n if (error.statusCode === 409) {\n importMediaDebug(\n `[Asset ${asset}] Cannot overwrite existing ${type} asset with hash ${hash}`,\n )\n return EMPTY\n }\n return EMPTY\n }),\n filter((response) => response.type === 'response'),\n tap(() => importMediaDebug(`[Asset ${asset}] Finished uploading new asset`)),\n // TODO: The `client.assets.upload` method should return `MediaLibraryUploadResponse` when operating on Media Library resources. When that occurs, this type assertion can be removed.\n map((response) => (response as unknown as MediaLibraryUploadResponse).body),\n map<MediaLibraryAsset, ResolvedAsset>((result) => ({\n assetIds: [result.asset._id],\n isExistingAsset: false,\n originalFilename: asset,\n sha1Hash: hash,\n })),\n )\n }, DEFAULT_CONCURRENCY)\n}\n"],"names":["createHash","createReadStream","fs","mkdtemp","tmpdir","path","text","pipeline","styleText","gunzipMaybe","peek","catchError","EMPTY","filter","from","map","mergeMap","mergeWith","of","switchMap","tap","zip","glob","isTar","buildNdjsonIndex","createExtractStream","importMediaDebug","DEFAULT_CONCURRENCY","importer","options","resolveSource","pipe","aspectsNdjsonPath","files","images","workingPath","fileCount","length","Error","aspectsIndexPromise","aspectsIndex","context","file","fetchExistingAssets","uploadAsset","resolveAspectData","setAspects","asset","sourcePath","stat","stats","isDirectory","join","tempPath","untarMaybe","importSourcePath","absolute","cwd","deep","undefined","dirname","Promise","all","outputPath","maxBuffer","newline","data","swap","fetchAssetsByHash","client","type","hash","observable","fetch","tag","assetIds","createSha1Hash","sha1hash","setEncoding","isExistingAsset","originalFilename","sha1Hash","resolvedAsset","aspects","get","replaceAspects","transaction","assetId","patch","set","JSON","stringify","commit","visibility","maybeResolvedAsset","assets","upload","error","statusCode","response","body","result","_id"],"mappings":"AAAA,SAAQA,UAAU,QAAO,cAAa;AACtC,SAAQC,gBAAgB,QAAO,UAAS;AACxC,OAAOC,MAAKC,OAAO,QAAO,mBAAkB;AAC5C,SAAQC,MAAM,QAAO,UAAS;AAC9B,OAAOC,UAAU,YAAW;AAC5B,SAAQC,IAAI,QAAO,wBAAuB;AAC1C,SAAQC,QAAQ,QAAO,uBAAsB;AAC7C,SAAQC,SAAS,QAAO,YAAW;AAInC,OAAOC,iBAAiB,eAAc;AACtC,0DAA0D;AAC1D,OAAOC,UAAU,cAAa;AAC9B,SACEC,UAAU,EACVC,KAAK,EAC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QAEvD,OAAOsB,OAAOG,UAAU,CAACuB,MAAM,CAC5BC,MAAM,CAAC1B,MAAMrE,iBAAiBI,KAAK+C,IAAI,CAACjB,aAAaY,SAAS;YAC7D2B,KAAK;QACP,GACC3C,IAAI,CACHpB,WAAW,CAACsF;YACV,oGAAoG;YACpG,EAAE;YACF,qBAAqB;YACrB,8EAA8E;YAC9E,uFAAuF;YACvF,IAAIA,MAAMC,UAAU,KAAK,KAAK;gBAC5BxE,iBACE,CAAC,OAAO,EAAEqB,MAAM,4BAA4B,EAAEuB,KAAK,iBAAiB,EAAEC,MAAM;gBAE9E,OAAO3D;YACT;YACA,OAAOA;QACT,IACAC,OAAO,CAACsF,WAAaA,SAAS7B,IAAI,KAAK,aACvClD,IAAI,IAAMM,iBAAiB,CAAC,OAAO,EAAEqB,MAAM,8BAA8B,CAAC,IAC1E,sLAAsL;QACtLhC,IAAI,CAACoF,WAAa,AAACA,SAAmDC,IAAI,GAC1ErF,IAAsC,CAACsF,SAAY,CAAA;gBACjD1B,UAAU;oBAAC0B,OAAOtD,KAAK,CAACuD,GAAG;iBAAC;gBAC5BvB,iBAAiB;gBACjBC,kBAAkBjC;gBAClBkC,UAAUV;YACZ,CAAA;IAEN,GAAG5C;AACL"}
|
package/dist/commands/login.js
CHANGED
|
@@ -27,7 +27,7 @@ export class LoginCommand extends SanityCommand {
|
|
|
27
27
|
description: 'Log in using a specific SSO provider within an organization'
|
|
28
28
|
}
|
|
29
29
|
];
|
|
30
|
-
static flags = {
|
|
30
|
+
/* eslint-disable perfectionist/sort-objects -- Keep token login first in generated usage. */ static flags = {
|
|
31
31
|
'with-token': Flags.boolean({
|
|
32
32
|
description: 'Read token from standard input',
|
|
33
33
|
exclusive: [
|
|
@@ -35,7 +35,6 @@ export class LoginCommand extends SanityCommand {
|
|
|
35
35
|
'sso'
|
|
36
36
|
]
|
|
37
37
|
}),
|
|
38
|
-
// eslint-disable-next-line perfectionist/sort-objects -- Keep token login first in generated usage.
|
|
39
38
|
experimental: Flags.boolean({
|
|
40
39
|
default: false,
|
|
41
40
|
hidden: true
|
|
@@ -69,7 +68,7 @@ export class LoginCommand extends SanityCommand {
|
|
|
69
68
|
helpValue: '<name>'
|
|
70
69
|
})
|
|
71
70
|
};
|
|
72
|
-
async run() {
|
|
71
|
+
/* eslint-enable perfectionist/sort-objects */ async run() {
|
|
73
72
|
const { flags } = await this.parse(LoginCommand);
|
|
74
73
|
const { 'sso-provider': ssoProvider, 'with-token': withToken, ...loginFlags } = flags;
|
|
75
74
|
try {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/commands/login.ts"],"sourcesContent":["import {Command, Flags} from '@oclif/core'\nimport {type FlagInput} from '@oclif/core/interfaces'\nimport {exitCodes, SanityCommand} from '@sanity/cli-core'\n\nimport {login} from '../actions/auth/login/login.js'\nimport {LOGIN_PROVIDER_IDS} from '../actions/auth/login/loginInstructions.js'\nimport {readTokenFromStdin} from '../util/readTokenFromStdin.js'\n\nexport class LoginCommand extends SanityCommand<typeof LoginCommand> {\n static override description = 'Log in to your Sanity account'\n static override examples: Array<Command.Example> = [\n {\n command: '<%= config.bin %> <%= command.id %>',\n description: 'Log in using default settings',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --with-token < token.txt',\n description: 'Log in using a token from standard input',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --provider github --no-open',\n description: 'Login with GitHub provider, but do not open a browser window automatically',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --sso my-organization',\n description: 'Log in using Single Sign-On with the \"my-organization\" slug',\n },\n {\n command:\n '<%= config.bin %> <%= command.id %> --sso my-organization --sso-provider \"Okta SSO\"',\n description: 'Log in using a specific SSO provider within an organization',\n },\n ]\n static override flags = {\n 'with-token': Flags.boolean({\n description: 'Read token from standard input',\n exclusive: ['provider', 'sso'],\n }),\n
|
|
1
|
+
{"version":3,"sources":["../../src/commands/login.ts"],"sourcesContent":["import {Command, Flags} from '@oclif/core'\nimport {type FlagInput} from '@oclif/core/interfaces'\nimport {exitCodes, SanityCommand} from '@sanity/cli-core'\n\nimport {login} from '../actions/auth/login/login.js'\nimport {LOGIN_PROVIDER_IDS} from '../actions/auth/login/loginInstructions.js'\nimport {readTokenFromStdin} from '../util/readTokenFromStdin.js'\n\nexport class LoginCommand extends SanityCommand<typeof LoginCommand> {\n static override description = 'Log in to your Sanity account'\n static override examples: Array<Command.Example> = [\n {\n command: '<%= config.bin %> <%= command.id %>',\n description: 'Log in using default settings',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --with-token < token.txt',\n description: 'Log in using a token from standard input',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --provider github --no-open',\n description: 'Login with GitHub provider, but do not open a browser window automatically',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --sso my-organization',\n description: 'Log in using Single Sign-On with the \"my-organization\" slug',\n },\n {\n command:\n '<%= config.bin %> <%= command.id %> --sso my-organization --sso-provider \"Okta SSO\"',\n description: 'Log in using a specific SSO provider within an organization',\n },\n ]\n /* eslint-disable perfectionist/sort-objects -- Keep token login first in generated usage. */\n static override flags = {\n 'with-token': Flags.boolean({\n description: 'Read token from standard input',\n exclusive: ['provider', 'sso'],\n }),\n experimental: Flags.boolean({\n default: false,\n hidden: true,\n }),\n open: Flags.boolean({\n allowNo: true,\n default: true,\n description: 'Open a browser window to log in (`--no-open` only prints URL)',\n }),\n provider: Flags.string({\n description: `Log in using a provider ID (${LOGIN_PROVIDER_IDS.join(', ')})`,\n exclusive: ['sso', 'with-token'],\n helpValue: '<providerId>',\n }),\n sso: Flags.string({\n description: 'Log in using Single Sign-On, using the given organization slug',\n exclusive: ['provider', 'with-token'],\n helpValue: '<slug>',\n }),\n 'sso-provider': Flags.string({\n dependsOn: ['sso'],\n description: 'Select a specific SSO provider by name (use with --sso)',\n helpValue: '<name>',\n }),\n } satisfies FlagInput\n /* eslint-enable perfectionist/sort-objects */\n\n public async run(): Promise<void> {\n const {flags} = await this.parse(LoginCommand)\n const {'sso-provider': ssoProvider, 'with-token': withToken, ...loginFlags} = flags\n\n try {\n const token = withToken\n ? await readTokenFromStdin(\n 'Token is required on standard input. Run `sanity login --with-token < token.txt`.',\n )\n : undefined\n\n await login({\n ...loginFlags,\n output: this.output,\n ssoProvider,\n telemetry: this.telemetry,\n token,\n })\n this.log('Login successful')\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n this.error(`Login failed: ${message}`, {exit: exitCodes.RUNTIME_ERROR})\n }\n }\n}\n"],"names":["Flags","exitCodes","SanityCommand","login","LOGIN_PROVIDER_IDS","readTokenFromStdin","LoginCommand","description","examples","command","flags","boolean","exclusive","experimental","default","hidden","open","allowNo","provider","string","join","helpValue","sso","dependsOn","run","parse","ssoProvider","withToken","loginFlags","token","undefined","output","telemetry","log","error","message","Error","String","exit","RUNTIME_ERROR"],"mappings":"AAAA,SAAiBA,KAAK,QAAO,cAAa;AAE1C,SAAQC,SAAS,EAAEC,aAAa,QAAO,mBAAkB;AAEzD,SAAQC,KAAK,QAAO,iCAAgC;AACpD,SAAQC,kBAAkB,QAAO,6CAA4C;AAC7E,SAAQC,kBAAkB,QAAO,gCAA+B;AAEhE,OAAO,MAAMC,qBAAqBJ;IAChC,OAAgBK,cAAc,gCAA+B;IAC7D,OAAgBC,WAAmC;QACjD;YACEC,SAAS;YACTF,aAAa;QACf;QACA;YACEE,SAAS;YACTF,aAAa;QACf;QACA;YACEE,SAAS;YACTF,aAAa;QACf;QACA;YACEE,SAAS;YACTF,aAAa;QACf;QACA;YACEE,SACE;YACFF,aAAa;QACf;KACD,CAAA;IACD,2FAA2F,GAC3F,OAAgBG,QAAQ;QACtB,cAAcV,MAAMW,OAAO,CAAC;YAC1BJ,aAAa;YACbK,WAAW;gBAAC;gBAAY;aAAM;QAChC;QACAC,cAAcb,MAAMW,OAAO,CAAC;YAC1BG,SAAS;YACTC,QAAQ;QACV;QACAC,MAAMhB,MAAMW,OAAO,CAAC;YAClBM,SAAS;YACTH,SAAS;YACTP,aAAa;QACf;QACAW,UAAUlB,MAAMmB,MAAM,CAAC;YACrBZ,aAAa,CAAC,4BAA4B,EAAEH,mBAAmBgB,IAAI,CAAC,MAAM,CAAC,CAAC;YAC5ER,WAAW;gBAAC;gBAAO;aAAa;YAChCS,WAAW;QACb;QACAC,KAAKtB,MAAMmB,MAAM,CAAC;YAChBZ,aAAa;YACbK,WAAW;gBAAC;gBAAY;aAAa;YACrCS,WAAW;QACb;QACA,gBAAgBrB,MAAMmB,MAAM,CAAC;YAC3BI,WAAW;gBAAC;aAAM;YAClBhB,aAAa;YACbc,WAAW;QACb;IACF,EAAqB;IACrB,4CAA4C,GAE5C,MAAaG,MAAqB;QAChC,MAAM,EAACd,KAAK,EAAC,GAAG,MAAM,IAAI,CAACe,KAAK,CAACnB;QACjC,MAAM,EAAC,gBAAgBoB,WAAW,EAAE,cAAcC,SAAS,EAAE,GAAGC,YAAW,GAAGlB;QAE9E,IAAI;YACF,MAAMmB,QAAQF,YACV,MAAMtB,mBACJ,uFAEFyB;YAEJ,MAAM3B,MAAM;gBACV,GAAGyB,UAAU;gBACbG,QAAQ,IAAI,CAACA,MAAM;gBACnBL;gBACAM,WAAW,IAAI,CAACA,SAAS;gBACzBH;YACF;YACA,IAAI,CAACI,GAAG,CAAC;QACX,EAAE,OAAOC,OAAO;YACd,MAAMC,UAAUD,iBAAiBE,QAAQF,MAAMC,OAAO,GAAGE,OAAOH;YAChE,IAAI,CAACA,KAAK,CAAC,CAAC,cAAc,EAAEC,SAAS,EAAE;gBAACG,MAAMrC,UAAUsC,aAAa;YAAA;QACvE;IACF;AACF"}
|
|
@@ -101,7 +101,9 @@
|
|
|
101
101
|
'installations/{installationId}/configs',
|
|
102
102
|
'installations/{installationId}/configs/{configId}',
|
|
103
103
|
'installations/{installationId}/interfaces',
|
|
104
|
+
'organizations/{organizationId}/applications',
|
|
104
105
|
'organizations/{organizationId}/applications/{applicationId}',
|
|
106
|
+
'projects/{projectId}/applications',
|
|
105
107
|
'projects/{projectId}/user-applications',
|
|
106
108
|
'projects/{projectId}/user-applications/{userApplicationId}',
|
|
107
109
|
'projects/{projectId}/user-applications/{userApplicationId}/config/{configKey}',
|
|
@@ -149,7 +151,9 @@
|
|
|
149
151
|
'installations/{installationId}/configs',
|
|
150
152
|
'installations/{installationId}/configs/{configId}',
|
|
151
153
|
'installations/{installationId}/interfaces',
|
|
154
|
+
'organizations/{organizationId}/applications',
|
|
152
155
|
'organizations/{organizationId}/applications/{applicationId}',
|
|
156
|
+
'projects/{projectId}/applications',
|
|
153
157
|
'projects/{projectId}/user-applications',
|
|
154
158
|
'projects/{projectId}/user-applications/{userApplicationId}',
|
|
155
159
|
'projects/{projectId}/user-applications/{userApplicationId}/config/{configKey}',
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/generated/apiRoutes.ts"],"sourcesContent":["/**\n * GENERATED FILE - DO NOT EDIT\n *\n * Routing manifest for `sanity api`, distilled from the published OpenAPI\n * specifications at https://www.sanity.io/docs/api/openapi\n *\n * Regenerate with: pnpm generate:api-routes\n */\nimport {type ApiRouteEntry} from '../actions/api/types.js'\n\nexport const apiRoutes: ApiRouteEntry[] = [\n {\n defaultApiVersion: 'v2025-07-11',\n host: 'global',\n pathPatterns: [\n 'access/invites/me',\n 'access/organization/{resourceId}/users/roles/default',\n 'access/requests/me',\n 'access/robots/me',\n 'access/robots/me/rotate',\n 'access/{resourceType}/{resourceId}/invites',\n 'access/{resourceType}/{resourceId}/invites/token/{inviteToken}',\n 'access/{resourceType}/{resourceId}/invites/token/{inviteToken}/accept',\n 'access/{resourceType}/{resourceId}/invites/token/{inviteToken}/eligibility',\n 'access/{resourceType}/{resourceId}/invites/{inviteId}',\n 'access/{resourceType}/{resourceId}/permissions',\n 'access/{resourceType}/{resourceId}/permissions/{permissionName}',\n 'access/{resourceType}/{resourceId}/requests',\n 'access/{resourceType}/{resourceId}/requests/state',\n 'access/{resourceType}/{resourceId}/requests/{requestId}/accept',\n 'access/{resourceType}/{resourceId}/requests/{requestId}/decline',\n 'access/{resourceType}/{resourceId}/robots',\n 'access/{resourceType}/{resourceId}/robots/{robotId}',\n 'access/{resourceType}/{resourceId}/roles',\n 'access/{resourceType}/{resourceId}/roles/{roleName}',\n 'access/{resourceType}/{resourceId}/user-permissions/me',\n 'access/{resourceType}/{resourceId}/user-permissions/me/check',\n 'access/{resourceType}/{resourceId}/users',\n 'access/{resourceType}/{resourceId}/users/me',\n 'access/{resourceType}/{resourceId}/users/{sanityUserId}',\n 'access/{resourceType}/{resourceId}/users/{sanityUserId}/roles',\n 'access/{resourceType}/{resourceId}/users/{sanityUserId}/roles/{roleName}'\n ],\n slug: 'access-api',\n title: 'Access API reference'\n },\n {\n defaultApiVersion: 'v2025-02-19',\n host: 'project',\n pathPatterns: [\n 'data/actions/{dataset}'\n ],\n slug: 'actions',\n title: 'Actions API reference'\n },\n {\n defaultApiVersion: 'v2021-02-01',\n host: 'global',\n pathPatterns: [\n 'activity',\n 'activity/export/csv'\n ],\n slug: 'activity-log',\n title: 'Activity Log API Reference'\n },\n {\n defaultApiVersion: 'vX',\n host: 'project',\n pathPatterns: [\n 'agent/action/generate/{dataset}',\n 'agent/action/patch/{dataset}',\n 'agent/action/prompt/{dataset}',\n 'agent/action/transform/{dataset}',\n 'agent/action/translate/{dataset}'\n ],\n slug: 'agent-actions',\n title: 'Agent Actions'\n },\n {\n host: 'global',\n pathPatterns: [\n 'applications',\n 'applications/dashboards',\n 'applications/dashboards/{dashboardId}',\n 'applications/dashboards/{dashboardId}/configs',\n 'applications/dashboards/{dashboardId}/configs/{configId}',\n 'applications/{applicationId}',\n 'applications/{applicationId}/access',\n 'applications/{applicationId}/deployments',\n 'applications/{applicationId}/embeddable',\n 'applications/{applicationId}/icon',\n 'applications/{applicationId}/installations',\n 'applications/{applicationId}/interfaces',\n 'applications/{applicationId}/interfaces/{interfaceId}/icon',\n 'applications/{applicationId}/workspaces',\n 'deploy',\n 'deploy/quickstart',\n 'installations',\n 'installations/ai-features',\n 'installations/catalog',\n 'installations/defaults',\n 'installations/{installationId}',\n 'installations/{installationId}/access',\n 'installations/{installationId}/configs',\n 'installations/{installationId}/configs/{configId}',\n 'installations/{installationId}/interfaces',\n 'organizations/{organizationId}/applications/{applicationId}',\n 'projects/{projectId}/user-applications',\n 'projects/{projectId}/user-applications/{userApplicationId}',\n 'projects/{projectId}/user-applications/{userApplicationId}/config/{configKey}',\n 'projects/{projectId}/user-applications/{userApplicationId}/deployments',\n 'studiohosts/{appHost}/availability',\n 'user-applications',\n 'user-applications/auto-update-version/{userApplicationId}',\n 'user-applications/resolve/application',\n 'user-applications/resolve/project',\n 'user-applications/workspaces',\n 'user-applications/{userApplicationId}',\n 'user-applications/{userApplicationId}/applicationData',\n 'user-applications/{userApplicationId}/config/{configKey}',\n 'user-applications/{userApplicationId}/deployments',\n 'user-applications/{userApplicationId}/workspaces'\n ],\n slug: 'applications-api',\n title: 'Applications API Reference'\n },\n {\n host: 'project',\n pathPatterns: [\n 'applications',\n 'applications/dashboards',\n 'applications/dashboards/{dashboardId}',\n 'applications/dashboards/{dashboardId}/configs',\n 'applications/dashboards/{dashboardId}/configs/{configId}',\n 'applications/{applicationId}',\n 'applications/{applicationId}/access',\n 'applications/{applicationId}/deployments',\n 'applications/{applicationId}/embeddable',\n 'applications/{applicationId}/icon',\n 'applications/{applicationId}/installations',\n 'applications/{applicationId}/interfaces',\n 'applications/{applicationId}/interfaces/{interfaceId}/icon',\n 'applications/{applicationId}/workspaces',\n 'deploy',\n 'deploy/quickstart',\n 'installations',\n 'installations/ai-features',\n 'installations/catalog',\n 'installations/defaults',\n 'installations/{installationId}',\n 'installations/{installationId}/access',\n 'installations/{installationId}/configs',\n 'installations/{installationId}/configs/{configId}',\n 'installations/{installationId}/interfaces',\n 'organizations/{organizationId}/applications/{applicationId}',\n 'projects/{projectId}/user-applications',\n 'projects/{projectId}/user-applications/{userApplicationId}',\n 'projects/{projectId}/user-applications/{userApplicationId}/config/{configKey}',\n 'projects/{projectId}/user-applications/{userApplicationId}/deployments',\n 'studiohosts/{appHost}/availability',\n 'user-applications',\n 'user-applications/auto-update-version/{userApplicationId}',\n 'user-applications/resolve/application',\n 'user-applications/resolve/project',\n 'user-applications/workspaces',\n 'user-applications/{userApplicationId}',\n 'user-applications/{userApplicationId}/applicationData',\n 'user-applications/{userApplicationId}/config/{configKey}',\n 'user-applications/{userApplicationId}/deployments',\n 'user-applications/{userApplicationId}/workspaces'\n ],\n slug: 'applications-api',\n title: 'Applications API Reference'\n },\n {\n defaultApiVersion: 'v2024-06-24',\n host: 'project',\n pathPatterns: [\n 'assets/files/{dataset}',\n 'assets/files/{dataset}/from-url',\n 'assets/images/{dataset}',\n 'assets/images/{dataset}/from-url',\n 'assets/media-library-link/{dataset}'\n ],\n slug: 'assets',\n title: 'Assets API reference'\n },\n {\n defaultApiVersion: 'v2025-02-19',\n host: 'global',\n pathPatterns: [\n 'projects/{projectId}/datasets/{datasetName}/backups',\n 'projects/{projectId}/datasets/{datasetName}/backups/{backupId}',\n 'projects/{projectId}/datasets/{datasetName}/settings/backups'\n ],\n slug: 'backups',\n title: 'Backups API reference'\n },\n {\n defaultApiVersion: 'v1',\n host: 'global',\n pathPatterns: [\n 'projects/{project_id}/datasets/{dataset_name}/assets/{asset_id}/purges',\n 'projects/{project_id}/datasets/{dataset_name}/purges'\n ],\n slug: 'cdn-cache-purge',\n title: 'CDN Cache Purge API Reference'\n },\n {\n defaultApiVersion: 'vX',\n host: 'global',\n pathPatterns: [\n 'collaboration/comments',\n 'collaboration/comments/listen',\n 'collaboration/comments/query',\n 'collaboration/comments/{id}',\n 'collaboration/comments/{id}/reactions',\n 'collaboration/comments/{id}/reactions/{shortName}'\n ],\n slug: 'comments-api',\n title: 'Comments API reference'\n },\n {\n defaultApiVersion: 'vX',\n host: 'project',\n pathPatterns: [\n 'collaboration/comments',\n 'collaboration/comments/listen',\n 'collaboration/comments/query',\n 'collaboration/comments/{id}',\n 'collaboration/comments/{id}/reactions',\n 'collaboration/comments/{id}/reactions/{shortName}'\n ],\n slug: 'comments-api',\n title: 'Comments API reference'\n },\n {\n defaultApiVersion: 'vX',\n host: 'global',\n pathPatterns: [\n 'agent/prompt',\n 'agent/{organizationId}/threads/{threadId}'\n ],\n slug: 'content-agent',\n title: 'Content Agent API reference'\n },\n {\n host: 'global',\n pathPatterns: [\n 'context/knowledge-bases',\n 'context/knowledge-bases/{knowledgeBaseId}',\n 'context/knowledge-bases/{knowledgeBaseId}/apply',\n 'context/knowledge-bases/{knowledgeBaseId}/build',\n 'context/knowledge-bases/{knowledgeBaseId}/build/cancel',\n 'context/knowledge-bases/{knowledgeBaseId}/discard',\n 'context/knowledge-bases/{knowledgeBaseId}/documents',\n 'context/knowledge-bases/{knowledgeBaseId}/documents/{documentId}',\n 'context/knowledge-bases/{knowledgeBaseId}/documents/{documentId}/content',\n 'context/knowledge-bases/{knowledgeBaseId}/entries/{entryPath}/rebuild',\n 'context/knowledge-bases/{knowledgeBaseId}/instructions',\n 'context/knowledge-bases/{knowledgeBaseId}/instructions/check',\n 'context/knowledge-bases/{knowledgeBaseId}/instructions/draft',\n 'context/knowledge-bases/{knowledgeBaseId}/instructions/{instructionId}',\n 'context/knowledge-bases/{knowledgeBaseId}/issues/apply',\n 'context/knowledge-bases/{knowledgeBaseId}/issues/{issueId}/dismiss',\n 'context/knowledge-bases/{knowledgeBaseId}/issues/{issueId}/reopen',\n 'context/knowledge-bases/{knowledgeBaseId}/issues/{issueId}/resolve',\n 'context/knowledge-bases/{knowledgeBaseId}/jobs/{jobId}',\n 'context/knowledge-bases/{knowledgeBaseId}/sources',\n 'context/knowledge-bases/{knowledgeBaseId}/sources/{sourceId}',\n 'context/knowledge-bases/{knowledgeBaseId}/sources/{sourceId}/syncs',\n 'context/knowledge-bases/{knowledgeBaseId}/sources/{sourceId}/syncs/{syncId}',\n 'context/knowledge-bases/{knowledgeBaseId}/sources/{sourceId}/uploads',\n 'context/knowledge-bases/{knowledgeBaseId}/sync',\n 'context/organizations/{organizationId}/conversations/{threadId}',\n 'context/organizations/{organizationId}/mcp',\n 'context/organizations/{organizationId}/mcp/{mcpEndpoint}',\n 'context/organizations/{organizationId}/mcp/{mcpEndpoint}/initial-context',\n 'context/organizations/{organizationId}/mcp/{mcpEndpoint}/status'\n ],\n slug: 'context-api',\n title: 'Context API reference'\n },\n {\n defaultApiVersion: 'v2025-02-19',\n host: 'global',\n pathPatterns: [\n 'projects/{projectId}/datasets/copy',\n 'projects/{projectId}/datasets/{dataset}/copy'\n ],\n slug: 'copy',\n title: 'Copy API reference'\n },\n {\n defaultApiVersion: 'v2025-02-19',\n host: 'project',\n pathPatterns: [\n 'data/doc/{dataset}/{documentId}'\n ],\n slug: 'doc',\n title: 'Doc API reference'\n },\n {\n defaultApiVersion: 'vX',\n host: 'project',\n pathPatterns: [\n 'embeddings-index/query/{dataset}/{indexName}',\n 'embeddings-index/{dataset}',\n 'embeddings-index/{dataset}/{indexName}'\n ],\n slug: 'embeddings-index',\n title: 'Embeddings Index API reference (deprecated)'\n },\n {\n defaultApiVersion: 'v2025-02-19',\n host: 'project',\n pathPatterns: [\n 'data/export/{dataset}'\n ],\n slug: 'export',\n title: 'Export API reference'\n },\n {\n host: 'global',\n pathPatterns: [\n 'functions',\n 'functions/durables/callback/{callbackId}/failure',\n 'functions/durables/callback/{callbackId}/success',\n 'functions/durables/{functionId}/executions',\n 'functions/durables/{functionId}/executions/{executionId}',\n 'functions/durables/{functionId}/executions/{executionId}/stop',\n 'functions/{functionId}',\n 'functions/{functionId}/envvars',\n 'functions/{functionId}/envvars/{envVarKey}',\n 'functions/{functionId}/invoke',\n 'functions/{functionId}/logs',\n 'functions/{functionId}/logs/stream'\n ],\n slug: 'functions-api',\n title: 'Functions API reference'\n },\n {\n defaultApiVersion: 'v2025-02-19',\n host: 'project',\n pathPatterns: [\n 'data/history/{dataset}/documents/{documentId}',\n 'data/history/{dataset}/transactions',\n 'data/history/{dataset}/transactions/{documentIds}'\n ],\n slug: 'history',\n title: 'History API reference'\n },\n {\n defaultApiVersion: 'v2021-06-07',\n host: 'global',\n pathPatterns: [\n 'jobs/{jobId}',\n 'jobs/{jobId}/listen'\n ],\n slug: 'jobs',\n title: 'Jobs API reference'\n },\n {\n defaultApiVersion: 'v2025-02-19',\n host: 'project',\n pathPatterns: [\n 'data/listen/{dataset}'\n ],\n slug: 'listen',\n title: 'Listen API reference'\n },\n {\n defaultApiVersion: 'v2025-02-19',\n host: 'project',\n pathPatterns: [\n 'data/live/events/{dataset}'\n ],\n slug: 'live',\n title: 'Live Content API reference'\n },\n {\n defaultApiVersion: 'v2025-02-19',\n host: 'global',\n pathPatterns: [\n 'media-libraries/{libraryId}/from-url',\n 'media-libraries/{libraryId}/mutate',\n 'media-libraries/{libraryId}/query',\n 'media-libraries/{libraryId}/references/documents/{assetId}/to',\n 'media-libraries/{libraryId}/refsearch',\n 'media-libraries/{libraryId}/signing-keys',\n 'media-libraries/{libraryId}/signing-keys/{keyId}',\n 'media-libraries/{libraryId}/upload',\n 'media-libraries/{libraryId}/video/{videoId}/playback-info',\n 'media-libraries/{libraryId}/video/{videoId}/playback/{type}',\n 'media-libraries/{libraryId}/video/{videoId}/renditions/{name}',\n 'media-libraries/{libraryId}/video/{videoId}/subtitles',\n 'media-libraries/{libraryId}/video/{videoId}/subtitles/upload',\n 'media-libraries/{libraryId}/video/{videoId}/subtitles/{subtitleId}'\n ],\n slug: 'media-library',\n title: 'Media Library API reference'\n },\n {\n defaultApiVersion: 'v2025-09-09',\n host: 'project',\n pathPatterns: [\n 'media-libraries/{libraryId}/from-url',\n 'media-libraries/{libraryId}/mutate',\n 'media-libraries/{libraryId}/query',\n 'media-libraries/{libraryId}/references/documents/{assetId}/to',\n 'media-libraries/{libraryId}/refsearch',\n 'media-libraries/{libraryId}/signing-keys',\n 'media-libraries/{libraryId}/signing-keys/{keyId}',\n 'media-libraries/{libraryId}/upload',\n 'media-libraries/{libraryId}/video/{videoId}/playback-info',\n 'media-libraries/{libraryId}/video/{videoId}/playback/{type}',\n 'media-libraries/{libraryId}/video/{videoId}/renditions/{name}',\n 'media-libraries/{libraryId}/video/{videoId}/subtitles',\n 'media-libraries/{libraryId}/video/{videoId}/subtitles/upload',\n 'media-libraries/{libraryId}/video/{videoId}/subtitles/{subtitleId}'\n ],\n slug: 'media-library',\n title: 'Media Library API reference'\n },\n {\n defaultApiVersion: 'v2025-02-19',\n host: 'project',\n pathPatterns: [\n 'data/mutate/{dataset}'\n ],\n slug: 'mutation',\n title: 'Mutation API reference'\n },\n {\n defaultApiVersion: 'v2021-06-07',\n host: 'global',\n pathPatterns: [\n 'projects',\n 'projects/{projectId}',\n 'projects/{projectId}/cors',\n 'projects/{projectId}/cors/{id}',\n 'projects/{projectId}/datasets',\n 'projects/{projectId}/datasets/copy',\n 'projects/{projectId}/datasets/{datasetName}/tags/{tagIdentifier}',\n 'projects/{projectId}/datasets/{name}',\n 'projects/{projectId}/datasets/{name}/copy',\n 'projects/{projectId}/datasets/{name}/settings/embeddings',\n 'projects/{projectId}/datasets/{name}/tags',\n 'projects/{projectId}/features',\n 'projects/{projectId}/permissions',\n 'projects/{projectId}/tags',\n 'projects/{projectId}/tags/{tagIdentifier}',\n 'projects/{projectId}/tokens',\n 'projects/{projectId}/tokens/{tokenId}',\n 'projects/{projectId}/users/{userId}'\n ],\n slug: 'projects-api',\n title: 'Projects API reference'\n },\n {\n defaultApiVersion: 'v2025-02-19',\n host: 'project',\n pathPatterns: [\n 'data/query/{dataset}'\n ],\n slug: 'query',\n title: 'Query API reference'\n },\n {\n defaultApiVersion: 'v2021-10-04',\n host: 'global',\n pathPatterns: [\n 'auth/organizations/{organizationId}/providers/{providerId}/projects/{projectId}/role-mappings',\n 'organizations/{organizationId}/acl',\n 'organizations/{organizationId}/acl/{sanityUserId}',\n 'organizations/{organizationId}/grants',\n 'projects/{projectId}/acl',\n 'projects/{projectId}/acl/{projectUserId}',\n 'projects/{projectId}/datasets/{datasetName}/acl',\n 'projects/{projectId}/datasets/{datasetName}/grants',\n 'projects/{projectId}/grants',\n 'projects/{projectId}/grants/{projectUserId}',\n 'projects/{projectId}/permissionResourceSchemas',\n 'projects/{projectId}/permissionResources',\n 'projects/{projectId}/permissionResources/{resourceId}',\n 'projects/{projectId}/roles',\n 'projects/{projectId}/roles/{roleName}'\n ],\n slug: 'roles',\n title: 'Roles API reference'\n },\n {\n defaultApiVersion: 'v2022-04-01',\n host: 'project',\n pathPatterns: [\n 'publish/{projectId}/{dataset}',\n 'schedules/{projectId}/{dataset}',\n 'schedules/{projectId}/{dataset}/{scheduleId}',\n 'schedules/{projectId}/{dataset}/{scheduleId}/publish',\n 'unpublish/{projectId}/{dataset}'\n ],\n slug: 'scheduling',\n title: 'Scheduling API reference'\n },\n {\n defaultApiVersion: 'v2026-09-01',\n host: 'global',\n pathPatterns: [\n 'usage/{resourceType}/{resourceId}/history',\n 'usage/{resourceType}/{resourceId}/snapshot',\n 'usage/{resourceType}/{resourceId}/{scope}/history',\n 'usage/{resourceType}/{resourceId}/{scope}/snapshot'\n ],\n slug: 'usage-api',\n title: 'Usage API reference'\n },\n {\n defaultApiVersion: 'v2026-04-27',\n host: 'global',\n pathPatterns: [\n 'organizations/{organizationId}/attribute-definitions',\n 'organizations/{organizationId}/attribute-definitions/{key}',\n 'organizations/{organizationId}/users/me/attributes',\n 'organizations/{organizationId}/users/{sanityUserId}/attributes'\n ],\n slug: 'user-attributes',\n title: 'User attributes API reference'\n },\n {\n defaultApiVersion: 'v2025-02-19',\n host: 'project',\n pathPatterns: [\n 'hooks/projects/{projectId}',\n 'hooks/projects/{projectId}/attempts/{attemptId}',\n 'hooks/projects/{projectId}/{id}',\n 'hooks/projects/{projectId}/{id}/attempts',\n 'hooks/projects/{projectId}/{id}/messages',\n 'hooks/projects/{projectId}/{id}/messages/{messageId}/attempts'\n ],\n slug: 'webhooks',\n title: 'Webhooks API reference'\n }\n]\n"],"names":["apiRoutes","defaultApiVersion","host","pathPatterns","slug","title"],"mappings":"AAAA;;;;;;;CAOC,GAGD,OAAO,MAAMA,YAA6B;IACxC;QACEC,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;YACA;YACA;YACA;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEH,MAAM;QACNC,cAAc;YACZ;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEH,MAAM;QACNC,cAAc;YACZ;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;YACA;YACA;YACA;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;YACA;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;YACA;YACA;YACA;YACA;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;YACA;YACA;YACA;YACA;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEH,MAAM;QACNC,cAAc;YACZ;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;YACA;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEH,MAAM;QACNC,cAAc;YACZ;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;YACA;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;YACA;YACA;YACA;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;YACA;YACA;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;YACA;YACA;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;YACA;YACA;YACA;YACA;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;CACD,CAAA"}
|
|
1
|
+
{"version":3,"sources":["../../src/generated/apiRoutes.ts"],"sourcesContent":["/**\n * GENERATED FILE - DO NOT EDIT\n *\n * Routing manifest for `sanity api`, distilled from the published OpenAPI\n * specifications at https://www.sanity.io/docs/api/openapi\n *\n * Regenerate with: pnpm generate:api-routes\n */\nimport {type ApiRouteEntry} from '../actions/api/types.js'\n\nexport const apiRoutes: ApiRouteEntry[] = [\n {\n defaultApiVersion: 'v2025-07-11',\n host: 'global',\n pathPatterns: [\n 'access/invites/me',\n 'access/organization/{resourceId}/users/roles/default',\n 'access/requests/me',\n 'access/robots/me',\n 'access/robots/me/rotate',\n 'access/{resourceType}/{resourceId}/invites',\n 'access/{resourceType}/{resourceId}/invites/token/{inviteToken}',\n 'access/{resourceType}/{resourceId}/invites/token/{inviteToken}/accept',\n 'access/{resourceType}/{resourceId}/invites/token/{inviteToken}/eligibility',\n 'access/{resourceType}/{resourceId}/invites/{inviteId}',\n 'access/{resourceType}/{resourceId}/permissions',\n 'access/{resourceType}/{resourceId}/permissions/{permissionName}',\n 'access/{resourceType}/{resourceId}/requests',\n 'access/{resourceType}/{resourceId}/requests/state',\n 'access/{resourceType}/{resourceId}/requests/{requestId}/accept',\n 'access/{resourceType}/{resourceId}/requests/{requestId}/decline',\n 'access/{resourceType}/{resourceId}/robots',\n 'access/{resourceType}/{resourceId}/robots/{robotId}',\n 'access/{resourceType}/{resourceId}/roles',\n 'access/{resourceType}/{resourceId}/roles/{roleName}',\n 'access/{resourceType}/{resourceId}/user-permissions/me',\n 'access/{resourceType}/{resourceId}/user-permissions/me/check',\n 'access/{resourceType}/{resourceId}/users',\n 'access/{resourceType}/{resourceId}/users/me',\n 'access/{resourceType}/{resourceId}/users/{sanityUserId}',\n 'access/{resourceType}/{resourceId}/users/{sanityUserId}/roles',\n 'access/{resourceType}/{resourceId}/users/{sanityUserId}/roles/{roleName}'\n ],\n slug: 'access-api',\n title: 'Access API reference'\n },\n {\n defaultApiVersion: 'v2025-02-19',\n host: 'project',\n pathPatterns: [\n 'data/actions/{dataset}'\n ],\n slug: 'actions',\n title: 'Actions API reference'\n },\n {\n defaultApiVersion: 'v2021-02-01',\n host: 'global',\n pathPatterns: [\n 'activity',\n 'activity/export/csv'\n ],\n slug: 'activity-log',\n title: 'Activity Log API Reference'\n },\n {\n defaultApiVersion: 'vX',\n host: 'project',\n pathPatterns: [\n 'agent/action/generate/{dataset}',\n 'agent/action/patch/{dataset}',\n 'agent/action/prompt/{dataset}',\n 'agent/action/transform/{dataset}',\n 'agent/action/translate/{dataset}'\n ],\n slug: 'agent-actions',\n title: 'Agent Actions'\n },\n {\n host: 'global',\n pathPatterns: [\n 'applications',\n 'applications/dashboards',\n 'applications/dashboards/{dashboardId}',\n 'applications/dashboards/{dashboardId}/configs',\n 'applications/dashboards/{dashboardId}/configs/{configId}',\n 'applications/{applicationId}',\n 'applications/{applicationId}/access',\n 'applications/{applicationId}/deployments',\n 'applications/{applicationId}/embeddable',\n 'applications/{applicationId}/icon',\n 'applications/{applicationId}/installations',\n 'applications/{applicationId}/interfaces',\n 'applications/{applicationId}/interfaces/{interfaceId}/icon',\n 'applications/{applicationId}/workspaces',\n 'deploy',\n 'deploy/quickstart',\n 'installations',\n 'installations/ai-features',\n 'installations/catalog',\n 'installations/defaults',\n 'installations/{installationId}',\n 'installations/{installationId}/access',\n 'installations/{installationId}/configs',\n 'installations/{installationId}/configs/{configId}',\n 'installations/{installationId}/interfaces',\n 'organizations/{organizationId}/applications',\n 'organizations/{organizationId}/applications/{applicationId}',\n 'projects/{projectId}/applications',\n 'projects/{projectId}/user-applications',\n 'projects/{projectId}/user-applications/{userApplicationId}',\n 'projects/{projectId}/user-applications/{userApplicationId}/config/{configKey}',\n 'projects/{projectId}/user-applications/{userApplicationId}/deployments',\n 'studiohosts/{appHost}/availability',\n 'user-applications',\n 'user-applications/auto-update-version/{userApplicationId}',\n 'user-applications/resolve/application',\n 'user-applications/resolve/project',\n 'user-applications/workspaces',\n 'user-applications/{userApplicationId}',\n 'user-applications/{userApplicationId}/applicationData',\n 'user-applications/{userApplicationId}/config/{configKey}',\n 'user-applications/{userApplicationId}/deployments',\n 'user-applications/{userApplicationId}/workspaces'\n ],\n slug: 'applications-api',\n title: 'Applications API Reference'\n },\n {\n host: 'project',\n pathPatterns: [\n 'applications',\n 'applications/dashboards',\n 'applications/dashboards/{dashboardId}',\n 'applications/dashboards/{dashboardId}/configs',\n 'applications/dashboards/{dashboardId}/configs/{configId}',\n 'applications/{applicationId}',\n 'applications/{applicationId}/access',\n 'applications/{applicationId}/deployments',\n 'applications/{applicationId}/embeddable',\n 'applications/{applicationId}/icon',\n 'applications/{applicationId}/installations',\n 'applications/{applicationId}/interfaces',\n 'applications/{applicationId}/interfaces/{interfaceId}/icon',\n 'applications/{applicationId}/workspaces',\n 'deploy',\n 'deploy/quickstart',\n 'installations',\n 'installations/ai-features',\n 'installations/catalog',\n 'installations/defaults',\n 'installations/{installationId}',\n 'installations/{installationId}/access',\n 'installations/{installationId}/configs',\n 'installations/{installationId}/configs/{configId}',\n 'installations/{installationId}/interfaces',\n 'organizations/{organizationId}/applications',\n 'organizations/{organizationId}/applications/{applicationId}',\n 'projects/{projectId}/applications',\n 'projects/{projectId}/user-applications',\n 'projects/{projectId}/user-applications/{userApplicationId}',\n 'projects/{projectId}/user-applications/{userApplicationId}/config/{configKey}',\n 'projects/{projectId}/user-applications/{userApplicationId}/deployments',\n 'studiohosts/{appHost}/availability',\n 'user-applications',\n 'user-applications/auto-update-version/{userApplicationId}',\n 'user-applications/resolve/application',\n 'user-applications/resolve/project',\n 'user-applications/workspaces',\n 'user-applications/{userApplicationId}',\n 'user-applications/{userApplicationId}/applicationData',\n 'user-applications/{userApplicationId}/config/{configKey}',\n 'user-applications/{userApplicationId}/deployments',\n 'user-applications/{userApplicationId}/workspaces'\n ],\n slug: 'applications-api',\n title: 'Applications API Reference'\n },\n {\n defaultApiVersion: 'v2024-06-24',\n host: 'project',\n pathPatterns: [\n 'assets/files/{dataset}',\n 'assets/files/{dataset}/from-url',\n 'assets/images/{dataset}',\n 'assets/images/{dataset}/from-url',\n 'assets/media-library-link/{dataset}'\n ],\n slug: 'assets',\n title: 'Assets API reference'\n },\n {\n defaultApiVersion: 'v2025-02-19',\n host: 'global',\n pathPatterns: [\n 'projects/{projectId}/datasets/{datasetName}/backups',\n 'projects/{projectId}/datasets/{datasetName}/backups/{backupId}',\n 'projects/{projectId}/datasets/{datasetName}/settings/backups'\n ],\n slug: 'backups',\n title: 'Backups API reference'\n },\n {\n defaultApiVersion: 'v1',\n host: 'global',\n pathPatterns: [\n 'projects/{project_id}/datasets/{dataset_name}/assets/{asset_id}/purges',\n 'projects/{project_id}/datasets/{dataset_name}/purges'\n ],\n slug: 'cdn-cache-purge',\n title: 'CDN Cache Purge API Reference'\n },\n {\n defaultApiVersion: 'vX',\n host: 'global',\n pathPatterns: [\n 'collaboration/comments',\n 'collaboration/comments/listen',\n 'collaboration/comments/query',\n 'collaboration/comments/{id}',\n 'collaboration/comments/{id}/reactions',\n 'collaboration/comments/{id}/reactions/{shortName}'\n ],\n slug: 'comments-api',\n title: 'Comments API reference'\n },\n {\n defaultApiVersion: 'vX',\n host: 'project',\n pathPatterns: [\n 'collaboration/comments',\n 'collaboration/comments/listen',\n 'collaboration/comments/query',\n 'collaboration/comments/{id}',\n 'collaboration/comments/{id}/reactions',\n 'collaboration/comments/{id}/reactions/{shortName}'\n ],\n slug: 'comments-api',\n title: 'Comments API reference'\n },\n {\n defaultApiVersion: 'vX',\n host: 'global',\n pathPatterns: [\n 'agent/prompt',\n 'agent/{organizationId}/threads/{threadId}'\n ],\n slug: 'content-agent',\n title: 'Content Agent API reference'\n },\n {\n host: 'global',\n pathPatterns: [\n 'context/knowledge-bases',\n 'context/knowledge-bases/{knowledgeBaseId}',\n 'context/knowledge-bases/{knowledgeBaseId}/apply',\n 'context/knowledge-bases/{knowledgeBaseId}/build',\n 'context/knowledge-bases/{knowledgeBaseId}/build/cancel',\n 'context/knowledge-bases/{knowledgeBaseId}/discard',\n 'context/knowledge-bases/{knowledgeBaseId}/documents',\n 'context/knowledge-bases/{knowledgeBaseId}/documents/{documentId}',\n 'context/knowledge-bases/{knowledgeBaseId}/documents/{documentId}/content',\n 'context/knowledge-bases/{knowledgeBaseId}/entries/{entryPath}/rebuild',\n 'context/knowledge-bases/{knowledgeBaseId}/instructions',\n 'context/knowledge-bases/{knowledgeBaseId}/instructions/check',\n 'context/knowledge-bases/{knowledgeBaseId}/instructions/draft',\n 'context/knowledge-bases/{knowledgeBaseId}/instructions/{instructionId}',\n 'context/knowledge-bases/{knowledgeBaseId}/issues/apply',\n 'context/knowledge-bases/{knowledgeBaseId}/issues/{issueId}/dismiss',\n 'context/knowledge-bases/{knowledgeBaseId}/issues/{issueId}/reopen',\n 'context/knowledge-bases/{knowledgeBaseId}/issues/{issueId}/resolve',\n 'context/knowledge-bases/{knowledgeBaseId}/jobs/{jobId}',\n 'context/knowledge-bases/{knowledgeBaseId}/sources',\n 'context/knowledge-bases/{knowledgeBaseId}/sources/{sourceId}',\n 'context/knowledge-bases/{knowledgeBaseId}/sources/{sourceId}/syncs',\n 'context/knowledge-bases/{knowledgeBaseId}/sources/{sourceId}/syncs/{syncId}',\n 'context/knowledge-bases/{knowledgeBaseId}/sources/{sourceId}/uploads',\n 'context/knowledge-bases/{knowledgeBaseId}/sync',\n 'context/organizations/{organizationId}/conversations/{threadId}',\n 'context/organizations/{organizationId}/mcp',\n 'context/organizations/{organizationId}/mcp/{mcpEndpoint}',\n 'context/organizations/{organizationId}/mcp/{mcpEndpoint}/initial-context',\n 'context/organizations/{organizationId}/mcp/{mcpEndpoint}/status'\n ],\n slug: 'context-api',\n title: 'Context API reference'\n },\n {\n defaultApiVersion: 'v2025-02-19',\n host: 'global',\n pathPatterns: [\n 'projects/{projectId}/datasets/copy',\n 'projects/{projectId}/datasets/{dataset}/copy'\n ],\n slug: 'copy',\n title: 'Copy API reference'\n },\n {\n defaultApiVersion: 'v2025-02-19',\n host: 'project',\n pathPatterns: [\n 'data/doc/{dataset}/{documentId}'\n ],\n slug: 'doc',\n title: 'Doc API reference'\n },\n {\n defaultApiVersion: 'vX',\n host: 'project',\n pathPatterns: [\n 'embeddings-index/query/{dataset}/{indexName}',\n 'embeddings-index/{dataset}',\n 'embeddings-index/{dataset}/{indexName}'\n ],\n slug: 'embeddings-index',\n title: 'Embeddings Index API reference (deprecated)'\n },\n {\n defaultApiVersion: 'v2025-02-19',\n host: 'project',\n pathPatterns: [\n 'data/export/{dataset}'\n ],\n slug: 'export',\n title: 'Export API reference'\n },\n {\n host: 'global',\n pathPatterns: [\n 'functions',\n 'functions/durables/callback/{callbackId}/failure',\n 'functions/durables/callback/{callbackId}/success',\n 'functions/durables/{functionId}/executions',\n 'functions/durables/{functionId}/executions/{executionId}',\n 'functions/durables/{functionId}/executions/{executionId}/stop',\n 'functions/{functionId}',\n 'functions/{functionId}/envvars',\n 'functions/{functionId}/envvars/{envVarKey}',\n 'functions/{functionId}/invoke',\n 'functions/{functionId}/logs',\n 'functions/{functionId}/logs/stream'\n ],\n slug: 'functions-api',\n title: 'Functions API reference'\n },\n {\n defaultApiVersion: 'v2025-02-19',\n host: 'project',\n pathPatterns: [\n 'data/history/{dataset}/documents/{documentId}',\n 'data/history/{dataset}/transactions',\n 'data/history/{dataset}/transactions/{documentIds}'\n ],\n slug: 'history',\n title: 'History API reference'\n },\n {\n defaultApiVersion: 'v2021-06-07',\n host: 'global',\n pathPatterns: [\n 'jobs/{jobId}',\n 'jobs/{jobId}/listen'\n ],\n slug: 'jobs',\n title: 'Jobs API reference'\n },\n {\n defaultApiVersion: 'v2025-02-19',\n host: 'project',\n pathPatterns: [\n 'data/listen/{dataset}'\n ],\n slug: 'listen',\n title: 'Listen API reference'\n },\n {\n defaultApiVersion: 'v2025-02-19',\n host: 'project',\n pathPatterns: [\n 'data/live/events/{dataset}'\n ],\n slug: 'live',\n title: 'Live Content API reference'\n },\n {\n defaultApiVersion: 'v2025-02-19',\n host: 'global',\n pathPatterns: [\n 'media-libraries/{libraryId}/from-url',\n 'media-libraries/{libraryId}/mutate',\n 'media-libraries/{libraryId}/query',\n 'media-libraries/{libraryId}/references/documents/{assetId}/to',\n 'media-libraries/{libraryId}/refsearch',\n 'media-libraries/{libraryId}/signing-keys',\n 'media-libraries/{libraryId}/signing-keys/{keyId}',\n 'media-libraries/{libraryId}/upload',\n 'media-libraries/{libraryId}/video/{videoId}/playback-info',\n 'media-libraries/{libraryId}/video/{videoId}/playback/{type}',\n 'media-libraries/{libraryId}/video/{videoId}/renditions/{name}',\n 'media-libraries/{libraryId}/video/{videoId}/subtitles',\n 'media-libraries/{libraryId}/video/{videoId}/subtitles/upload',\n 'media-libraries/{libraryId}/video/{videoId}/subtitles/{subtitleId}'\n ],\n slug: 'media-library',\n title: 'Media Library API reference'\n },\n {\n defaultApiVersion: 'v2025-09-09',\n host: 'project',\n pathPatterns: [\n 'media-libraries/{libraryId}/from-url',\n 'media-libraries/{libraryId}/mutate',\n 'media-libraries/{libraryId}/query',\n 'media-libraries/{libraryId}/references/documents/{assetId}/to',\n 'media-libraries/{libraryId}/refsearch',\n 'media-libraries/{libraryId}/signing-keys',\n 'media-libraries/{libraryId}/signing-keys/{keyId}',\n 'media-libraries/{libraryId}/upload',\n 'media-libraries/{libraryId}/video/{videoId}/playback-info',\n 'media-libraries/{libraryId}/video/{videoId}/playback/{type}',\n 'media-libraries/{libraryId}/video/{videoId}/renditions/{name}',\n 'media-libraries/{libraryId}/video/{videoId}/subtitles',\n 'media-libraries/{libraryId}/video/{videoId}/subtitles/upload',\n 'media-libraries/{libraryId}/video/{videoId}/subtitles/{subtitleId}'\n ],\n slug: 'media-library',\n title: 'Media Library API reference'\n },\n {\n defaultApiVersion: 'v2025-02-19',\n host: 'project',\n pathPatterns: [\n 'data/mutate/{dataset}'\n ],\n slug: 'mutation',\n title: 'Mutation API reference'\n },\n {\n defaultApiVersion: 'v2021-06-07',\n host: 'global',\n pathPatterns: [\n 'projects',\n 'projects/{projectId}',\n 'projects/{projectId}/cors',\n 'projects/{projectId}/cors/{id}',\n 'projects/{projectId}/datasets',\n 'projects/{projectId}/datasets/copy',\n 'projects/{projectId}/datasets/{datasetName}/tags/{tagIdentifier}',\n 'projects/{projectId}/datasets/{name}',\n 'projects/{projectId}/datasets/{name}/copy',\n 'projects/{projectId}/datasets/{name}/settings/embeddings',\n 'projects/{projectId}/datasets/{name}/tags',\n 'projects/{projectId}/features',\n 'projects/{projectId}/permissions',\n 'projects/{projectId}/tags',\n 'projects/{projectId}/tags/{tagIdentifier}',\n 'projects/{projectId}/tokens',\n 'projects/{projectId}/tokens/{tokenId}',\n 'projects/{projectId}/users/{userId}'\n ],\n slug: 'projects-api',\n title: 'Projects API reference'\n },\n {\n defaultApiVersion: 'v2025-02-19',\n host: 'project',\n pathPatterns: [\n 'data/query/{dataset}'\n ],\n slug: 'query',\n title: 'Query API reference'\n },\n {\n defaultApiVersion: 'v2021-10-04',\n host: 'global',\n pathPatterns: [\n 'auth/organizations/{organizationId}/providers/{providerId}/projects/{projectId}/role-mappings',\n 'organizations/{organizationId}/acl',\n 'organizations/{organizationId}/acl/{sanityUserId}',\n 'organizations/{organizationId}/grants',\n 'projects/{projectId}/acl',\n 'projects/{projectId}/acl/{projectUserId}',\n 'projects/{projectId}/datasets/{datasetName}/acl',\n 'projects/{projectId}/datasets/{datasetName}/grants',\n 'projects/{projectId}/grants',\n 'projects/{projectId}/grants/{projectUserId}',\n 'projects/{projectId}/permissionResourceSchemas',\n 'projects/{projectId}/permissionResources',\n 'projects/{projectId}/permissionResources/{resourceId}',\n 'projects/{projectId}/roles',\n 'projects/{projectId}/roles/{roleName}'\n ],\n slug: 'roles',\n title: 'Roles API reference'\n },\n {\n defaultApiVersion: 'v2022-04-01',\n host: 'project',\n pathPatterns: [\n 'publish/{projectId}/{dataset}',\n 'schedules/{projectId}/{dataset}',\n 'schedules/{projectId}/{dataset}/{scheduleId}',\n 'schedules/{projectId}/{dataset}/{scheduleId}/publish',\n 'unpublish/{projectId}/{dataset}'\n ],\n slug: 'scheduling',\n title: 'Scheduling API reference'\n },\n {\n defaultApiVersion: 'v2026-09-01',\n host: 'global',\n pathPatterns: [\n 'usage/{resourceType}/{resourceId}/history',\n 'usage/{resourceType}/{resourceId}/snapshot',\n 'usage/{resourceType}/{resourceId}/{scope}/history',\n 'usage/{resourceType}/{resourceId}/{scope}/snapshot'\n ],\n slug: 'usage-api',\n title: 'Usage API reference'\n },\n {\n defaultApiVersion: 'v2026-04-27',\n host: 'global',\n pathPatterns: [\n 'organizations/{organizationId}/attribute-definitions',\n 'organizations/{organizationId}/attribute-definitions/{key}',\n 'organizations/{organizationId}/users/me/attributes',\n 'organizations/{organizationId}/users/{sanityUserId}/attributes'\n ],\n slug: 'user-attributes',\n title: 'User attributes API reference'\n },\n {\n defaultApiVersion: 'v2025-02-19',\n host: 'project',\n pathPatterns: [\n 'hooks/projects/{projectId}',\n 'hooks/projects/{projectId}/attempts/{attemptId}',\n 'hooks/projects/{projectId}/{id}',\n 'hooks/projects/{projectId}/{id}/attempts',\n 'hooks/projects/{projectId}/{id}/messages',\n 'hooks/projects/{projectId}/{id}/messages/{messageId}/attempts'\n ],\n slug: 'webhooks',\n title: 'Webhooks API reference'\n }\n]\n"],"names":["apiRoutes","defaultApiVersion","host","pathPatterns","slug","title"],"mappings":"AAAA;;;;;;;CAOC,GAGD,OAAO,MAAMA,YAA6B;IACxC;QACEC,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;YACA;YACA;YACA;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEH,MAAM;QACNC,cAAc;YACZ;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEH,MAAM;QACNC,cAAc;YACZ;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;YACA;YACA;YACA;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;YACA;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;YACA;YACA;YACA;YACA;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;YACA;YACA;YACA;YACA;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEH,MAAM;QACNC,cAAc;YACZ;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;YACA;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEH,MAAM;QACNC,cAAc;YACZ;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;YACA;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;YACA;YACA;YACA;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;YACA;YACA;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;YACA;YACA;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;IACA;QACEJ,mBAAmB;QACnBC,MAAM;QACNC,cAAc;YACZ;YACA;YACA;YACA;YACA;YACA;SACD;QACDC,MAAM;QACNC,OAAO;IACT;CACD,CAAA"}
|
|
@@ -47,6 +47,14 @@ function parseJsonBody(body) {
|
|
|
47
47
|
function getString(value) {
|
|
48
48
|
return typeof value === 'string' && value.length > 0 ? value : undefined;
|
|
49
49
|
}
|
|
50
|
+
function getTrimmedMessage(body) {
|
|
51
|
+
const data = parseJsonBody(body);
|
|
52
|
+
if (!data || typeof data !== 'object' || Array.isArray(data)) return undefined;
|
|
53
|
+
const message = data.message;
|
|
54
|
+
if (typeof message !== 'string') return undefined;
|
|
55
|
+
const trimmed = message.trim();
|
|
56
|
+
return trimmed.length > 0 ? trimmed : undefined;
|
|
57
|
+
}
|
|
50
58
|
function parseProvisionResponse(body) {
|
|
51
59
|
const data = parseJsonBody(body);
|
|
52
60
|
const response = data && typeof data === 'object' && !Array.isArray(data) ? data : {};
|
|
@@ -114,6 +122,9 @@ function parseProvisionResponse(body) {
|
|
|
114
122
|
if (response.status === 429) {
|
|
115
123
|
throw new Error('Project creation rate limit reached for this machine. Try again later.');
|
|
116
124
|
}
|
|
125
|
+
if (response.status === 410) {
|
|
126
|
+
throw new Error(getTrimmedMessage(response.text()) ?? 'Project creation failed (HTTP 410). Try again later.');
|
|
127
|
+
}
|
|
117
128
|
if (response.status < 200 || response.status >= 300) {
|
|
118
129
|
throw new Error(`Project creation failed (HTTP ${response.status}). Try again later.`);
|
|
119
130
|
}
|