@sanity/cli 8.28.1 → 8.29.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/actions/build/buildApp.js +1 -0
- package/dist/actions/build/buildApp.js.map +1 -1
- package/dist/actions/build/buildStudio.js +1 -0
- package/dist/actions/build/buildStudio.js.map +1 -1
- package/dist/actions/deploy/createUserApplication.js +4 -1
- package/dist/actions/deploy/createUserApplication.js.map +1 -1
- package/dist/actions/deploy/deployChecks.js +3 -2
- package/dist/actions/deploy/deployChecks.js.map +1 -1
- package/dist/actions/deploy/deployRunner.js +3 -2
- package/dist/actions/deploy/deployRunner.js.map +1 -1
- package/dist/actions/deploy/findUserApplication.js +4 -3
- package/dist/actions/deploy/findUserApplication.js.map +1 -1
- package/dist/actions/deploy/serviceUnavailable.js +49 -0
- package/dist/actions/deploy/serviceUnavailable.js.map +1 -0
- package/dist/actions/dev/servers/getDevServerConfig.js +1 -0
- package/dist/actions/dev/servers/getDevServerConfig.js.map +1 -1
- package/dist/actions/documents/validateDocuments.worker.js +27 -27
- package/dist/actions/documents/validateDocuments.worker.js.map +1 -1
- package/dist/actions/skills/readSkillState.js +21 -34
- package/dist/actions/skills/readSkillState.js.map +1 -1
- package/dist/actions/skills/setupSkills.js +36 -36
- package/dist/actions/skills/setupSkills.js.map +1 -1
- package/dist/exports/runtime.d.ts +2 -2
- package/dist/exports/runtime.js +1 -1
- package/dist/exports/runtime.js.map +1 -1
- package/dist/generated/apiRoutes.js +12 -0
- package/dist/generated/apiRoutes.js.map +1 -1
- package/dist/server/devServer.js +2 -1
- package/dist/server/devServer.js.map +1 -1
- package/oclif.manifest.json +2152 -2152
- package/package.json +20 -18
|
@@ -37,6 +37,7 @@ export function getDevServerConfig({ cliConfig, flags, httpPort, output, workDir
|
|
|
37
37
|
return {
|
|
38
38
|
...baseConfig,
|
|
39
39
|
bundledDev,
|
|
40
|
+
documentComponent: cliConfig?.unstable_documentComponent,
|
|
40
41
|
// The app's navigable entry. A branded app that omits `entry` has no app
|
|
41
42
|
// view: the runtime/federation skip the `./App` render path entirely.
|
|
42
43
|
entry: resolveAppEntry(app),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/actions/dev/servers/getDevServerConfig.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {type CliConfig, getSanityEnvVar, type Output} from '@sanity/cli-core'\nimport {logSymbols, spinner} from '@sanity/cli-core/ux'\nimport {isWorkbenchApp} from '@sanity/workbench-cli'\nimport {resolveAppEntry, resolveWorkbenchConfig} from '@sanity/workbench-cli/build'\n\nimport {type DevServerOptions} from '../../../server/devServer.js'\nimport {determineIsApp} from '../../../util/determineIsApp.js'\nimport {getSharedServerConfig} from '../../../util/getSharedServerConfig.js'\nimport {resolveReactStrictMode} from '../../../util/resolveReactStrictMode.js'\nimport {type DevFlags} from '../types.js'\n\nexport function getDevServerConfig({\n cliConfig,\n flags,\n httpPort,\n output,\n workDir,\n}: {\n cliConfig?: CliConfig\n flags: DevFlags\n httpPort?: number\n output: Output\n workDir: string\n}): Omit<DevServerOptions, 'spinner'> {\n const configSpinner = spinner('Checking configuration files...')\n\n const baseConfig = getSharedServerConfig({\n cliConfig,\n flags: {\n host: flags.host,\n port: flags.port,\n },\n workDir,\n })\n\n configSpinner.succeed()\n\n const isApp = cliConfig ? determineIsApp(cliConfig) : false\n const reactStrictMode = resolveReactStrictMode(cliConfig)\n // `views`/`webWorkers` are declared via `defineApplication`, so read them off\n // the branded app result rather than the legacy `app` config type. A config is\n // not an app — it resolves separately and expands only its `fields`.\n const app = cliConfig?.app\n const workbenchConfig = resolveWorkbenchConfig(cliConfig)\n\n const envBasePath = getSanityEnvVar('BASEPATH', isApp ?? false)\n if (envBasePath && cliConfig?.project?.basePath) {\n output.warn(\n `Overriding configured base path (${cliConfig.project.basePath}) with value from environment variable (${envBasePath})`,\n )\n }\n\n // Unstable opt-in to Vite's experimental bundled dev mode, via\n // `unstable_bundledDev` in sanity.cli.ts. Defaults to off.\n const bundledDev = cliConfig?.unstable_bundledDev ?? false\n if (bundledDev) {\n output.log(`${logSymbols.info} Running dev server with experimental Vite bundled dev mode`)\n }\n\n return {\n ...baseConfig,\n bundledDev,\n // The app's navigable entry. A branded app that omits `entry` has no app\n // view: the runtime/federation skip the `./App` render path entirely.\n entry: resolveAppEntry(app),\n exposes: isWorkbenchApp(app)\n ? {views: app.views, webWorkers: app.webWorkers}\n : workbenchConfig\n ? {config: {appType: workbenchConfig.appType, fields: workbenchConfig.fields}}\n : undefined,\n // `devAction` passes an explicit port when a running workbench claimed the\n // configured one; otherwise the shared resolution stands.\n httpPort: httpPort ?? baseConfig.httpPort,\n isWorkbenchApp: isWorkbenchApp(app) || !!workbenchConfig,\n reactCompiler: cliConfig && 'reactCompiler' in cliConfig ? cliConfig.reactCompiler : undefined,\n reactStrictMode,\n staticPath: path.join(workDir, 'static'),\n typegen: cliConfig?.typegen,\n workbenchAppId: isWorkbenchApp(app) ? app.slug : undefined,\n }\n}\n"],"names":["path","getSanityEnvVar","logSymbols","spinner","isWorkbenchApp","resolveAppEntry","resolveWorkbenchConfig","determineIsApp","getSharedServerConfig","resolveReactStrictMode","getDevServerConfig","cliConfig","flags","httpPort","output","workDir","configSpinner","baseConfig","host","port","succeed","isApp","reactStrictMode","app","workbenchConfig","envBasePath","project","basePath","warn","bundledDev","unstable_bundledDev","log","info","entry","exposes","views","webWorkers","config","appType","fields","undefined","reactCompiler","staticPath","join","typegen","workbenchAppId","slug"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAE5B,SAAwBC,eAAe,QAAoB,mBAAkB;AAC7E,SAAQC,UAAU,EAAEC,OAAO,QAAO,sBAAqB;AACvD,SAAQC,cAAc,QAAO,wBAAuB;AACpD,SAAQC,eAAe,EAAEC,sBAAsB,QAAO,8BAA6B;AAGnF,SAAQC,cAAc,QAAO,kCAAiC;AAC9D,SAAQC,qBAAqB,QAAO,yCAAwC;AAC5E,SAAQC,sBAAsB,QAAO,0CAAyC;AAG9E,OAAO,SAASC,mBAAmB,EACjCC,SAAS,EACTC,KAAK,EACLC,QAAQ,EACRC,MAAM,EACNC,OAAO,EAOR;IACC,MAAMC,gBAAgBb,QAAQ;IAE9B,MAAMc,aAAaT,sBAAsB;QACvCG;QACAC,OAAO;YACLM,MAAMN,MAAMM,IAAI;YAChBC,MAAMP,MAAMO,IAAI;QAClB;QACAJ;IACF;IAEAC,cAAcI,OAAO;IAErB,MAAMC,QAAQV,YAAYJ,eAAeI,aAAa;IACtD,MAAMW,kBAAkBb,uBAAuBE;IAC/C,8EAA8E;IAC9E,+EAA+E;IAC/E,qEAAqE;IACrE,MAAMY,MAAMZ,WAAWY;IACvB,MAAMC,kBAAkBlB,uBAAuBK;IAE/C,MAAMc,cAAcxB,gBAAgB,YAAYoB,SAAS;IACzD,IAAII,eAAed,WAAWe,SAASC,UAAU;QAC/Cb,OAAOc,IAAI,CACT,CAAC,iCAAiC,EAAEjB,UAAUe,OAAO,CAACC,QAAQ,CAAC,wCAAwC,EAAEF,YAAY,CAAC,CAAC;IAE3H;IAEA,+DAA+D;IAC/D,2DAA2D;IAC3D,MAAMI,aAAalB,WAAWmB,uBAAuB;IACrD,IAAID,YAAY;QACdf,OAAOiB,GAAG,CAAC,GAAG7B,WAAW8B,IAAI,CAAC,2DAA2D,CAAC;IAC5F;IAEA,OAAO;QACL,GAAGf,UAAU;QACbY;
|
|
1
|
+
{"version":3,"sources":["../../../../src/actions/dev/servers/getDevServerConfig.ts"],"sourcesContent":["import path from 'node:path'\n\nimport {type CliConfig, getSanityEnvVar, type Output} from '@sanity/cli-core'\nimport {logSymbols, spinner} from '@sanity/cli-core/ux'\nimport {isWorkbenchApp} from '@sanity/workbench-cli'\nimport {resolveAppEntry, resolveWorkbenchConfig} from '@sanity/workbench-cli/build'\n\nimport {type DevServerOptions} from '../../../server/devServer.js'\nimport {determineIsApp} from '../../../util/determineIsApp.js'\nimport {getSharedServerConfig} from '../../../util/getSharedServerConfig.js'\nimport {resolveReactStrictMode} from '../../../util/resolveReactStrictMode.js'\nimport {type DevFlags} from '../types.js'\n\nexport function getDevServerConfig({\n cliConfig,\n flags,\n httpPort,\n output,\n workDir,\n}: {\n cliConfig?: CliConfig\n flags: DevFlags\n httpPort?: number\n output: Output\n workDir: string\n}): Omit<DevServerOptions, 'spinner'> {\n const configSpinner = spinner('Checking configuration files...')\n\n const baseConfig = getSharedServerConfig({\n cliConfig,\n flags: {\n host: flags.host,\n port: flags.port,\n },\n workDir,\n })\n\n configSpinner.succeed()\n\n const isApp = cliConfig ? determineIsApp(cliConfig) : false\n const reactStrictMode = resolveReactStrictMode(cliConfig)\n // `views`/`webWorkers` are declared via `defineApplication`, so read them off\n // the branded app result rather than the legacy `app` config type. A config is\n // not an app — it resolves separately and expands only its `fields`.\n const app = cliConfig?.app\n const workbenchConfig = resolveWorkbenchConfig(cliConfig)\n\n const envBasePath = getSanityEnvVar('BASEPATH', isApp ?? false)\n if (envBasePath && cliConfig?.project?.basePath) {\n output.warn(\n `Overriding configured base path (${cliConfig.project.basePath}) with value from environment variable (${envBasePath})`,\n )\n }\n\n // Unstable opt-in to Vite's experimental bundled dev mode, via\n // `unstable_bundledDev` in sanity.cli.ts. Defaults to off.\n const bundledDev = cliConfig?.unstable_bundledDev ?? false\n if (bundledDev) {\n output.log(`${logSymbols.info} Running dev server with experimental Vite bundled dev mode`)\n }\n\n return {\n ...baseConfig,\n bundledDev,\n documentComponent: cliConfig?.unstable_documentComponent,\n // The app's navigable entry. A branded app that omits `entry` has no app\n // view: the runtime/federation skip the `./App` render path entirely.\n entry: resolveAppEntry(app),\n exposes: isWorkbenchApp(app)\n ? {views: app.views, webWorkers: app.webWorkers}\n : workbenchConfig\n ? {config: {appType: workbenchConfig.appType, fields: workbenchConfig.fields}}\n : undefined,\n // `devAction` passes an explicit port when a running workbench claimed the\n // configured one; otherwise the shared resolution stands.\n httpPort: httpPort ?? baseConfig.httpPort,\n isWorkbenchApp: isWorkbenchApp(app) || !!workbenchConfig,\n reactCompiler: cliConfig && 'reactCompiler' in cliConfig ? cliConfig.reactCompiler : undefined,\n reactStrictMode,\n staticPath: path.join(workDir, 'static'),\n typegen: cliConfig?.typegen,\n workbenchAppId: isWorkbenchApp(app) ? app.slug : undefined,\n }\n}\n"],"names":["path","getSanityEnvVar","logSymbols","spinner","isWorkbenchApp","resolveAppEntry","resolveWorkbenchConfig","determineIsApp","getSharedServerConfig","resolveReactStrictMode","getDevServerConfig","cliConfig","flags","httpPort","output","workDir","configSpinner","baseConfig","host","port","succeed","isApp","reactStrictMode","app","workbenchConfig","envBasePath","project","basePath","warn","bundledDev","unstable_bundledDev","log","info","documentComponent","unstable_documentComponent","entry","exposes","views","webWorkers","config","appType","fields","undefined","reactCompiler","staticPath","join","typegen","workbenchAppId","slug"],"mappings":"AAAA,OAAOA,UAAU,YAAW;AAE5B,SAAwBC,eAAe,QAAoB,mBAAkB;AAC7E,SAAQC,UAAU,EAAEC,OAAO,QAAO,sBAAqB;AACvD,SAAQC,cAAc,QAAO,wBAAuB;AACpD,SAAQC,eAAe,EAAEC,sBAAsB,QAAO,8BAA6B;AAGnF,SAAQC,cAAc,QAAO,kCAAiC;AAC9D,SAAQC,qBAAqB,QAAO,yCAAwC;AAC5E,SAAQC,sBAAsB,QAAO,0CAAyC;AAG9E,OAAO,SAASC,mBAAmB,EACjCC,SAAS,EACTC,KAAK,EACLC,QAAQ,EACRC,MAAM,EACNC,OAAO,EAOR;IACC,MAAMC,gBAAgBb,QAAQ;IAE9B,MAAMc,aAAaT,sBAAsB;QACvCG;QACAC,OAAO;YACLM,MAAMN,MAAMM,IAAI;YAChBC,MAAMP,MAAMO,IAAI;QAClB;QACAJ;IACF;IAEAC,cAAcI,OAAO;IAErB,MAAMC,QAAQV,YAAYJ,eAAeI,aAAa;IACtD,MAAMW,kBAAkBb,uBAAuBE;IAC/C,8EAA8E;IAC9E,+EAA+E;IAC/E,qEAAqE;IACrE,MAAMY,MAAMZ,WAAWY;IACvB,MAAMC,kBAAkBlB,uBAAuBK;IAE/C,MAAMc,cAAcxB,gBAAgB,YAAYoB,SAAS;IACzD,IAAII,eAAed,WAAWe,SAASC,UAAU;QAC/Cb,OAAOc,IAAI,CACT,CAAC,iCAAiC,EAAEjB,UAAUe,OAAO,CAACC,QAAQ,CAAC,wCAAwC,EAAEF,YAAY,CAAC,CAAC;IAE3H;IAEA,+DAA+D;IAC/D,2DAA2D;IAC3D,MAAMI,aAAalB,WAAWmB,uBAAuB;IACrD,IAAID,YAAY;QACdf,OAAOiB,GAAG,CAAC,GAAG7B,WAAW8B,IAAI,CAAC,2DAA2D,CAAC;IAC5F;IAEA,OAAO;QACL,GAAGf,UAAU;QACbY;QACAI,mBAAmBtB,WAAWuB;QAC9B,yEAAyE;QACzE,sEAAsE;QACtEC,OAAO9B,gBAAgBkB;QACvBa,SAAShC,eAAemB,OACpB;YAACc,OAAOd,IAAIc,KAAK;YAAEC,YAAYf,IAAIe,UAAU;QAAA,IAC7Cd,kBACE;YAACe,QAAQ;gBAACC,SAAShB,gBAAgBgB,OAAO;gBAAEC,QAAQjB,gBAAgBiB,MAAM;YAAA;QAAC,IAC3EC;QACN,2EAA2E;QAC3E,0DAA0D;QAC1D7B,UAAUA,YAAYI,WAAWJ,QAAQ;QACzCT,gBAAgBA,eAAemB,QAAQ,CAAC,CAACC;QACzCmB,eAAehC,aAAa,mBAAmBA,YAAYA,UAAUgC,aAAa,GAAGD;QACrFpB;QACAsB,YAAY5C,KAAK6C,IAAI,CAAC9B,SAAS;QAC/B+B,SAASnC,WAAWmC;QACpBC,gBAAgB3C,eAAemB,OAAOA,IAAIyB,IAAI,GAAGN;IACnD;AACF"}
|
|
@@ -4,8 +4,10 @@ import path from 'node:path';
|
|
|
4
4
|
import readline from 'node:readline';
|
|
5
5
|
import { Readable } from 'node:stream';
|
|
6
6
|
import { workerData as _workerData, isMainThread, parentPort } from 'node:worker_threads';
|
|
7
|
-
import { getStudioWorkspaces, getWorkspace
|
|
7
|
+
import { getStudioWorkspaces, getWorkspace } from '@sanity/cli-core';
|
|
8
8
|
import { createClient } from '@sanity/client';
|
|
9
|
+
import { createClientConcurrencyLimiter } from '@sanity/util/client';
|
|
10
|
+
import { validateDocument } from '@sanity/validation';
|
|
9
11
|
import { WorkerChannelReporter } from '@sanity/worker-channels';
|
|
10
12
|
import pMap from 'p-map';
|
|
11
13
|
import { checkDocumentAvailability, exportDocuments, getDocumentCount } from '../../services/documents.js';
|
|
@@ -128,16 +130,12 @@ async function downloadFromFile(filePath) {
|
|
|
128
130
|
referencedIds
|
|
129
131
|
};
|
|
130
132
|
}
|
|
131
|
-
async function checkReferenceExistence({ dataset: datasetName, documentIds, projectId: projId, referencedIds: _referencedIds }) {
|
|
132
|
-
const existingIds = new Set(documentIds);
|
|
133
|
+
async function checkReferenceExistence({ dataset: datasetName, documentIds: existingIds, projectId: projId, referencedIds: _referencedIds }) {
|
|
133
134
|
const idsToCheck = [
|
|
134
135
|
..._referencedIds
|
|
135
136
|
].filter((id)=>!existingIds.has(id) && isValidId(id)).toSorted();
|
|
136
|
-
const batches = [];
|
|
137
137
|
for(let i = 0; i < idsToCheck.length; i += REFERENCE_INTEGRITY_BATCH_SIZE){
|
|
138
|
-
|
|
139
|
-
}
|
|
140
|
-
for (const batch of batches){
|
|
138
|
+
const batch = idsToCheck.slice(i, i + REFERENCE_INTEGRITY_BATCH_SIZE);
|
|
141
139
|
const { omitted } = await checkDocumentAvailability({
|
|
142
140
|
dataset: datasetName,
|
|
143
141
|
documentIds: batch,
|
|
@@ -175,8 +173,6 @@ async function main() {
|
|
|
175
173
|
projectId: projId,
|
|
176
174
|
referencedIds
|
|
177
175
|
});
|
|
178
|
-
const getClient = (options)=>client.withConfig(options);
|
|
179
|
-
const getDocumentExists = ({ id })=>Promise.resolve(existingIds.has(id));
|
|
180
176
|
const getLevel = (markers)=>{
|
|
181
177
|
let foundWarning = false;
|
|
182
178
|
for (const marker of markers){
|
|
@@ -186,33 +182,37 @@ async function main() {
|
|
|
186
182
|
if (foundWarning) return 'warning';
|
|
187
183
|
return 'info';
|
|
188
184
|
};
|
|
185
|
+
// Share the fetch limit across documents, including clients reconfigured by validators.
|
|
186
|
+
const validationClient = createClientConcurrencyLimiter(maxFetchConcurrency ?? 25)(client);
|
|
189
187
|
let validatedCount = 0;
|
|
190
188
|
const validate = async (document)=>{
|
|
191
189
|
let markers;
|
|
192
190
|
try {
|
|
193
|
-
const
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
]);
|
|
207
|
-
if (result === timeout) {
|
|
208
|
-
throw new Error(`Document '${document._id}' failed to validate within ${DOCUMENT_VALIDATION_TIMEOUT}ms.`);
|
|
209
|
-
}
|
|
210
|
-
markers = result// filter out unwanted levels
|
|
191
|
+
const result = await validateDocument({
|
|
192
|
+
client: validationClient,
|
|
193
|
+
document,
|
|
194
|
+
getDocumentExists: ({ id })=>Promise.resolve(existingIds.has(id)),
|
|
195
|
+
i18n: workspace.i18n,
|
|
196
|
+
maxCustomValidationConcurrency,
|
|
197
|
+
maxFetchConcurrency,
|
|
198
|
+
schema: workspace.schema,
|
|
199
|
+
signal: AbortSignal.timeout(DOCUMENT_VALIDATION_TIMEOUT),
|
|
200
|
+
// Referenced documents can exist only in the input, without a live API counterpart
|
|
201
|
+
validateReferenceTypes: false
|
|
202
|
+
});
|
|
203
|
+
markers = result.markers// filter out unwanted levels
|
|
211
204
|
.filter((marker)=>{
|
|
212
205
|
const markerValue = levelValues[marker.level];
|
|
213
206
|
const flagLevelValue = levelValues[level] ?? levelValues.info;
|
|
214
207
|
return markerValue <= flagLevelValue;
|
|
215
208
|
});
|
|
209
|
+
if (!result.complete && !markers.some((marker)=>marker.level === 'error')) {
|
|
210
|
+
markers.push({
|
|
211
|
+
level: 'error',
|
|
212
|
+
message: 'Document validation is incomplete. Check the schema and any reported validation errors, then rerun this command.',
|
|
213
|
+
path: []
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
216
|
} catch (err) {
|
|
217
217
|
const errorMessage = err instanceof Error ? err.message : 'Unknown error';
|
|
218
218
|
const message = `Exception occurred while validating value: ${errorMessage}`;
|
|
@@ -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, resolveLocalPackage} from '@sanity/cli-core'\nimport {type ClientConfig, createClient, type SanityDocument} from '@sanity/client'\nimport {type ValidationContext, type ValidationMarker} from '@sanity/types'\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 Set<string>()\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.add(document._id)\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 Set<string>()\n const getDocuments = () => extractDocumentsFromNdjsonOrTarball(fs.createReadStream(filePath))\n\n for await (const document of getDocuments()) {\n if (shouldIncludeDocument(document)) {\n documentIds.add(document._id)\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: Set<string>\n projectId: string\n referencedIds: Set<string>\n}\n\nasync function checkReferenceExistence({\n dataset: datasetName,\n documentIds,\n projectId: projId,\n referencedIds: _referencedIds,\n}: CheckReferenceExistenceOptions) {\n const existingIds = new Set(documentIds)\n const idsToCheck = [..._referencedIds]\n .filter((id) => !existingIds.has(id) && isValidId(id))\n .toSorted()\n\n const batches: string[][] = []\n for (let i = 0; i < idsToCheck.length; i += REFERENCE_INTEGRITY_BATCH_SIZE) {\n batches.push(idsToCheck.slice(i, i + REFERENCE_INTEGRITY_BATCH_SIZE))\n }\n\n for (const batch of batches) {\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.add(id)\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 getClient = <TOptions extends Partial<ClientConfig>>(options: TOptions) =>\n client.withConfig(options)\n\n const getDocumentExists: ValidationContext['getDocumentExists'] = ({id}) =>\n Promise.resolve(existingIds.has(id))\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 let validatedCount = 0\n\n const validate = async (document: SanityDocument) => {\n let markers: ValidationMarker[]\n\n try {\n const timeout = Symbol('timeout')\n\n const {validateDocument} = await resolveLocalPackage<typeof import('sanity')>(\n 'sanity',\n workDir,\n )\n\n const result = await Promise.race([\n validateDocument({\n document,\n environment: 'cli',\n getClient,\n getDocumentExists,\n maxCustomValidationConcurrency,\n maxFetchConcurrency,\n workspace,\n }),\n new Promise<typeof timeout>((resolve) =>\n setTimeout(() => resolve(timeout), DOCUMENT_VALIDATION_TIMEOUT),\n ),\n ])\n\n if (result === timeout) {\n throw new Error(\n `Document '${document._id}' failed to validate within ${DOCUMENT_VALIDATION_TIMEOUT}ms.`,\n )\n }\n\n markers = result\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 } 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","resolveLocalPackage","createClient","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","lines","createInterface","input","slugDate","Date","toISOString","replaceAll","toLowerCase","tempOutputFile","join","tmpdir","outputStream","createWriteStream","line","document","JSON","parse","add","_id","referenceId","write","stream","exportProgress","emit","Promise","resolve","reject","close","err","end","exportFinished","totalDocumentsToValidate","size","getDocuments","createReadStream","cleanup","promises","rm","downloadFromFile","filePath","undefined","checkReferenceExistence","_referencedIds","existingIds","idsToCheck","filter","id","has","toSorted","batches","i","length","push","slice","batch","omitted","omittedIds","item","reason","loadedReferenceIntegrity","cleanupDownloadedDocuments","getClient","options","withConfig","getDocumentExists","getLevel","markers","foundWarning","marker","validatedCount","validate","timeout","Symbol","validateDocument","result","race","environment","setTimeout","markerValue","flagLevelValue","info","errorMessage","message","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,EAAEC,mBAAmB,QAAO,mBAAkB;AACvF,SAA2BC,YAAY,QAA4B,iBAAgB;AAEnF,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,GAAG9B;AAEJ,IAAIC,gBAAgB,CAACC,YAAY;IAC/B,MAAM,IAAI6B,MAAM;AAClB;AAEA,MAAMC,SAASzB,sBAAsB0B,IAAI,CAA0B/B;AAEnE,mEAAmE;AACnE,gBAAgBgC,kBAAkBC,MAA+C;IAC/E,MAAO,K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H,WAAWH,SAAS;oBACtB,MAAM,IAAI1G,MACR,CAAC,UAAU,EAAEiD,SAASI,GAAG,CAAC,4BAA4B,EAAEvE,4BAA4B,GAAG,CAAC;gBAE5F;gBAEAuH,UAAUQ,MACR,6BAA6B;iBAC5B7B,MAAM,CAAC,CAACuB;oBACP,MAAMU,cAAchI,WAAW,CAACsH,OAAOhH,KAAK,CAAC;oBAC7C,MAAM2H,iBACJjI,WAAW,CAACM,MAAkC,IAAIN,YAAYkI,IAAI;oBACpE,OAAOF,eAAeC;gBACxB;YACJ,EAAE,OAAOnD,KAAK;gBACZ,MAAMqD,eAAerD,eAAe/D,QAAQ+D,IAAIsD,OAAO,GAAG;gBAE1D,MAAMA,UAAU,CAAC,2CAA2C,EAAED,cAAc;gBAE5Ef,UAAU;oBACR;wBACE9G,OAAO;wBACP8H;wBACAxJ,MAAM,EAAE;oBACV;iBACD;YACH;YAEA2I;YAEA,MAAMc,YACJ1H,cACA,GAAGA,aAAa/B,KAAK+F,OAAO,CAC1B9D,UAAUuB,QAAQ,EAClB,CAAC,gBAAgB,EAAEkG,mBAAmBtE,SAASI,GAAG,EAAE,MAAM,EAAEkE,mBAC1DtE,SAASuE,KAAK,GACb,GACF;YAELvH,OAAOuD,MAAM,CAACiE,UAAU,CAAC/D,IAAI,CAAC;gBAC5BgE,YAAYzE,SAASI,GAAG;gBACxBsE,cAAc1E,SAASuE,KAAK;gBAC5B,GAAIF,aAAa;oBAACA;gBAAS,CAAC;gBAC5B/H,OAAO6G,SAASC;gBAChBA;gBACAuB,UAAU3E,SAAS4E,IAAI;gBACvBrB;YACF;QACF;QAEA,MAAM/H,KAAK2F,gBAAgBqC,UAAU;YAACqB,aAAa5I;QAA0B;QAE7Ee,OAAOuD,MAAM,CAACiE,UAAU,CAACzD,GAAG;IAC9B,SAAU;QACR,MAAM+B;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} 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 Set<string>()\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.add(document._id)\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 Set<string>()\n const getDocuments = () => extractDocumentsFromNdjsonOrTarball(fs.createReadStream(filePath))\n\n for await (const document of getDocuments()) {\n if (shouldIncludeDocument(document)) {\n documentIds.add(document._id)\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: Set<string>\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.add(id)\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: ({id}) => Promise.resolve(existingIds.has(id)),\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","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","lines","createInterface","input","slugDate","Date","toISOString","replaceAll","toLowerCase","tempOutputFile","join","tmpdir","outputStream","createWriteStream","line","document","JSON","parse","add","_id","referenceId","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","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;A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e/D,QAAQ+D,IAAIoD,OAAO,GAAG;gBAE1D,MAAMA,UAAU,CAAC,2CAA2C,EAAEC,cAAc;gBAE5ErB,UAAU;oBACR;wBACExG,OAAO;wBACP4H;wBACAvJ,MAAM,EAAE;oBACV;iBACD;YACH;YAEAuI;YAEA,MAAMkB,YACJzH,cACA,GAAGA,aAAahC,KAAKgG,OAAO,CAC1B9D,UAAUuB,QAAQ,EAClB,CAAC,gBAAgB,EAAEiG,mBAAmBrE,SAASI,GAAG,EAAE,MAAM,EAAEiE,mBAC1DrE,SAASsE,KAAK,GACb,GACF;YAELtH,OAAOuD,MAAM,CAACgE,UAAU,CAAC9D,IAAI,CAAC;gBAC5B+D,YAAYxE,SAASI,GAAG;gBACxBqE,cAAczE,SAASsE,KAAK;gBAC5B,GAAIF,aAAa;oBAACA;gBAAS,CAAC;gBAC5B9H,OAAOuG,SAASC;gBAChBA;gBACA4B,UAAU1E,SAAS2E,IAAI;gBACvBzB;YACF;QACF;QAEA,MAAM1H,KAAK2F,gBAAgBgC,UAAU;YAACyB,aAAa3I;QAA0B;QAE7Ee,OAAOuD,MAAM,CAACgE,UAAU,CAACxD,GAAG;IAC9B,SAAU;QACR,MAAM6B;IACR;AACF"}
|
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
import { subdebug } from '@sanity/cli-core';
|
|
2
|
-
import {
|
|
3
|
-
import { getSkillsCliAgentDisplayName, isUniversalSkillsCliAgentByEditorName, UNIVERSAL_SKILLS_DIR } from '../mcp/editorConfigs.js';
|
|
4
|
-
import { SKILLS_BIN_PATH } from './setupSkills.js';
|
|
2
|
+
import { getSkillsCliAgentDisplayName, getSkillsCliAgentDisplayNameById, isUniversalSkillsCliAgentByEditorName, UNIVERSAL_SKILLS_DIR } from '../mcp/editorConfigs.js';
|
|
5
3
|
const debug = subdebug('skills:state');
|
|
4
|
+
/** Upper bound for reading the global skill state (checked between steps). */ const LIST_TIMEOUT_MS = 10_000;
|
|
6
5
|
/** Normalizes path separators to `/` so comparisons are OS-agnostic. */ function toPosixPath(value) {
|
|
7
6
|
return value.replaceAll('\\', '/');
|
|
8
7
|
}
|
|
@@ -11,22 +10,22 @@ const debug = subdebug('skills:state');
|
|
|
11
10
|
* path is under `.agents/skills`. The `skills` CLI installs universal-agent
|
|
12
11
|
* skills there directly (rather than under an agent-specific directory).
|
|
13
12
|
*/ function isUniversalSkillPath(skillPath) {
|
|
14
|
-
if (typeof skillPath !== 'string') return false;
|
|
15
13
|
return toPosixPath(skillPath).includes(`${UNIVERSAL_SKILLS_DIR}/`);
|
|
16
14
|
}
|
|
17
15
|
/**
|
|
18
|
-
*
|
|
19
|
-
* display names that have every skill in
|
|
16
|
+
* Lists global skills via the bundled `skills` package's `listSkills` and
|
|
17
|
+
* returns the set of agent display names that have every skill in
|
|
18
|
+
* `skillNames` installed globally.
|
|
20
19
|
* Agents missing any of the skills are excluded, so they get a (idempotent)
|
|
21
20
|
* re-install that fills the gap.
|
|
22
21
|
*
|
|
23
22
|
* "Universal" agents (those whose `skillsDir` is the shared `.agents/skills`
|
|
24
23
|
* directory) are credited whenever every requested skill lives in that shared
|
|
25
|
-
* directory. `
|
|
24
|
+
* directory. `listSkills` only attributes a skill to agents it independently
|
|
26
25
|
* detects, so a universal editor we detected may be absent from the output even
|
|
27
26
|
* though it reads from the shared directory and already has the skills.
|
|
28
27
|
*
|
|
29
|
-
* Any failure (
|
|
28
|
+
* Any failure (import, read, timeout) is debug-logged and
|
|
30
29
|
* resolved with an empty set. Callers should treat that as "treat all agents
|
|
31
30
|
* as not installed" — re-installing is idempotent, so over-installing is
|
|
32
31
|
* safer than skipping based on a flaky probe.
|
|
@@ -35,40 +34,28 @@ const debug = subdebug('skills:state');
|
|
|
35
34
|
const empty = {
|
|
36
35
|
installedAgentDisplayNames: new Set()
|
|
37
36
|
};
|
|
38
|
-
let
|
|
37
|
+
let entries;
|
|
39
38
|
try {
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
timeout: 10_000
|
|
39
|
+
// Loaded lazily so a problem with the `skills` package only affects this
|
|
40
|
+
// best-effort probe, not every command that imports this module.
|
|
41
|
+
// eslint-disable-next-line no-restricted-syntax -- package import, not a file path
|
|
42
|
+
const { listSkills } = await import('skills');
|
|
43
|
+
const result = await listSkills({
|
|
44
|
+
scope: 'global',
|
|
45
|
+
signal: AbortSignal.timeout(LIST_TIMEOUT_MS)
|
|
48
46
|
});
|
|
49
|
-
|
|
47
|
+
entries = result.skills;
|
|
50
48
|
} catch (error) {
|
|
51
49
|
debug('skills list failed: %O', error);
|
|
52
50
|
return empty;
|
|
53
51
|
}
|
|
54
|
-
let parsed;
|
|
55
|
-
try {
|
|
56
|
-
parsed = JSON.parse(stdout);
|
|
57
|
-
} catch (error) {
|
|
58
|
-
debug('Failed to parse skills list JSON: %O', error);
|
|
59
|
-
return empty;
|
|
60
|
-
}
|
|
61
|
-
if (!Array.isArray(parsed)) {
|
|
62
|
-
debug('Unexpected skills list JSON shape (not an array)');
|
|
63
|
-
return empty;
|
|
64
|
-
}
|
|
65
|
-
const entries = parsed;
|
|
66
52
|
const agentSets = skillNames.map((skillName)=>{
|
|
67
|
-
const match = entries.find((entry)=>entry
|
|
68
|
-
if (!match
|
|
53
|
+
const match = entries.find((entry)=>entry.name === skillName);
|
|
54
|
+
if (!match) {
|
|
69
55
|
return new Set();
|
|
70
56
|
}
|
|
71
|
-
|
|
57
|
+
// `listSkills` reports agent IDs; callers match on display names.
|
|
58
|
+
return new Set(match.agents.map((agentId)=>getSkillsCliAgentDisplayNameById(agentId) ?? agentId));
|
|
72
59
|
});
|
|
73
60
|
const installed = new Set([
|
|
74
61
|
...agentSets[0] ?? []
|
|
@@ -78,7 +65,7 @@ const debug = subdebug('skills:state');
|
|
|
78
65
|
// detected universal editor that the `skills` CLI didn't independently detect
|
|
79
66
|
// would be treated as missing and trigger a redundant re-install.
|
|
80
67
|
const allSkillsInUniversalDir = skillNames.length > 0 && skillNames.every((skillName)=>{
|
|
81
|
-
const match = entries.find((entry)=>entry
|
|
68
|
+
const match = entries.find((entry)=>entry.name === skillName);
|
|
82
69
|
return match ? isUniversalSkillPath(match.path) : false;
|
|
83
70
|
});
|
|
84
71
|
if (allSkillsInUniversalDir) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/skills/readSkillState.ts"],"sourcesContent":["import {subdebug} from '@sanity/cli-core'\nimport {
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/skills/readSkillState.ts"],"sourcesContent":["import {subdebug} from '@sanity/cli-core'\nimport {type InstalledSkillInfo} from 'skills'\n\nimport {\n getSkillsCliAgentDisplayName,\n getSkillsCliAgentDisplayNameById,\n isUniversalSkillsCliAgentByEditorName,\n UNIVERSAL_SKILLS_DIR,\n} from '../mcp/editorConfigs.js'\nimport {type Editor} from '../mcp/types.js'\n\nconst debug = subdebug('skills:state')\n\ninterface ReadSkillStateOptions {\n /**\n * Detected editors. Used to credit \"universal\" agents (those that read from\n * the shared `.agents/skills` directory) when the skills live there — see\n * note in `readSkillState`.\n */\n editors: Editor[]\n /** Names of the skills to look up (match the `name` of `listSkills()` entries). */\n skillNames: string[]\n}\n\ninterface SkillState {\n /** Display names of agents that have all of these skills installed globally. */\n installedAgentDisplayNames: Set<string>\n}\n\n/** Upper bound for reading the global skill state (checked between steps). */\nconst LIST_TIMEOUT_MS = 10_000\n\n/** Normalizes path separators to `/` so comparisons are OS-agnostic. */\nfunction toPosixPath(value: string): string {\n return value.replaceAll('\\\\', '/')\n}\n\n/**\n * A skill lives in the shared universal skills directory when its canonical\n * path is under `.agents/skills`. The `skills` CLI installs universal-agent\n * skills there directly (rather than under an agent-specific directory).\n */\nfunction isUniversalSkillPath(skillPath: string): boolean {\n return toPosixPath(skillPath).includes(`${UNIVERSAL_SKILLS_DIR}/`)\n}\n\n/**\n * Lists global skills via the bundled `skills` package's `listSkills` and\n * returns the set of agent display names that have every skill in\n * `skillNames` installed globally.\n * Agents missing any of the skills are excluded, so they get a (idempotent)\n * re-install that fills the gap.\n *\n * \"Universal\" agents (those whose `skillsDir` is the shared `.agents/skills`\n * directory) are credited whenever every requested skill lives in that shared\n * directory. `listSkills` only attributes a skill to agents it independently\n * detects, so a universal editor we detected may be absent from the output even\n * though it reads from the shared directory and already has the skills.\n *\n * Any failure (import, read, timeout) is debug-logged and\n * resolved with an empty set. Callers should treat that as \"treat all agents\n * as not installed\" — re-installing is idempotent, so over-installing is\n * safer than skipping based on a flaky probe.\n */\nexport async function readSkillState(opts: ReadSkillStateOptions): Promise<SkillState> {\n const {editors, skillNames} = opts\n const empty: SkillState = {installedAgentDisplayNames: new Set()}\n\n let entries: readonly InstalledSkillInfo[]\n try {\n // Loaded lazily so a problem with the `skills` package only affects this\n // best-effort probe, not every command that imports this module.\n // eslint-disable-next-line no-restricted-syntax -- package import, not a file path\n const {listSkills} = await import('skills')\n const result = await listSkills({\n scope: 'global',\n signal: AbortSignal.timeout(LIST_TIMEOUT_MS),\n })\n entries = result.skills\n } catch (error) {\n debug('skills list failed: %O', error)\n return empty\n }\n\n const agentSets = skillNames.map((skillName) => {\n const match = entries.find((entry) => entry.name === skillName)\n if (!match) {\n return new Set<string>()\n }\n // `listSkills` reports agent IDs; callers match on display names.\n return new Set(\n match.agents.map((agentId) => getSkillsCliAgentDisplayNameById(agentId) ?? agentId),\n )\n })\n\n const installed = new Set(\n [...(agentSets[0] ?? [])].filter((agent) => agentSets.every((set) => set.has(agent))),\n )\n\n // Universal agents share the `.agents/skills` directory. If every requested\n // skill lives there, credit each detected universal editor — otherwise a\n // detected universal editor that the `skills` CLI didn't independently detect\n // would be treated as missing and trigger a redundant re-install.\n const allSkillsInUniversalDir =\n skillNames.length > 0 &&\n skillNames.every((skillName) => {\n const match = entries.find((entry) => entry.name === skillName)\n return match ? isUniversalSkillPath(match.path) : false\n })\n\n if (allSkillsInUniversalDir) {\n for (const editor of editors) {\n if (!isUniversalSkillsCliAgentByEditorName(editor.name)) continue\n const displayName = getSkillsCliAgentDisplayName(editor.name)\n if (displayName) installed.add(displayName)\n }\n }\n\n return {installedAgentDisplayNames: installed}\n}\n"],"names":["subdebug","getSkillsCliAgentDisplayName","getSkillsCliAgentDisplayNameById","isUniversalSkillsCliAgentByEditorName","UNIVERSAL_SKILLS_DIR","debug","LIST_TIMEOUT_MS","toPosixPath","value","replaceAll","isUniversalSkillPath","skillPath","includes","readSkillState","opts","editors","skillNames","empty","installedAgentDisplayNames","Set","entries","listSkills","result","scope","signal","AbortSignal","timeout","skills","error","agentSets","map","skillName","match","find","entry","name","agents","agentId","installed","filter","agent","every","set","has","allSkillsInUniversalDir","length","path","editor","displayName","add"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,mBAAkB;AAGzC,SACEC,4BAA4B,EAC5BC,gCAAgC,EAChCC,qCAAqC,EACrCC,oBAAoB,QACf,0BAAyB;AAGhC,MAAMC,QAAQL,SAAS;AAkBvB,4EAA4E,GAC5E,MAAMM,kBAAkB;AAExB,sEAAsE,GACtE,SAASC,YAAYC,KAAa;IAChC,OAAOA,MAAMC,UAAU,CAAC,MAAM;AAChC;AAEA;;;;CAIC,GACD,SAASC,qBAAqBC,SAAiB;IAC7C,OAAOJ,YAAYI,WAAWC,QAAQ,CAAC,GAAGR,qBAAqB,CAAC,CAAC;AACnE;AAEA;;;;;;;;;;;;;;;;;CAiBC,GACD,OAAO,eAAeS,eAAeC,IAA2B;IAC9D,MAAM,EAACC,OAAO,EAAEC,UAAU,EAAC,GAAGF;IAC9B,MAAMG,QAAoB;QAACC,4BAA4B,IAAIC;IAAK;IAEhE,IAAIC;IACJ,IAAI;QACF,yEAAyE;QACzE,iEAAiE;QACjE,mFAAmF;QACnF,MAAM,EAACC,UAAU,EAAC,GAAG,MAAM,MAAM,CAAC;QAClC,MAAMC,SAAS,MAAMD,WAAW;YAC9BE,OAAO;YACPC,QAAQC,YAAYC,OAAO,CAACpB;QAC9B;QACAc,UAAUE,OAAOK,MAAM;IACzB,EAAE,OAAOC,OAAO;QACdvB,MAAM,0BAA0BuB;QAChC,OAAOX;IACT;IAEA,MAAMY,YAAYb,WAAWc,GAAG,CAAC,CAACC;QAChC,MAAMC,QAAQZ,QAAQa,IAAI,CAAC,CAACC,QAAUA,MAAMC,IAAI,KAAKJ;QACrD,IAAI,CAACC,OAAO;YACV,OAAO,IAAIb;QACb;QACA,kEAAkE;QAClE,OAAO,IAAIA,IACTa,MAAMI,MAAM,CAACN,GAAG,CAAC,CAACO,UAAYnC,iCAAiCmC,YAAYA;IAE/E;IAEA,MAAMC,YAAY,IAAInB,IACpB;WAAKU,SAAS,CAAC,EAAE,IAAI,EAAE;KAAE,CAACU,MAAM,CAAC,CAACC,QAAUX,UAAUY,KAAK,CAAC,CAACC,MAAQA,IAAIC,GAAG,CAACH;IAG/E,4EAA4E;IAC5E,yEAAyE;IACzE,8EAA8E;IAC9E,kEAAkE;IAClE,MAAMI,0BACJ5B,WAAW6B,MAAM,GAAG,KACpB7B,WAAWyB,KAAK,CAAC,CAACV;QAChB,MAAMC,QAAQZ,QAAQa,IAAI,CAAC,CAACC,QAAUA,MAAMC,IAAI,KAAKJ;QACrD,OAAOC,QAAQtB,qBAAqBsB,MAAMc,IAAI,IAAI;IACpD;IAEF,IAAIF,yBAAyB;QAC3B,KAAK,MAAMG,UAAUhC,QAAS;YAC5B,IAAI,CAACZ,sCAAsC4C,OAAOZ,IAAI,GAAG;YACzD,MAAMa,cAAc/C,6BAA6B8C,OAAOZ,IAAI;YAC5D,IAAIa,aAAaV,UAAUW,GAAG,CAACD;QACjC;IACF;IAEA,OAAO;QAAC9B,4BAA4BoB;IAAS;AAC/C"}
|
|
@@ -1,21 +1,15 @@
|
|
|
1
|
-
import { fileURLToPath } from 'node:url';
|
|
2
1
|
import { styleText } from 'node:util';
|
|
3
2
|
import { subdebug } from '@sanity/cli-core';
|
|
4
3
|
import { getErrorMessage, toError } from '@sanity/cli-core/errors';
|
|
5
4
|
import { logSymbols, spinner } from '@sanity/cli-core/ux';
|
|
6
|
-
import { execa } from 'execa';
|
|
7
5
|
import { getSkillsCliAgentDisplayNameById, getSkillsCliAgentSkillsDir, UNIVERSAL_SKILLS_DIR } from '../mcp/editorConfigs.js';
|
|
8
6
|
const skillsDebug = subdebug('skills:setup');
|
|
9
|
-
/** Source repo for the bundled `skills`
|
|
7
|
+
/** Source repo for the bundled `skills` package. See https://www.sanity.io/docs/ai/skills. */ export const SANITY_SKILLS_REPO = 'sanity-io/agent-toolkit';
|
|
10
8
|
/** Names of the skills we install — must match the entries in the source repo. */ export const SANITY_SKILL_NAMES = [
|
|
11
9
|
'sanity-best-practices',
|
|
12
10
|
'sanity-migration'
|
|
13
11
|
];
|
|
14
|
-
/**
|
|
15
|
-
* Absolute path to the bundled `skills` CLI bin. Resolved once at module load
|
|
16
|
-
* via `import.meta.resolve` so we run the version pinned in our package.json
|
|
17
|
-
* instead of paying the `npx -y` registry lookup at runtime.
|
|
18
|
-
*/ export const SKILLS_BIN_PATH = fileURLToPath(import.meta.resolve('skills/bin/cli.mjs', import.meta.url));
|
|
12
|
+
/** Upper bound for fetching and installing the skills (checked between steps). */ const INSTALL_TIMEOUT_MS = 90_000;
|
|
19
13
|
/**
|
|
20
14
|
* Prints a short summary beneath the success line: the skills that were
|
|
21
15
|
* installed, grouped by where they live. Universal agents share
|
|
@@ -52,7 +46,9 @@ const skillsDebug = subdebug('skills:setup');
|
|
|
52
46
|
output.log('');
|
|
53
47
|
}
|
|
54
48
|
/**
|
|
55
|
-
*
|
|
49
|
+
* Installs the Sanity skills globally for the given agents using the bundled
|
|
50
|
+
* `skills` package's programmatic API (equivalent to
|
|
51
|
+
* `skills add <repo> --skill <names> -g -a <agent>... -y`). Failures are
|
|
56
52
|
* surfaced as warnings and never throw — skills install is best-effort and
|
|
57
53
|
* must not abort `sanity init`.
|
|
58
54
|
*/ export async function setupSkills(options) {
|
|
@@ -67,33 +63,40 @@ const skillsDebug = subdebug('skills:setup');
|
|
|
67
63
|
skipped: true
|
|
68
64
|
};
|
|
69
65
|
}
|
|
70
|
-
|
|
71
|
-
SKILLS_BIN_PATH,
|
|
72
|
-
'add',
|
|
73
|
-
SANITY_SKILLS_REPO,
|
|
74
|
-
'--skill',
|
|
75
|
-
...SANITY_SKILL_NAMES,
|
|
76
|
-
'-g',
|
|
77
|
-
...uniqueAgents.flatMap((agent)=>[
|
|
78
|
-
'-a',
|
|
79
|
-
agent
|
|
80
|
-
]),
|
|
81
|
-
'-y'
|
|
82
|
-
];
|
|
83
|
-
skillsDebug('Running: %s %s', process.execPath, args.join(' '));
|
|
66
|
+
skillsDebug('Installing %s from %s globally for agents: %s', SANITY_SKILL_NAMES.join(', '), SANITY_SKILLS_REPO, uniqueAgents.join(', '));
|
|
84
67
|
const spin = spinner('Installing Sanity agent skills').start();
|
|
85
68
|
try {
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
69
|
+
// Loaded lazily so a problem with the `skills` package only affects this
|
|
70
|
+
// best-effort step, not every command that imports this module.
|
|
71
|
+
// eslint-disable-next-line no-restricted-syntax -- package import, not a file path
|
|
72
|
+
const { installSkills } = await import('skills');
|
|
73
|
+
const result = await installSkills(SANITY_SKILLS_REPO, {
|
|
74
|
+
agents: uniqueAgents,
|
|
75
|
+
onWarning: (warning)=>skillsDebug('skills warning: %s', warning.message),
|
|
76
|
+
scope: 'global',
|
|
77
|
+
signal: AbortSignal.timeout(INSTALL_TIMEOUT_MS),
|
|
78
|
+
skills: SANITY_SKILL_NAMES
|
|
89
79
|
});
|
|
90
|
-
skillsDebug('skills
|
|
91
|
-
skillsDebug('skills stderr: %s', result.stderr);
|
|
80
|
+
skillsDebug('skills install result: %O', result);
|
|
92
81
|
spin.stop();
|
|
93
|
-
|
|
94
|
-
|
|
82
|
+
const failedAgents = new Set(result.failed.map((failure)=>failure.agent));
|
|
83
|
+
const installedAgents = uniqueAgents.filter((agent)=>!failedAgents.has(agent));
|
|
84
|
+
if (installedAgents.length > 0) {
|
|
85
|
+
output.log(`${logSymbols.success} Sanity agent skills installed: [${SANITY_SKILL_NAMES.join(', ')}]`);
|
|
86
|
+
printInstallSummary(installedAgents, output);
|
|
87
|
+
}
|
|
88
|
+
if (result.failed.length === 0) {
|
|
89
|
+
return {
|
|
90
|
+
installedAgents,
|
|
91
|
+
skipped: false
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
const failureMessages = result.failed.map((failure)=>failure.message);
|
|
95
|
+
output.warn(installedAgents.length > 0 ? 'Could not install Sanity agent skills for some agents:' : 'Could not install Sanity agent skills:');
|
|
96
|
+
for (const message of failureMessages)output.warn(message);
|
|
95
97
|
return {
|
|
96
|
-
|
|
98
|
+
error: new Error(failureMessages.join('\n')),
|
|
99
|
+
installedAgents,
|
|
97
100
|
skipped: false
|
|
98
101
|
};
|
|
99
102
|
} catch (error) {
|
|
@@ -101,11 +104,8 @@ const skillsDebug = subdebug('skills:setup');
|
|
|
101
104
|
const err = toError(error);
|
|
102
105
|
spin.stop();
|
|
103
106
|
output.warn(`Could not install Sanity agent skills: ${getErrorMessage(error)}`);
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
if (stdout) output.warn(stdout);
|
|
107
|
-
if (stderr) output.warn(stderr);
|
|
108
|
-
}
|
|
107
|
+
const fix = error?.fix;
|
|
108
|
+
if (typeof fix === 'string' && fix) output.warn(fix);
|
|
109
109
|
return {
|
|
110
110
|
error: err,
|
|
111
111
|
installedAgents: [],
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/skills/setupSkills.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/skills/setupSkills.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {type Output, subdebug} from '@sanity/cli-core'\nimport {getErrorMessage, toError} from '@sanity/cli-core/errors'\nimport {logSymbols, spinner} from '@sanity/cli-core/ux'\n\nimport {\n getSkillsCliAgentDisplayNameById,\n getSkillsCliAgentSkillsDir,\n UNIVERSAL_SKILLS_DIR,\n} from '../mcp/editorConfigs.js'\n\nconst skillsDebug = subdebug('skills:setup')\n\n/** Source repo for the bundled `skills` package. See https://www.sanity.io/docs/ai/skills. */\nexport const SANITY_SKILLS_REPO = 'sanity-io/agent-toolkit'\n\n/** Names of the skills we install — must match the entries in the source repo. */\nexport const SANITY_SKILL_NAMES = ['sanity-best-practices', 'sanity-migration']\n\n/** Upper bound for fetching and installing the skills (checked between steps). */\nconst INSTALL_TIMEOUT_MS = 90_000\n\ninterface SetupSkillsOptions {\n /** Skills-CLI agent IDs (e.g. 'cursor', 'claude-code') to install for. */\n agents: string[]\n\n /**\n * Output to use for user-facing messages, so they go through the calling\n * command rather than directly to stdout/stderr.\n */\n output: Output\n}\n\ninterface SetupSkillsResult {\n /** Deduplicated agent IDs the skills were installed for. */\n installedAgents: string[]\n skipped: boolean\n\n error?: Error\n}\n\n/**\n * Prints a short summary beneath the success line: the skills that were\n * installed, grouped by where they live. Universal agents share\n * `~/.agents/skills`, so they're listed together under one header; any agent\n * with its own directory (e.g. Claude Code) is listed separately with its\n * location. Global (`-g`) installs are home-anchored, so locations show `~/`.\n */\nfunction printInstallSummary(agents: string[], output: Output): void {\n const universal: string[] = []\n const additional: {dir: string; name: string}[] = []\n\n for (const agent of agents) {\n const name = getSkillsCliAgentDisplayNameById(agent) ?? agent\n const dir = getSkillsCliAgentSkillsDir(agent)\n if (dir && dir !== UNIVERSAL_SKILLS_DIR) {\n additional.push({dir, name})\n } else {\n universal.push(name)\n }\n }\n\n if (universal.length > 0) {\n output.log('')\n output.log(styleText('dim', ` Universal (~/${UNIVERSAL_SKILLS_DIR})`))\n output.log(styleText('dim', ` ${universal.join(', ')}`))\n }\n\n if (additional.length > 0) {\n output.log('')\n output.log(styleText('dim', ' Additional agents'))\n for (const {dir, name} of additional) {\n output.log(styleText('dim', ` ${name} (~/${dir})`))\n }\n }\n output.log('')\n}\n\n/**\n * Installs the Sanity skills globally for the given agents using the bundled\n * `skills` package's programmatic API (equivalent to\n * `skills add <repo> --skill <names> -g -a <agent>... -y`). Failures are\n * surfaced as warnings and never throw — skills install is best-effort and\n * must not abort `sanity init`.\n */\nexport async function setupSkills(options: SetupSkillsOptions): Promise<SetupSkillsResult> {\n const {output} = options\n const uniqueAgents = [...new Set(options.agents)]\n\n if (uniqueAgents.length === 0) {\n skillsDebug('No agents passed — skipping skills install')\n return {installedAgents: [], skipped: true}\n }\n\n skillsDebug(\n 'Installing %s from %s globally for agents: %s',\n SANITY_SKILL_NAMES.join(', '),\n SANITY_SKILLS_REPO,\n uniqueAgents.join(', '),\n )\n\n const spin = spinner('Installing Sanity agent skills').start()\n\n try {\n // Loaded lazily so a problem with the `skills` package only affects this\n // best-effort step, not every command that imports this module.\n // eslint-disable-next-line no-restricted-syntax -- package import, not a file path\n const {installSkills} = await import('skills')\n const result = await installSkills(SANITY_SKILLS_REPO, {\n agents: uniqueAgents,\n onWarning: (warning) => skillsDebug('skills warning: %s', warning.message),\n scope: 'global',\n signal: AbortSignal.timeout(INSTALL_TIMEOUT_MS),\n skills: SANITY_SKILL_NAMES,\n })\n skillsDebug('skills install result: %O', result)\n spin.stop()\n\n const failedAgents = new Set(result.failed.map((failure) => failure.agent))\n const installedAgents = uniqueAgents.filter((agent) => !failedAgents.has(agent))\n\n if (installedAgents.length > 0) {\n output.log(\n `${logSymbols.success} Sanity agent skills installed: [${SANITY_SKILL_NAMES.join(', ')}]`,\n )\n printInstallSummary(installedAgents, output)\n }\n\n if (result.failed.length === 0) {\n return {installedAgents, skipped: false}\n }\n\n const failureMessages = result.failed.map((failure) => failure.message)\n output.warn(\n installedAgents.length > 0\n ? 'Could not install Sanity agent skills for some agents:'\n : 'Could not install Sanity agent skills:',\n )\n for (const message of failureMessages) output.warn(message)\n return {error: new Error(failureMessages.join('\\n')), installedAgents, skipped: false}\n } catch (error) {\n skillsDebug('Error installing skills %O', error)\n const err = toError(error)\n spin.stop()\n output.warn(`Could not install Sanity agent skills: ${getErrorMessage(error)}`)\n const fix = (error as {fix?: unknown} | null)?.fix\n if (typeof fix === 'string' && fix) output.warn(fix)\n return {error: err, installedAgents: [], skipped: false}\n }\n}\n"],"names":["styleText","subdebug","getErrorMessage","toError","logSymbols","spinner","getSkillsCliAgentDisplayNameById","getSkillsCliAgentSkillsDir","UNIVERSAL_SKILLS_DIR","skillsDebug","SANITY_SKILLS_REPO","SANITY_SKILL_NAMES","INSTALL_TIMEOUT_MS","printInstallSummary","agents","output","universal","additional","agent","name","dir","push","length","log","join","setupSkills","options","uniqueAgents","Set","installedAgents","skipped","spin","start","installSkills","result","onWarning","warning","message","scope","signal","AbortSignal","timeout","skills","stop","failedAgents","failed","map","failure","filter","has","success","failureMessages","warn","error","Error","err","fix"],"mappings":"AAAA,SAAQA,SAAS,QAAO,YAAW;AAEnC,SAAqBC,QAAQ,QAAO,mBAAkB;AACtD,SAAQC,eAAe,EAAEC,OAAO,QAAO,0BAAyB;AAChE,SAAQC,UAAU,EAAEC,OAAO,QAAO,sBAAqB;AAEvD,SACEC,gCAAgC,EAChCC,0BAA0B,EAC1BC,oBAAoB,QACf,0BAAyB;AAEhC,MAAMC,cAAcR,SAAS;AAE7B,4FAA4F,GAC5F,OAAO,MAAMS,qBAAqB,0BAAyB;AAE3D,gFAAgF,GAChF,OAAO,MAAMC,qBAAqB;IAAC;IAAyB;CAAmB,CAAA;AAE/E,gFAAgF,GAChF,MAAMC,qBAAqB;AAqB3B;;;;;;CAMC,GACD,SAASC,oBAAoBC,MAAgB,EAAEC,MAAc;IAC3D,MAAMC,YAAsB,EAAE;IAC9B,MAAMC,aAA4C,EAAE;IAEpD,KAAK,MAAMC,SAASJ,OAAQ;QAC1B,MAAMK,OAAOb,iCAAiCY,UAAUA;QACxD,MAAME,MAAMb,2BAA2BW;QACvC,IAAIE,OAAOA,QAAQZ,sBAAsB;YACvCS,WAAWI,IAAI,CAAC;gBAACD;gBAAKD;YAAI;QAC5B,OAAO;YACLH,UAAUK,IAAI,CAACF;QACjB;IACF;IAEA,IAAI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-
import { AssetSourceComponent, AssetSourceViewComponents, DefinedService, DefinedView, PanelComponent, PanelViewComponents, PanelViewProps, ServiceBus, ServiceCallback, ServiceContext, ServiceInfo, ServiceType, TileComponent, TileSize, TileViewComponents, TileViewProps, ViewComponentsBySurface, ViewSurface, unstable_defineService, unstable_defineView } from "@sanity/workbench-cli";
|
|
3
|
-
export { type AssetSource, type AssetSourceComponent, type AssetSourceComponentProps, type AssetSourceViewComponents, type DefinedService, type DefinedView, type PanelComponent, type PanelViewComponents, type PanelViewProps, type ServiceBus, type ServiceCallback, type ServiceContext, type ServiceInfo, type ServiceType, type TileComponent, type TileSize, type TileViewComponents, type TileViewProps, type ViewComponentsBySurface, type ViewSurface, unstable_defineService, unstable_defineView };
|
|
2
|
+
import { AssetSourceComponent, AssetSourceViewComponents, DefinedService, DefinedView, PanelComponent, PanelViewComponents, PanelViewProps, ServiceBus, ServiceCallback, ServiceContext, ServiceInfo, ServiceType, TileComponent, TileSize, TileViewComponents, TileViewProps, ViewComponentsBySurface, ViewSurface, WebWorkerBus, WebWorkerInfo, WebWorkerProps, WebWorkerType, unstable_defineService, unstable_defineView } from "@sanity/workbench-cli";
|
|
3
|
+
export { type AssetSource, type AssetSourceComponent, type AssetSourceComponentProps, type AssetSourceViewComponents, type DefinedService, type DefinedView, type PanelComponent, type PanelViewComponents, type PanelViewProps, type ServiceBus, type ServiceCallback, type ServiceContext, type ServiceInfo, type ServiceType, type TileComponent, type TileSize, type TileViewComponents, type TileViewProps, type ViewComponentsBySurface, type ViewSurface, type WebWorkerBus, type WebWorkerInfo, type WebWorkerProps, type WebWorkerType, unstable_defineService, unstable_defineView };
|
package/dist/exports/runtime.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Browser-safe runtime authoring helpers for the module-federation extension API.
|
|
2
2
|
//
|
|
3
|
-
// View/
|
|
3
|
+
// View/web worker src files bundle to the browser, so this entry re-exports ONLY
|
|
4
4
|
// from dependency-light, browser-safe modules — it must never import
|
|
5
5
|
// `@sanity/cli-core` or anything Node-only, or it would drag the CLI into the
|
|
6
6
|
// frontend bundle. The `sanity` runtime package re-exports from here, so the
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/exports/runtime.ts"],"sourcesContent":["// Browser-safe runtime authoring helpers for the module-federation extension API.\n//\n// View/
|
|
1
|
+
{"version":3,"sources":["../../src/exports/runtime.ts"],"sourcesContent":["// Browser-safe runtime authoring helpers for the module-federation extension API.\n//\n// View/web worker src files bundle to the browser, so this entry re-exports ONLY\n// from dependency-light, browser-safe modules — it must never import\n// `@sanity/cli-core` or anything Node-only, or it would drag the CLI into the\n// frontend bundle. The `sanity` runtime package re-exports from here, so the\n// same constraint protects it.\n//\n// `defineApplication` is config-time (Node) and stays on the main `@sanity/cli`\n// entry; only the runtime helpers live here.\nexport type {AssetSource, AssetSourceComponentProps} from '@sanity/types'\nexport type {\n AssetSourceComponent,\n AssetSourceViewComponents,\n DefinedService,\n DefinedView,\n PanelComponent,\n PanelViewComponents,\n PanelViewProps,\n ServiceBus,\n ServiceCallback,\n ServiceContext,\n ServiceInfo,\n ServiceType,\n TileComponent,\n TileSize,\n TileViewComponents,\n TileViewProps,\n ViewComponentsBySurface,\n ViewSurface,\n WebWorkerBus,\n WebWorkerInfo,\n WebWorkerProps,\n WebWorkerType,\n} from '@sanity/workbench-cli'\nexport {unstable_defineService, unstable_defineView} from '@sanity/workbench-cli'\n"],"names":["unstable_defineService","unstable_defineView"],"mappings":"AAAA,kFAAkF;AAClF,EAAE;AACF,iFAAiF;AACjF,qEAAqE;AACrE,8EAA8E;AAC9E,6EAA6E;AAC7E,+BAA+B;AAC/B,EAAE;AACF,gFAAgF;AAChF,6CAA6C;AA0B7C,SAAQA,sBAAsB,EAAEC,mBAAmB,QAAO,wBAAuB"}
|
|
@@ -445,6 +445,18 @@
|
|
|
445
445
|
slug: 'scheduling',
|
|
446
446
|
title: 'Scheduling API reference'
|
|
447
447
|
},
|
|
448
|
+
{
|
|
449
|
+
defaultApiVersion: 'v2026-09-01',
|
|
450
|
+
host: 'global',
|
|
451
|
+
pathPatterns: [
|
|
452
|
+
'usage/{resourceType}/{resourceId}/history',
|
|
453
|
+
'usage/{resourceType}/{resourceId}/snapshot',
|
|
454
|
+
'usage/{resourceType}/{resourceId}/{scope}/history',
|
|
455
|
+
'usage/{resourceType}/{resourceId}/{scope}/snapshot'
|
|
456
|
+
],
|
|
457
|
+
slug: 'usage-api',
|
|
458
|
+
title: 'Usage API reference'
|
|
459
|
+
},
|
|
448
460
|
{
|
|
449
461
|
defaultApiVersion: 'v2026-04-27',
|
|
450
462
|
host: 'global',
|