@sanity/cli 8.38.0 → 8.38.1
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/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/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 +1000 -1000
- package/package.json +3 -3
|
@@ -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,Q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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,SAAQC,eAAe,EAAEC,QAAQ,QAAO,mBAAkB;AAC1D,SAAQC,kBAAkB,EAAEC,gBAAgB,QAAO,6BAA4B;AAC/E,SAAQC,OAAO,QAAO,MAAK;AAE3B,MAAMC,QAAQJ,SAAS;AAEvB,MAAMK,mBAAmB;IACvB,qDAAqD;IACrD;CACD;AAED,MAAMC,UAAU;IACd,GAAGJ,gBAAgB;IACnBK,YAAY;IACZC,aAAa;AACf;AAoBA,OAAO,SAASC,uBAAuBC,QAAkB;IACvD,MAAM,EAACC,MAAM,EAAEC,QAAQ,EAAEC,IAAI,EAAEC,QAAQ,EAAC,GAAGJ;IAC3C,OAAO,CAAC,kCAAkC,EAAEI,SAAS,CAAC,EAAED,KAAK,CAAC,EAAEF,OAAO,CAAC,EAAEC,UAAU;AACtF;AAEA,SAASG,sBAAsBC,KAAa;IAC1C,IAAIC,IAAIC,QAAQ,CAACF,QAAQ;QACvB,OAAO;IACT;IACA,gEAAgE;IAChE,mBAAmB;IACnB,qCAAqC;IACrC,uCAAuC;IACvC,2DAA2D;IAC3D,OAAO,iCAAiCG,IAAI,CAACH;AAC/C;AAEA,SAASI,gBAAgBJ,KAAmB;IAC1C,IAAI,CAACC,IAAIC,QAAQ,CAACF,QAAQ;QACxB,OAAO;IACT;IACA,MAAMK,MAAM,IAAIJ,IAAID;IACpB,MAAMM,eAAeD,IAAIE,QAAQ,CAACC,KAAK,CAAC,GAAGC,KAAK,CAAC;IAEjD,OACEJ,IAAIK,QAAQ,KAAK,YACjBL,IAAIM,QAAQ,KAAK,gBACjB,yEAAyE;IACzE,6DAA6D;IAC7D,kCAAkC;IAClC,4CAA4C;I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AAMlG,gBAAgBH,KAAKqD,MAAM;QAC7CgD,IAAIpF,IAAI,GAAGA;QAEX,MAAMlB,UAAUC,KAAKqD,MAAM,iBAAiBiD,KAAKC,SAAS,CAACF,KAAK,MAAM;IACxE,EAAE,OAAM;IACN,OAAO;IACT;AACF"}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
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;AAC5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,EAAEoE,mBAAmBd,gBAAgB,CAAC,8CAA8C,EAAEc,mBAAmBb,QAAQ,EAAE;YAE7H,OAAOhE,GAAG6E;QACZ;QAEA,MAAM,CAACxB,MAAMvB,OAAOwB,KAAK,GAAGuB;QAC5BpE,iBAAiB,CAAC,OAAO,EAAEqB,MAAM,qBAAqB,CAAC;QAEvD,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,UAA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AO,EAAEoE,mBAAmBd,gBAAgB,CAAC,8CAA8C,EAAEc,mBAAmBb,QAAQ,EAAE;YAE7H,OAAO/D,GAAG4E;QACZ;QAEA,MAAM,CAACxB,MAAMvB,OAAOwB,KAAK,GAAGuB;QAC5BpE,iBAAiB,CAAC,OAAO,EAAEqB,MAAM,qBAAqB,CAAC;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"}
|
|
@@ -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
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/services/mintProject.ts"],"sourcesContent":["import {getCliToken} from '@sanity/cli-core/config'\nimport {subdebug} from '@sanity/cli-core/debug'\nimport {createRequester} from '@sanity/cli-core/request'\nimport {isStaging} from '@sanity/cli-core/util'\n\nimport {\n TERMS_OF_SERVICE_FALLBACK_NOTICE,\n TERMS_OF_SERVICE_FALLBACK_URL,\n} from '../util/mintProjectConstants.js'\n\nconst debug = subdebug('new:provision')\n\n/** Provision API version for minting unclaimed projects. */\nexport const PROVISION_API_VERSION = 'v2026-06-23'\n\n/**\n * Request tag identifying the caller to the provisioning funnel, using the same `?tag=` convention\n * as every other Sanity API request. `sanity new` is deliberately usable without an account, so a\n * mint often has no user to attribute — the tag names the tool instead, and is how synthetic\n * callers are kept out of mint-to-claim conversion.\n */\nexport const MINT_REQUEST_TAG = 'sanity.cli'\n\n/**\n * Overrides {@link MINT_REQUEST_TAG}. Internal plumbing for the scheduled smoke test, which mints\n * against production several times an hour and never claims; it sets `sanity.cli.smoketest` so\n * those mints can be excluded from reporting.\n */\nconst MINT_TAG_ENV_VAR = 'SANITY_CLI_MINT_TAG'\n\n/** Mirrors `@sanity/client`'s `requestTag` rule, which is what the API accepts. */\nconst TAG_PATTERN = /^[a-z0-9._-]{1,75}$/i\n\nfunction getRequestTag(): string {\n const override = process.env[MINT_TAG_ENV_VAR]\n if (!override) return MINT_REQUEST_TAG\n if (!TAG_PATTERN.test(override)) {\n // A malformed override would be dropped by the API anyway; fall back rather than mint\n // untagged, so the request is still attributable.\n debug('ignoring malformed %s value %j', MINT_TAG_ENV_VAR, override)\n return MINT_REQUEST_TAG\n }\n return override\n}\n\nconst request = createRequester({httpErrors: false})\n\nexport interface MintedProject {\n apiHost: string\n claimApiUrl: string\n claimToken: string\n claimUrl: string\n datasetName: string\n expiresAt: string\n resourceId: string\n /** Terms of Service accepted by using the project. Falls back to the bundled constants. */\n termsNotice: string\n termsUrl: string\n token: string\n}\n\nfunction getProvisionApiBase(): string {\n const override = process.env.SANITY_API_HOST\n if (override) return override.replace(/\\/$/u, '')\n return isStaging() ? 'https://api.sanity.work' : 'https://api.sanity.io'\n}\n\nfunction parseJsonBody(body: unknown): unknown {\n if (typeof body !== 'string') return body\n\n try {\n return JSON.parse(body)\n } catch {\n return undefined\n }\n}\n\nfunction getString(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n\nfunction parseProvisionResponse(body: unknown): MintedProject {\n const data = parseJsonBody(body)\n const response =\n data && typeof data === 'object' && !Array.isArray(data)\n ? (data as Record<string, unknown>)\n : {}\n const links =\n response.links && typeof response.links === 'object' && !Array.isArray(response.links)\n ? (response.links as Record<string, unknown>)\n : {}\n const terms =\n response.terms && typeof response.terms === 'object' && !Array.isArray(response.terms)\n ? (response.terms as Record<string, unknown>)\n : {}\n\n const minted = {\n apiHost: getString(response.apiHost),\n claimApiUrl: getString(links.claimApiUrl),\n claimToken: getString(response.claimToken),\n claimUrl: getString(links.claimUrl),\n datasetName: getString(response.datasetName),\n expiresAt: getString(response.expiresAt),\n resourceId: getString(response.resourceId),\n token: getString(response.token),\n }\n const missing = Object.entries(minted)\n .filter(([, value]) => value === undefined)\n .map(([key]) => key)\n\n if (response.resourceType !== 'project') {\n missing.push('resourceType')\n }\n if (missing.length > 0) {\n throw new Error(`Project creation response is missing or invalid: ${missing.join(', ')}`)\n }\n\n return {\n ...(minted as Omit<MintedProject, 'termsNotice' | 'termsUrl'>),\n termsNotice: getString(terms.notice) ?? TERMS_OF_SERVICE_FALLBACK_NOTICE,\n termsUrl: getString(terms.url) ?? TERMS_OF_SERVICE_FALLBACK_URL,\n }\n}\n\n/**\n * Mint an unclaimed Sanity project through the public provision endpoint.\n *\n * Works logged out. Credentials, when there are any, are sent only so the mint can be attributed\n * and are dropped on rejection, so being logged in changes reporting and nothing else.\n */\nexport async function mintUnclaimedProject(options: {displayName: string}): Promise<MintedProject> {\n const displayName = options.displayName.trim()\n if (!displayName || displayName.length > 80) {\n throw new Error('Project name must be 1-80 characters.')\n }\n\n const url = new URL(`${PROVISION_API_VERSION}/provision`, getProvisionApiBase())\n url.searchParams.set('tag', getRequestTag())\n debug('minting unclaimed project at %s', url.toString())\n\n const mint = (token?: string) =>\n request({\n body: JSON.stringify({displayName, resourceType: 'project'}),\n headers: {\n 'Content-Type': 'application/json',\n ...(token ? {Authorization: `Bearer ${token}`} : {}),\n },\n method: 'POST',\n url: url.toString(),\n })\n\n const token = await getCliToken()\n let response = await mint(token)\n\n if (token && (response.status === 401 || response.status === 403)) {\n debug('stored credentials rejected (HTTP %d), minting anonymously', response.status)\n response = await mint()\n }\n\n if (response.status === 404) {\n throw new Error(\n 'Creating projects without an account is currently unavailable. Try again later, or run `sanity login` and `sanity init`.',\n )\n }\n if (response.status === 429) {\n throw new Error('Project creation rate limit reached for this machine. Try again later.')\n }\n if (response.status < 200 || response.status >= 300) {\n throw new Error(`Project creation failed (HTTP ${response.status}). Try again later.`)\n }\n\n return parseProvisionResponse(response.text())\n}\n"],"names":["getCliToken","subdebug","createRequester","isStaging","TERMS_OF_SERVICE_FALLBACK_NOTICE","TERMS_OF_SERVICE_FALLBACK_URL","debug","PROVISION_API_VERSION","MINT_REQUEST_TAG","MINT_TAG_ENV_VAR","TAG_PATTERN","getRequestTag","override","process","env","test","request","httpErrors","getProvisionApiBase","SANITY_API_HOST","replace","parseJsonBody","body","JSON","parse","undefined","getString","value","length","parseProvisionResponse","data","response","Array","isArray","links","terms","minted","apiHost","claimApiUrl","claimToken","claimUrl","datasetName","expiresAt","resourceId","token","missing","Object","entries","filter","map","key","resourceType","push","Error","join","termsNotice","notice","termsUrl","url","mintUnclaimedProject","options","displayName","trim","URL","searchParams","set","toString","mint","stringify","headers","Authorization","method","status","text"],"mappings":"AAAA,SAAQA,WAAW,QAAO,0BAAyB;AACnD,SAAQC,QAAQ,QAAO,yBAAwB;AAC/C,SAAQC,eAAe,QAAO,2BAA0B;AACxD,SAAQC,SAAS,QAAO,wBAAuB;AAE/C,SACEC,gCAAgC,EAChCC,6BAA6B,QACxB,kCAAiC;AAExC,MAAMC,QAAQL,SAAS;AAEvB,0DAA0D,GAC1D,OAAO,MAAMM,wBAAwB,cAAa;AAElD;;;;;CAKC,GACD,OAAO,MAAMC,mBAAmB,aAAY;AAE5C;;;;CAIC,GACD,MAAMC,mBAAmB;AAEzB,iFAAiF,GACjF,MAAMC,cAAc;AAEpB,SAASC;IACP,MAAMC,WAAWC,QAAQC,GAAG,CAACL,iBAAiB;IAC9C,IAAI,CAACG,UAAU,OAAOJ;IACtB,IAAI,CAACE,YAAYK,IAAI,CAACH,WAAW;QAC/B,sFAAsF;QACtF,kDAAkD;QAClDN,MAAM,kCAAkCG,kBAAkBG;QAC1D,OAAOJ;IACT;IACA,OAAOI;AACT;AAEA,MAAMI,UAAUd,gBAAgB;IAACe,YAAY;AAAK;AAgBlD,SAASC;IACP,MAAMN,WAAWC,QAAQC,GAAG,CAACK,eAAe;IAC5C,IAAIP,UAAU,OAAOA,SAASQ,OAAO,CAAC,QAAQ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IAAItB,SAASyC,MAAM,GAAG,OAAOzC,SAASyC,MAAM,IAAI,KAAK;QACnD,MAAM,IAAInB,MAAM,CAAC,8BAA8B,EAAEtB,SAASyC,MAAM,CAAC,mBAAmB,CAAC;IACvF;IAEA,OAAO3C,uBAAuBE,SAAS0C,IAAI;AAC7C"}
|
|
1
|
+
{"version":3,"sources":["../../src/services/mintProject.ts"],"sourcesContent":["import {getCliToken} from '@sanity/cli-core/config'\nimport {subdebug} from '@sanity/cli-core/debug'\nimport {createRequester} from '@sanity/cli-core/request'\nimport {isStaging} from '@sanity/cli-core/util'\n\nimport {\n TERMS_OF_SERVICE_FALLBACK_NOTICE,\n TERMS_OF_SERVICE_FALLBACK_URL,\n} from '../util/mintProjectConstants.js'\n\nconst debug = subdebug('new:provision')\n\n/** Provision API version for minting unclaimed projects. */\nexport const PROVISION_API_VERSION = 'v2026-06-23'\n\n/**\n * Request tag identifying the caller to the provisioning funnel, using the same `?tag=` convention\n * as every other Sanity API request. `sanity new` is deliberately usable without an account, so a\n * mint often has no user to attribute — the tag names the tool instead, and is how synthetic\n * callers are kept out of mint-to-claim conversion.\n */\nexport const MINT_REQUEST_TAG = 'sanity.cli'\n\n/**\n * Overrides {@link MINT_REQUEST_TAG}. Internal plumbing for the scheduled smoke test, which mints\n * against production several times an hour and never claims; it sets `sanity.cli.smoketest` so\n * those mints can be excluded from reporting.\n */\nconst MINT_TAG_ENV_VAR = 'SANITY_CLI_MINT_TAG'\n\n/** Mirrors `@sanity/client`'s `requestTag` rule, which is what the API accepts. */\nconst TAG_PATTERN = /^[a-z0-9._-]{1,75}$/i\n\nfunction getRequestTag(): string {\n const override = process.env[MINT_TAG_ENV_VAR]\n if (!override) return MINT_REQUEST_TAG\n if (!TAG_PATTERN.test(override)) {\n // A malformed override would be dropped by the API anyway; fall back rather than mint\n // untagged, so the request is still attributable.\n debug('ignoring malformed %s value %j', MINT_TAG_ENV_VAR, override)\n return MINT_REQUEST_TAG\n }\n return override\n}\n\nconst request = createRequester({httpErrors: false})\n\nexport interface MintedProject {\n apiHost: string\n claimApiUrl: string\n claimToken: string\n claimUrl: string\n datasetName: string\n expiresAt: string\n resourceId: string\n /** Terms of Service accepted by using the project. Falls back to the bundled constants. */\n termsNotice: string\n termsUrl: string\n token: string\n}\n\nfunction getProvisionApiBase(): string {\n const override = process.env.SANITY_API_HOST\n if (override) return override.replace(/\\/$/u, '')\n return isStaging() ? 'https://api.sanity.work' : 'https://api.sanity.io'\n}\n\nfunction parseJsonBody(body: unknown): unknown {\n if (typeof body !== 'string') return body\n\n try {\n return JSON.parse(body)\n } catch {\n return undefined\n }\n}\n\nfunction getString(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n\nfunction getTrimmedMessage(body: unknown): string | undefined {\n const data = parseJsonBody(body)\n if (!data || typeof data !== 'object' || Array.isArray(data)) return undefined\n const message = (data as Record<string, unknown>).message\n if (typeof message !== 'string') return undefined\n const trimmed = message.trim()\n return trimmed.length > 0 ? trimmed : undefined\n}\n\nfunction parseProvisionResponse(body: unknown): MintedProject {\n const data = parseJsonBody(body)\n const response =\n data && typeof data === 'object' && !Array.isArray(data)\n ? (data as Record<string, unknown>)\n : {}\n const links =\n response.links && typeof response.links === 'object' && !Array.isArray(response.links)\n ? (response.links as Record<string, unknown>)\n : {}\n const terms =\n response.terms && typeof response.terms === 'object' && !Array.isArray(response.terms)\n ? (response.terms as Record<string, unknown>)\n : {}\n\n const minted = {\n apiHost: getString(response.apiHost),\n claimApiUrl: getString(links.claimApiUrl),\n claimToken: getString(response.claimToken),\n claimUrl: getString(links.claimUrl),\n datasetName: getString(response.datasetName),\n expiresAt: getString(response.expiresAt),\n resourceId: getString(response.resourceId),\n token: getString(response.token),\n }\n const missing = Object.entries(minted)\n .filter(([, value]) => value === undefined)\n .map(([key]) => key)\n\n if (response.resourceType !== 'project') {\n missing.push('resourceType')\n }\n if (missing.length > 0) {\n throw new Error(`Project creation response is missing or invalid: ${missing.join(', ')}`)\n }\n\n return {\n ...(minted as Omit<MintedProject, 'termsNotice' | 'termsUrl'>),\n termsNotice: getString(terms.notice) ?? TERMS_OF_SERVICE_FALLBACK_NOTICE,\n termsUrl: getString(terms.url) ?? TERMS_OF_SERVICE_FALLBACK_URL,\n }\n}\n\n/**\n * Mint an unclaimed Sanity project through the public provision endpoint.\n *\n * Works logged out. Credentials, when there are any, are sent only so the mint can be attributed\n * and are dropped on rejection, so being logged in changes reporting and nothing else.\n */\nexport async function mintUnclaimedProject(options: {displayName: string}): Promise<MintedProject> {\n const displayName = options.displayName.trim()\n if (!displayName || displayName.length > 80) {\n throw new Error('Project name must be 1-80 characters.')\n }\n\n const url = new URL(`${PROVISION_API_VERSION}/provision`, getProvisionApiBase())\n url.searchParams.set('tag', getRequestTag())\n debug('minting unclaimed project at %s', url.toString())\n\n const mint = (token?: string) =>\n request({\n body: JSON.stringify({displayName, resourceType: 'project'}),\n headers: {\n 'Content-Type': 'application/json',\n ...(token ? {Authorization: `Bearer ${token}`} : {}),\n },\n method: 'POST',\n url: url.toString(),\n })\n\n const token = await getCliToken()\n let response = await mint(token)\n\n if (token && (response.status === 401 || response.status === 403)) {\n debug('stored credentials rejected (HTTP %d), minting anonymously', response.status)\n response = await mint()\n }\n\n if (response.status === 404) {\n throw new Error(\n 'Creating projects without an account is currently unavailable. Try again later, or run `sanity login` and `sanity init`.',\n )\n }\n if (response.status === 429) {\n throw new Error('Project creation rate limit reached for this machine. Try again later.')\n }\n if (response.status === 410) {\n throw new Error(\n getTrimmedMessage(response.text()) ?? 'Project creation failed (HTTP 410). Try again later.',\n )\n }\n if (response.status < 200 || response.status >= 300) {\n throw new Error(`Project creation failed (HTTP ${response.status}). Try again later.`)\n }\n\n return parseProvisionResponse(response.text())\n}\n"],"names":["getCliToken","subdebug","createRequester","isStaging","TERMS_OF_SERVICE_FALLBACK_NOTICE","TERMS_OF_SERVICE_FALLBACK_URL","debug","PROVISION_API_VERSION","MINT_REQUEST_TAG","MINT_TAG_ENV_VAR","TAG_PATTERN","getRequestTag","override","process","env","test","request","httpErrors","getProvisionApiBase","SANITY_API_HOST","replace","parseJsonBody","body","JSON","parse","undefined","getString","value","length","getTrimmedMessage","data","Array","isArray","message","trimmed","trim","parseProvisionResponse","response","links","terms","minted","apiHost","claimApiUrl","claimToken","claimUrl","datasetName","expiresAt","resourceId","token","missing","Object","entries","filter","map","key","resourceType","push","Error","join","termsNotice","notice","termsUrl","url","mintUnclaimedProject","options","displayName","URL","searchParams","set","toString","mint","stringify","headers","Authorization","method","status","text"],"mappings":"AAAA,SAAQA,WAAW,QAAO,0BAAyB;AACnD,SAAQC,QAAQ,QAAO,yBAAwB;AAC/C,SAAQC,eAAe,QAAO,2BAA0B;AACxD,SAAQC,SAAS,QAAO,wBAAuB;AAE/C,SACEC,gCAAgC,EAChCC,6BAA6B,QACxB,kCAAiC;AAExC,MAAMC,QAAQL,SAAS;AAEvB,0DAA0D,GAC1D,OAAO,MAAMM,wBAAwB,cAAa;AAElD;;;;;CAKC,GACD,OAAO,MAAMC,mBAAmB,aAAY;AAE5C;;;;CAIC,GACD,MAAMC,mBAAmB;AAEzB,iFAAiF,GACjF,MAAMC,cAAc;AAEpB,SAASC;IACP,MAAMC,WAAWC,QAAQC,GAAG,CAACL,iBAAiB;IAC9C,IAAI,CAACG,UAAU,OAAOJ;IACtB,IAAI,CAACE,YAAYK,IAAI,CAACH,WAAW;QAC/B,sFAAsF;QACtF,kDAAkD;QAClDN,MAAM,kCAAkCG,kBAAkBG;QAC1D,OAAOJ;IACT;IACA,OAAOI;AACT;AAEA,MAAMI,UAAUd,gBAAgB;IAACe,YAAY;AAAK;AAgBlD,SAASC;IACP,MAAMN,WAAWC,QAAQC,GAAG,CAACK,eAAe;IAC5C,IAAIP,UAAU,OAAOA,SAASQ,OAAO,CAAC,QAAQ;IAC9C,OAAOjB,cAAc,4BAA4B;AACnD;AAEA,SAASkB,cAAcC,IAAa;IAClC,IAAI,OAAOA,SAAS,UAAU,OAAOA;IAErC,IA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,SAASsC,MAAM;QACnFtC,WAAW,MAAMiC;IACnB;IAEA,IAAIjC,SAASsC,MAAM,KAAK,KAAK;QAC3B,MAAM,IAAIlB,MACR;IAEJ;IACA,IAAIpB,SAASsC,MAAM,KAAK,KAAK;QAC3B,MAAM,IAAIlB,MAAM;IAClB;IACA,IAAIpB,SAASsC,MAAM,KAAK,KAAK;QAC3B,MAAM,IAAIlB,MACR5B,kBAAkBQ,SAASuC,IAAI,OAAO;IAE1C;IACA,IAAIvC,SAASsC,MAAM,GAAG,OAAOtC,SAASsC,MAAM,IAAI,KAAK;QACnD,MAAM,IAAIlB,MAAM,CAAC,8BAA8B,EAAEpB,SAASsC,MAAM,CAAC,mBAAmB,CAAC;IACvF;IAEA,OAAOvC,uBAAuBC,SAASuC,IAAI;AAC7C"}
|
|
@@ -3,7 +3,8 @@ export const PROJECTS_API_VERSION = '2025-09-22';
|
|
|
3
3
|
export const CREATE_PROJECT_API_VERSION = 'v2025-05-14';
|
|
4
4
|
// The logo routes are only on vX while they are experimental.
|
|
5
5
|
const PROJECT_LOGO_API_VERSION = 'vX';
|
|
6
|
-
const
|
|
6
|
+
const ANONYMOUS_ROBOT_ROLE = 'anonymous-robot';
|
|
7
|
+
const CLAIM_STATUS_API_VERSION = 'v2026-11-24';
|
|
7
8
|
/**
|
|
8
9
|
* Create a new Sanity project
|
|
9
10
|
*/ export async function createProject(options) {
|
|
@@ -56,19 +57,31 @@ export async function getProjectById(projectId) {
|
|
|
56
57
|
});
|
|
57
58
|
return client.projects.getById(projectId);
|
|
58
59
|
}
|
|
60
|
+
function isUnclaimedRoleForProject(role, projectId) {
|
|
61
|
+
if (!role || typeof role !== 'object') {
|
|
62
|
+
return false;
|
|
63
|
+
}
|
|
64
|
+
const { name, resourceId } = role;
|
|
65
|
+
return name === ANONYMOUS_ROBOT_ROLE && (resourceId === undefined || resourceId === projectId);
|
|
66
|
+
}
|
|
59
67
|
export async function getProjectClaimStatus(projectId, token) {
|
|
60
68
|
try {
|
|
61
69
|
const client = await getProjectCliClient({
|
|
62
|
-
apiVersion:
|
|
70
|
+
apiVersion: CLAIM_STATUS_API_VERSION,
|
|
63
71
|
projectId,
|
|
64
72
|
requireUser: true,
|
|
65
73
|
token
|
|
66
74
|
});
|
|
67
|
-
const
|
|
68
|
-
|
|
75
|
+
const user = await client.request({
|
|
76
|
+
query: {
|
|
77
|
+
includeRoles: 'true'
|
|
78
|
+
},
|
|
79
|
+
url: '/users/me'
|
|
80
|
+
});
|
|
81
|
+
if (!Array.isArray(user?.roles) || user.roles.length === 0) {
|
|
69
82
|
return 'unknown';
|
|
70
83
|
}
|
|
71
|
-
return
|
|
84
|
+
return user.roles.some((role)=>isUnclaimedRoleForProject(role, projectId)) ? 'unclaimed' : 'claimed';
|
|
72
85
|
} catch (error) {
|
|
73
86
|
debug('failed to check claim status for project %s: %s', projectId, error instanceof Error ? error.message : `${error}`);
|
|
74
87
|
return 'unknown';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/services/projects.ts"],"sourcesContent":["import {debug, getGlobalCliClient, getProjectCliClient} from '@sanity/cli-core'\nimport {type ImageFile} from '@sanity/cli-core/images'\nimport {SanityProject} from '@sanity/client'\n\nimport {type Invite, type Role} from '../actions/users/types.js'\n\nexport const PROJECTS_API_VERSION = '2025-09-22'\n\nexport const CREATE_PROJECT_API_VERSION = 'v2025-05-14'\n\n// The logo routes are only on vX while they are experimental.\nconst PROJECT_LOGO_API_VERSION = 'vX'\n\nconst
|
|
1
|
+
{"version":3,"sources":["../../src/services/projects.ts"],"sourcesContent":["import {debug, getGlobalCliClient, getProjectCliClient} from '@sanity/cli-core'\nimport {type ImageFile} from '@sanity/cli-core/images'\nimport {SanityProject} from '@sanity/client'\n\nimport {type Invite, type Role} from '../actions/users/types.js'\n\nexport const PROJECTS_API_VERSION = '2025-09-22'\n\nexport const CREATE_PROJECT_API_VERSION = 'v2025-05-14'\n\n// The logo routes are only on vX while they are experimental.\nconst PROJECT_LOGO_API_VERSION = 'vX'\n\nconst ANONYMOUS_ROBOT_ROLE = 'anonymous-robot'\n\nconst CLAIM_STATUS_API_VERSION = 'v2026-11-24'\n\nexport type ProjectClaimStatus = 'claimed' | 'unclaimed' | 'unknown'\n\ninterface CreateProjectOptions {\n displayName: string\n\n metadata?: {\n coupon?: string\n integration?: string\n }\n organizationId?: string\n subscription?: {planId: string}\n}\n\nexport interface CreateProjectResult {\n displayName: string\n projectId: string\n}\n\n/**\n * Create a new Sanity project\n */\nexport async function createProject(options: CreateProjectOptions): Promise<CreateProjectResult> {\n const client = await getGlobalCliClient({\n apiVersion: CREATE_PROJECT_API_VERSION,\n requireUser: true,\n })\n\n try {\n const response = await client.request({\n body: {\n ...options,\n metadata: {\n ...options?.metadata,\n integration: 'cli',\n },\n },\n method: 'POST',\n url: '/projects',\n })\n\n return {\n displayName: options.displayName || '',\n projectId: response.projectId || response.id,\n }\n } catch (err) {\n debug('Error creating project', err)\n throw err\n }\n}\n\n/**\n * Set a project's logo, replacing any previous logo\n */\nexport async function setProjectLogo(\n projectId: string,\n logo: ImageFile,\n): Promise<{logoUrl: string}> {\n const client = await getGlobalCliClient({\n apiVersion: PROJECT_LOGO_API_VERSION,\n requireUser: true,\n })\n\n return client.request<{logoUrl: string}>({\n body: logo.image,\n headers: {'Content-Type': logo.contentType},\n method: 'put',\n url: `/projects/${projectId}/logo`,\n })\n}\n\nexport async function getProjectById(projectId: string) {\n const client = await getProjectCliClient({\n apiVersion: PROJECTS_API_VERSION,\n projectId,\n requireUser: true,\n })\n\n return client.projects.getById(projectId)\n}\n\nfunction isUnclaimedRoleForProject(role: unknown, projectId: string): boolean {\n if (!role || typeof role !== 'object') {\n return false\n }\n const {name, resourceId} = role as {name?: unknown; resourceId?: unknown}\n return name === ANONYMOUS_ROBOT_ROLE && (resourceId === undefined || resourceId === projectId)\n}\n\nexport async function getProjectClaimStatus(\n projectId: string,\n token: string,\n): Promise<ProjectClaimStatus> {\n try {\n const client = await getProjectCliClient({\n apiVersion: CLAIM_STATUS_API_VERSION,\n projectId,\n requireUser: true,\n token,\n })\n const user = await client.request<{roles?: unknown}>({\n query: {includeRoles: 'true'},\n url: '/users/me',\n })\n\n if (!Array.isArray(user?.roles) || user.roles.length === 0) {\n return 'unknown'\n }\n\n return user.roles.some((role) => isUnclaimedRoleForProject(role, projectId))\n ? 'unclaimed'\n : 'claimed'\n } catch (error) {\n debug(\n 'failed to check claim status for project %s: %s',\n projectId,\n error instanceof Error ? error.message : `${error}`,\n )\n return 'unknown'\n }\n}\n\nexport async function getProjectRoles(projectId: string) {\n const client = await getGlobalCliClient({\n apiVersion: PROJECTS_API_VERSION,\n requireUser: true,\n })\n\n return client.request<Role[]>({url: `/projects/${projectId}/roles`})\n}\n\ninterface InviteUserOptions {\n email: string\n projectId: string\n role: string\n}\n\nexport async function inviteUser({email, projectId, role}: InviteUserOptions) {\n const client = await getGlobalCliClient({\n apiVersion: PROJECTS_API_VERSION,\n requireUser: true,\n })\n\n return client.request({\n body: {email, role},\n maxRedirects: 0,\n method: 'POST',\n url: `/invitations/project/${projectId}`,\n useGlobalApi: true,\n })\n}\n\nexport async function listProjects({\n onlyExplicitMembership = true,\n}: {\n onlyExplicitMembership?: boolean\n} = {}) {\n const client = await getGlobalCliClient({\n apiVersion: PROJECTS_API_VERSION,\n requireUser: true,\n })\n\n return client.projects.list({onlyExplicitMembership})\n}\n\nexport async function getProjectInvites(projectId: string) {\n const client = await getGlobalCliClient({\n apiVersion: PROJECTS_API_VERSION,\n requireUser: true,\n })\n\n return client.request<Invite[]>({url: `/invitations/project/${projectId}`})\n}\n\nexport async function updateProjectInitializedAt(projectId: string) {\n const client = await getProjectCliClient({\n apiVersion: PROJECTS_API_VERSION,\n projectId,\n requireUser: true,\n })\n\n const project = await client.request<SanityProject>({url: `/projects/${projectId}`})\n\n if (!project?.metadata?.cliInitializedAt) {\n await client.request({\n body: {metadata: {cliInitializedAt: new Date().toISOString()}},\n method: 'PATCH',\n url: `/projects/${projectId}`,\n })\n }\n}\n\nexport async function updateProjectInitalTemplate(projectId: string, templateName: string) {\n const client = await getProjectCliClient({\n apiVersion: PROJECTS_API_VERSION,\n projectId,\n requireUser: true,\n })\n\n await client.request({\n body: {metadata: {initialTemplate: templateName}},\n method: 'PATCH',\n url: `/projects/${projectId}`,\n })\n}\n"],"names":["debug","getGlobalCliClient","getProjectCliClient","PROJECTS_API_VERSION","CREATE_PROJECT_API_VERSION","PROJECT_LOGO_API_VERSION","ANONYMOUS_ROBOT_ROLE","CLAIM_STATUS_API_VERSION","createProject","options","client","apiVersion","requireUser","response","request","body","metadata","integration","method","url","displayName","projectId","id","err","setProjectLogo","logo","image","headers","contentType","getProjectById","projects","getById","isUnclaimedRoleForProject","role","name","resourceId","undefined","getProjectClaimStatus","token","user","query","includeRoles","Array","isArray","roles","length","some","error","Error","message","getProjectRoles","inviteUser","email","maxRedirects","useGlobalApi","listProjects","onlyExplicitMembership","list","getProjectInvites","updateProjectInitializedAt","project","cliInitializedAt","Date","toISOString","updateProjectInitalTemplate","templateName","initialTemplate"],"mappings":"AAAA,SAAQA,KAAK,EAAEC,kBAAkB,EAAEC,mBAAmB,QAAO,mBAAkB;AAM/E,OAAO,MAAMC,uBAAuB,aAAY;AAEhD,OAAO,MAAMC,6BAA6B,cAAa;AAEvD,8DAA8D;AAC9D,MAAMC,2BAA2B;AAEjC,MAAMC,uBAAuB;AAE7B,MAAMC,2BAA2B;AAoBjC;;CAEC,GACD,OAAO,eAAeC,cAAcC,OAA6B;IAC/D,MAAMC,SAAS,MAAMT,mBAAmB;QACtCU,YAAYP;QACZQ,aAAa;IACf;IAEA,IAAI;QACF,MAAMC,WAAW,MAAMH,OAAOI,OAAO,CAAC;YACpCC,MAAM;gBACJ,GAAGN,OAAO;gBACVO,UAAU;oBACR,GAAGP,SAASO,QAAQ;oBACpBC,aAAa;gBACf;YACF;YACAC,QAAQ;YACRC,KAAK;QACP;QAEA,OAAO;YACLC,aAAaX,QAAQW,WAAW,IAAI;YACpCC,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AAEE,WAAW;IAAA;IAElF,IAAI,CAACuC,SAAS5C,UAAU6C,kBAAkB;QACxC,MAAMnD,OAAOI,OAAO,CAAC;YACnBC,MAAM;gBAACC,UAAU;oBAAC6C,kBAAkB,IAAIC,OAAOC,WAAW;gBAAE;YAAC;YAC7D7C,QAAQ;YACRC,KAAK,CAAC,UAAU,EAAEE,WAAW;QAC/B;IACF;AACF;AAEA,OAAO,eAAe2C,4BAA4B3C,SAAiB,EAAE4C,YAAoB;IACvF,MAAMvD,SAAS,MAAMR,oBAAoB;QACvCS,YAAYR;QACZkB;QACAT,aAAa;IACf;IAEA,MAAMF,OAAOI,OAAO,CAAC;QACnBC,MAAM;YAACC,UAAU;gBAACkD,iBAAiBD;YAAY;QAAC;QAChD/C,QAAQ;QACRC,KAAK,CAAC,UAAU,EAAEE,WAAW;IAC/B;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/services/userApplications.ts"],"sourcesContent":["import {PassThrough} from 'node:stream'\nimport {type Gzip} from 'node:zlib'\n\nimport {type CoreAppManifest} from '@sanity/cli-build/_internal/manifest'\nimport {type AppVisibility, debug, getGlobalCliClient} from '@sanity/cli-core'\nimport FormData from 'form-data'\nimport {type StudioManifest} from 'sanity'\n\nexport const USER_APPLICATIONS_API_VERSION = 'v2024-08-01'\n\ninterface ActiveDeployment {\n createdAt: string\n deployedAt: string\n deployedBy: string\n isActiveDeployment: boolean\n isAutoUpdating: boolean | null\n size: string | null\n updatedAt: string\n version: string\n}\n\nexport interface UserApplication {\n appHost: string\n createdAt: string\n id: string\n organizationId: string | null\n projectId: string | null\n title: string | null\n type: 'coreApp' | 'studio'\n updatedAt: string\n urlType: 'external' | 'internal'\n\n activeDeployment?: ActiveDeployment | null\n /** Dashboard visibility. Defaults to `default` server-side when unset. */\n dashboardStatus?: AppVisibility\n}\n\n/** A core app always belongs to an organization. */\nexport interface UserApplicationResolved extends UserApplication {\n organizationId: string\n type: 'coreApp'\n}\n\ntype GetUserApplicationOptions =\n | {appHost?: never; appId: string; isSdkApp: true; projectId?: never}\n | {appHost?: string; appId?: string; isSdkApp: false; projectId: string}\n\nexport async function getUserApplication(options: {\n appHost?: never\n appId: string\n isSdkApp: true\n projectId?: never\n}): Promise<UserApplicationResolved | null>\nexport async function getUserApplication(options: {\n appHost?: string\n appId?: string\n isSdkApp: false\n projectId: string\n}): Promise<UserApplication | null>\nexport async function getUserApplication({\n appHost,\n appId,\n isSdkApp,\n projectId,\n}: GetUserApplicationOptions): Promise<UserApplication | null> {\n let query: Record<string, string | string[]> | undefined\n let url: string\n\n // set the url\n if (isSdkApp) {\n url = appId ? `/user-applications/${appId}` : '/user-applications'\n } else {\n url = appId\n ? `/projects/${projectId}/user-applications/${appId}`\n : `/projects/${projectId}/user-applications`\n }\n\n // set the query\n if (isSdkApp) {\n query = {appType: 'coreApp'}\n } else if (!appId) {\n // In practice, this function isn't called if we don't have at least one of appHost or appId,\n // so the default case won't be called. But leaving this ternary in for now (from old CLI code) just in case.\n query = appHost ? {appHost, appType: 'studio'} : {default: 'true'}\n }\n\n const client = await getGlobalCliClient({\n apiVersion: USER_APPLICATIONS_API_VERSION,\n requireUser: true,\n })\n\n try {\n const options = query ? {query, url} : {url}\n return await client.request(options)\n } catch (err) {\n if (err?.statusCode === 404) {\n return null\n }\n\n debug('Error getting user application', err)\n throw err\n }\n}\n\ninterface DeleteUserApplicationOptions {\n applicationId: string\n appType: 'coreApp' | 'studio'\n}\n\nexport async function deleteUserApplication({\n applicationId,\n appType,\n}: DeleteUserApplicationOptions): Promise<void> {\n const client = await getGlobalCliClient({\n apiVersion: USER_APPLICATIONS_API_VERSION,\n requireUser: true,\n })\n\n await client.request({\n method: 'DELETE',\n query: {appType},\n url: `/user-applications/${applicationId}`,\n })\n}\n\ninterface UpdateUserApplicationBody {\n dashboardStatus?: AppVisibility\n title?: string\n}\n\ninterface UpdateUserApplicationOptions {\n applicationId: string\n // Updating studio properties requires further UX thought\n // (because of workspaces et al.)\n appType: 'coreApp'\n body: UpdateUserApplicationBody\n}\n\nexport async function updateUserApplication({\n applicationId,\n appType,\n body,\n}: UpdateUserApplicationOptions): Promise<UserApplicationResolved> {\n const client = await getGlobalCliClient({\n apiVersion: USER_APPLICATIONS_API_VERSION,\n requireUser: true,\n })\n\n return client.request({\n body,\n method: 'PATCH',\n query: {appType},\n url: `/user-applications/${applicationId}`,\n })\n}\n\nexport async function getUserApplications(options: {\n appType: 'studio'\n projectId: string\n}): Promise<UserApplication[]>\nexport async function getUserApplications(options: {\n appType: 'coreApp'\n organizationId: string\n}): Promise<UserApplicationResolved[]>\nexport async function getUserApplications(\n options:\n | {\n appType: 'coreApp'\n organizationId?: string\n }\n | {\n appType: 'studio'\n projectId?: string\n },\n): Promise<UserApplication[] | null> {\n const {appType} = options\n const client = await getGlobalCliClient({\n apiVersion: USER_APPLICATIONS_API_VERSION,\n requireUser: true,\n })\n\n if (appType === 'studio') {\n const {projectId} = options as {appType: 'studio'; projectId?: string}\n return await client.request({\n query: {appType: 'studio'},\n url: `/projects/${projectId}/user-applications`,\n })\n }\n\n const {organizationId} = options as {appType: 'coreApp'; organizationId?: string}\n\n try {\n return await client.request({\n query: {appType: 'coreApp', organizationId: organizationId!},\n url: `/user-applications`,\n })\n } catch (error) {\n // User doesn't have permission to view applications for the org,\n // or the organization ID doesn’t exist\n if (error?.statusCode === 403) {\n throw error\n }\n\n debug('Error finding user applications', error)\n return null\n }\n}\n\nexport async function createUserApplication(options: {\n appType: 'coreApp'\n body: Pick<UserApplication, 'appHost' | 'type' | 'urlType'> & {\n dashboardStatus?: AppVisibility\n title?: string\n }\n organizationId?: string\n}): Promise<UserApplicationResolved>\nexport async function createUserApplication(options: {\n appType: 'studio'\n body: Pick<UserApplication, 'appHost' | 'type' | 'urlType'> & {\n dashboardStatus?: AppVisibility\n title?: string\n }\n projectId: string\n}): Promise<UserApplication>\nexport async function createUserApplication(options: {\n appType: 'coreApp' | 'studio'\n body: Pick<UserApplication, 'appHost' | 'type' | 'urlType'> & {\n dashboardStatus?: AppVisibility\n title?: string\n }\n organizationId?: string\n projectId?: string\n}): Promise<UserApplication> {\n const {appType, body} = options\n\n const client = await getGlobalCliClient({\n apiVersion: USER_APPLICATIONS_API_VERSION,\n requireUser: true,\n })\n\n let url\n let query\n\n // If we have an organizationId, we're creating a core app\n if (appType === 'coreApp') {\n const {organizationId} = options as {appType: 'coreApp'; organizationId?: string}\n url = '/user-applications'\n query = {appType: 'coreApp', organizationId: organizationId!}\n } else {\n const {projectId} = options as {appType: 'studio'; projectId?: string}\n url = `/projects/${projectId}/user-applications`\n query = {appType: 'studio'}\n }\n\n return client.request({body, method: 'POST', query, url})\n}\n\ninterface CreateDeploymentOptions {\n applicationId: string\n isAutoUpdating: boolean\n version: string\n\n isApp?: boolean\n\n manifest?: CoreAppManifest | StudioManifest | null\n\n projectId?: string\n\n tarball?: Gzip\n}\n\nexport async function createDeployment({\n applicationId,\n isApp,\n isAutoUpdating,\n manifest,\n projectId,\n tarball,\n version,\n}: CreateDeploymentOptions): Promise<{location: string}> {\n const client = await getGlobalCliClient({\n apiVersion: USER_APPLICATIONS_API_VERSION,\n requireUser: true,\n })\n\n const formData = new FormData()\n formData.append('isAutoUpdating', isAutoUpdating.toString())\n formData.append('version', version)\n if (manifest) {\n formData.append('manifest', JSON.stringify(manifest))\n }\n\n if (tarball) {\n formData.append('tarball', tarball, {contentType: 'application/gzip', filename: 'app.tar.gz'})\n }\n\n let url\n let query\n\n if (isApp) {\n url = `/user-applications/${applicationId}/deployments`\n query = {appType: 'coreApp'}\n } else {\n url = `/projects/${projectId}/user-applications/${applicationId}/deployments`\n query = {appType: 'studio'}\n }\n\n return client.request({\n body: formData.pipe(new PassThrough()),\n headers: formData.getHeaders(),\n method: 'POST',\n query,\n url,\n })\n}\n"],"names":["PassThrough","debug","getGlobalCliClient","FormData","USER_APPLICATIONS_API_VERSION","getUserApplication","appHost","appId","isSdkApp","projectId","query","url","appType","default","client","apiVersion","requireUser","options","request","err","statusCode","deleteUserApplication","applicationId","method","updateUserApplication","body","getUserApplications","organizationId","error","createUserApplication","createDeployment","isApp","isAutoUpdating","manifest","tarball","version","formData","append","toString","JSON","stringify","contentType","filename","pipe","headers","getHeaders"],"mappings":"AAAA,SAAQA,WAAW,QAAO,cAAa;AAIvC,SAA4BC,KAAK,EAAEC,kBAAkB,QAAO,mBAAkB;AAC9E,OAAOC,cAAc,YAAW;AAGhC,OAAO,MAAMC,gCAAgC,cAAa;AAmD1D,OAAO,eAAeC,mBAAmB,EACvCC,OAAO,EACPC,KAAK,EACLC,QAAQ,EACRC,SAAS,EACiB;IAC1B,IAAIC;IACJ,IAAIC;IAEJ,cAAc;IACd,IAAIH,UAAU;QACZG,MAAMJ,QAAQ,CAAC,mBAAmB,EAAEA,OAAO,GAAG;IAChD,OAAO;QACLI,MAAMJ,QACF,CAAC,UAAU,EAAEE,UAAU,mBAAmB,EAAEF,OAAO,GACnD,CAAC,UAAU,EAAEE,UAAU,kBAAkB,CAAC;IAChD;IAEA,gBAAgB;IAChB,IAAID,UAAU;QACZE,QAAQ;YAACE,SAAS;QAAS;IAC7B,OAAO,IAAI,CAACL,OAAO;QACjB,6FAA6F;QAC7F,6GAA6G;QAC7GG,QAAQJ,UAAU;YAACA;YAASM,SAAS;QAAQ,IAAI;YAACC,SAAS;QAAM;IACnE;IAEA,MAAMC,SAAS,MAAMZ,mBAAmB;QACtCa,YAAYX;QACZY,aAAa;IACf;IAEA,IAAI;QACF,MAAMC,UAAUP,QAAQ;YAACA;YAAOC;QAAG,IAAI;YAACA;QAAG;QAC3C,OAAO,MAAMG,OAAOI,OAAO,CAACD;IAC9B,EAAE,OAAOE,KAAK;QACZ,IAAIA,KAAKC,eAAe,KAAK;YAC3B,OAAO;QACT;QAEAnB,MAAM,kCAAkCkB;QACxC,MAAMA;IACR;AACF;AAOA,OAAO,eAAeE,sBAAsB,EAC1CC,aAAa,EACbV,OAAO,EACsB;IAC7B,MAAME,SAAS,MAAMZ,mBAAmB;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xB4C,SAASR,SAASS,UAAU;QAC5BtB,QAAQ;QACRb;QACAC;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../src/services/userApplications.ts"],"sourcesContent":["import {PassThrough, type Readable} from 'node:stream'\n\nimport {type CoreAppManifest} from '@sanity/cli-build/_internal/manifest'\nimport {type AppVisibility, debug, getGlobalCliClient} from '@sanity/cli-core'\nimport FormData from 'form-data'\nimport {type StudioManifest} from 'sanity'\n\nexport const USER_APPLICATIONS_API_VERSION = 'v2024-08-01'\n\ninterface ActiveDeployment {\n createdAt: string\n deployedAt: string\n deployedBy: string\n isActiveDeployment: boolean\n isAutoUpdating: boolean | null\n size: string | null\n updatedAt: string\n version: string\n}\n\nexport interface UserApplication {\n appHost: string\n createdAt: string\n id: string\n organizationId: string | null\n projectId: string | null\n title: string | null\n type: 'coreApp' | 'studio'\n updatedAt: string\n urlType: 'external' | 'internal'\n\n activeDeployment?: ActiveDeployment | null\n /** Dashboard visibility. Defaults to `default` server-side when unset. */\n dashboardStatus?: AppVisibility\n}\n\n/** A core app always belongs to an organization. */\nexport interface UserApplicationResolved extends UserApplication {\n organizationId: string\n type: 'coreApp'\n}\n\ntype GetUserApplicationOptions =\n | {appHost?: never; appId: string; isSdkApp: true; projectId?: never}\n | {appHost?: string; appId?: string; isSdkApp: false; projectId: string}\n\nexport async function getUserApplication(options: {\n appHost?: never\n appId: string\n isSdkApp: true\n projectId?: never\n}): Promise<UserApplicationResolved | null>\nexport async function getUserApplication(options: {\n appHost?: string\n appId?: string\n isSdkApp: false\n projectId: string\n}): Promise<UserApplication | null>\nexport async function getUserApplication({\n appHost,\n appId,\n isSdkApp,\n projectId,\n}: GetUserApplicationOptions): Promise<UserApplication | null> {\n let query: Record<string, string | string[]> | undefined\n let url: string\n\n // set the url\n if (isSdkApp) {\n url = appId ? `/user-applications/${appId}` : '/user-applications'\n } else {\n url = appId\n ? `/projects/${projectId}/user-applications/${appId}`\n : `/projects/${projectId}/user-applications`\n }\n\n // set the query\n if (isSdkApp) {\n query = {appType: 'coreApp'}\n } else if (!appId) {\n // In practice, this function isn't called if we don't have at least one of appHost or appId,\n // so the default case won't be called. But leaving this ternary in for now (from old CLI code) just in case.\n query = appHost ? {appHost, appType: 'studio'} : {default: 'true'}\n }\n\n const client = await getGlobalCliClient({\n apiVersion: USER_APPLICATIONS_API_VERSION,\n requireUser: true,\n })\n\n try {\n const options = query ? {query, url} : {url}\n return await client.request(options)\n } catch (err) {\n if (err?.statusCode === 404) {\n return null\n }\n\n debug('Error getting user application', err)\n throw err\n }\n}\n\ninterface DeleteUserApplicationOptions {\n applicationId: string\n appType: 'coreApp' | 'studio'\n}\n\nexport async function deleteUserApplication({\n applicationId,\n appType,\n}: DeleteUserApplicationOptions): Promise<void> {\n const client = await getGlobalCliClient({\n apiVersion: USER_APPLICATIONS_API_VERSION,\n requireUser: true,\n })\n\n await client.request({\n method: 'DELETE',\n query: {appType},\n url: `/user-applications/${applicationId}`,\n })\n}\n\ninterface UpdateUserApplicationBody {\n dashboardStatus?: AppVisibility\n title?: string\n}\n\ninterface UpdateUserApplicationOptions {\n applicationId: string\n // Updating studio properties requires further UX thought\n // (because of workspaces et al.)\n appType: 'coreApp'\n body: UpdateUserApplicationBody\n}\n\nexport async function updateUserApplication({\n applicationId,\n appType,\n body,\n}: UpdateUserApplicationOptions): Promise<UserApplicationResolved> {\n const client = await getGlobalCliClient({\n apiVersion: USER_APPLICATIONS_API_VERSION,\n requireUser: true,\n })\n\n return client.request({\n body,\n method: 'PATCH',\n query: {appType},\n url: `/user-applications/${applicationId}`,\n })\n}\n\nexport async function getUserApplications(options: {\n appType: 'studio'\n projectId: string\n}): Promise<UserApplication[]>\nexport async function getUserApplications(options: {\n appType: 'coreApp'\n organizationId: string\n}): Promise<UserApplicationResolved[]>\nexport async function getUserApplications(\n options:\n | {\n appType: 'coreApp'\n organizationId?: string\n }\n | {\n appType: 'studio'\n projectId?: string\n },\n): Promise<UserApplication[] | null> {\n const {appType} = options\n const client = await getGlobalCliClient({\n apiVersion: USER_APPLICATIONS_API_VERSION,\n requireUser: true,\n })\n\n if (appType === 'studio') {\n const {projectId} = options as {appType: 'studio'; projectId?: string}\n return await client.request({\n query: {appType: 'studio'},\n url: `/projects/${projectId}/user-applications`,\n })\n }\n\n const {organizationId} = options as {appType: 'coreApp'; organizationId?: string}\n\n try {\n return await client.request({\n query: {appType: 'coreApp', organizationId: organizationId!},\n url: `/user-applications`,\n })\n } catch (error) {\n // User doesn't have permission to view applications for the org,\n // or the organization ID doesn’t exist\n if (error?.statusCode === 403) {\n throw error\n }\n\n debug('Error finding user applications', error)\n return null\n }\n}\n\nexport async function createUserApplication(options: {\n appType: 'coreApp'\n body: Pick<UserApplication, 'appHost' | 'type' | 'urlType'> & {\n dashboardStatus?: AppVisibility\n title?: string\n }\n organizationId?: string\n}): Promise<UserApplicationResolved>\nexport async function createUserApplication(options: {\n appType: 'studio'\n body: Pick<UserApplication, 'appHost' | 'type' | 'urlType'> & {\n dashboardStatus?: AppVisibility\n title?: string\n }\n projectId: string\n}): Promise<UserApplication>\nexport async function createUserApplication(options: {\n appType: 'coreApp' | 'studio'\n body: Pick<UserApplication, 'appHost' | 'type' | 'urlType'> & {\n dashboardStatus?: AppVisibility\n title?: string\n }\n organizationId?: string\n projectId?: string\n}): Promise<UserApplication> {\n const {appType, body} = options\n\n const client = await getGlobalCliClient({\n apiVersion: USER_APPLICATIONS_API_VERSION,\n requireUser: true,\n })\n\n let url\n let query\n\n // If we have an organizationId, we're creating a core app\n if (appType === 'coreApp') {\n const {organizationId} = options as {appType: 'coreApp'; organizationId?: string}\n url = '/user-applications'\n query = {appType: 'coreApp', organizationId: organizationId!}\n } else {\n const {projectId} = options as {appType: 'studio'; projectId?: string}\n url = `/projects/${projectId}/user-applications`\n query = {appType: 'studio'}\n }\n\n return client.request({body, method: 'POST', query, url})\n}\n\ninterface CreateDeploymentOptions {\n applicationId: string\n isAutoUpdating: boolean\n version: string\n\n isApp?: boolean\n\n manifest?: CoreAppManifest | StudioManifest | null\n\n projectId?: string\n\n tarball?: Readable\n}\n\nexport async function createDeployment({\n applicationId,\n isApp,\n isAutoUpdating,\n manifest,\n projectId,\n tarball,\n version,\n}: CreateDeploymentOptions): Promise<{location: string}> {\n const client = await getGlobalCliClient({\n apiVersion: USER_APPLICATIONS_API_VERSION,\n requireUser: true,\n })\n\n const formData = new FormData()\n formData.append('isAutoUpdating', isAutoUpdating.toString())\n formData.append('version', version)\n if (manifest) {\n formData.append('manifest', JSON.stringify(manifest))\n }\n\n if (tarball) {\n formData.append('tarball', tarball, {contentType: 'application/gzip', filename: 'app.tar.gz'})\n }\n\n let url\n let query\n\n if (isApp) {\n url = `/user-applications/${applicationId}/deployments`\n query = {appType: 'coreApp'}\n } else {\n url = `/projects/${projectId}/user-applications/${applicationId}/deployments`\n query = {appType: 'studio'}\n }\n\n return client.request({\n body: formData.pipe(new PassThrough()),\n headers: formData.getHeaders(),\n method: 'POST',\n query,\n url,\n })\n}\n"],"names":["PassThrough","debug","getGlobalCliClient","FormData","USER_APPLICATIONS_API_VERSION","getUserApplication","appHost","appId","isSdkApp","projectId","query","url","appType","default","client","apiVersion","requireUser","options","request","err","statusCode","deleteUserApplication","applicationId","method","updateUserApplication","body","getUserApplications","organizationId","error","createUserApplication","createDeployment","isApp","isAutoUpdating","manifest","tarball","version","formData","append","toString","JSON","stringify","contentType","filename","pipe","headers","getHeaders"],"mappings":"AAAA,SAAQA,WAAW,QAAsB,cAAa;AAGtD,SAA4BC,KAAK,EAAEC,kBAAkB,QAAO,mBAAkB;AAC9E,OAAOC,cAAc,YAAW;AAGhC,OAAO,MAAMC,gCAAgC,cAAa;AAmD1D,OAAO,eAAeC,mBAAmB,EACvCC,OAAO,EACPC,KAAK,EACLC,QAAQ,EACRC,SAAS,EACiB;IAC1B,IAAIC;IACJ,IAAIC;IAEJ,cAAc;IACd,IAAIH,UAAU;QACZG,MAAMJ,QAAQ,CAAC,mBAAmB,EAAEA,OAAO,GAAG;IAChD,OAA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