@sanity/cli 8.31.0 → 8.32.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/README.md +179 -103
- package/bin/run.js +1 -1
- package/dist/actions/context/waitForSourceSync.js +1 -1
- package/dist/actions/context/waitForSourceSync.js.map +1 -1
- package/dist/actions/cors/filterAndValidateOrigin.js +1 -1
- package/dist/actions/cors/filterAndValidateOrigin.js.map +1 -1
- package/dist/actions/deploy/deployStudioSchemasAndManifestsWorker.js +13 -1
- package/dist/actions/deploy/deployStudioSchemasAndManifestsWorker.js.map +1 -1
- package/dist/actions/documents/validateDocuments.worker.js +2 -1
- package/dist/actions/documents/validateDocuments.worker.js.map +1 -1
- package/dist/actions/graphql/extractFromSanitySchema.js +1 -1
- package/dist/actions/graphql/extractFromSanitySchema.js.map +1 -1
- package/dist/actions/init/initStudio.js +1 -1
- package/dist/actions/init/initStudio.js.map +1 -1
- package/dist/actions/init/processTemplate.js +1 -1
- package/dist/actions/init/processTemplate.js.map +1 -1
- package/dist/actions/init/remoteTemplate.js +1 -1
- package/dist/actions/init/remoteTemplate.js.map +1 -1
- package/dist/actions/media/pullAspects.js +1 -1
- package/dist/actions/media/pullAspects.js.map +1 -1
- package/dist/actions/organizations/readOrganizationLogo.js +49 -0
- package/dist/actions/organizations/readOrganizationLogo.js.map +1 -0
- package/dist/actions/preview/previewAction.js +1 -1
- package/dist/actions/preview/previewAction.js.map +1 -1
- package/dist/actions/skills/readSkillState.js +1 -1
- package/dist/actions/skills/readSkillState.js.map +1 -1
- package/dist/actions/skills/setupSkills.js +1 -1
- package/dist/actions/skills/setupSkills.js.map +1 -1
- package/dist/commands/organizations/create.js +43 -3
- package/dist/commands/organizations/create.js.map +1 -1
- package/dist/commands/organizations/update.js +67 -14
- package/dist/commands/organizations/update.js.map +1 -1
- package/dist/exports/invokeSanityCli/commandPolicies/mcpPolicy.js +7 -2
- package/dist/exports/invokeSanityCli/commandPolicies/mcpPolicy.js.map +1 -1
- package/dist/generated/contextOperations.js +2 -2
- package/dist/generated/contextOperations.js.map +1 -1
- package/dist/hooks/commandNotFound/topicAliases.js +1 -1
- package/dist/hooks/commandNotFound/topicAliases.js.map +1 -1
- package/dist/server/devServer.js +8 -10
- package/dist/server/devServer.js.map +1 -1
- package/dist/services/organizations.js +30 -0
- package/dist/services/organizations.js.map +1 -1
- package/dist/util/telemetry/cliCommandIdentity.js +3 -2
- package/dist/util/telemetry/cliCommandIdentity.js.map +1 -1
- package/dist/util/update/updateChecker.js +1 -1
- package/dist/util/update/updateChecker.js.map +1 -1
- package/oclif.config.js +1 -1
- package/oclif.manifest.json +874 -832
- package/package.json +26 -27
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/deploy/deployStudioSchemasAndManifestsWorker.ts"],"sourcesContent":["import {\n extractValidationFromSchemaError,\n workerBuildStudioSchemasAndManifests,\n} from '@sanity/cli-build/_internal/extract'\nimport {subdebug} from '@sanity/cli-core'\n\nimport {updateWorkspacesSchemas} from '../schema/updateWorkspaceSchema.js'\nimport {\n deployStudioSchemasAndManifestsWorkerData,\n type DeployStudioSchemasAndManifestsWorkerMessage,\n} from './types.js'\n\nconst debug = subdebug('deployStudioSchemasAndManifests.worker')\n\n/**\n * The subset of `MessagePort` this worker needs, so the body can be driven\n * without a real thread.\n */\nexport interface DeployStudioSchemasAndManifestsPort {\n postMessage: (message: DeployStudioSchemasAndManifestsWorkerMessage) => void\n}\n\n/**\n * Body of `deployStudioSchemasAndManifests.worker.ts`, kept out of the thread entry point so it\n * can be exercised directly in tests.\n *\n * 1. Validates the worker data\n * 2. Builds the studio schemas and manifests, updating the `/schemas` endpoint along the way\n * 3. Posts either the resulting studio manifest or a serialized error back to the parent\n *\n * @param port - The port to post the result to\n * @param workerData - The unvalidated worker data handed to the worker\n */\nexport async function deployStudioSchemasAndManifestsWorker(\n port: DeployStudioSchemasAndManifestsPort,\n workerData: unknown,\n): Promise<void> {\n const parsedWorkerData = deployStudioSchemasAndManifestsWorkerData.parse(workerData)\n\n const options: Parameters<typeof workerBuildStudioSchemasAndManifests>[0] = parsedWorkerData\n\n options.workspaceSchemaHandler = async (schemaInputs) => {\n // Updates the workspaces schemas to /schemas endpoint\n await updateWorkspacesSchemas({verbose: options.verbose, workspaces: schemaInputs})\n }\n\n try {\n const result = await workerBuildStudioSchemasAndManifests(options)\n\n port.postMessage({\n studioManifest: result.studioManifest,\n type: 'success',\n })\n } catch (error) {\n debug('Error deploying studio schemas and manifests', error)\n const validation = await extractValidationFromSchemaError(error, options.workDir)\n port.postMessage({\n error: error instanceof Error ? error.message : String(error),\n type: 'error',\n validation,\n })\n }\n}\n"],"names":["extractValidationFromSchemaError","workerBuildStudioSchemasAndManifests","subdebug","updateWorkspacesSchemas","deployStudioSchemasAndManifestsWorkerData","debug","deployStudioSchemasAndManifestsWorker","port","workerData","parsedWorkerData","parse","options","workspaceSchemaHandler","schemaInputs","verbose","workspaces","
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/deploy/deployStudioSchemasAndManifestsWorker.ts"],"sourcesContent":["import {\n extractValidationFromSchemaError,\n workerBuildStudioSchemasAndManifests,\n} from '@sanity/cli-build/_internal/extract'\nimport {subdebug} from '@sanity/cli-core'\nimport {spinner} from '@sanity/cli-core/ux'\n\nimport {updateWorkspacesSchemas} from '../schema/updateWorkspaceSchema.js'\nimport {\n deployStudioSchemasAndManifestsWorkerData,\n type DeployStudioSchemasAndManifestsWorkerMessage,\n} from './types.js'\n\nconst debug = subdebug('deployStudioSchemasAndManifests.worker')\n\n/**\n * The subset of `MessagePort` this worker needs, so the body can be driven\n * without a real thread.\n */\nexport interface DeployStudioSchemasAndManifestsPort {\n postMessage: (message: DeployStudioSchemasAndManifestsWorkerMessage) => void\n}\n\n/**\n * Body of `deployStudioSchemasAndManifests.worker.ts`, kept out of the thread entry point so it\n * can be exercised directly in tests.\n *\n * 1. Validates the worker data\n * 2. Builds the studio schemas and manifests, updating the `/schemas` endpoint along the way\n * 3. Posts either the resulting studio manifest or a serialized error back to the parent\n *\n * @param port - The port to post the result to\n * @param workerData - The unvalidated worker data handed to the worker\n */\nexport async function deployStudioSchemasAndManifestsWorker(\n port: DeployStudioSchemasAndManifestsPort,\n workerData: unknown,\n): Promise<void> {\n const parsedWorkerData = deployStudioSchemasAndManifestsWorkerData.parse(workerData)\n\n const options: Parameters<typeof workerBuildStudioSchemasAndManifests>[0] = parsedWorkerData\n\n options.workspaceSchemaHandler = async (schemaInputs) => {\n // Updates the workspaces schemas to /schemas endpoint\n await updateWorkspacesSchemas({verbose: options.verbose, workspaces: schemaInputs})\n }\n\n try {\n const spin = spinner('Generating studio manifest')\n const result = await workerBuildStudioSchemasAndManifests(options, {\n onGenerateManifestDone() {\n spin.succeed('Generated studio manifest')\n },\n onGenerateManifestFail(error) {\n spin.fail(error instanceof Error ? error.message : 'Unknown error')\n },\n onGenerateManifestStart() {\n spin.start()\n },\n })\n\n port.postMessage({\n studioManifest: result.studioManifest,\n type: 'success',\n })\n } catch (error) {\n debug('Error deploying studio schemas and manifests', error)\n const validation = await extractValidationFromSchemaError(error, options.workDir)\n port.postMessage({\n error: error instanceof Error ? error.message : String(error),\n type: 'error',\n validation,\n })\n }\n}\n"],"names":["extractValidationFromSchemaError","workerBuildStudioSchemasAndManifests","subdebug","spinner","updateWorkspacesSchemas","deployStudioSchemasAndManifestsWorkerData","debug","deployStudioSchemasAndManifestsWorker","port","workerData","parsedWorkerData","parse","options","workspaceSchemaHandler","schemaInputs","verbose","workspaces","spin","result","onGenerateManifestDone","succeed","onGenerateManifestFail","error","fail","Error","message","onGenerateManifestStart","start","postMessage","studioManifest","type","validation","workDir","String"],"mappings":"AAAA,SACEA,gCAAgC,EAChCC,oCAAoC,QAC/B,sCAAqC;AAC5C,SAAQC,QAAQ,QAAO,mBAAkB;AACzC,SAAQC,OAAO,QAAO,sBAAqB;AAE3C,SAAQC,uBAAuB,QAAO,qCAAoC;AAC1E,SACEC,yCAAyC,QAEpC,aAAY;AAEnB,MAAMC,QAAQJ,SAAS;AAUvB;;;;;;;;;;CAUC,GACD,OAAO,eAAeK,sCACpBC,IAAyC,EACzCC,UAAmB;IAEnB,MAAMC,mBAAmBL,0CAA0CM,KAAK,CAACF;IAEzE,MAAMG,UAAsEF;IAE5EE,QAAQC,sBAAsB,GAAG,OAAOC;QACtC,sDAAsD;QACtD,MAAMV,wBAAwB;YAACW,SAASH,QAAQG,OAAO;YAAEC,YAAYF;QAAY;IACnF;IAEA,IAAI;QACF,MAAMG,OAAOd,QAAQ;QACrB,MAAMe,SAAS,MAAMjB,qCAAqCW,SAAS;YACjEO;gBACEF,KAAKG,OAAO,CAAC;YACf;YACAC,wBAAuBC,KAAK;gBAC1BL,KAAKM,IAAI,CAACD,iBAAiBE,QAAQF,MAAMG,OAAO,GAAG;YACrD;YACAC;gBACET,KAAKU,KAAK;YACZ;QACF;QAEAnB,KAAKoB,WAAW,CAAC;YACfC,gBAAgBX,OAAOW,cAAc;YACrCC,MAAM;QACR;IACF,EAAE,OAAOR,OAAO;QACdhB,MAAM,gDAAgDgB;QACtD,MAAMS,aAAa,MAAM/B,iCAAiCsB,OAAOV,QAAQoB,OAAO;QAChFxB,KAAKoB,WAAW,CAAC;YACfN,OAAOA,iBAAiBE,QAAQF,MAAMG,OAAO,GAAGQ,OAAOX;YACvDQ,MAAM;YACNC;QACF;IACF;AACF"}
|
|
@@ -18,7 +18,7 @@ if (isMainThread || !parentPort) {
|
|
|
18
18
|
throw new Error('This module must be run as a worker thread');
|
|
19
19
|
}
|
|
20
20
|
const report = WorkerChannelReporter.from(parentPort);
|
|
21
|
-
// eslint-disable-next-line n/no-unsupported-features/node-builtins
|
|
21
|
+
// eslint-disable-next-line n-js/no-unsupported-features/node-builtins
|
|
22
22
|
async function* readerToGenerator(reader) {
|
|
23
23
|
while(true){
|
|
24
24
|
const { done, value } = await reader.read();
|
|
@@ -186,6 +186,7 @@ async function main() {
|
|
|
186
186
|
const validationClient = createClientConcurrencyLimiter(maxFetchConcurrency ?? 25)(client);
|
|
187
187
|
let validatedCount = 0;
|
|
188
188
|
const validate = async (document)=>{
|
|
189
|
+
if (!shouldIncludeDocument(document)) return;
|
|
189
190
|
let markers;
|
|
190
191
|
try {
|
|
191
192
|
const result = await validateDocument({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/documents/validateDocuments.worker.ts"],"sourcesContent":["import fs from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\nimport readline from 'node:readline'\nimport {Readable} from 'node:stream'\nimport {workerData as _workerData, isMainThread, parentPort} from 'node:worker_threads'\n\nimport {getStudioWorkspaces, getWorkspace} from '@sanity/cli-core'\nimport {createClient, type SanityDocument} from '@sanity/client'\nimport {type ValidationMarker} from '@sanity/types'\nimport {createClientConcurrencyLimiter} from '@sanity/util/client'\nimport {validateDocument, withReleaseReferences} from '@sanity/validation'\nimport {WorkerChannelReporter} from '@sanity/worker-channels'\nimport pMap from 'p-map'\n\nimport {\n type AvailabilityResponse,\n checkDocumentAvailability,\n exportDocuments,\n getDocumentCount,\n} from '../../services/documents.js'\nimport {extractDocumentsFromNdjsonOrTarball} from '../../util/extractDocumentsFromNdjsonOrTarball.js'\nimport {\n DOCUMENT_VALIDATION_TIMEOUT,\n getReferenceIds,\n isValidId,\n levelValues,\n MAX_VALIDATION_CONCURRENCY,\n REFERENCE_INTEGRITY_BATCH_SIZE,\n shouldIncludeDocument,\n} from '../../util/validation/validateDocumentsUtils.js'\nimport {type ValidateDocumentsWorkerData, type ValidationWorkerChannel} from './types.js'\n\nconst {\n clientConfig,\n dataset,\n level,\n maxCustomValidationConcurrency,\n maxFetchConcurrency,\n ndjsonFilePath,\n projectId,\n studioHost,\n workDir,\n workspace: workspaceName,\n} = _workerData as ValidateDocumentsWorkerData\n\nif (isMainThread || !parentPort) {\n throw new Error('This module must be run as a worker thread')\n}\n\nconst report = WorkerChannelReporter.from<ValidationWorkerChannel>(parentPort)\n\n// eslint-disable-next-line n/no-unsupported-features/node-builtins\nasync function* readerToGenerator(reader: ReadableStreamDefaultReader<Uint8Array>) {\n while (true) {\n const {done, value} = await reader.read()\n if (value) yield value\n if (done) return\n }\n}\n\nawait main()\nprocess.exit()\n\nasync function loadWorkspace() {\n const workspaces = await getStudioWorkspaces(workDir)\n const workspace = getWorkspace(workspaces, workspaceName)\n\n const resolvedDataset = dataset || workspace.dataset\n const resolvedProjectId = projectId || workspace.projectId\n\n const client = createClient({\n ...clientConfig,\n dataset: resolvedDataset,\n projectId: resolvedProjectId,\n requestTagPrefix: 'sanity.cli.validate',\n }).config({apiVersion: 'v2021-03-25'})\n\n report.event.loadedWorkspace({\n basePath: workspace.basePath,\n dataset: workspace.dataset,\n name: workspace.name,\n projectId: workspace.projectId,\n })\n\n return {client, dataset: resolvedDataset, projectId: resolvedProjectId, workspace}\n}\n\ninterface DownloadFromExportOptions {\n dataset: string\n projectId: string\n}\n\nasync function downloadFromExport({\n dataset: datasetName,\n projectId: projId,\n}: DownloadFromExportOptions) {\n const documentCount = await getDocumentCount({dataset: datasetName, projectId: projId})\n report.event.loadedDocumentCount({documentCount})\n\n const response = await exportDocuments({dataset: datasetName, projectId: projId})\n\n const reader = response.body?.getReader()\n if (!reader) throw new Error('Could not get reader from response body.')\n\n let downloadedCount = 0\n const referencedIds = new Set<string>()\n const documentIds = new Map<string, boolean>()\n const lines = readline.createInterface({input: Readable.from(readerToGenerator(reader))})\n\n // Note: we stream the export to a file and then re-read from that file to\n // make this less memory intensive.\n // this is a similar pattern to the import/export CLI commands\n const slugDate = new Date()\n .toISOString()\n .replaceAll(/[^a-z0-9]/gi, '-')\n .toLowerCase()\n const tempOutputFile = path.join(os.tmpdir(), `sanity-validate-${slugDate}.ndjson`)\n const outputStream = fs.createWriteStream(tempOutputFile)\n\n for await (const line of lines) {\n const document = JSON.parse(line) as SanityDocument\n\n if (shouldIncludeDocument(document)) {\n documentIds.set(document._id, document._system?.delete !== true)\n for (const referenceId of getReferenceIds(document)) {\n referencedIds.add(referenceId)\n }\n\n outputStream.write(`${line}\\n`)\n }\n\n downloadedCount++\n report.stream.exportProgress.emit({documentCount, downloadedCount})\n }\n\n await new Promise<void>((resolve, reject) =>\n outputStream.close((err) => (err ? reject(err) : resolve())),\n )\n\n report.stream.exportProgress.end()\n report.event.exportFinished({totalDocumentsToValidate: documentIds.size})\n\n const getDocuments = () =>\n extractDocumentsFromNdjsonOrTarball(fs.createReadStream(tempOutputFile))\n\n return {cleanup: () => fs.promises.rm(tempOutputFile), documentIds, getDocuments, referencedIds}\n}\n\nasync function downloadFromFile(filePath: string) {\n const referencedIds = new Set<string>()\n const documentIds = new Map<string, boolean>()\n const getDocuments = () => extractDocumentsFromNdjsonOrTarball(fs.createReadStream(filePath))\n\n for await (const document of getDocuments()) {\n if (shouldIncludeDocument(document)) {\n documentIds.set(document._id, document._system?.delete !== true)\n for (const referenceId of getReferenceIds(document)) {\n referencedIds.add(referenceId)\n }\n }\n }\n\n report.event.exportFinished({totalDocumentsToValidate: documentIds.size})\n\n return {cleanup: undefined, documentIds, getDocuments, referencedIds}\n}\n\ninterface CheckReferenceExistenceOptions {\n dataset: string\n documentIds: Map<string, boolean>\n projectId: string\n referencedIds: Set<string>\n}\n\nasync function checkReferenceExistence({\n dataset: datasetName,\n documentIds: existingIds,\n projectId: projId,\n referencedIds: _referencedIds,\n}: CheckReferenceExistenceOptions) {\n const idsToCheck = [..._referencedIds]\n .filter((id) => !existingIds.has(id) && isValidId(id))\n .toSorted()\n\n for (let i = 0; i < idsToCheck.length; i += REFERENCE_INTEGRITY_BATCH_SIZE) {\n const batch = idsToCheck.slice(i, i + REFERENCE_INTEGRITY_BATCH_SIZE)\n const {omitted} = await checkDocumentAvailability({\n dataset: datasetName,\n documentIds: batch,\n projectId: projId,\n })\n\n const omittedIds: Record<string, AvailabilityResponse['omitted'][number]['reason']> = {}\n for (const item of omitted) {\n omittedIds[item.id] = item.reason\n }\n\n for (const id of batch) {\n // unless the document ID is in the `omitted` object explictly due to\n // the reason `'existence'`, then it should exist\n if (omittedIds[id] !== 'existence') {\n existingIds.set(id, true)\n }\n }\n }\n report.event.loadedReferenceIntegrity()\n\n return {existingIds}\n}\n\nasync function main() {\n let cleanupDownloadedDocuments: (() => Promise<void>) | undefined\n\n try {\n const {client, dataset: datasetName, projectId: projId, workspace} = await loadWorkspace()\n const {cleanup, documentIds, getDocuments, referencedIds} = ndjsonFilePath\n ? await downloadFromFile(ndjsonFilePath)\n : await downloadFromExport({dataset: datasetName, projectId: projId})\n cleanupDownloadedDocuments = cleanup\n const {existingIds} = await checkReferenceExistence({\n dataset: datasetName,\n documentIds,\n projectId: projId,\n referencedIds,\n })\n\n const getLevel = (markers: ValidationMarker[]) => {\n let foundWarning = false\n for (const marker of markers) {\n if (marker.level === 'error') return 'error'\n if (marker.level === 'warning') foundWarning = true\n }\n\n if (foundWarning) return 'warning'\n return 'info'\n }\n\n // Share the fetch limit across documents, including clients reconfigured by validators.\n const validationClient = createClientConcurrencyLimiter(maxFetchConcurrency ?? 25)(client)\n let validatedCount = 0\n\n const validate = async (document: SanityDocument) => {\n let markers: ValidationMarker[]\n\n try {\n const result = await validateDocument({\n client: validationClient,\n document,\n getDocumentExists: withReleaseReferences({\n document,\n getDocumentExists: ({id}) => Promise.resolve(existingIds.has(id)),\n isUnpublished: ({id}) => Promise.resolve(existingIds.get(id) === false),\n }),\n i18n: workspace.i18n,\n maxCustomValidationConcurrency,\n maxFetchConcurrency,\n schema: workspace.schema,\n signal: AbortSignal.timeout(DOCUMENT_VALIDATION_TIMEOUT),\n // Referenced documents can exist only in the input, without a live API counterpart\n validateReferenceTypes: false,\n })\n\n markers = result.markers\n // filter out unwanted levels\n .filter((marker) => {\n const markerValue = levelValues[marker.level]\n const flagLevelValue =\n levelValues[level as keyof typeof levelValues] ?? levelValues.info\n return markerValue <= flagLevelValue\n })\n\n if (!result.complete && !markers.some((marker) => marker.level === 'error')) {\n markers.push({\n level: 'error',\n message:\n 'Document validation is incomplete. Check the schema and any reported validation errors, then rerun this command.',\n path: [],\n })\n }\n } catch (err) {\n const errorMessage = err instanceof Error ? err.message : 'Unknown error'\n\n const message = `Exception occurred while validating value: ${errorMessage}`\n\n markers = [\n {\n level: 'error',\n message,\n path: [],\n },\n ]\n }\n\n validatedCount++\n\n const intentUrl =\n studioHost &&\n `${studioHost}${path.resolve(\n workspace.basePath,\n `/intent/edit/id=${encodeURIComponent(document._id)};type=${encodeURIComponent(\n document._type,\n )}`,\n )}`\n\n report.stream.validation.emit({\n documentId: document._id,\n documentType: document._type,\n ...(intentUrl && {intentUrl}),\n level: getLevel(markers),\n markers,\n revision: document._rev,\n validatedCount,\n })\n }\n\n await pMap(getDocuments(), validate, {concurrency: MAX_VALIDATION_CONCURRENCY})\n\n report.stream.validation.end()\n } finally {\n await cleanupDownloadedDocuments?.()\n }\n}\n"],"names":["fs","os","path","readline","Readable","workerData","_workerData","isMainThread","parentPort","getStudioWorkspaces","getWorkspace","createClient","createClientConcurrencyLimiter","validateDocument","withReleaseReferences","WorkerChannelReporter","pMap","checkDocumentAvailability","exportDocuments","getDocumentCount","extractDocumentsFromNdjsonOrTarball","DOCUMENT_VALIDATION_TIMEOUT","getReferenceIds","isValidId","levelValues","MAX_VALIDATION_CONCURRENCY","REFERENCE_INTEGRITY_BATCH_SIZE","shouldIncludeDocument","clientConfig","dataset","level","maxCustomValidationConcurrency","maxFetchConcurrency","ndjsonFilePath","projectId","studioHost","workDir","workspace","workspaceName","Error","report","from","readerToGenerator","reader","done","value","read","main","process","exit","loadWorkspace","workspaces","resolvedDataset","resolvedProjectId","client","requestTagPrefix","config","apiVersion","event","loadedWorkspace","basePath","name","downloadFromExport","datasetName","projId","documentCount","loadedDocumentCount","response","body","getReader","downloadedCount","referencedIds","Set","documentIds","Map","lines","createInterface","input","slugDate","Date","toISOString","replaceAll","toLowerCase","tempOutputFile","join","tmpdir","outputStream","createWriteStream","line","document","JSON","parse","set","_id","_system","delete","referenceId","add","write","stream","exportProgress","emit","Promise","resolve","reject","close","err","end","exportFinished","totalDocumentsToValidate","size","getDocuments","createReadStream","cleanup","promises","rm","downloadFromFile","filePath","undefined","checkReferenceExistence","existingIds","_referencedIds","idsToCheck","filter","id","has","toSorted","i","length","batch","slice","omitted","omittedIds","item","reason","loadedReferenceIntegrity","cleanupDownloadedDocuments","getLevel","markers","foundWarning","marker","validationClient","validatedCount","validate","result","getDocumentExists","isUnpublished","get","i18n","schema","signal","AbortSignal","timeout","validateReferenceTypes","markerValue","flagLevelValue","info","complete","some","push","message","errorMessage","intentUrl","encodeURIComponent","_type","validation","documentId","documentType","revision","_rev","concurrency"],"mappings":"AAAA,OAAOA,QAAQ,UAAS;AACxB,OAAOC,QAAQ,UAAS;AACxB,OAAOC,UAAU,YAAW;AAC5B,OAAOC,cAAc,gBAAe;AACpC,SAAQC,QAAQ,QAAO,cAAa;AACpC,SAAQC,cAAcC,WAAW,EAAEC,YAAY,EAAEC,UAAU,QAAO,sBAAqB;AAEvF,SAAQC,mBAAmB,EAAEC,YAAY,QAAO,mBAAkB;AAClE,SAAQC,YAAY,QAA4B,iBAAgB;AAEhE,SAAQC,8BAA8B,QAAO,sBAAqB;AAClE,SAAQC,gBAAgB,EAAEC,qBAAqB,QAAO,qBAAoB;AAC1E,SAAQC,qBAAqB,QAAO,0BAAyB;AAC7D,OAAOC,UAAU,QAAO;AAExB,SAEEC,yBAAyB,EACzBC,eAAe,EACfC,gBAAgB,QACX,8BAA6B;AACpC,SAAQC,mCAAmC,QAAO,oDAAmD;AACrG,SACEC,2BAA2B,EAC3BC,eAAe,EACfC,SAAS,EACTC,WAAW,EACXC,0BAA0B,EAC1BC,8BAA8B,EAC9BC,qBAAqB,QAChB,kDAAiD;AAGxD,MAAM,EACJC,YAAY,EACZC,OAAO,EACPC,KAAK,EACLC,8BAA8B,EAC9BC,mBAAmB,EACnBC,cAAc,EACdC,SAAS,EACTC,UAAU,EACVC,OAAO,EACPC,WAAWC,aAAa,EACzB,GAAGhC;AAEJ,IAAIC,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AAU/E,SAASgF,IAAI;gBACvB3B;YACF;QACF;QAEA,MAAM9H,KAAK+F,gBAAgBgC,UAAU;YAAC2B,aAAajJ;QAA0B;QAE7Ee,OAAO2D,MAAM,CAACkE,UAAU,CAAC1D,GAAG;IAC9B,SAAU;QACR,MAAM6B;IACR;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/documents/validateDocuments.worker.ts"],"sourcesContent":["import fs from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\nimport readline from 'node:readline'\nimport {Readable} from 'node:stream'\nimport {workerData as _workerData, isMainThread, parentPort} from 'node:worker_threads'\n\nimport {getStudioWorkspaces, getWorkspace} from '@sanity/cli-core'\nimport {createClient, type SanityDocument} from '@sanity/client'\nimport {type ValidationMarker} from '@sanity/types'\nimport {createClientConcurrencyLimiter} from '@sanity/util/client'\nimport {validateDocument, withReleaseReferences} from '@sanity/validation'\nimport {WorkerChannelReporter} from '@sanity/worker-channels'\nimport pMap from 'p-map'\n\nimport {\n type AvailabilityResponse,\n checkDocumentAvailability,\n exportDocuments,\n getDocumentCount,\n} from '../../services/documents.js'\nimport {extractDocumentsFromNdjsonOrTarball} from '../../util/extractDocumentsFromNdjsonOrTarball.js'\nimport {\n DOCUMENT_VALIDATION_TIMEOUT,\n getReferenceIds,\n isValidId,\n levelValues,\n MAX_VALIDATION_CONCURRENCY,\n REFERENCE_INTEGRITY_BATCH_SIZE,\n shouldIncludeDocument,\n} from '../../util/validation/validateDocumentsUtils.js'\nimport {type ValidateDocumentsWorkerData, type ValidationWorkerChannel} from './types.js'\n\nconst {\n clientConfig,\n dataset,\n level,\n maxCustomValidationConcurrency,\n maxFetchConcurrency,\n ndjsonFilePath,\n projectId,\n studioHost,\n workDir,\n workspace: workspaceName,\n} = _workerData as ValidateDocumentsWorkerData\n\nif (isMainThread || !parentPort) {\n throw new Error('This module must be run as a worker thread')\n}\n\nconst report = WorkerChannelReporter.from<ValidationWorkerChannel>(parentPort)\n\n// eslint-disable-next-line n-js/no-unsupported-features/node-builtins\nasync function* readerToGenerator(reader: ReadableStreamDefaultReader<Uint8Array>) {\n while (true) {\n const {done, value} = await reader.read()\n if (value) yield value\n if (done) return\n }\n}\n\nawait main()\nprocess.exit()\n\nasync function loadWorkspace() {\n const workspaces = await getStudioWorkspaces(workDir)\n const workspace = getWorkspace(workspaces, workspaceName)\n\n const resolvedDataset = dataset || workspace.dataset\n const resolvedProjectId = projectId || workspace.projectId\n\n const client = createClient({\n ...clientConfig,\n dataset: resolvedDataset,\n projectId: resolvedProjectId,\n requestTagPrefix: 'sanity.cli.validate',\n }).config({apiVersion: 'v2021-03-25'})\n\n report.event.loadedWorkspace({\n basePath: workspace.basePath,\n dataset: workspace.dataset,\n name: workspace.name,\n projectId: workspace.projectId,\n })\n\n return {client, dataset: resolvedDataset, projectId: resolvedProjectId, workspace}\n}\n\ninterface DownloadFromExportOptions {\n dataset: string\n projectId: string\n}\n\nasync function downloadFromExport({\n dataset: datasetName,\n projectId: projId,\n}: DownloadFromExportOptions) {\n const documentCount = await getDocumentCount({dataset: datasetName, projectId: projId})\n report.event.loadedDocumentCount({documentCount})\n\n const response = await exportDocuments({dataset: datasetName, projectId: projId})\n\n const reader = response.body?.getReader()\n if (!reader) throw new Error('Could not get reader from response body.')\n\n let downloadedCount = 0\n const referencedIds = new Set<string>()\n const documentIds = new Map<string, boolean>()\n const lines = readline.createInterface({input: Readable.from(readerToGenerator(reader))})\n\n // Note: we stream the export to a file and then re-read from that file to\n // make this less memory intensive.\n // this is a similar pattern to the import/export CLI commands\n const slugDate = new Date()\n .toISOString()\n .replaceAll(/[^a-z0-9]/gi, '-')\n .toLowerCase()\n const tempOutputFile = path.join(os.tmpdir(), `sanity-validate-${slugDate}.ndjson`)\n const outputStream = fs.createWriteStream(tempOutputFile)\n\n for await (const line of lines) {\n const document = JSON.parse(line) as SanityDocument\n\n if (shouldIncludeDocument(document)) {\n documentIds.set(document._id, document._system?.delete !== true)\n for (const referenceId of getReferenceIds(document)) {\n referencedIds.add(referenceId)\n }\n\n outputStream.write(`${line}\\n`)\n }\n\n downloadedCount++\n report.stream.exportProgress.emit({documentCount, downloadedCount})\n }\n\n await new Promise<void>((resolve, reject) =>\n outputStream.close((err) => (err ? reject(err) : resolve())),\n )\n\n report.stream.exportProgress.end()\n report.event.exportFinished({totalDocumentsToValidate: documentIds.size})\n\n const getDocuments = () =>\n extractDocumentsFromNdjsonOrTarball(fs.createReadStream(tempOutputFile))\n\n return {cleanup: () => fs.promises.rm(tempOutputFile), documentIds, getDocuments, referencedIds}\n}\n\nasync function downloadFromFile(filePath: string) {\n const referencedIds = new Set<string>()\n const documentIds = new Map<string, boolean>()\n const getDocuments = () => extractDocumentsFromNdjsonOrTarball(fs.createReadStream(filePath))\n\n for await (const document of getDocuments()) {\n if (shouldIncludeDocument(document)) {\n documentIds.set(document._id, document._system?.delete !== true)\n for (const referenceId of getReferenceIds(document)) {\n referencedIds.add(referenceId)\n }\n }\n }\n\n report.event.exportFinished({totalDocumentsToValidate: documentIds.size})\n\n return {cleanup: undefined, documentIds, getDocuments, referencedIds}\n}\n\ninterface CheckReferenceExistenceOptions {\n dataset: string\n documentIds: Map<string, boolean>\n projectId: string\n referencedIds: Set<string>\n}\n\nasync function checkReferenceExistence({\n dataset: datasetName,\n documentIds: existingIds,\n projectId: projId,\n referencedIds: _referencedIds,\n}: CheckReferenceExistenceOptions) {\n const idsToCheck = [..._referencedIds]\n .filter((id) => !existingIds.has(id) && isValidId(id))\n .toSorted()\n\n for (let i = 0; i < idsToCheck.length; i += REFERENCE_INTEGRITY_BATCH_SIZE) {\n const batch = idsToCheck.slice(i, i + REFERENCE_INTEGRITY_BATCH_SIZE)\n const {omitted} = await checkDocumentAvailability({\n dataset: datasetName,\n documentIds: batch,\n projectId: projId,\n })\n\n const omittedIds: Record<string, AvailabilityResponse['omitted'][number]['reason']> = {}\n for (const item of omitted) {\n omittedIds[item.id] = item.reason\n }\n\n for (const id of batch) {\n // unless the document ID is in the `omitted` object explictly due to\n // the reason `'existence'`, then it should exist\n if (omittedIds[id] !== 'existence') {\n existingIds.set(id, true)\n }\n }\n }\n report.event.loadedReferenceIntegrity()\n\n return {existingIds}\n}\n\nasync function main() {\n let cleanupDownloadedDocuments: (() => Promise<void>) | undefined\n\n try {\n const {client, dataset: datasetName, projectId: projId, workspace} = await loadWorkspace()\n const {cleanup, documentIds, getDocuments, referencedIds} = ndjsonFilePath\n ? await downloadFromFile(ndjsonFilePath)\n : await downloadFromExport({dataset: datasetName, projectId: projId})\n cleanupDownloadedDocuments = cleanup\n const {existingIds} = await checkReferenceExistence({\n dataset: datasetName,\n documentIds,\n projectId: projId,\n referencedIds,\n })\n\n const getLevel = (markers: ValidationMarker[]) => {\n let foundWarning = false\n for (const marker of markers) {\n if (marker.level === 'error') return 'error'\n if (marker.level === 'warning') foundWarning = true\n }\n\n if (foundWarning) return 'warning'\n return 'info'\n }\n\n // Share the fetch limit across documents, including clients reconfigured by validators.\n const validationClient = createClientConcurrencyLimiter(maxFetchConcurrency ?? 25)(client)\n let validatedCount = 0\n\n const validate = async (document: SanityDocument) => {\n if (!shouldIncludeDocument(document)) return\n\n let markers: ValidationMarker[]\n\n try {\n const result = await validateDocument({\n client: validationClient,\n document,\n getDocumentExists: withReleaseReferences({\n document,\n getDocumentExists: ({id}) => Promise.resolve(existingIds.has(id)),\n isUnpublished: ({id}) => Promise.resolve(existingIds.get(id) === false),\n }),\n i18n: workspace.i18n,\n maxCustomValidationConcurrency,\n maxFetchConcurrency,\n schema: workspace.schema,\n signal: AbortSignal.timeout(DOCUMENT_VALIDATION_TIMEOUT),\n // Referenced documents can exist only in the input, without a live API counterpart\n validateReferenceTypes: false,\n })\n\n markers = result.markers\n // filter out unwanted levels\n .filter((marker) => {\n const markerValue = levelValues[marker.level]\n const flagLevelValue =\n levelValues[level as keyof typeof levelValues] ?? levelValues.info\n return markerValue <= flagLevelValue\n })\n\n if (!result.complete && !markers.some((marker) => marker.level === 'error')) {\n markers.push({\n level: 'error',\n message:\n 'Document validation is incomplete. Check the schema and any reported validation errors, then rerun this command.',\n path: [],\n })\n }\n } catch (err) {\n const errorMessage = err instanceof Error ? err.message : 'Unknown error'\n\n const message = `Exception occurred while validating value: ${errorMessage}`\n\n markers = [\n {\n level: 'error',\n message,\n path: [],\n },\n ]\n }\n\n validatedCount++\n\n const intentUrl =\n studioHost &&\n `${studioHost}${path.resolve(\n workspace.basePath,\n `/intent/edit/id=${encodeURIComponent(document._id)};type=${encodeURIComponent(\n document._type,\n )}`,\n )}`\n\n report.stream.validation.emit({\n documentId: document._id,\n documentType: document._type,\n ...(intentUrl && {intentUrl}),\n level: getLevel(markers),\n markers,\n revision: document._rev,\n validatedCount,\n })\n }\n\n await pMap(getDocuments(), validate, {concurrency: MAX_VALIDATION_CONCURRENCY})\n\n report.stream.validation.end()\n } finally {\n await cleanupDownloadedDocuments?.()\n }\n}\n"],"names":["fs","os","path","readline","Readable","workerData","_workerData","isMainThread","parentPort","getStudioWorkspaces","getWorkspace","createClient","createClientConcurrencyLimiter","validateDocument","withReleaseReferences","WorkerChannelReporter","pMap","checkDocumentAvailability","exportDocuments","getDocumentCount","extractDocumentsFromNdjsonOrTarball","DOCUMENT_VALIDATION_TIMEOUT","getReferenceIds","isValidId","levelValues","MAX_VALIDATION_CONCURRENCY","REFERENCE_INTEGRITY_BATCH_SIZE","shouldIncludeDocument","clientConfig","dataset","level","maxCustomValidationConcurrency","maxFetchConcurrency","ndjsonFilePath","projectId","studioHost","workDir","workspace","workspaceName","Error","report","from","readerToGenerator","reader","done","value","read","main","process","exit","loadWorkspace","workspaces","resolvedDataset","resolvedProjectId","client","requestTagPrefix","config","apiVersion","event","loadedWorkspace","basePath","name","downloadFromExport","datasetName","projId","documentCount","loadedDocumentCount","response","body","getReader","downloadedCount","referencedIds","Set","documentIds","Map","lines","createInterface","input","slugDate","Date","toISOString","replaceAll","toLowerCase","tempOutputFile","join","tmpdir","outputStream","createWriteStream","line","document","JSON","parse","set","_id","_system","delete","referenceId","add","write","stream","exportProgress","emit","Promise","resolve","reject","close","err","end","exportFinished","totalDocumentsToValidate","size","getDocuments","createReadStream","cleanup","promises","rm","downloadFromFile","filePath","undefined","checkReferenceExistence","existingIds","_referencedIds","idsToCheck","filter","id","has","toSorted","i","length","batch","slice","omitted","omittedIds","item","reason","loadedReferenceIntegrity","cleanupDownloadedDocuments","getLevel","markers","foundWarning","marker","validationClient","validatedCount","validate","result","getDocumentExists","isUnpublished","get","i18n","schema","signal","AbortSignal","timeout","validateReferenceTypes","markerValue","flagLevelValue","info","complete","some","push","message","errorMessage","intentUrl","encodeURIComponent","_type","validation","documentId","documentType","revision","_rev","concurrency"],"mappings":"AAAA,OAAOA,QAAQ,UAAS;AACxB,OAAOC,QAAQ,UAAS;AACxB,OAAOC,UAAU,YAAW;AAC5B,OAAOC,cAAc,gBAAe;AACpC,SAAQC,QAAQ,QAAO,cAAa;AACpC,SAAQC,cAAcC,WAAW,EAAEC,YAAY,EAAEC,UAAU,QAAO,sBAAqB;AAEvF,SAAQC,mBAAmB,EAAEC,YAAY,QAAO,mBAAkB;AAClE,SAAQC,YAAY,QAA4B,iBAAgB;AAEhE,SAAQC,8BAA8B,QAAO,sBAAqB;AAClE,SAAQC,gBAAgB,EAAEC,qBAAqB,QAAO,qBAAoB;AAC1E,SAAQC,qBAAqB,QAAO,0BAAyB;AAC7D,OAAOC,UAAU,QAAO;AAExB,SAEEC,yBAAyB,EACzBC,eAAe,EACfC,gBAAgB,QACX,8BAA6B;AACpC,SAAQC,mCAAmC,QAAO,oDAAmD;AACrG,SACEC,2BAA2B,EAC3BC,eAAe,EACfC,SAAS,EACTC,WAAW,EACXC,0BAA0B,EAC1BC,8BAA8B,EAC9BC,qBAAqB,QAChB,kDAAiD;AAGxD,MAAM,EACJC,YAAY,EACZC,OAAO,EACPC,KAAK,EACLC,8BAA8B,EAC9BC,mBAAmB,EACnBC,cAAc,EACdC,SAAS,EACTC,UAAU,EACVC,OAAO,EACPC,WAAWC,aAAa,EACz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oBAACA;gBAAS,CAAC;gBAC5BpI,OAAO2G,SAASC;gBAChBA;gBACA8B,UAAU/E,SAASgF,IAAI;gBACvB3B;YACF;QACF;QAEA,MAAM9H,KAAK+F,gBAAgBgC,UAAU;YAAC2B,aAAajJ;QAA0B;QAE7Ee,OAAO2D,MAAM,CAACkE,UAAU,CAAC1D,GAAG;IAC9B,SAAU;QACR,MAAM6B;IACR;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/* eslint-disable unicorn/consistent-function-scoping */ import { generateHelpUrl } from '@sanity/generate-help-url';
|
|
1
|
+
/* eslint-disable unicorn-js/consistent-function-scoping */ import { generateHelpUrl } from '@sanity/generate-help-url';
|
|
2
2
|
import { Schema } from '@sanity/schema';
|
|
3
3
|
import { isDeprecationConfiguration } from '@sanity/types';
|
|
4
4
|
import startCase from 'lodash-es/startCase.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/graphql/extractFromSanitySchema.ts"],"sourcesContent":["/* eslint-disable unicorn/consistent-function-scoping */\nimport {generateHelpUrl} from '@sanity/generate-help-url'\nimport {Schema} from '@sanity/schema'\nimport {\n type ArraySchemaType,\n type Schema as CompiledSchema,\n type CrossDatasetReferenceSchemaType,\n type IntrinsicTypeName,\n isDeprecationConfiguration,\n type ObjectField,\n type ObjectFieldType,\n type ObjectSchemaType,\n type ReferenceSchemaType,\n type SchemaType,\n} from '@sanity/types'\nimport startCase from 'lodash-es/startCase.js'\nimport uniqBy from 'lodash-es/uniqBy.js'\nimport {oneline} from 'oneline'\n\nimport {SCHEMA_LIFT_ANONYMOUS_OBJECT_TYPE} from './helpUrls.js'\nimport {SchemaError} from './SchemaError.js'\nimport {\n type ApiSpecification,\n type ConvertedFieldDefinition,\n type ConvertedInterface,\n type ConvertedType,\n type ConvertedUnion,\n type Deprecation,\n} from './types.js'\n\nconst skipTypes = new Set(['document', 'reference'])\nconst allowedJsonTypes = new Set(['array', 'object'])\nconst disallowedCustomizedMembers = new Set(['array', 'block', 'file', 'image', 'object'])\nconst disabledBlockFields = new Set(['markDefs'])\nconst scalars = new Set(['boolean', 'number', 'string'])\n\nfunction getBaseType(baseSchema: CompiledSchema, typeName: IntrinsicTypeName): SchemaType {\n if (typeName === 'crossDatasetReference') {\n return Schema.compile({\n parent: baseSchema,\n types: [\n {\n name: `__placeholder__`,\n // Just needs _something_ to refer to, doesn't matter what\n to: [{type: 'sanity.imageAsset'}],\n type: 'crossDatasetReference',\n },\n ],\n }).get('__placeholder__')\n }\n if (typeName === 'globalDocumentReference') {\n return Schema.compile({\n parent: baseSchema,\n types: [\n {\n name: `__placeholder__`,\n // Just needs _something_ to refer to, doesn't matter what\n to: [{type: 'sanity.imageAsset'}],\n type: 'globalDocumentReference',\n },\n ],\n }).get('__placeholder__')\n }\n\n return Schema.compile({\n parent: baseSchema,\n types: [{name: `__placeholder__`, options: {hotspot: true}, type: typeName}],\n }).get('__placeholder__')\n}\n\nfunction getTypeName(str: string): string {\n const name = startCase(str).replaceAll(/\\s+/g, '')\n return name === 'Number' ? 'Float' : name\n}\n\nfunction isBaseType(type: SchemaType): boolean {\n return (\n type.name !== type.jsonType &&\n allowedJsonTypes.has(type.jsonType) &&\n !skipTypes.has(type.name) &&\n !isReference(type)\n )\n}\n\nfunction isBlockType(typeDef: ObjectField | SchemaType): boolean {\n if (typeDef.name === 'block') {\n return true\n }\n\n if (typeDef.type) {\n return isBlockType(typeDef.type)\n }\n\n return false\n}\n\nfunction hasBlockParent(typeDef: SchemaType): boolean {\n if (typeDef.type && typeDef.type.name === 'block' && !typeDef.type.type) {\n return true\n }\n\n return Boolean(typeDef.type && hasBlockParent(typeDef.type))\n}\n\nfunction isArrayOfBlocks(typeDef: ObjectField | SchemaType): boolean {\n const type = typeDef.type || typeDef\n if (!('jsonType' in type) || type.jsonType !== 'array') {\n return false\n }\n\n return (type.of || []).some((item) => hasBlockParent(item))\n}\n\nfunction isType(typeDef: ObjectField | ObjectFieldType | SchemaType, typeName: string): boolean {\n let type: ObjectField | ObjectFieldType | SchemaType | undefined = typeDef\n while (type) {\n if (type.name === typeName || (type.type && type.type.name === typeName)) {\n return true\n }\n\n type = type.type\n }\n return false\n}\n\nfunction isReference(\n typeDef: ObjectField | ObjectFieldType | SchemaType,\n): typeDef is ReferenceSchemaType {\n return isType(typeDef, 'reference')\n}\n\nfunction isCrossDatasetReference(\n typeDef: CrossDatasetReferenceSchemaType | ObjectField | ObjectFieldType | SchemaType,\n) {\n return isType(typeDef, 'crossDatasetReference')\n}\n\nfunction getCrossDatasetReferenceMetadata(\n typeDef: CrossDatasetReferenceSchemaType | ObjectField | ObjectFieldType | SchemaType,\n) {\n if (!isCrossDatasetReference(typeDef)) return\n\n function getTypeNames(\n type: CrossDatasetReferenceSchemaType | ObjectField | ObjectFieldType | SchemaType | undefined,\n ) {\n if (!type) return\n if (!('to' in type)) return getTypeNames(type.type)\n return type.to.map((t) => t.type).filter((t): t is string => typeof t === 'string')\n }\n\n function getDataset(\n type: CrossDatasetReferenceSchemaType | ObjectField | ObjectFieldType | SchemaType | undefined,\n ) {\n if (!type) return\n if ('dataset' in type && typeof type.dataset === 'string') return type.dataset\n if (type.type) return getDataset(type.type)\n }\n\n const typeNames = getTypeNames(typeDef)\n if (!typeNames) return\n\n const dataset = getDataset(typeDef)\n if (typeof dataset !== 'string') return\n\n return {dataset, typeNames}\n}\n\nexport function extractFromSanitySchema(\n sanitySchema: CompiledSchema,\n extractOptions: {nonNullDocumentFields?: boolean; withUnionCache?: boolean} = {},\n): ApiSpecification {\n const {nonNullDocumentFields, withUnionCache} = extractOptions\n const unionRecursionGuards = new Set<string>()\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const unionDefinitionCache = new Map<string, any>()\n const hasErrors =\n sanitySchema._validation &&\n sanitySchema._validation.some((group) =>\n group.problems.some((problem) => problem.severity === 'error'),\n )\n\n if (hasErrors && Array.isArray(sanitySchema._validation)) {\n throw new SchemaError(sanitySchema._validation)\n }\n\n const sanityTypes = sanitySchema._original?.types || []\n const typeNames = sanitySchema.getTypeNames()\n const unionTypes: ConvertedUnion[] = []\n const types: ConvertedType[] = []\n\n for (const typeName of typeNames) {\n const schemaType = sanitySchema.get(typeName)\n if (schemaType === undefined) {\n continue\n }\n if (!isBaseType(schemaType)) {\n continue\n }\n\n const convertedType = convertType(schemaType)\n types.push(convertedType)\n }\n\n const withUnions = [...types, ...unionTypes]\n return {interfaces: [getDocumentInterfaceDefinition()], types: withUnions}\n\n function isTopLevelType(typeName: string): boolean {\n return typeNames.includes(typeName)\n }\n\n function mapFieldType(field: ObjectField | ObjectFieldType | SchemaType): string {\n if (!field.type) {\n throw new Error('Field has no type!')\n }\n\n const jsonType = 'jsonType' in field ? field.jsonType : ''\n const isScalar = scalars.has(jsonType)\n if (isScalar && jsonType === 'number') {\n return hasValidationFlag(field, 'integer') ? 'Int' : 'Float'\n } else if (isScalar) {\n return getTypeName(jsonType)\n }\n\n const type = field.type.type || field.type\n\n // In the case of nested scalars, recurse (markdown -> longText -> text -> string)\n if (type.type) {\n return mapFieldType(type)\n }\n\n switch (type.name) {\n case 'number': {\n return hasValidationFlag(field, 'integer') ? 'Int' : 'Float'\n }\n default: {\n return getTypeName(type.name)\n }\n }\n }\n\n function isArrayType(type: ObjectField | SchemaType): type is ArraySchemaType {\n return Boolean(\n ('jsonType' in type && type.jsonType === 'array') ||\n (type.type && type.type.jsonType === 'array'),\n )\n }\n\n function _convertType(\n type: ObjectField | SchemaType,\n parent: string,\n options: {isField?: boolean},\n ): ConvertedType {\n let name: string | undefined\n if (type.type) {\n name = type.type.name\n } else if ('jsonType' in type) {\n name = type.jsonType\n }\n\n if (isReference(type)) {\n return getReferenceDefinition(type)\n }\n\n if (isArrayType(type)) {\n return getArrayDefinition(type, parent, options)\n }\n\n if (name === 'document') {\n return getDocumentDefinition(type as ObjectSchemaType)\n }\n\n if (name === 'block' || name === 'object') {\n return getObjectDefinition(type, parent)\n }\n\n if (hasFields(type)) {\n return getObjectDefinition(type, parent)\n }\n\n return {\n description: getDescription(type),\n type: mapFieldType(type),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any\n }\n\n function convertType(\n type: ObjectField | SchemaType,\n parent?: string,\n props: Partial<Deprecation> & {fieldName?: string} = {},\n ): ConvertedType {\n const mapped = _convertType(type, parent || '', {isField: Boolean(props.fieldName)})\n const gqlName = props.fieldName || mapped.name\n const originalName = type.name\n const original = gqlName === originalName ? {} : {originalName: originalName}\n const crossDatasetReferenceMetadata = getCrossDatasetReferenceMetadata(type)\n\n return {\n ...getDeprecation(type.type),\n ...props,\n ...mapped,\n ...original,\n ...(crossDatasetReferenceMetadata && {crossDatasetReferenceMetadata}),\n }\n }\n\n function isField(def: ObjectField | SchemaType): def is ObjectField {\n return !('jsonType' in def) || !def.jsonType\n }\n\n function getObjectDefinition(def: ObjectField | SchemaType, parent?: string): ConvertedType {\n const isInline = isField(def)\n const isDocument = def.type ? def.type.name === 'document' : false\n const actualType = isInline ? def.type : def\n\n if (typeNeedsHoisting(actualType)) {\n throw createLiftTypeError(def.name, parent || '', actualType.name)\n }\n\n if (isInline && parent && def.type.name === 'object') {\n throw createLiftTypeError(def.name, parent)\n }\n\n if (parent && def.type && isTopLevelType(def.type.name)) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return {type: getTypeName(def.type.name)} as any\n }\n\n const name = `${parent || ''}${getTypeName(def.name)}`\n const fields = collectFields(def)\n const firstUnprefixed = Math.max(\n 0,\n fields.findIndex((field) => field.name[0] !== '_'),\n )\n\n const keyField = createStringField('_key')\n\n fields.splice(firstUnprefixed, 0, keyField)\n\n if (!isDocument) {\n fields.splice(firstUnprefixed + 1, 0, createStringField('_type'))\n }\n\n const objectIsBlock = isBlockType(def)\n const objectFields = objectIsBlock\n ? fields.filter((field) => !disabledBlockFields.has(field.name))\n : fields\n\n return {\n _internal: {\n ...getDeprecation(def),\n },\n description: getDescription(def),\n fields: objectFields.map((field) =>\n isArrayOfBlocks(field)\n ? buildRawField(field, name)\n : (convertType(field, name, {\n fieldName: field.name,\n ...getDeprecation(def),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }) as any),\n ),\n kind: 'Type',\n name,\n type: 'Object',\n }\n }\n\n function buildRawField(field: ObjectField, parentName: string) {\n return {\n ...convertType(field, parentName, {fieldName: `${field.name}Raw`}),\n isRawAlias: true,\n type: 'JSON',\n }\n }\n\n function createStringField(name: string): ObjectField {\n return {\n name,\n type: {\n jsonType: 'string',\n name: 'string',\n type: {jsonType: 'string', name: 'string', type: undefined},\n },\n }\n }\n\n function collectFields(def: ObjectField | SchemaType) {\n const fields = gatherAllFields(def)\n if (fields.length > 0) {\n return fields\n }\n\n const extended = getBaseType(sanitySchema, def.name as IntrinsicTypeName)\n return gatherAllFields(extended)\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n function getReferenceDefinition(def: SchemaType): any {\n const base = {description: getDescription(def), isReference: true}\n const candidates = arrayify(gatherAllReferenceCandidates(def))\n if (candidates.length === 0) {\n throw new Error('No candidates for reference')\n }\n\n if (candidates.length === 1) {\n return {type: getTypeName(candidates[0].type.name), ...base}\n }\n\n const allTypeNames = candidates.map((c) => getTypeName(c.type.name))\n const targetTypes = [...new Set(allTypeNames)].toSorted()\n const name = targetTypes.join('Or')\n\n // Register the union type if we haven't seen it before\n if (!unionTypes.some((item) => item.name === name)) {\n unionTypes.push({\n kind: 'Union',\n name,\n types: targetTypes,\n })\n }\n\n return {\n type: name,\n ...base,\n }\n }\n\n function getArrayDefinition(\n def: ArraySchemaType,\n parent: string,\n options: {isField?: boolean} = {},\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): any {\n const base = {description: getDescription(def), kind: 'List'}\n const name = !options.isField && def.name ? {name: getTypeName(def.name)} : {}\n const candidates = def.type?.type && 'of' in def.type ? arrayify(def.type.of) : def.of\n\n return candidates.length === 1\n ? {\n children: getArrayChildDefinition(candidates[0], def),\n ...base,\n ...name,\n }\n : {\n children: getUnionDefinition(candidates, def, {grandParent: parent}),\n ...base,\n ...name,\n }\n }\n\n function getArrayChildDefinition(child: SchemaType, arrayDef: SchemaType) {\n if (typeNeedsHoisting(child)) {\n // Seems to be inline? Should be hoisted?\n throw createLiftTypeError(child.name, arrayDef.name)\n }\n\n if (isReference(child)) {\n return getReferenceDefinition(child)\n }\n\n // In the case of nested scalars, recurse (markdown -> longText -> text -> string)\n if (scalars.has(child.jsonType) && !scalars.has(child.name)) {\n return {type: mapFieldType(child)}\n }\n\n return {type: getTypeName(child.name)}\n }\n\n function typeNeedsHoisting(type: SchemaType & {isCustomized?: boolean}): boolean {\n if (type.name === 'object') {\n return true\n }\n\n if (type.jsonType === 'object' && !isTopLevelType(type.name)) {\n return true\n }\n\n if (type.isCustomized && !isTopLevelType(type.name)) {\n return true\n }\n\n if (type.isCustomized && disallowedCustomizedMembers.has(type.name)) {\n return true\n }\n\n return false\n }\n\n function getUnionDefinition(\n candidates: ObjectSchemaType[],\n parent: SchemaType,\n options: {grandParent?: string} = {},\n ) {\n if (candidates.length < 2) {\n throw new Error('Not enough candidates for a union type')\n }\n\n // #1482: When creating union definition do not get caught in recursion loop\n // for types that reference themselves\n const guardPathName = `${typeof parent === 'object' ? parent.name : parent}`\n if (unionRecursionGuards.has(guardPathName)) {\n return {}\n }\n\n const unionCacheKey = `${options.grandParent}-${guardPathName}-${candidates\n .map((c) => c.type?.name)\n .join('-')}`\n if (withUnionCache && unionDefinitionCache.has(unionCacheKey)) {\n return unionDefinitionCache.get(unionCacheKey)\n }\n\n try {\n unionRecursionGuards.add(guardPathName)\n\n for (const [i, def] of candidates.entries()) {\n if (typeNeedsHoisting(def)) {\n throw createLiftTypeArrayError(\n i,\n parent.name,\n def.type ? def.type.name : def.name,\n options.grandParent,\n )\n }\n }\n\n const converted = candidates.map((def) => convertType(def))\n\n const getName = (def: {type: string | {name: string}}): string =>\n typeof def.type === 'string' ? def.type : def.type.name\n\n // We might end up with union types being returned - these needs to be flattened\n // so that an ImageOr(PersonOrPet) becomes ImageOrPersonOrPet\n // eslint-disable-next-line unicorn/no-array-reduce\n const flattened = converted.reduce(\n (acc, candidate) => {\n const union = unionTypes.find((item) => item.name === candidate.type)\n return union\n ? // eslint-disable-next-line unicorn/prefer-spread\n acc.concat(union.types.map((type) => ({isReference: candidate.isReference, type})))\n : [...acc, candidate]\n },\n [] as {isReference?: boolean; name?: string; type: string | {name: string}}[],\n )\n\n let allCandidatesAreDocuments = true\n const refs: (string | {name: string})[] = []\n const inlineObjs: string[] = []\n const allTypeNames: string[] = []\n for (const def of flattened) {\n if (def.isReference) {\n refs.push(def.type)\n }\n if (!isReference) {\n inlineObjs.push(def.name || '')\n }\n\n const typeName = typeof def.type === 'string' ? def.type : def.type.name\n\n // Here we remove duplicates, as they might appear twice due to in-line usage of types as well as references\n if (def.name || def.type) {\n allTypeNames.push(def.isReference ? typeName : def.name || '')\n }\n\n const typeDef = sanityTypes.find((type) => type.name === getName(def))\n if (!typeDef || typeDef.type !== 'document') {\n allCandidatesAreDocuments = false\n }\n }\n\n const interfaces = allCandidatesAreDocuments ? ['Document'] : undefined\n const possibleTypes = [...new Set(allTypeNames)].toSorted()\n\n if (possibleTypes.length < 2) {\n throw new Error(`Not enough types for a union type. Parent: ${parent.name}`)\n }\n\n const name = possibleTypes.join('Or')\n\n if (!unionTypes.some((item) => item.name === name)) {\n unionTypes.push({\n interfaces,\n kind: 'Union',\n name,\n types: possibleTypes,\n })\n }\n\n const references = refs.length > 0 ? refs : undefined\n const inlineObjects = inlineObjs.length > 0 ? inlineObjs : undefined\n\n const unionDefinition = isReference(parent)\n ? {references, type: name}\n : {inlineObjects, references, type: name}\n\n unionDefinitionCache.set(unionCacheKey, unionDefinition)\n return unionDefinition\n } finally {\n unionRecursionGuards.delete(guardPathName)\n }\n }\n\n function getDocumentDefinition(def: ObjectSchemaType) {\n const objectDef = getObjectDefinition(def)\n const fields = [...getDocumentInterfaceFields(def), ...objectDef.fields]\n\n return {...objectDef, fields, interfaces: ['Document']}\n }\n\n function getDocumentInterfaceDefinition(): ConvertedInterface {\n return {\n description: 'A Sanity document',\n fields: getDocumentInterfaceFields(),\n kind: 'Interface',\n name: 'Document',\n }\n }\n\n function getDocumentInterfaceFields(type?: ObjectSchemaType): ConvertedFieldDefinition[] {\n const isNullable = typeof nonNullDocumentFields === 'boolean' ? !nonNullDocumentFields : true\n return [\n {\n description: 'Document ID',\n fieldName: '_id',\n isNullable,\n type: 'ID',\n ...getDeprecation(type),\n },\n {\n description: 'Document type',\n fieldName: '_type',\n isNullable,\n type: 'String',\n ...getDeprecation(type),\n },\n {\n description: 'Date the document was created',\n fieldName: '_createdAt',\n isNullable,\n type: 'Datetime',\n ...getDeprecation(type),\n },\n {\n description: 'Date the document was last modified',\n fieldName: '_updatedAt',\n isNullable,\n type: 'Datetime',\n ...getDeprecation(type),\n },\n {\n description: 'Current document revision',\n fieldName: '_rev',\n isNullable,\n type: 'String',\n ...getDeprecation(type),\n },\n ]\n }\n\n function arrayify(thing: unknown) {\n if (Array.isArray(thing)) {\n return thing\n }\n\n return thing === null || thing === undefined ? [] : [thing]\n }\n\n function hasValidationFlag(\n field: ObjectField | ObjectFieldType | SchemaType,\n flag: string,\n ): boolean {\n return (\n 'validation' in field &&\n Array.isArray(field.validation) &&\n field.validation.some(\n (rule) => rule && '_rules' in rule && rule._rules.some((item) => item.flag === flag),\n )\n )\n }\n\n function getDescription(type: ObjectField | SchemaType): string | undefined {\n const description = type.type && type.type.description\n return typeof description === 'string' ? description : undefined\n }\n\n function gatherAllReferenceCandidates(type: SchemaType): ObjectSchemaType[] {\n const allFields = gatherReferenceCandidates(type)\n return uniqBy(allFields, 'name')\n }\n\n function gatherReferenceCandidates(type: SchemaType): ObjectSchemaType[] {\n const refTo = 'to' in type ? type.to : []\n return 'type' in type && type.type ? [...gatherReferenceCandidates(type.type), ...refTo] : refTo\n }\n\n function gatherAllFields(type: ObjectField | SchemaType) {\n const allFields = gatherFields(type)\n return uniqBy(allFields, 'name')\n }\n\n function gatherFields(type: ObjectField | SchemaType): ObjectField[] {\n if ('fields' in type) {\n return type.type ? [...gatherFields(type.type), ...type.fields] : type.fields\n }\n\n return []\n }\n\n function hasFieldsLikeShape(type: unknown): type is {fields: unknown} {\n return typeof type === 'object' && type !== null && 'fields' in type\n }\n\n function hasArrayOfFields(type: unknown): type is {fields: ObjectField[]} {\n return hasFieldsLikeShape(type) && Array.isArray(type.fields)\n }\n\n function hasFields(type: ObjectField | SchemaType): boolean {\n if (hasArrayOfFields(type)) {\n return gatherAllFields(type).length > 0\n }\n\n return 'type' in type && type.type ? hasFields(type.type) : false\n }\n}\n\nfunction createLiftTypeArrayError(\n index: number,\n parent: string,\n inlineType = 'object',\n grandParent = '',\n) {\n const helpUrl = generateHelpUrl(SCHEMA_LIFT_ANONYMOUS_OBJECT_TYPE)\n const context = [grandParent, parent].filter(Boolean).join('/')\n return new HelpfulError(\n oneline`\n Encountered anonymous inline ${inlineType} at index ${index} for type/field ${context}.\n To use this type with GraphQL you will need to create a top-level schema type for it.\n See ${helpUrl}`,\n helpUrl,\n )\n}\n\nfunction createLiftTypeError(typeName: string, parent: string, inlineType = 'object') {\n const helpUrl = generateHelpUrl(SCHEMA_LIFT_ANONYMOUS_OBJECT_TYPE)\n return new HelpfulError(\n oneline`\n Encountered anonymous inline ${inlineType} \"${typeName}\" for field/type \"${parent}\".\n To use this field with GraphQL you will need to create a top-level schema type for it.\n See ${helpUrl}`,\n helpUrl,\n )\n}\n\nclass HelpfulError extends Error {\n helpUrl?: string\n\n constructor(message: string, helpUrl?: string) {\n super(message)\n this.name = 'HelpfulError'\n this.helpUrl = helpUrl\n }\n}\n\nfunction getDeprecation(type?: ObjectField | ObjectFieldType | SchemaType): Partial<Deprecation> {\n return isDeprecationConfiguration(type)\n ? {\n deprecationReason: type.deprecated.reason,\n }\n : {}\n}\n"],"names":["generateHelpUrl","Schema","isDeprecationConfiguration","startCase","uniqBy","oneline","SCHEMA_LIFT_ANONYMOUS_OBJECT_TYPE","SchemaError","skipTypes","Set","allowedJsonTypes","disallowedCustomizedMembers","disabledBlockFields","scalars","getBaseType","baseSchema","typeName","compile","parent","types","name","to","type","get","options","hotspot","getTypeName","str","replaceAll","isBaseType","jsonType","has","isReference","isBlockType","typeDef","hasBlockParent","Boolean","isArrayOfBlocks","of","some","item","isType","isCrossDatasetReference","getCrossDatasetReferenceMetadata","getTypeNames","map","t","filter","getDataset","dataset","typeNames","extractFromSanitySchema","sanitySchema","extractOptions","nonNullDocumentFields","withUnionCache","unionRecursionGuards","unionDefinitionCache","Map","hasErrors","_validation","group","problems","problem","severity","Array","isArray","sanityTypes","_original","unionTypes","schemaType","undefined","convertedType","convertType","push","withUnions","interfaces","getDocumentInterfaceDefinition","isTopLevelType","includes","mapFieldType","field","Error","isScalar","hasValidationFlag","isArrayType","_convertType","getReferenceDefinition","getArrayDefinition","getDocumentDefinition","getObjectDefinition","hasFields","description","getDescription","props","mapped","isField","fieldName","gqlName","originalName","original","crossDatasetReferenceMetadata","getDeprecation","def","isInline","isDocument","actualType","typeNeedsHoisting","createLiftTypeError","fields","collectFields","firstUnprefixed","Math","max","findIndex","keyField","createStringField","splice","objectIsBlock","objectFields","_internal","buildRawField","kind","parentName","isRawAlias","gatherAllFields","length","extended","base","candidates","arrayify","gatherAllReferenceCandidates","allTypeNames","c","targetTypes","toSorted","join","children","getArrayChildDefinition","getUnionDefinition","grandParent","child","arrayDef","isCustomized","guardPathName","unionCacheKey","add","i","entries","createLiftTypeArrayError","converted","getName","flattened","reduce","acc","candidate","union","find","concat","allCandidatesAreDocuments","refs","inlineObjs","possibleTypes","references","inlineObjects","unionDefinition","set","delete","objectDef","getDocumentInterfaceFields","isNullable","thing","flag","validation","rule","_rules","allFields","gatherReferenceCandidates","refTo","gatherFields","hasFieldsLikeShape","hasArrayOfFields","index","inlineType","helpUrl","context","HelpfulError","message","deprecationReason","deprecated","reason"],"mappings":"AAAA,sDAAsD,GACtD,SAAQA,eAAe,QAAO,4BAA2B;AACzD,SAAQC,MAAM,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E,KAAKA,IAAI,IAAI;IAC9D;AACF;AAEA,SAAS+H,yBACPiC,KAAa,EACbpK,MAAc,EACdqK,aAAa,QAAQ,EACrB3C,cAAc,EAAE;IAEhB,MAAM4C,UAAUxL,gBAAgBM;IAChC,MAAMmL,UAAU;QAAC7C;QAAa1H;KAAO,CAAC6B,MAAM,CAACX,SAASoG,IAAI,CAAC;IAC3D,OAAO,IAAIkD,aACTrL,OAAO,CAAC;iCACqB,EAAEkL,WAAW,UAAU,EAAED,MAAM,gBAAgB,EAAEG,QAAQ;;QAElF,EAAED,QAAQ,CAAC,EACfA;AAEJ;AAEA,SAAS5E,oBAAoB5F,QAAgB,EAAEE,MAAc,EAAEqK,aAAa,QAAQ;IAClF,MAAMC,UAAUxL,gBAAgBM;IAChC,OAAO,IAAIoL,aACTrL,OAAO,CAAC;iCACqB,EAAEkL,WAAW,EAAE,EAAEvK,SAAS,kBAAkB,EAAEE,OAAO;;QAE9E,EAAEsK,QAAQ,CAAC,EACfA;AAEJ;AAEA,MAAME,qBAAqBxG;IACzBsG,QAAgB;IAEhB,YAAYG,OAAe,EAAEH,OAAgB,CAAE;QAC7C,KAAK,CAACG;QACN,IAAI,CAACvK,IAAI,GAAG;QACZ,IAAI,CAACoK,OAAO,GAAGA;IACjB;AACF;AAEA,SAASlF,eAAehF,IAAiD;IACvE,OAAOpB,2BAA2BoB,QAC9B;QACEsK,mBAAmBtK,KAAKuK,UAAU,CAACC,MAAM;IAC3C,IACA,CAAC;AACP"}
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/graphql/extractFromSanitySchema.ts"],"sourcesContent":["/* eslint-disable unicorn-js/consistent-function-scoping */\nimport {generateHelpUrl} from '@sanity/generate-help-url'\nimport {Schema} from '@sanity/schema'\nimport {\n type ArraySchemaType,\n type Schema as CompiledSchema,\n type CrossDatasetReferenceSchemaType,\n type IntrinsicTypeName,\n isDeprecationConfiguration,\n type ObjectField,\n type ObjectFieldType,\n type ObjectSchemaType,\n type ReferenceSchemaType,\n type SchemaType,\n} from '@sanity/types'\nimport startCase from 'lodash-es/startCase.js'\nimport uniqBy from 'lodash-es/uniqBy.js'\nimport {oneline} from 'oneline'\n\nimport {SCHEMA_LIFT_ANONYMOUS_OBJECT_TYPE} from './helpUrls.js'\nimport {SchemaError} from './SchemaError.js'\nimport {\n type ApiSpecification,\n type ConvertedFieldDefinition,\n type ConvertedInterface,\n type ConvertedType,\n type ConvertedUnion,\n type Deprecation,\n} from './types.js'\n\nconst skipTypes = new Set(['document', 'reference'])\nconst allowedJsonTypes = new Set(['array', 'object'])\nconst disallowedCustomizedMembers = new Set(['array', 'block', 'file', 'image', 'object'])\nconst disabledBlockFields = new Set(['markDefs'])\nconst scalars = new Set(['boolean', 'number', 'string'])\n\nfunction getBaseType(baseSchema: CompiledSchema, typeName: IntrinsicTypeName): SchemaType {\n if (typeName === 'crossDatasetReference') {\n return Schema.compile({\n parent: baseSchema,\n types: [\n {\n name: `__placeholder__`,\n // Just needs _something_ to refer to, doesn't matter what\n to: [{type: 'sanity.imageAsset'}],\n type: 'crossDatasetReference',\n },\n ],\n }).get('__placeholder__')\n }\n if (typeName === 'globalDocumentReference') {\n return Schema.compile({\n parent: baseSchema,\n types: [\n {\n name: `__placeholder__`,\n // Just needs _something_ to refer to, doesn't matter what\n to: [{type: 'sanity.imageAsset'}],\n type: 'globalDocumentReference',\n },\n ],\n }).get('__placeholder__')\n }\n\n return Schema.compile({\n parent: baseSchema,\n types: [{name: `__placeholder__`, options: {hotspot: true}, type: typeName}],\n }).get('__placeholder__')\n}\n\nfunction getTypeName(str: string): string {\n const name = startCase(str).replaceAll(/\\s+/g, '')\n return name === 'Number' ? 'Float' : name\n}\n\nfunction isBaseType(type: SchemaType): boolean {\n return (\n type.name !== type.jsonType &&\n allowedJsonTypes.has(type.jsonType) &&\n !skipTypes.has(type.name) &&\n !isReference(type)\n )\n}\n\nfunction isBlockType(typeDef: ObjectField | SchemaType): boolean {\n if (typeDef.name === 'block') {\n return true\n }\n\n if (typeDef.type) {\n return isBlockType(typeDef.type)\n }\n\n return false\n}\n\nfunction hasBlockParent(typeDef: SchemaType): boolean {\n if (typeDef.type && typeDef.type.name === 'block' && !typeDef.type.type) {\n return true\n }\n\n return Boolean(typeDef.type && hasBlockParent(typeDef.type))\n}\n\nfunction isArrayOfBlocks(typeDef: ObjectField | SchemaType): boolean {\n const type = typeDef.type || typeDef\n if (!('jsonType' in type) || type.jsonType !== 'array') {\n return false\n }\n\n return (type.of || []).some((item) => hasBlockParent(item))\n}\n\nfunction isType(typeDef: ObjectField | ObjectFieldType | SchemaType, typeName: string): boolean {\n let type: ObjectField | ObjectFieldType | SchemaType | undefined = typeDef\n while (type) {\n if (type.name === typeName || (type.type && type.type.name === typeName)) {\n return true\n }\n\n type = type.type\n }\n return false\n}\n\nfunction isReference(\n typeDef: ObjectField | ObjectFieldType | SchemaType,\n): typeDef is ReferenceSchemaType {\n return isType(typeDef, 'reference')\n}\n\nfunction isCrossDatasetReference(\n typeDef: CrossDatasetReferenceSchemaType | ObjectField | ObjectFieldType | SchemaType,\n) {\n return isType(typeDef, 'crossDatasetReference')\n}\n\nfunction getCrossDatasetReferenceMetadata(\n typeDef: CrossDatasetReferenceSchemaType | ObjectField | ObjectFieldType | SchemaType,\n) {\n if (!isCrossDatasetReference(typeDef)) return\n\n function getTypeNames(\n type: CrossDatasetReferenceSchemaType | ObjectField | ObjectFieldType | SchemaType | undefined,\n ) {\n if (!type) return\n if (!('to' in type)) return getTypeNames(type.type)\n return type.to.map((t) => t.type).filter((t): t is string => typeof t === 'string')\n }\n\n function getDataset(\n type: CrossDatasetReferenceSchemaType | ObjectField | ObjectFieldType | SchemaType | undefined,\n ) {\n if (!type) return\n if ('dataset' in type && typeof type.dataset === 'string') return type.dataset\n if (type.type) return getDataset(type.type)\n }\n\n const typeNames = getTypeNames(typeDef)\n if (!typeNames) return\n\n const dataset = getDataset(typeDef)\n if (typeof dataset !== 'string') return\n\n return {dataset, typeNames}\n}\n\nexport function extractFromSanitySchema(\n sanitySchema: CompiledSchema,\n extractOptions: {nonNullDocumentFields?: boolean; withUnionCache?: boolean} = {},\n): ApiSpecification {\n const {nonNullDocumentFields, withUnionCache} = extractOptions\n const unionRecursionGuards = new Set<string>()\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const unionDefinitionCache = new Map<string, any>()\n const hasErrors =\n sanitySchema._validation &&\n sanitySchema._validation.some((group) =>\n group.problems.some((problem) => problem.severity === 'error'),\n )\n\n if (hasErrors && Array.isArray(sanitySchema._validation)) {\n throw new SchemaError(sanitySchema._validation)\n }\n\n const sanityTypes = sanitySchema._original?.types || []\n const typeNames = sanitySchema.getTypeNames()\n const unionTypes: ConvertedUnion[] = []\n const types: ConvertedType[] = []\n\n for (const typeName of typeNames) {\n const schemaType = sanitySchema.get(typeName)\n if (schemaType === undefined) {\n continue\n }\n if (!isBaseType(schemaType)) {\n continue\n }\n\n const convertedType = convertType(schemaType)\n types.push(convertedType)\n }\n\n const withUnions = [...types, ...unionTypes]\n return {interfaces: [getDocumentInterfaceDefinition()], types: withUnions}\n\n function isTopLevelType(typeName: string): boolean {\n return typeNames.includes(typeName)\n }\n\n function mapFieldType(field: ObjectField | ObjectFieldType | SchemaType): string {\n if (!field.type) {\n throw new Error('Field has no type!')\n }\n\n const jsonType = 'jsonType' in field ? field.jsonType : ''\n const isScalar = scalars.has(jsonType)\n if (isScalar && jsonType === 'number') {\n return hasValidationFlag(field, 'integer') ? 'Int' : 'Float'\n } else if (isScalar) {\n return getTypeName(jsonType)\n }\n\n const type = field.type.type || field.type\n\n // In the case of nested scalars, recurse (markdown -> longText -> text -> string)\n if (type.type) {\n return mapFieldType(type)\n }\n\n switch (type.name) {\n case 'number': {\n return hasValidationFlag(field, 'integer') ? 'Int' : 'Float'\n }\n default: {\n return getTypeName(type.name)\n }\n }\n }\n\n function isArrayType(type: ObjectField | SchemaType): type is ArraySchemaType {\n return Boolean(\n ('jsonType' in type && type.jsonType === 'array') ||\n (type.type && type.type.jsonType === 'array'),\n )\n }\n\n function _convertType(\n type: ObjectField | SchemaType,\n parent: string,\n options: {isField?: boolean},\n ): ConvertedType {\n let name: string | undefined\n if (type.type) {\n name = type.type.name\n } else if ('jsonType' in type) {\n name = type.jsonType\n }\n\n if (isReference(type)) {\n return getReferenceDefinition(type)\n }\n\n if (isArrayType(type)) {\n return getArrayDefinition(type, parent, options)\n }\n\n if (name === 'document') {\n return getDocumentDefinition(type as ObjectSchemaType)\n }\n\n if (name === 'block' || name === 'object') {\n return getObjectDefinition(type, parent)\n }\n\n if (hasFields(type)) {\n return getObjectDefinition(type, parent)\n }\n\n return {\n description: getDescription(type),\n type: mapFieldType(type),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any\n }\n\n function convertType(\n type: ObjectField | SchemaType,\n parent?: string,\n props: Partial<Deprecation> & {fieldName?: string} = {},\n ): ConvertedType {\n const mapped = _convertType(type, parent || '', {isField: Boolean(props.fieldName)})\n const gqlName = props.fieldName || mapped.name\n const originalName = type.name\n const original = gqlName === originalName ? {} : {originalName: originalName}\n const crossDatasetReferenceMetadata = getCrossDatasetReferenceMetadata(type)\n\n return {\n ...getDeprecation(type.type),\n ...props,\n ...mapped,\n ...original,\n ...(crossDatasetReferenceMetadata && {crossDatasetReferenceMetadata}),\n }\n }\n\n function isField(def: ObjectField | SchemaType): def is ObjectField {\n return !('jsonType' in def) || !def.jsonType\n }\n\n function getObjectDefinition(def: ObjectField | SchemaType, parent?: string): ConvertedType {\n const isInline = isField(def)\n const isDocument = def.type ? def.type.name === 'document' : false\n const actualType = isInline ? def.type : def\n\n if (typeNeedsHoisting(actualType)) {\n throw createLiftTypeError(def.name, parent || '', actualType.name)\n }\n\n if (isInline && parent && def.type.name === 'object') {\n throw createLiftTypeError(def.name, parent)\n }\n\n if (parent && def.type && isTopLevelType(def.type.name)) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return {type: getTypeName(def.type.name)} as any\n }\n\n const name = `${parent || ''}${getTypeName(def.name)}`\n const fields = collectFields(def)\n const firstUnprefixed = Math.max(\n 0,\n fields.findIndex((field) => field.name[0] !== '_'),\n )\n\n const keyField = createStringField('_key')\n\n fields.splice(firstUnprefixed, 0, keyField)\n\n if (!isDocument) {\n fields.splice(firstUnprefixed + 1, 0, createStringField('_type'))\n }\n\n const objectIsBlock = isBlockType(def)\n const objectFields = objectIsBlock\n ? fields.filter((field) => !disabledBlockFields.has(field.name))\n : fields\n\n return {\n _internal: {\n ...getDeprecation(def),\n },\n description: getDescription(def),\n fields: objectFields.map((field) =>\n isArrayOfBlocks(field)\n ? buildRawField(field, name)\n : (convertType(field, name, {\n fieldName: field.name,\n ...getDeprecation(def),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }) as any),\n ),\n kind: 'Type',\n name,\n type: 'Object',\n }\n }\n\n function buildRawField(field: ObjectField, parentName: string) {\n return {\n ...convertType(field, parentName, {fieldName: `${field.name}Raw`}),\n isRawAlias: true,\n type: 'JSON',\n }\n }\n\n function createStringField(name: string): ObjectField {\n return {\n name,\n type: {\n jsonType: 'string',\n name: 'string',\n type: {jsonType: 'string', name: 'string', type: undefined},\n },\n }\n }\n\n function collectFields(def: ObjectField | SchemaType) {\n const fields = gatherAllFields(def)\n if (fields.length > 0) {\n return fields\n }\n\n const extended = getBaseType(sanitySchema, def.name as IntrinsicTypeName)\n return gatherAllFields(extended)\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n function getReferenceDefinition(def: SchemaType): any {\n const base = {description: getDescription(def), isReference: true}\n const candidates = arrayify(gatherAllReferenceCandidates(def))\n if (candidates.length === 0) {\n throw new Error('No candidates for reference')\n }\n\n if (candidates.length === 1) {\n return {type: getTypeName(candidates[0].type.name), ...base}\n }\n\n const allTypeNames = candidates.map((c) => getTypeName(c.type.name))\n const targetTypes = [...new Set(allTypeNames)].toSorted()\n const name = targetTypes.join('Or')\n\n // Register the union type if we haven't seen it before\n if (!unionTypes.some((item) => item.name === name)) {\n unionTypes.push({\n kind: 'Union',\n name,\n types: targetTypes,\n })\n }\n\n return {\n type: name,\n ...base,\n }\n }\n\n function getArrayDefinition(\n def: ArraySchemaType,\n parent: string,\n options: {isField?: boolean} = {},\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): any {\n const base = {description: getDescription(def), kind: 'List'}\n const name = !options.isField && def.name ? {name: getTypeName(def.name)} : {}\n const candidates = def.type?.type && 'of' in def.type ? arrayify(def.type.of) : def.of\n\n return candidates.length === 1\n ? {\n children: getArrayChildDefinition(candidates[0], def),\n ...base,\n ...name,\n }\n : {\n children: getUnionDefinition(candidates, def, {grandParent: parent}),\n ...base,\n ...name,\n }\n }\n\n function getArrayChildDefinition(child: SchemaType, arrayDef: SchemaType) {\n if (typeNeedsHoisting(child)) {\n // Seems to be inline? Should be hoisted?\n throw createLiftTypeError(child.name, arrayDef.name)\n }\n\n if (isReference(child)) {\n return getReferenceDefinition(child)\n }\n\n // In the case of nested scalars, recurse (markdown -> longText -> text -> string)\n if (scalars.has(child.jsonType) && !scalars.has(child.name)) {\n return {type: mapFieldType(child)}\n }\n\n return {type: getTypeName(child.name)}\n }\n\n function typeNeedsHoisting(type: SchemaType & {isCustomized?: boolean}): boolean {\n if (type.name === 'object') {\n return true\n }\n\n if (type.jsonType === 'object' && !isTopLevelType(type.name)) {\n return true\n }\n\n if (type.isCustomized && !isTopLevelType(type.name)) {\n return true\n }\n\n if (type.isCustomized && disallowedCustomizedMembers.has(type.name)) {\n return true\n }\n\n return false\n }\n\n function getUnionDefinition(\n candidates: ObjectSchemaType[],\n parent: SchemaType,\n options: {grandParent?: string} = {},\n ) {\n if (candidates.length < 2) {\n throw new Error('Not enough candidates for a union type')\n }\n\n // #1482: When creating union definition do not get caught in recursion loop\n // for types that reference themselves\n const guardPathName = `${typeof parent === 'object' ? parent.name : parent}`\n if (unionRecursionGuards.has(guardPathName)) {\n return {}\n }\n\n const unionCacheKey = `${options.grandParent}-${guardPathName}-${candidates\n .map((c) => c.type?.name)\n .join('-')}`\n if (withUnionCache && unionDefinitionCache.has(unionCacheKey)) {\n return unionDefinitionCache.get(unionCacheKey)\n }\n\n try {\n unionRecursionGuards.add(guardPathName)\n\n for (const [i, def] of candidates.entries()) {\n if (typeNeedsHoisting(def)) {\n throw createLiftTypeArrayError(\n i,\n parent.name,\n def.type ? def.type.name : def.name,\n options.grandParent,\n )\n }\n }\n\n const converted = candidates.map((def) => convertType(def))\n\n const getName = (def: {type: string | {name: string}}): string =>\n typeof def.type === 'string' ? def.type : def.type.name\n\n // We might end up with union types being returned - these needs to be flattened\n // so that an ImageOr(PersonOrPet) becomes ImageOrPersonOrPet\n // eslint-disable-next-line unicorn/no-array-reduce\n const flattened = converted.reduce(\n (acc, candidate) => {\n const union = unionTypes.find((item) => item.name === candidate.type)\n return union\n ? // eslint-disable-next-line unicorn/prefer-spread\n acc.concat(union.types.map((type) => ({isReference: candidate.isReference, type})))\n : [...acc, candidate]\n },\n [] as {isReference?: boolean; name?: string; type: string | {name: string}}[],\n )\n\n let allCandidatesAreDocuments = true\n const refs: (string | {name: string})[] = []\n const inlineObjs: string[] = []\n const allTypeNames: string[] = []\n for (const def of flattened) {\n if (def.isReference) {\n refs.push(def.type)\n }\n if (!isReference) {\n inlineObjs.push(def.name || '')\n }\n\n const typeName = typeof def.type === 'string' ? def.type : def.type.name\n\n // Here we remove duplicates, as they might appear twice due to in-line usage of types as well as references\n if (def.name || def.type) {\n allTypeNames.push(def.isReference ? typeName : def.name || '')\n }\n\n const typeDef = sanityTypes.find((type) => type.name === getName(def))\n if (!typeDef || typeDef.type !== 'document') {\n allCandidatesAreDocuments = false\n }\n }\n\n const interfaces = allCandidatesAreDocuments ? ['Document'] : undefined\n const possibleTypes = [...new Set(allTypeNames)].toSorted()\n\n if (possibleTypes.length < 2) {\n throw new Error(`Not enough types for a union type. Parent: ${parent.name}`)\n }\n\n const name = possibleTypes.join('Or')\n\n if (!unionTypes.some((item) => item.name === name)) {\n unionTypes.push({\n interfaces,\n kind: 'Union',\n name,\n types: possibleTypes,\n })\n }\n\n const references = refs.length > 0 ? refs : undefined\n const inlineObjects = inlineObjs.length > 0 ? inlineObjs : undefined\n\n const unionDefinition = isReference(parent)\n ? {references, type: name}\n : {inlineObjects, references, type: name}\n\n unionDefinitionCache.set(unionCacheKey, unionDefinition)\n return unionDefinition\n } finally {\n unionRecursionGuards.delete(guardPathName)\n }\n }\n\n function getDocumentDefinition(def: ObjectSchemaType) {\n const objectDef = getObjectDefinition(def)\n const fields = [...getDocumentInterfaceFields(def), ...objectDef.fields]\n\n return {...objectDef, fields, interfaces: ['Document']}\n }\n\n function getDocumentInterfaceDefinition(): ConvertedInterface {\n return {\n description: 'A Sanity document',\n fields: getDocumentInterfaceFields(),\n kind: 'Interface',\n name: 'Document',\n }\n }\n\n function getDocumentInterfaceFields(type?: ObjectSchemaType): ConvertedFieldDefinition[] {\n const isNullable = typeof nonNullDocumentFields === 'boolean' ? !nonNullDocumentFields : true\n return [\n {\n description: 'Document ID',\n fieldName: '_id',\n isNullable,\n type: 'ID',\n ...getDeprecation(type),\n },\n {\n description: 'Document type',\n fieldName: '_type',\n isNullable,\n type: 'String',\n ...getDeprecation(type),\n },\n {\n description: 'Date the document was created',\n fieldName: '_createdAt',\n isNullable,\n type: 'Datetime',\n ...getDeprecation(type),\n },\n {\n description: 'Date the document was last modified',\n fieldName: '_updatedAt',\n isNullable,\n type: 'Datetime',\n ...getDeprecation(type),\n },\n {\n description: 'Current document revision',\n fieldName: '_rev',\n isNullable,\n type: 'String',\n ...getDeprecation(type),\n },\n ]\n }\n\n function arrayify(thing: unknown) {\n if (Array.isArray(thing)) {\n return thing\n }\n\n return thing === null || thing === undefined ? [] : [thing]\n }\n\n function hasValidationFlag(\n field: ObjectField | ObjectFieldType | SchemaType,\n flag: string,\n ): boolean {\n return (\n 'validation' in field &&\n Array.isArray(field.validation) &&\n field.validation.some(\n (rule) => rule && '_rules' in rule && rule._rules.some((item) => item.flag === flag),\n )\n )\n }\n\n function getDescription(type: ObjectField | SchemaType): string | undefined {\n const description = type.type && type.type.description\n return typeof description === 'string' ? description : undefined\n }\n\n function gatherAllReferenceCandidates(type: SchemaType): ObjectSchemaType[] {\n const allFields = gatherReferenceCandidates(type)\n return uniqBy(allFields, 'name')\n }\n\n function gatherReferenceCandidates(type: SchemaType): ObjectSchemaType[] {\n const refTo = 'to' in type ? type.to : []\n return 'type' in type && type.type ? [...gatherReferenceCandidates(type.type), ...refTo] : refTo\n }\n\n function gatherAllFields(type: ObjectField | SchemaType) {\n const allFields = gatherFields(type)\n return uniqBy(allFields, 'name')\n }\n\n function gatherFields(type: ObjectField | SchemaType): ObjectField[] {\n if ('fields' in type) {\n return type.type ? [...gatherFields(type.type), ...type.fields] : type.fields\n }\n\n return []\n }\n\n function hasFieldsLikeShape(type: unknown): type is {fields: unknown} {\n return typeof type === 'object' && type !== null && 'fields' in type\n }\n\n function hasArrayOfFields(type: unknown): type is {fields: ObjectField[]} {\n return hasFieldsLikeShape(type) && Array.isArray(type.fields)\n }\n\n function hasFields(type: ObjectField | SchemaType): boolean {\n if (hasArrayOfFields(type)) {\n return gatherAllFields(type).length > 0\n }\n\n return 'type' in type && type.type ? hasFields(type.type) : false\n }\n}\n\nfunction createLiftTypeArrayError(\n index: number,\n parent: string,\n inlineType = 'object',\n grandParent = '',\n) {\n const helpUrl = generateHelpUrl(SCHEMA_LIFT_ANONYMOUS_OBJECT_TYPE)\n const context = [grandParent, parent].filter(Boolean).join('/')\n return new HelpfulError(\n oneline`\n Encountered anonymous inline ${inlineType} at index ${index} for type/field ${context}.\n To use this type with GraphQL you will need to create a top-level schema type for it.\n See ${helpUrl}`,\n helpUrl,\n )\n}\n\nfunction createLiftTypeError(typeName: string, parent: string, inlineType = 'object') {\n const helpUrl = generateHelpUrl(SCHEMA_LIFT_ANONYMOUS_OBJECT_TYPE)\n return new HelpfulError(\n oneline`\n Encountered anonymous inline ${inlineType} \"${typeName}\" for field/type \"${parent}\".\n To use this field with GraphQL you will need to create a top-level schema type for it.\n See ${helpUrl}`,\n helpUrl,\n )\n}\n\nclass HelpfulError extends Error {\n helpUrl?: string\n\n constructor(message: string, helpUrl?: string) {\n super(message)\n this.name = 'HelpfulError'\n this.helpUrl = helpUrl\n }\n}\n\nfunction getDeprecation(type?: ObjectField | ObjectFieldType | SchemaType): Partial<Deprecation> {\n return isDeprecationConfiguration(type)\n ? {\n deprecationReason: type.deprecated.reason,\n }\n : {}\n}\n"],"names":["generateHelpUrl","Schema","isDeprecationConfiguration","startCase","uniqBy","oneline","SCHEMA_LIFT_ANONYMOUS_OBJECT_TYPE","SchemaError","skipTypes","Set","allowedJsonTypes","disallowedCustomizedMembers","disabledBlockFields","scalars","getBaseType","baseSchema","typeName","compile","parent","types","name","to","type","get","options","hotspot","getTypeName","str","replaceAll","isBaseType","jsonType","has","isReference","isBlockType","typeDef","hasBlockParent","Boolean","isArrayOfBlocks","of","some","item","isType","isCrossDatasetReference","getCrossDatasetReferenceMetadata","getTypeNames","map","t","filter","getDataset","dataset","typeNames","extractFromSanitySchema","sanitySchema","extractOptions","nonNullDocumentFields","withUnionCache","unionRecursionGuards","unionDefinitionCache","Map","hasErrors","_validation","group","problems","problem","severity","Array","isArray","sanityTypes","_original","unionTypes","schemaType","undefined","convertedType","convertType","push","withUnions","interfaces","getDocumentInterfaceDefinition","isTopLevelType","includes","mapFieldType","field","Error","isScalar","hasValidationFlag","isArrayType","_convertType","getReferenceDefinition","getArrayDefinition","getDocumentDefinition","getObjectDefinition","hasFields","description","getDescription","props","mapped","isField","fieldName","gqlName","originalName","original","crossDatasetReferenceMetadata","getDeprecation","def","isInline","isDocument","actualType","typeNeedsHoisting","createLiftTypeError","fields","collectFields","firstUnprefixed","Math","max","findIndex","keyField","createStringField","splice","objectIsBlock","objectFields","_internal","buildRawField","kind","parentName","isRawAlias","gatherAllFields","length","extended","base","candidates","arrayify","gatherAllReferenceCandidates","allTypeNames","c","targetTypes","toSorted","join","children","getArrayChildDefinition","getUnionDefinition","grandParent","child","arrayDef","isCustomized","guardPathName","unionCacheKey","add","i","entries","createLiftTypeArrayError","converted","getName","flattened","reduce","acc","candidate","union","find","concat","allCandidatesAreDocuments","refs","inlineObjs","possibleTypes","references","inlineObjects","unionDefinition","set","delete","objectDef","getDocumentInterfaceFields","isNullable","thing","flag","validation","rule","_rules","allFields","gatherReferenceCandidates","refTo","gatherFields","hasFieldsLikeShape","hasArrayOfFields","index","inlineType","helpUrl","context","HelpfulError","message","deprecationReason","deprecated","reason"],"mappings":"AAAA,yDAAyD,GACzD,SAAQA,eAAe,QAAO,4BAA2B;AACzD,SAAQC,MAAM,QAAO,iBAAgB;AACrC,SAKEC,0BAA0B,QAMrB,gBAAe;AACtB,OAAOC,eAAe,yBAAwB;AAC9C,OAAOC,YAAY,sBAAqB;AACxC,SAAQC,OAAO,QAAO,UAAS;AAE/B,SAAQC,iCAAiC,QAAO,gBAAe;AAC/D,SAAQC,WAAW,QAAO,mBAAkB;AAU5C,MAAMC,YAAY,IAAIC,IAAI;IAAC;IAAY;CAAY;AACnD,MAAMC,mBAAmB,IAAID,IAAI;IAAC;IAAS;CAAS;AACpD,MAAME,8BAA8B,IAAIF,IAAI;IAAC;IAAS;IAAS;IAAQ;IAAS;CAAS;AACzF,MAAMG,sBAAsB,IAAIH,IAAI;IAAC;CAAW;AAChD,MAAMI,UAAU,IAAIJ,IAAI;IAAC;IAAW;IAAU;CAAS;AAEvD,SAASK,YAAYC,UAA0B,EAAEC,QAA2B;IAC1E,IAAIA,aAAa,yBAAyB;QACxC,OAAOf,OAAOgB,OAAO,CAAC;YACpBC,QAAQH;YACRI,OAAO;gBACL;oBACEC,MAAM,CAAC,eAAe,CAAC;oBACvB,0DAA0D;oBAC1DC,IAAI;wBAAC;4BAACC,MAAM;wBAAmB;qBAAE;oBACjCA,MAAM;gBACR;aACD;QACH,GAAGC,GAAG,CAAC;IACT;IACA,IAAIP,aAAa,2BAA2B;QAC1C,OAAOf,OAAOgB,OAAO,CAAC;YACpBC,QAAQH;YACRI,OAAO;g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BtK,KAAKuK,UAAU,CAACC,MAAM;IAC3C,IACA,CAAC;AACP"}
|
|
@@ -60,7 +60,7 @@ export async function initStudio({ datasetName, defaults, displayName, isFirstPr
|
|
|
60
60
|
if (!token) {
|
|
61
61
|
throw new InitError('Authentication required to import dataset', 1);
|
|
62
62
|
}
|
|
63
|
-
// eslint-disable-next-line no-restricted-syntax
|
|
63
|
+
// eslint-disable-next-line eslint-js/no-restricted-syntax
|
|
64
64
|
const { ImportDatasetCommand } = await import('../../commands/datasets/import.js');
|
|
65
65
|
await ImportDatasetCommand.run([
|
|
66
66
|
resolvedTemplate.datasetUrl,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/init/initStudio.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {getCliToken, type Output, subdebug, type TelemetryUserProperties} from '@sanity/cli-core'\nimport {confirm} from '@sanity/cli-core/ux'\nimport {type TelemetryTrace} from '@sanity/telemetry'\n\nimport {updateProjectInitializedAt} from '../../services/projects.js'\nimport {type InitStepResult} from '../../telemetry/init.telemetry.js'\nimport {getInstallCommand} from '../../util/packageManager/installPackages.js'\nimport {type PackageManager} from '../../util/packageManager/packageManagerChoice.js'\nimport {type EditorName} from '../mcp/editorConfigs.js'\nimport {InitError} from './initError.js'\nimport {getPostInitMCPPrompt} from './initHelpers.js'\nimport {type RepoInfo} from './remoteTemplate.js'\nimport {scaffoldAndInstall, selectTemplate} from './scaffoldTemplate.js'\nimport {type InitOptions} from './types.js'\n\nconst debug = subdebug('init')\n\nasync function promptForDatasetImport(message?: string): Promise<boolean> {\n return confirm({\n default: true,\n message: message || 'This template includes a sample dataset, would you like to use it?',\n })\n}\n\nexport async function initStudio({\n datasetName,\n defaults,\n displayName,\n isFirstProject,\n mcpConfigured,\n options,\n organizationId,\n output,\n outputPath,\n preclaim = false,\n projectId,\n remoteTemplateInfo,\n sluggedName,\n trace,\n workbench,\n workDir,\n}: {\n datasetName: string\n defaults: {projectName: string}\n displayName: string\n isFirstProject: boolean\n mcpConfigured: EditorName[]\n options: InitOptions\n organizationId: string | undefined\n output: Output\n outputPath: string\n preclaim?: boolean\n projectId: string\n remoteTemplateInfo: RepoInfo | undefined\n sluggedName: string\n trace: TelemetryTrace<TelemetryUserProperties, InitStepResult>\n workbench: boolean\n workDir: string\n}): Promise<void> {\n const {importDataset, install, unattended} = options\n const {\n template: resolvedTemplate,\n templateName,\n useTypeScript,\n } = await selectTemplate({\n options,\n remoteTemplateInfo,\n trace,\n })\n\n if (!remoteTemplateInfo && !resolvedTemplate) {\n throw new InitError(`Template \"${templateName}\" not found`, 1)\n }\n\n // If the template has a sample dataset, prompt the user whether or not we should import it\n const shouldImport =\n resolvedTemplate?.datasetUrl &&\n (importDataset ??\n (!unattended && (await promptForDatasetImport(resolvedTemplate.importPrompt))))\n\n trace.log({\n selectedOption: shouldImport ? 'yes' : 'no',\n step: 'importTemplateDataset',\n })\n\n if (!preclaim) {\n try {\n await updateProjectInitializedAt(projectId)\n } catch (err) {\n // Non-critical update\n debug('Failed to update cliInitializedAt metadata', err)\n }\n }\n\n const {pkgManager} = await scaffoldAndInstall({\n datasetName,\n defaults,\n displayName,\n options,\n organizationId,\n output,\n outputPath,\n projectId,\n remoteTemplateInfo,\n sluggedName,\n templateName,\n trace,\n useTypeScript,\n workbench,\n workDir,\n })\n\n // Prompt for dataset import (if a dataset is defined)\n if (shouldImport && resolvedTemplate?.datasetUrl) {\n const token = await getCliToken()\n if (!token) {\n throw new InitError('Authentication required to import dataset', 1)\n }\n // eslint-disable-next-line no-restricted-syntax\n const {ImportDatasetCommand} = await import('../../commands/datasets/import.js')\n await ImportDatasetCommand.run(\n [\n resolvedTemplate.datasetUrl,\n '--project',\n projectId,\n '--dataset',\n datasetName,\n '--token',\n token,\n '--missing',\n ],\n {\n root: outputPath,\n },\n )\n\n output.log('')\n output.log('If you want to delete the imported data, use')\n output.log(` ${styleText('cyan', `npx sanity dataset delete ${datasetName}`)}`)\n output.log('and create a new clean dataset with')\n output.log(` ${styleText('cyan', `npx sanity dataset create <name>`)}\\n`)\n }\n\n // `sanity new` owns the combined Studio/frontend outro.\n if (preclaim) return\n\n const devCommandMap: Record<PackageManager, string> = {\n bun: 'bun dev',\n manual: 'npm run dev',\n npm: 'npm run dev',\n pnpm: 'pnpm dev',\n yarn: 'yarn dev',\n }\n const devCommand = devCommandMap[pkgManager]\n\n const isCurrentDir = outputPath === workDir\n const goToProjectDir = `\\n(${styleText('cyan', `cd ${outputPath}`)} to navigate to your new project directory)`\n\n //output for Studios here\n output.log(`\\u2705 ${styleText(['green', 'bold'], 'Success!')} Your Studio has been created.`)\n if (!isCurrentDir) output.log(goToProjectDir)\n const startupCommands = install\n ? styleText('cyan', devCommand)\n : `${styleText('cyan', getInstallCommand(pkgManager))}, then ${styleText('cyan', devCommand)}`\n output.log(\n `\\nGet started by running ${startupCommands} to launch your Studio's development server`,\n )\n if (mcpConfigured && mcpConfigured.length > 0) {\n const message = await getPostInitMCPPrompt(mcpConfigured)\n output.log(`\\n${message}`)\n output.log(`\\nLearn more: ${styleText('cyan', 'https://mcp.sanity.io')}`)\n output.log(\n `\\nHave feedback? Tell us in the community: ${styleText('cyan', 'https://www.sanity.io/community/join')}`,\n )\n }\n output.log('\\n')\n output.log(`Other helpful commands:`)\n output.log(`npx sanity docs browse to open the documentation in a browser`)\n output.log(`npx sanity manage to open the project settings in a browser`)\n output.log(`npx sanity help to explore the CLI manual`)\n\n if (isFirstProject) {\n trace.log({selectedOption: 'yes', step: 'sendCommunityInvite'})\n\n const DISCORD_INVITE_LINK = 'https://www.sanity.io/community/join'\n\n output.log(`\\nJoin the Sanity community: ${styleText('cyan', DISCORD_INVITE_LINK)}`)\n output.log('We look forward to seeing you there!\\n')\n }\n}\n"],"names":["styleText","getCliToken","subdebug","confirm","updateProjectInitializedAt","getInstallCommand","InitError","getPostInitMCPPrompt","scaffoldAndInstall","selectTemplate","debug","promptForDatasetImport","message","default","initStudio","datasetName","defaults","displayName","isFirstProject","mcpConfigured","options","organizationId","output","outputPath","preclaim","projectId","remoteTemplateInfo","sluggedName","trace","workbench","workDir","importDataset","install","unattended","template","resolvedTemplate","templateName","useTypeScript","shouldImport","datasetUrl","importPrompt","log","selectedOption","step","err","pkgManager","token","ImportDatasetCommand","run","root","devCommandMap","bun","manual","npm","pnpm","yarn","devCommand","isCurrentDir","goToProjectDir","startupCommands","length","DISCORD_INVITE_LINK"],"mappings":"AAAA,SAAQA,SAAS,QAAO,YAAW;AAEnC,SAAQC,WAAW,EAAeC,QAAQ,QAAqC,mBAAkB;AACjG,SAAQC,OAAO,QAAO,sBAAqB;AAG3C,SAAQC,0BAA0B,QAAO,6BAA4B;AAErE,SAAQC,iBAAiB,QAAO,+CAA8C;AAG9E,SAAQC,SAAS,QAAO,iBAAgB;AACxC,SAAQC,oBAAoB,QAAO,mBAAkB;AAErD,SAAQC,kBAAkB,EAAEC,cAAc,QAAO,wBAAuB;AAGxE,MAAMC,QAAQR,SAAS;AAEvB,eAAeS,uBAAuBC,OAAgB;IACpD,OAAOT,QAAQ;QACbU,SAAS;QACTD,SAASA,WAAW;IACtB;AACF;AAEA,OAAO,eAAeE,WAAW,EAC/BC,WAAW,EACXC,QAAQ,EACRC,WAAW,EACXC,cAAc,EACdC,aAAa,EACbC,OAAO,EACPC,cAAc,EACdC,MAAM,EACNC,UAAU,EACVC,WAAW,KAAK,EAChBC,SAAS,EACTC,kBAAkB,EAClBC,WAAW,EACXC,KAAK,EACLC,SAAS,EACTC,OAAO,EAkBR;IACC,MAAM,EAACC,aAAa,EAAEC,OAAO,EAAEC,UAAU,EAAC,GAAGb;IAC7C,MAAM,EACJc,UAAUC,gBAAgB,EAC1BC,YAAY,EACZC,aAAa,EACd,GAAG,MAAM5B,eAAe;QACvBW;QACAM;QACAE;IACF;IAEA,IAAI,CAACF,sBAAsB,CAACS,kBAAkB;QAC5C,MAAM,IAAI7B,UAAU,CAAC,UAAU,EAAE8B,aAAa,WAAW,CAAC,EAAE;IAC9D;IA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zC,UAAU,QAAQ6D,sBAAsB;QACnFvC,OAAOmB,GAAG,CAAC;IACb;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/init/initStudio.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {getCliToken, type Output, subdebug, type TelemetryUserProperties} from '@sanity/cli-core'\nimport {confirm} from '@sanity/cli-core/ux'\nimport {type TelemetryTrace} from '@sanity/telemetry'\n\nimport {updateProjectInitializedAt} from '../../services/projects.js'\nimport {type InitStepResult} from '../../telemetry/init.telemetry.js'\nimport {getInstallCommand} from '../../util/packageManager/installPackages.js'\nimport {type PackageManager} from '../../util/packageManager/packageManagerChoice.js'\nimport {type EditorName} from '../mcp/editorConfigs.js'\nimport {InitError} from './initError.js'\nimport {getPostInitMCPPrompt} from './initHelpers.js'\nimport {type RepoInfo} from './remoteTemplate.js'\nimport {scaffoldAndInstall, selectTemplate} from './scaffoldTemplate.js'\nimport {type InitOptions} from './types.js'\n\nconst debug = subdebug('init')\n\nasync function promptForDatasetImport(message?: string): Promise<boolean> {\n return confirm({\n default: true,\n message: message || 'This template includes a sample dataset, would you like to use it?',\n })\n}\n\nexport async function initStudio({\n datasetName,\n defaults,\n displayName,\n isFirstProject,\n mcpConfigured,\n options,\n organizationId,\n output,\n outputPath,\n preclaim = false,\n projectId,\n remoteTemplateInfo,\n sluggedName,\n trace,\n workbench,\n workDir,\n}: {\n datasetName: string\n defaults: {projectName: string}\n displayName: string\n isFirstProject: boolean\n mcpConfigured: EditorName[]\n options: InitOptions\n organizationId: string | undefined\n output: Output\n outputPath: string\n preclaim?: boolean\n projectId: string\n remoteTemplateInfo: RepoInfo | undefined\n sluggedName: string\n trace: TelemetryTrace<TelemetryUserProperties, InitStepResult>\n workbench: boolean\n workDir: string\n}): Promise<void> {\n const {importDataset, install, unattended} = options\n const {\n template: resolvedTemplate,\n templateName,\n useTypeScript,\n } = await selectTemplate({\n options,\n remoteTemplateInfo,\n trace,\n })\n\n if (!remoteTemplateInfo && !resolvedTemplate) {\n throw new InitError(`Template \"${templateName}\" not found`, 1)\n }\n\n // If the template has a sample dataset, prompt the user whether or not we should import it\n const shouldImport =\n resolvedTemplate?.datasetUrl &&\n (importDataset ??\n (!unattended && (await promptForDatasetImport(resolvedTemplate.importPrompt))))\n\n trace.log({\n selectedOption: shouldImport ? 'yes' : 'no',\n step: 'importTemplateDataset',\n })\n\n if (!preclaim) {\n try {\n await updateProjectInitializedAt(projectId)\n } catch (err) {\n // Non-critical update\n debug('Failed to update cliInitializedAt metadata', err)\n }\n }\n\n const {pkgManager} = await scaffoldAndInstall({\n datasetName,\n defaults,\n displayName,\n options,\n organizationId,\n output,\n outputPath,\n projectId,\n remoteTemplateInfo,\n sluggedName,\n templateName,\n trace,\n useTypeScript,\n workbench,\n workDir,\n })\n\n // Prompt for dataset import (if a dataset is defined)\n if (shouldImport && resolvedTemplate?.datasetUrl) {\n const token = await getCliToken()\n if (!token) {\n throw new InitError('Authentication required to import dataset', 1)\n }\n // eslint-disable-next-line eslint-js/no-restricted-syntax\n const {ImportDatasetCommand} = await import('../../commands/datasets/import.js')\n await ImportDatasetCommand.run(\n [\n resolvedTemplate.datasetUrl,\n '--project',\n projectId,\n '--dataset',\n datasetName,\n '--token',\n token,\n '--missing',\n ],\n {\n root: outputPath,\n },\n )\n\n output.log('')\n output.log('If you want to delete the imported data, use')\n output.log(` ${styleText('cyan', `npx sanity dataset delete ${datasetName}`)}`)\n output.log('and create a new clean dataset with')\n output.log(` ${styleText('cyan', `npx sanity dataset create <name>`)}\\n`)\n }\n\n // `sanity new` owns the combined Studio/frontend outro.\n if (preclaim) return\n\n const devCommandMap: Record<PackageManager, string> = {\n bun: 'bun dev',\n manual: 'npm run dev',\n npm: 'npm run dev',\n pnpm: 'pnpm dev',\n yarn: 'yarn dev',\n }\n const devCommand = devCommandMap[pkgManager]\n\n const isCurrentDir = outputPath === workDir\n const goToProjectDir = `\\n(${styleText('cyan', `cd ${outputPath}`)} to navigate to your new project directory)`\n\n //output for Studios here\n output.log(`\\u2705 ${styleText(['green', 'bold'], 'Success!')} Your Studio has been created.`)\n if (!isCurrentDir) output.log(goToProjectDir)\n const startupCommands = install\n ? styleText('cyan', devCommand)\n : `${styleText('cyan', getInstallCommand(pkgManager))}, then ${styleText('cyan', devCommand)}`\n output.log(\n `\\nGet started by running ${startupCommands} to launch your Studio's development server`,\n )\n if (mcpConfigured && mcpConfigured.length > 0) {\n const message = await getPostInitMCPPrompt(mcpConfigured)\n output.log(`\\n${message}`)\n output.log(`\\nLearn more: ${styleText('cyan', 'https://mcp.sanity.io')}`)\n output.log(\n `\\nHave feedback? Tell us in the community: ${styleText('cyan', 'https://www.sanity.io/community/join')}`,\n )\n }\n output.log('\\n')\n output.log(`Other helpful commands:`)\n output.log(`npx sanity docs browse to open the documentation in a browser`)\n output.log(`npx sanity manage to open the project settings in a browser`)\n output.log(`npx sanity help to explore the CLI manual`)\n\n if (isFirstProject) {\n trace.log({selectedOption: 'yes', step: 'sendCommunityInvite'})\n\n const DISCORD_INVITE_LINK = 'https://www.sanity.io/community/join'\n\n output.log(`\\nJoin the Sanity community: ${styleText('cyan', DISCORD_INVITE_LINK)}`)\n output.log('We look forward to seeing you there!\\n')\n }\n}\n"],"names":["styleText","getCliToken","subdebug","confirm","updateProjectInitializedAt","getInstallCommand","InitError","getPostInitMCPPrompt","scaffoldAndInstall","selectTemplate","debug","promptForDatasetImport","message","default","initStudio","datasetName","defaults","displayName","isFirstProject","mcpConfigured","options","organizationId","output","outputPath","preclaim","projectId","remoteTemplateInfo","sluggedName","trace","workbench","workDir","importDataset","install","unattended","template","resolvedTemplate","templateName","useTypeScript","shouldImport","datasetUrl","importPrompt","log","selectedOption","step","err","pkgManager","token","ImportDatasetCommand","run","root","devCommandMap","bun","manual","npm","pnpm","yarn","devCommand","isCurrentDir","goToProjectDir","startupCommands","length","DISCORD_INVITE_LINK"],"mappings":"AAAA,SAAQA,SAAS,QAAO,YAAW;AAEnC,SAAQC,WAAW,EAAeC,QAAQ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C,OAAOmB,GAAG,CAACiB;IAC9B,MAAMC,kBAAkB3B,UACpBhC,UAAU,QAAQwD,cAClB,GAAGxD,UAAU,QAAQK,kBAAkBwC,aAAa,OAAO,EAAE7C,UAAU,QAAQwD,aAAa;IAChGlC,OAAOmB,GAAG,CACR,CAAC,yBAAyB,EAAEkB,gBAAgB,2CAA2C,CAAC;IAE1F,IAAIxC,iBAAiBA,cAAcyC,MAAM,GAAG,GAAG;QAC7C,MAAMhD,UAAU,MAAML,qBAAqBY;QAC3CG,OAAOmB,GAAG,CAAC,CAAC,EAAE,EAAE7B,SAAS;QACzBU,OAAOmB,GAAG,CAAC,CAAC,cAAc,EAAEzC,UAAU,QAAQ,0BAA0B;QACxEsB,OAAOmB,GAAG,CACR,CAAC,2CAA2C,EAAEzC,UAAU,QAAQ,yCAAyC;IAE7G;IACAsB,OAAOmB,GAAG,CAAC;IACXnB,OAAOmB,GAAG,CAAC,CAAC,uBAAuB,CAAC;IACpCnB,OAAOmB,GAAG,CAAC,CAAC,iEAAiE,CAAC;IAC9EnB,OAAOmB,GAAG,CAAC,CAAC,oEAAoE,CAAC;IACjFnB,OAAOmB,GAAG,CAAC,CAAC,oDAAoD,CAAC;IAEjE,IAAIvB,gBAAgB;QAClBU,MAAMa,GAAG,CAAC;YAACC,gBAAgB;YAAOC,MAAM;QAAqB;QAE7D,MAAMkB,sBAAsB;QAE5BvC,OAAOmB,GAAG,CAAC,CAAC,6BAA6B,EAAEzC,UAAU,QAAQ6D,sBAAsB;QACnFvC,OAAOmB,GAAG,CAAC;IACb;AACF"}
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
}
|
|
13
13
|
const newValue = typeof variables[variableName] === 'string' ? variables[variableName] : '';
|
|
14
14
|
// Escape backslashes first, then the surrounding quote character
|
|
15
|
-
const escaped = newValue.replaceAll('\\',
|
|
15
|
+
const escaped = newValue.replaceAll('\\', String.raw`\\`).replaceAll(quote, `\\${quote}`);
|
|
16
16
|
return `${quote}${escaped}${quote}`;
|
|
17
17
|
});
|
|
18
18
|
// Replace boolean placeholders: __BOOL__variableName__
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/init/processTemplate.ts"],"sourcesContent":["interface TemplateOptions<T> {\n template: string\n variables: T\n\n includeBooleanTransform?: boolean\n}\n\n/**\n * Process a template string by replacing placeholder variables with actual values.\n *\n * String variables use the format `'%variableName%'` (inside string literals).\n * Boolean variables use the format `__BOOL__variableName__` (as bare identifiers).\n */\nexport function processTemplate<T extends object>(options: TemplateOptions<T>): string {\n const {includeBooleanTransform = false, template, variables} = options\n\n // Replace string placeholders: '%variableName%' or \"%variableName%\"\n let result = template\n .trimStart()\n .replaceAll(/(['\"])%([\\w]+)%\\1/g, (_match, quote: string, variableName: string) => {\n if (!(variableName in variables)) {\n throw new Error(`Template variable '%${variableName}%' not defined`)\n }\n const newValue =\n typeof variables[variableName as keyof T] === 'string'\n ? variables[variableName as keyof T]\n : ''\n // Escape backslashes first, then the surrounding quote character\n const escaped = (newValue as string).replaceAll('\\\\',
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/init/processTemplate.ts"],"sourcesContent":["interface TemplateOptions<T> {\n template: string\n variables: T\n\n includeBooleanTransform?: boolean\n}\n\n/**\n * Process a template string by replacing placeholder variables with actual values.\n *\n * String variables use the format `'%variableName%'` (inside string literals).\n * Boolean variables use the format `__BOOL__variableName__` (as bare identifiers).\n */\nexport function processTemplate<T extends object>(options: TemplateOptions<T>): string {\n const {includeBooleanTransform = false, template, variables} = options\n\n // Replace string placeholders: '%variableName%' or \"%variableName%\"\n let result = template\n .trimStart()\n .replaceAll(/(['\"])%([\\w]+)%\\1/g, (_match, quote: string, variableName: string) => {\n if (!(variableName in variables)) {\n throw new Error(`Template variable '%${variableName}%' not defined`)\n }\n const newValue =\n typeof variables[variableName as keyof T] === 'string'\n ? variables[variableName as keyof T]\n : ''\n // Escape backslashes first, then the surrounding quote character\n const escaped = (newValue as string)\n .replaceAll('\\\\', String.raw`\\\\`)\n .replaceAll(quote, `\\\\${quote}`)\n return `${quote}${escaped}${quote}`\n })\n\n // Replace boolean placeholders: __BOOL__variableName__\n if (includeBooleanTransform) {\n result = result.replaceAll(/__BOOL__(\\w+)__/g, (_match, variableName: string) => {\n if (!(variableName in variables)) {\n throw new Error(`Template variable '${variableName}' not defined`)\n }\n const value = variables[variableName as keyof T]\n if (typeof value !== 'boolean') {\n throw new TypeError(`Expected boolean value for '${variableName}'`)\n }\n return String(value)\n })\n }\n\n return result\n}\n"],"names":["processTemplate","options","includeBooleanTransform","template","variables","result","trimStart","replaceAll","_match","quote","variableName","Error","newValue","escaped","String","raw","value","TypeError"],"mappings":"AAOA;;;;;CAKC,GACD,OAAO,SAASA,gBAAkCC,OAA2B;IAC3E,MAAM,EAACC,0BAA0B,KAAK,EAAEC,QAAQ,EAAEC,SAAS,EAAC,GAAGH;IAE/D,oEAAoE;IACpE,IAAII,SAASF,SACVG,SAAS,GACTC,UAAU,CAAC,sBAAsB,CAACC,QAAQC,OAAeC;QACxD,IAAI,CAAEA,CAAAA,gBAAgBN,SAAQ,GAAI;YAChC,MAAM,IAAIO,MAAM,CAAC,oBAAoB,EAAED,aAAa,cAAc,CAAC;QACrE;QACA,MAAME,WACJ,OAAOR,SAAS,CAACM,aAAwB,KAAK,WAC1CN,SAAS,CAACM,aAAwB,GAClC;QACN,iEAAiE;QACjE,MAAMG,UAAU,AAACD,SACdL,UAAU,CAAC,MAAMO,OAAOC,GAAG,CAAC,EAAE,CAAC,EAC/BR,UAAU,CAACE,OAAO,CAAC,EAAE,EAAEA,OAAO;QACjC,OAAO,GAAGA,QAAQI,UAAUJ,OAAO;IACrC;IAEF,uDAAuD;IACvD,IAAIP,yBAAyB;QAC3BG,SAASA,OAAOE,UAAU,CAAC,oBAAoB,CAACC,QAAQE;YACtD,IAAI,CAAEA,CAAAA,gBAAgBN,SAAQ,GAAI;gBAChC,MAAM,IAAIO,MAAM,CAAC,mBAAmB,EAAED,aAAa,aAAa,CAAC;YACnE;YACA,MAAMM,QAAQZ,SAAS,CAACM,aAAwB;YAChD,IAAI,OAAOM,UAAU,WAAW;gBAC9B,MAAM,IAAIC,UAAU,CAAC,4BAA4B,EAAEP,aAAa,CAAC,CAAC;YACpE;YACA,OAAOI,OAAOE;QAChB;IACF;IAEA,OAAOX;AACT"}
|
|
@@ -53,7 +53,7 @@ async function downloadTarStream(url, bearerToken) {
|
|
|
53
53
|
if (!res.body) {
|
|
54
54
|
throw new Error(`Failed to download: ${url}`);
|
|
55
55
|
}
|
|
56
|
-
// eslint-disable-next-line n/no-unsupported-features/node-builtins
|
|
56
|
+
// eslint-disable-next-line n-js/no-unsupported-features/node-builtins
|
|
57
57
|
return Readable.fromWeb(res.body);
|
|
58
58
|
}
|
|
59
59
|
export function checkIsRemoteTemplate(templateName) {
|
|
@@ -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/no-unsupported-features/node-builtins\n return Readable.fromWeb(res.body as Parameters<typeof Readable.fromWeb>[0])\n}\n\nexport function checkIsRemoteTemplate(templateName?: string): boolean {\n return templateName?.includes('/') ?? false\n}\n\nexport async function getGitHubRepoInfo(value: string, bearerToken?: string): Promise<RepoInfo> {\n let username = ''\n let name = ''\n let branch = ''\n let filePath = ''\n\n if (isGitHubRepoShorthand(value)) {\n const parts = value.split('/')\n username = parts[0]\n name = parts[1]\n // If there are more segments after owner/repo, they form the file path\n if (parts.length > 2) {\n filePath = parts.slice(2).join('/')\n }\n }\n\n if (isGitHubRepoUrl(value)) {\n const url = new URL(value)\n const pathSegments = url.pathname.slice(1).split('/')\n username = pathSegments[0]\n name = pathSegments[1]\n\n // If we have a \"tree\" segment, everything after branch is the file path\n if (pathSegments[2] === 'tree') {\n branch = pathSegments[3]\n if (pathSegments.length > 4) {\n filePath = pathSegments.slice(4).join('/')\n }\n }\n }\n\n if (!username || !name) {\n throw new Error('Invalid GitHub repository format')\n }\n\n const tokenMessage =\n 'GitHub repository not found. For private repositories, use --template-token to provide an access token.\\n\\n' +\n 'You can generate a new token at https://github.com/settings/personal-access-tokens/new\\n' +\n 'Set the token to \"read-only\" with repository access and a short expiry (e.g. 7 days) for security.'\n\n try {\n const headers: Record<string, string> = {}\n if (bearerToken) {\n headers.Authorization = `Bearer ${bearerToken}`\n }\n\n const infoResponse = await fetch(`https://api.github.com/repos/${username}/${name}`, {\n headers,\n })\n\n if (infoResponse.status !== 200) {\n if (infoResponse.status === 404) {\n throw new Error(tokenMessage)\n }\n throw new Error('GitHub repository not found')\n }\n\n const info = await infoResponse.json()\n\n return {\n branch: branch || info.default_branch,\n filePath,\n name,\n username,\n }\n } catch {\n throw new Error(tokenMessage)\n }\n}\n\nexport async function downloadAndExtractRepo(\n root: string,\n {branch, filePath, name, username}: RepoInfo,\n bearerToken?: string,\n): Promise<void> {\n let rootPath: string | null = null\n await pipeline(\n await downloadTarStream(\n `https://codeload.github.com/${username}/${name}/tar.gz/${branch}`,\n bearerToken,\n ),\n x({\n cwd: root,\n filter: (p: string) => {\n const posixPath = p.split(sep).join(posix.sep)\n if (rootPath === null) {\n const pathSegments = posixPath.split(posix.sep)\n rootPath = pathSegments.length > 0 ? pathSegments[0] : null\n }\n for (const disallowedPath of DISALLOWED_PATHS) {\n if (posixPath.includes(disallowedPath)) return false\n }\n return posixPath.startsWith(`${rootPath}${filePath ? `/${filePath}/` : '/'}`)\n },\n strip: filePath ? filePath.split('/').length + 1 : 1,\n }),\n )\n}\n\nexport async function checkIfNeedsApiToken(root: string, type: 'read' | 'write'): Promise<boolean> {\n try {\n const templatePath = await Promise.any(\n ENV_TEMPLATE_FILES.map(async (file) => {\n await access(join(root, file))\n return file\n }),\n )\n const templateContent = await readFile(join(root, templatePath), 'utf8')\n return templateContent.includes(type === 'read' ? ENV_VAR.READ_TOKEN : ENV_VAR.WRITE_TOKEN)\n } catch {\n return false\n }\n}\n\nexport async function applyEnvVariables(\n root: string,\n envData: EnvData,\n targetName = '.env',\n): Promise<void> {\n const templatePath = await Promise.any(\n ENV_TEMPLATE_FILES.map(async (file) => {\n await access(join(root, file))\n return file\n }),\n ).catch(() => {})\n\n if (!templatePath) {\n return // No template .env file found, skip\n }\n\n try {\n const templateContent = await readFile(join(root, templatePath), 'utf8')\n const {dataset, projectId, readToken = '', writeToken = ''} = envData\n\n const findAndReplaceVariable = (\n content: string,\n varRegex: RegExp | string,\n value: string,\n useQuotes: boolean,\n ) => {\n const varPattern = typeof varRegex === 'string' ? varRegex : varRegex.source\n const pattern = new RegExp(`.*${varPattern}=.*$`, 'gm')\n const matches = content.matchAll(pattern)\n\n let result = content\n for (const match of matches) {\n if (!match[0]) continue\n const varName = match[0].split('=')[0].trim()\n result = result.replaceAll(\n new RegExp(`${varName}=.*$`, 'gm'),\n `${varName}=${useQuotes ? `\"${value}\"` : value}`,\n )\n }\n\n return result\n }\n\n let envContent = templateContent\n const vars = [\n {pattern: ENV_VAR.PROJECT_ID, value: projectId},\n {pattern: ENV_VAR.DATASET, value: dataset},\n {pattern: ENV_VAR.READ_TOKEN, value: readToken},\n {pattern: ENV_VAR.WRITE_TOKEN, value: writeToken},\n ]\n const useQuotes = templateContent.includes('=\"')\n\n for (const {pattern, value} of vars) {\n envContent = findAndReplaceVariable(envContent, pattern, value, useQuotes)\n }\n\n await writeFile(join(root, targetName), envContent)\n } catch (err) {\n debug(`Error setting environment variables: ${err}`)\n throw new Error(\n 'Failed to set environment variables. This could be due to file permissions or the .env file format. See https://www.sanity.io/docs/environment-variables for details on environment variable setup.',\n {cause: err},\n )\n }\n}\n\nexport async function tryApplyPackageName(root: string, name: string): Promise<void> {\n try {\n const pkg = await readPackageJson(join(root, 'package.json'))\n pkg.name = name\n\n await writeFile(join(root, 'package.json'), JSON.stringify(pkg, null, 2))\n } catch {\n // noop\n }\n}\n"],"names":["access","readFile","writeFile","join","posix","sep","Readable","pipeline","readPackageJson","subdebug","ENV_TEMPLATE_FILES","REQUIRED_ENV_VAR","x","debug","DISALLOWED_PATHS","ENV_VAR","READ_TOKEN","WRITE_TOKEN","getGitHubRawContentUrl","repoInfo","branch","filePath","name","username","isGitHubRepoShorthand","value","URL","canParse","test","isGitHubRepoUrl","url","pathSegments","pathname","slice","split","protocol","hostname","length","downloadTarStream","bearerToken","headers","Authorization","res","fetch","body","Error","fromWeb","checkIsRemoteTemplate","templateName","includes","getGitHubRepoInfo","parts","tokenMessage","infoResponse","status","info","json","default_branch","downloadAndExtractRepo","root","rootPath","cwd","filter","p","posixPath","disallowedPath","startsWith","strip","checkIfNeedsApiToken","type","templatePath","Promise","any","map","file","templateContent","applyEnvVariables","envData","targetName","catch","dataset","projectId","readToken","writeToken","findAndReplaceVariable","content","varRegex","useQuotes","varPattern","source","pattern","RegExp","matches","matchAll","result","match","varName","trim","replaceAll","envContent","vars","PROJECT_ID","DATASET","err","cause","tryApplyPackageName","pkg","JSON","stringify"],"mappings":"AAAA,SAAQA,MAAM,EAAEC,QAAQ,EAAEC,SAAS,QAAO,mBAAkB;AAC5D,SAAQC,IAAI,EAAEC,KAAK,EAAEC,GAAG,QAAO,YAAW;AAC1C,SAAQC,QAAQ,QAAO,cAAa;AACpC,SAAQC,QAAQ,QAAO,uBAAsB;AAE7C,SAAQC,eAAe,EAAEC,QAAQ,QAAO,mBAAkB;AAC1D,SAAQC,kBAAkB,EAAEC,gBAAgB,QAAO,6BAA4B;AAC/E,SAAQC,CAAC,QAAO,MAAK;AAErB,MAAMC,QAAQJ,SAAS;AAEvB,MAAMK,mBAAmB;IACvB,qDAAqD;IACrD;CACD;AAED,MAAMC,UAA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AE,OAC7B,GAAGA,QAAQ,CAAC,EAAET,YAAY,CAAC,CAAC,EAAE9D,MAAM,CAAC,CAAC,GAAGA,OAAO;YAEpD;YAEA,OAAOqE;QACT;QAEA,IAAIK,aAAaxB;QACjB,MAAMyB,OAAO;YACX;gBAACV,SAAS3E,QAAQsF,UAAU;gBAAE5E,OAAOwD;YAAS;YAC9C;gBAACS,SAAS3E,QAAQuF,OAAO;gBAAE7E,OAAOuD;YAAO;YACzC;gBAACU,SAAS3E,QAAQC,UAAU;gBAAES,OAAOyD;YAAS;YAC9C;gBAACQ,SAAS3E,QAAQE,WAAW;gBAAEQ,OAAO0D;YAAU;SACjD;QACD,MAAMI,YAAYZ,gBAAgB1B,QAAQ,CAAC;QAE3C,KAAK,MAAM,EAACyC,OAAO,EAAEjE,KAAK,EAAC,IAAI2E,KAAM;YACnCD,aAAaf,uBAAuBe,YAAYT,SAASjE,OAAO8D;QAClE;QAEA,MAAMrF,UAAUC,KAAKwD,MAAMmB,aAAaqB;IAC1C,EAAE,OAAOI,KAAK;QACZ1F,MAAM,CAAC,qCAAqC,EAAE0F,KAAK;QACnD,MAAM,IAAI1D,MACR,uMACA;YAAC2D,OAAOD;QAAG;IAEf;AACF;AAEA,OAAO,eAAeE,oBAAoB9C,IAAY,EAAErC,IAAY;IAClE,IAAI;QACF,MAAMoF,MAAM,MAAMlG,gBAAgBL,KAAKwD,MAAM;QAC7C+C,IAAIpF,IAAI,GAAGA;QAEX,MAAMpB,UAAUC,KAAKwD,MAAM,iBAAiBgD,KAAKC,SAAS,CAACF,KAAK,MAAM;IACxE,EAAE,OAAM;IACN,OAAO;IACT;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/init/remoteTemplate.ts"],"sourcesContent":["import {access, readFile, writeFile} from 'node:fs/promises'\nimport {join, posix, sep} from 'node:path'\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","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AEf;AACF;AAEA,OAAO,eAAeE,oBAAoB9C,IAAY,EAAErC,IAAY;IAClE,IAAI;QACF,MAAMoF,MAAM,MAAMlG,gBAAgBL,KAAKwD,MAAM;QAC7C+C,IAAIpF,IAAI,GAAGA;QAEX,MAAMpB,UAAUC,KAAKwD,MAAM,iBAAiBgD,KAAKC,SAAS,CAACF,KAAK,MAAM;IACxE,EAAE,OAAM;IACN,OAAO;IACT;AACF"}
|
|
@@ -177,7 +177,7 @@ function printFieldModule(definition) {
|
|
|
177
177
|
return `import {${imports}} from 'sanity'\n\nexport default defineField(${literal})\n`;
|
|
178
178
|
}
|
|
179
179
|
function quote(value) {
|
|
180
|
-
const escaped = value.replaceAll('\\',
|
|
180
|
+
const escaped = value.replaceAll('\\', String.raw`\\`).replaceAll("'", String.raw`\'`).replaceAll('\n', String.raw`\n`).replaceAll('\r', String.raw`\r`).replaceAll('\t', String.raw`\t`);
|
|
181
181
|
return `'${escaped}'`;
|
|
182
182
|
}
|
|
183
183
|
function printKey(key) {
|