@sanity/cli 7.15.0 → 7.15.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 +1 -1
- package/dist/actions/telemetry/resolveConsent.js +4 -2
- package/dist/actions/telemetry/resolveConsent.js.map +1 -1
- package/dist/commands/datasets/copy.js +5 -3
- package/dist/commands/datasets/copy.js.map +1 -1
- package/dist/commands/documents/query.js +5 -4
- package/dist/commands/documents/query.js.map +1 -1
- package/dist/exports/invokeSanityCli/index.d.ts +5 -9
- package/dist/exports/invokeSanityCli/index.js +47 -20
- package/dist/exports/invokeSanityCli/index.js.map +1 -1
- package/dist/services/telemetry.js +4 -0
- package/dist/services/telemetry.js.map +1 -1
- package/oclif.manifest.json +40 -41
- package/package.json +7 -7
package/README.md
CHANGED
|
@@ -1862,7 +1862,7 @@ ARGUMENTS
|
|
|
1862
1862
|
|
|
1863
1863
|
FLAGS
|
|
1864
1864
|
--anonymous Send the query without any authorization token
|
|
1865
|
-
--api-version=<value>
|
|
1865
|
+
--api-version=<value> API version to use (defaults to 2025-08-15)
|
|
1866
1866
|
--pretty Colorize JSON output
|
|
1867
1867
|
|
|
1868
1868
|
OVERRIDE FLAGS
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { getCliToken, isCi } from '@sanity/cli-core';
|
|
2
|
+
import { getCliExecutionContext } from '@sanity/cli-core/executionContext';
|
|
2
3
|
import { fetchTelemetryConsent, isValidApiConsentStatus, VALID_API_STATUSES } from '../../services/telemetry.js';
|
|
3
4
|
import { isTrueish } from './isTrueish.js';
|
|
4
5
|
import { telemetryDebug } from './telemetryDebug.js';
|
|
@@ -10,13 +11,14 @@ function parseApiConsentStatus(value) {
|
|
|
10
11
|
}
|
|
11
12
|
export async function resolveConsent() {
|
|
12
13
|
telemetryDebug('Resolving consent…');
|
|
13
|
-
|
|
14
|
+
const hasCliExecutionContext = Boolean(getCliExecutionContext());
|
|
15
|
+
if (!hasCliExecutionContext && isCi()) {
|
|
14
16
|
telemetryDebug('CI environment detected, treating telemetry consent as denied');
|
|
15
17
|
return {
|
|
16
18
|
status: 'denied'
|
|
17
19
|
};
|
|
18
20
|
}
|
|
19
|
-
if (isTrueish(process.env.DO_NOT_TRACK)) {
|
|
21
|
+
if (!hasCliExecutionContext && isTrueish(process.env.DO_NOT_TRACK)) {
|
|
20
22
|
telemetryDebug('DO_NOT_TRACK is set, consent is denied');
|
|
21
23
|
return {
|
|
22
24
|
reason: 'localOverride',
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/actions/telemetry/resolveConsent.ts"],"sourcesContent":["import {type ConsentInformation, getCliToken, isCi} from '@sanity/cli-core'\n\nimport {\n fetchTelemetryConsent,\n isValidApiConsentStatus,\n VALID_API_STATUSES,\n type ValidApiConsentStatus,\n} from '../../services/telemetry.js'\nimport {isTrueish} from './isTrueish.js'\nimport {telemetryDebug} from './telemetryDebug.js'\n\nfunction parseApiConsentStatus(value: unknown): ValidApiConsentStatus {\n if (typeof value === 'string' && isValidApiConsentStatus(value)) {\n return value\n }\n throw new Error(`Invalid consent status. Must be one of: ${VALID_API_STATUSES.join(', ')}`)\n}\n\nexport async function resolveConsent(): Promise<ConsentInformation> {\n telemetryDebug('Resolving consent…')\n if (isCi()) {\n telemetryDebug('CI environment detected, treating telemetry consent as denied')\n return {status: 'denied'}\n }\n\n if (isTrueish(process.env.DO_NOT_TRACK)) {\n telemetryDebug('DO_NOT_TRACK is set, consent is denied')\n return {\n reason: 'localOverride',\n status: 'denied',\n }\n }\n\n const token = await getCliToken()\n if (!token) {\n telemetryDebug('User is not logged in, consent is undetermined')\n return {\n reason: 'unauthenticated',\n status: 'undetermined',\n }\n }\n\n try {\n const response = await fetchTelemetryConsent()\n\n telemetryDebug('User consent status is %s', response.status)\n return {status: parseApiConsentStatus(response.status)}\n } catch (err) {\n telemetryDebug('Failed to fetch user consent status, treating it as \"undetermined\": %s', err)\n return {\n reason: 'fetchError',\n status: 'undetermined',\n }\n }\n}\n"],"names":["getCliToken","isCi","fetchTelemetryConsent","isValidApiConsentStatus","VALID_API_STATUSES","isTrueish","telemetryDebug","parseApiConsentStatus","value","Error","join","resolveConsent","status","process","env","DO_NOT_TRACK","reason","token","response","err"],"mappings":"AAAA,SAAiCA,WAAW,EAAEC,IAAI,QAAO,mBAAkB;
|
|
1
|
+
{"version":3,"sources":["../../../src/actions/telemetry/resolveConsent.ts"],"sourcesContent":["import {type ConsentInformation, getCliToken, isCi} from '@sanity/cli-core'\nimport {getCliExecutionContext} from '@sanity/cli-core/executionContext'\n\nimport {\n fetchTelemetryConsent,\n isValidApiConsentStatus,\n VALID_API_STATUSES,\n type ValidApiConsentStatus,\n} from '../../services/telemetry.js'\nimport {isTrueish} from './isTrueish.js'\nimport {telemetryDebug} from './telemetryDebug.js'\n\nfunction parseApiConsentStatus(value: unknown): ValidApiConsentStatus {\n if (typeof value === 'string' && isValidApiConsentStatus(value)) {\n return value\n }\n throw new Error(`Invalid consent status. Must be one of: ${VALID_API_STATUSES.join(', ')}`)\n}\n\nexport async function resolveConsent(): Promise<ConsentInformation> {\n telemetryDebug('Resolving consent…')\n const hasCliExecutionContext = Boolean(getCliExecutionContext())\n\n if (!hasCliExecutionContext && isCi()) {\n telemetryDebug('CI environment detected, treating telemetry consent as denied')\n return {status: 'denied'}\n }\n\n if (!hasCliExecutionContext && isTrueish(process.env.DO_NOT_TRACK)) {\n telemetryDebug('DO_NOT_TRACK is set, consent is denied')\n return {\n reason: 'localOverride',\n status: 'denied',\n }\n }\n\n const token = await getCliToken()\n if (!token) {\n telemetryDebug('User is not logged in, consent is undetermined')\n return {\n reason: 'unauthenticated',\n status: 'undetermined',\n }\n }\n\n try {\n const response = await fetchTelemetryConsent()\n\n telemetryDebug('User consent status is %s', response.status)\n return {status: parseApiConsentStatus(response.status)}\n } catch (err) {\n telemetryDebug('Failed to fetch user consent status, treating it as \"undetermined\": %s', err)\n return {\n reason: 'fetchError',\n status: 'undetermined',\n }\n }\n}\n"],"names":["getCliToken","isCi","getCliExecutionContext","fetchTelemetryConsent","isValidApiConsentStatus","VALID_API_STATUSES","isTrueish","telemetryDebug","parseApiConsentStatus","value","Error","join","resolveConsent","hasCliExecutionContext","Boolean","status","process","env","DO_NOT_TRACK","reason","token","response","err"],"mappings":"AAAA,SAAiCA,WAAW,EAAEC,IAAI,QAAO,mBAAkB;AAC3E,SAAQC,sBAAsB,QAAO,oCAAmC;AAExE,SACEC,qBAAqB,EACrBC,uBAAuB,EACvBC,kBAAkB,QAEb,8BAA6B;AACpC,SAAQC,SAAS,QAAO,iBAAgB;AACxC,SAAQC,cAAc,QAAO,sBAAqB;AAElD,SAASC,sBAAsBC,KAAc;IAC3C,IAAI,OAAOA,UAAU,YAAYL,wBAAwBK,QAAQ;QAC/D,OAAOA;IACT;IACA,MAAM,IAAIC,MAAM,CAAC,wCAAwC,EAAEL,mBAAmBM,IAAI,CAAC,OAAO;AAC5F;AAEA,OAAO,eAAeC;IACpBL,eAAe;IACf,MAAMM,yBAAyBC,QAAQZ;IAEvC,IAAI,CAACW,0BAA0BZ,QAAQ;QACrCM,eAAe;QACf,OAAO;YAACQ,QAAQ;QAAQ;IAC1B;IAEA,IAAI,CAACF,0BAA0BP,UAAUU,QAAQC,GAAG,CAACC,YAAY,GAAG;QAClEX,eAAe;QACf,OAAO;YACLY,QAAQ;YACRJ,QAAQ;QACV;IACF;IAEA,MAAMK,QAAQ,MAAMpB;IACpB,IAAI,CAACoB,OAAO;QACVb,eAAe;QACf,OAAO;YACLY,QAAQ;YACRJ,QAAQ;QACV;IACF;IAEA,IAAI;QACF,MAAMM,WAAW,MAAMlB;QAEvBI,eAAe,6BAA6Bc,SAASN,MAAM;QAC3D,OAAO;YAACA,QAAQP,sBAAsBa,SAASN,MAAM;QAAC;IACxD,EAAE,OAAOO,KAAK;QACZf,eAAe,0EAA0Ee;QACzF,OAAO;YACLH,QAAQ;YACRJ,QAAQ;QACV;IACF;AACF"}
|
|
@@ -3,6 +3,7 @@ import { Args, Flags } from '@oclif/core';
|
|
|
3
3
|
import { exit } from '@oclif/core/errors';
|
|
4
4
|
import { exitCodes } from '@sanity/cli-core';
|
|
5
5
|
import { subdebug } from '@sanity/cli-core/debug';
|
|
6
|
+
import { getCliExecutionContext } from '@sanity/cli-core/executionContext';
|
|
6
7
|
import { SanityCommand } from '@sanity/cli-core/SanityCommand';
|
|
7
8
|
import { spinner } from '@sanity/cli-core/ux';
|
|
8
9
|
import { Table } from 'console-table-printer';
|
|
@@ -385,6 +386,7 @@ export class CopyDatasetCommand extends SanityCommand {
|
|
|
385
386
|
}
|
|
386
387
|
async subscribeToProgress(projectId, jobId) {
|
|
387
388
|
const spin = spinner('').start();
|
|
389
|
+
const hasCliExecutionContext = Boolean(getCliExecutionContext());
|
|
388
390
|
return new Promise((resolve, reject)=>{
|
|
389
391
|
const sigintHandler = ()=>{
|
|
390
392
|
subscription.unsubscribe();
|
|
@@ -396,12 +398,12 @@ export class CopyDatasetCommand extends SanityCommand {
|
|
|
396
398
|
projectId
|
|
397
399
|
}).subscribe({
|
|
398
400
|
complete: ()=>{
|
|
399
|
-
process.off('SIGINT', sigintHandler);
|
|
401
|
+
if (!hasCliExecutionContext) process.off('SIGINT', sigintHandler);
|
|
400
402
|
spin.succeed('Copy finished.');
|
|
401
403
|
resolve();
|
|
402
404
|
},
|
|
403
405
|
error: (err)=>{
|
|
404
|
-
process.off('SIGINT', sigintHandler);
|
|
406
|
+
if (!hasCliExecutionContext) process.off('SIGINT', sigintHandler);
|
|
405
407
|
spin.fail('Copy failed.');
|
|
406
408
|
reject(err);
|
|
407
409
|
},
|
|
@@ -411,7 +413,7 @@ export class CopyDatasetCommand extends SanityCommand {
|
|
|
411
413
|
}
|
|
412
414
|
}
|
|
413
415
|
});
|
|
414
|
-
process.once('SIGINT', sigintHandler);
|
|
416
|
+
if (!hasCliExecutionContext) process.once('SIGINT', sigintHandler);
|
|
415
417
|
});
|
|
416
418
|
}
|
|
417
419
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/commands/datasets/copy.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {Args, Flags} from '@oclif/core'\nimport {exit} from '@oclif/core/errors'\nimport {exitCodes} from '@sanity/cli-core'\nimport {subdebug} from '@sanity/cli-core/debug'\nimport {SanityCommand} from '@sanity/cli-core/SanityCommand'\nimport {spinner} from '@sanity/cli-core/ux'\nimport {Table} from 'console-table-printer'\nimport {formatDistance} from 'date-fns/formatDistance'\nimport {formatDistanceToNow} from 'date-fns/formatDistanceToNow'\nimport {parseISO} from 'date-fns/parseISO'\n\nimport {validateDatasetName} from '../../actions/dataset/validateDatasetName.js'\nimport {promptForDataset} from '../../prompts/promptForDataset.js'\nimport {promptForDatasetName} from '../../prompts/promptForDatasetName.js'\nimport {promptForProject} from '../../prompts/promptForProject.js'\nimport {\n copyDataset,\n type CopyJobProgressEvent,\n type DatasetCopyJob,\n followCopyJobProgress,\n listDatasetCopyJobs,\n listDatasets,\n} from '../../services/datasets.js'\nimport {formatCliErrorMessages} from '../../util/formatCliErrorMessages.js'\nimport {getProjectIdFlag} from '../../util/sharedFlags.js'\n\nconst copyDatasetDebug = subdebug('dataset:copy')\n\nexport class CopyDatasetCommand extends SanityCommand<typeof CopyDatasetCommand> {\n static override args = {\n source: Args.string({\n description: 'Name of the dataset to copy from',\n required: false,\n }),\n target: Args.string({\n description: 'Name of the dataset to copy to',\n required: false,\n }),\n }\n\n static override description = 'Copy a dataset or manage copy jobs'\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %>',\n description: 'Interactively copy a dataset',\n },\n {\n command: '<%= config.bin %> <%= command.id %> source-dataset',\n description: 'Copy from source-dataset (prompts for target)',\n },\n {\n command: '<%= config.bin %> <%= command.id %> source-dataset target-dataset',\n description: 'Copy from source-dataset to target-dataset',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --skip-history source target',\n description: 'Copy without preserving document history (faster for large datasets)',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --skip-content-releases source target',\n description: 'Copy without content release documents',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --detach source target',\n description: 'Start copy job without waiting for completion',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --attach <job-id>',\n description: 'Attach to a running copy job to follow progress',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --list',\n description: 'List all dataset copy jobs',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --list --offset 2 --limit 10',\n description: 'List copy jobs with pagination',\n },\n ]\n\n static override flags = {\n ...getProjectIdFlag({\n description: 'Project ID to copy dataset in',\n semantics: 'override',\n }),\n attach: Flags.string({\n description: 'Attach to the running copy process to show progress',\n exclusive: ['list', 'detach', 'skip-history'],\n required: false,\n }),\n detach: Flags.boolean({\n description: 'Start the copy without waiting for it to finish',\n exclusive: ['list', 'attach'],\n required: false,\n }),\n limit: Flags.integer({\n dependsOn: ['list'],\n description: 'Maximum number of jobs returned (default 10, max 1000)',\n max: 1000,\n required: false,\n }),\n list: Flags.boolean({\n description: 'Lists all dataset copy jobs',\n exclusive: ['attach', 'detach', 'skip-history'],\n required: false,\n }),\n offset: Flags.integer({\n dependsOn: ['list'],\n description: 'Start position in the list of jobs (default 0)',\n required: false,\n }),\n 'skip-content-releases': Flags.boolean({\n description: \"Don't copy content release documents to the target dataset\",\n exclusive: ['list', 'attach'],\n required: false,\n }),\n 'skip-history': Flags.boolean({\n description: \"Don't preserve document history on copy\",\n exclusive: ['list', 'attach'],\n required: false,\n }),\n }\n\n static override hiddenAliases: string[] = ['dataset:copy']\n\n public async run(): Promise<void> {\n const {args, flags} = await this.parse(CopyDatasetCommand)\n\n if (!flags.list && !flags.attach && this.isUnattended()) {\n const errors: string[] = []\n\n if (!args.source) {\n errors.push('Source dataset is required. Pass it as the `<source>` argument.')\n }\n if (!args.target) {\n errors.push('Target dataset is required. Pass it as the `<target>` argument.')\n }\n\n if (errors.length > 0) {\n this.output.error(formatCliErrorMessages(errors), {exit: exitCodes.USAGE_ERROR})\n }\n }\n\n const projectId = await this.getProjectId({\n fallback: () =>\n promptForProject({\n requiredPermissions: [\n {grant: 'read', permission: 'sanity.project.datasets'},\n {grant: 'create', permission: 'sanity.project.datasets'},\n ],\n }),\n })\n\n // Route to appropriate mode\n if (flags.list) {\n return this.handleListMode(projectId, flags)\n }\n\n if (flags.attach) {\n return this.handleAttachMode(projectId, flags.attach)\n }\n\n return this.handleCopyMode(projectId, args, flags)\n }\n\n private displayCopyJobsTable(jobs: DatasetCopyJob[]): void {\n const table = new Table({\n columns: [\n {alignment: 'left', name: 'id', title: 'Job ID'},\n {alignment: 'left', name: 'sourceDataset', title: 'Source Dataset'},\n {alignment: 'left', name: 'targetDataset', title: 'Target Dataset'},\n {alignment: 'left', name: 'state', title: 'State'},\n {alignment: 'left', name: 'withHistory', title: 'With history'},\n {alignment: 'left', name: 'timeStarted', title: 'Time started'},\n {alignment: 'left', name: 'timeTaken', title: 'Time taken'},\n ],\n title: 'Dataset copy jobs for this project in descending order',\n })\n\n for (const job of jobs) {\n const {createdAt, id, sourceDataset, state, targetDataset, updatedAt, withHistory} = job\n\n let timeStarted = ''\n if (createdAt !== '') {\n timeStarted = formatDistanceToNow(parseISO(createdAt))\n }\n\n let timeTaken = ''\n if (updatedAt !== '') {\n timeTaken = formatDistance(parseISO(updatedAt), parseISO(createdAt))\n }\n\n let color: '' | 'green' | 'red' | 'yellow'\n switch (state) {\n case 'completed': {\n color = 'green'\n break\n }\n case 'failed': {\n color = 'red'\n break\n }\n case 'pending': {\n color = 'yellow'\n break\n }\n default: {\n color = ''\n }\n }\n\n table.addRow(\n {\n id,\n sourceDataset,\n state,\n targetDataset,\n timeStarted: `${timeStarted} ago`,\n timeTaken,\n withHistory,\n },\n {color},\n )\n }\n\n this.output.log(table.render())\n }\n\n private async handleAttachMode(projectId: string, jobId: string): Promise<void> {\n copyDatasetDebug('Attaching to copy job %s', jobId)\n\n if (jobId.trim() === '') {\n return this.output.error('Please supply a valid jobId', {exit: exitCodes.RUNTIME_ERROR})\n }\n\n try {\n await this.subscribeToProgress(projectId, jobId)\n this.output.log(`Job ${styleText('green', jobId)} completed`)\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n copyDatasetDebug('Failed to attach to copy job: %s', message, error)\n return this.output.error(`Failed to attach to copy job: ${message}`, {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n }\n\n private async handleCopyMode(\n projectId: string,\n args: {source?: string; target?: string},\n flags: {detach?: boolean; 'skip-content-releases'?: boolean; 'skip-history'?: boolean},\n ): Promise<void> {\n copyDatasetDebug('Starting copy mode')\n\n const skipHistory = Boolean(flags['skip-history'])\n const skipContentReleases = Boolean(flags['skip-content-releases'])\n\n // Surfaced before any prompting so the flag is still actionable: a copy job\n // can't be canceled once started, so mentioning it after the job kicks off\n // leaves nothing to decide.\n if (!skipHistory) {\n this.output.log(\n `Note: You can run this command with flag '--skip-history'. The flag will reduce copy time in larger datasets.`,\n )\n }\n\n // Get and validate source dataset\n let sourceDataset = args.source\n if (sourceDataset) {\n const nameError = validateDatasetName(sourceDataset)\n if (nameError) {\n return this.output.error(nameError, {exit: exitCodes.USAGE_ERROR})\n }\n }\n\n let datasetsResponse\n try {\n datasetsResponse = await listDatasets(projectId)\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n copyDatasetDebug('Failed to fetch datasets: %s', message, error)\n return this.output.error(`Failed to fetch datasets: ${message}`, {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n\n const datasetNames = new Set(datasetsResponse.map((ds) => ds.name))\n\n // Prompt for source if not provided\n if (!sourceDataset) {\n sourceDataset = await promptForDataset({\n datasets: datasetsResponse,\n })\n }\n\n if (!datasetNames.has(sourceDataset)) {\n return this.output.error(`Source dataset \"${sourceDataset}\" doesn't exist`, {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n\n // Get and validate target dataset\n let targetDataset = args.target\n if (targetDataset) {\n const nameError = validateDatasetName(targetDataset)\n if (nameError) {\n return this.output.error(nameError, {exit: exitCodes.USAGE_ERROR})\n }\n } else {\n targetDataset = await promptForDatasetName({\n message: 'Target dataset name:',\n })\n }\n\n if (datasetNames.has(targetDataset)) {\n return this.output.error(`Target dataset \"${targetDataset}\" already exists`, {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n\n // Start the copy job\n try {\n this.output.log(\n `Copying dataset ${styleText('green', sourceDataset)} to ${styleText('green', targetDataset)}...`,\n )\n\n const response = await copyDataset({\n projectId,\n skipContentReleases,\n skipHistory,\n sourceDataset,\n targetDataset,\n })\n\n this.output.log(`Job ${styleText('green', response.jobId)} started`)\n\n if (flags.detach) {\n return\n }\n\n await this.subscribeToProgress(projectId, response.jobId)\n this.output.log(`Job ${styleText('green', response.jobId)} completed`)\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n copyDatasetDebug('Dataset copying failed: %s', message, error)\n return this.output.error(`Dataset copying failed: ${message}`, {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n }\n\n private async handleListMode(\n projectId: string,\n flags: {limit?: number; offset?: number},\n ): Promise<void> {\n copyDatasetDebug('Listing dataset copy jobs')\n\n try {\n const jobs = await listDatasetCopyJobs({\n limit: flags.limit,\n offset: flags.offset,\n projectId,\n })\n\n if (jobs.length === 0) {\n this.output.log(\"This project doesn't have any dataset copy jobs\")\n return\n }\n\n this.displayCopyJobsTable(jobs)\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n copyDatasetDebug('Failed to list dataset copy jobs: %s', message, error)\n return this.output.error(`Failed to list dataset copy jobs: ${message}`, {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n }\n\n private async subscribeToProgress(projectId: string, jobId: string): Promise<void> {\n const spin = spinner('').start()\n\n return new Promise<void>((resolve, reject) => {\n const sigintHandler = () => {\n subscription.unsubscribe()\n spin.fail('Copy interrupted.')\n exit(130)\n }\n\n const subscription = followCopyJobProgress({jobId, projectId}).subscribe({\n complete: () => {\n process.off('SIGINT', sigintHandler)\n spin.succeed('Copy finished.')\n resolve()\n },\n error: (err) => {\n process.off('SIGINT', sigintHandler)\n spin.fail('Copy failed.')\n reject(err)\n },\n next: (event: CopyJobProgressEvent) => {\n if (typeof event.progress === 'number') {\n spin.text = `Copy in progress: ${event.progress}%`\n }\n },\n })\n\n process.once('SIGINT', sigintHandler)\n })\n }\n}\n"],"names":["styleText","Args","Flags","exit","exitCodes","subdebug","SanityCommand","spinner","Table","formatDistance","formatDistanceToNow","parseISO","validateDatasetName","promptForDataset","promptForDatasetName","promptForProject","copyDataset","followCopyJobProgress","listDatasetCopyJobs","listDatasets","formatCliErrorMessages","getProjectIdFlag","copyDatasetDebug","CopyDatasetCommand","args","source","string","description","required","target","examples","command","flags","semantics","attach","exclusive","detach","boolean","limit","integer","dependsOn","max","list","offset","hiddenAliases","run","parse","isUnattended","errors","push","length","output","error","USAGE_ERROR","projectId","getProjectId","fallback","requiredPermissions","grant","permission","handleListMode","handleAttachMode","handleCopyMode","displayCopyJobsTable","jobs","table","columns","alignment","name","title","job","createdAt","id","sourceDataset","state","targetDataset","updatedAt","withHistory","timeStarted","timeTaken","color","addRow","log","render","jobId","trim","RUNTIME_ERROR","subscribeToProgress","message","Error","String","skipHistory","Boolean","skipContentReleases","nameError","datasetsResponse","datasetNames","Set","map","ds","datasets","has","response","spin","start","Promise","resolve","reject","sigintHandler","subscription","unsubscribe","fail","subscribe","complete","process","off","succeed","err","next","event","progress","text","once"],"mappings":"AAAA,SAAQA,SAAS,QAAO,YAAW;AAEnC,SAAQC,IAAI,EAAEC,KAAK,QAAO,cAAa;AACvC,SAAQC,IAAI,QAAO,qBAAoB;AACvC,SAAQC,SAAS,QAAO,mBAAkB;AAC1C,SAAQC,QAAQ,QAAO,yBAAwB;AAC/C,SAAQC,aAAa,QAAO,iCAAgC;AAC5D,SAAQC,OAAO,QAAO,sBAAqB;AAC3C,SAAQC,KAAK,QAAO,wBAAuB;AAC3C,SAAQC,cAAc,QAAO,0BAAyB;AACtD,SAAQC,mBAAmB,Q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AK;gBAClBK,QAAQX,MAAMW,MAAM;gBACpBW;YACF;YAEA,IAAIU,KAAKd,MAAM,KAAK,GAAG;gBACrB,IAAI,CAACC,MAAM,CAAC+B,GAAG,CAAC;gBAChB;YACF;YAEA,IAAI,CAACnB,oBAAoB,CAACC;QAC5B,EAAE,OAAOZ,OAAO;YACd,MAAMoC,UAAUpC,iBAAiBqC,QAAQrC,MAAMoC,OAAO,GAAGE,OAAOtC;YAChE9B,iBAAiB,wCAAwCkE,SAASpC;YAClE,OAAO,IAAI,CAACD,MAAM,CAACC,KAAK,CAAC,CAAC,kCAAkC,EAAEoC,SAAS,EAAE;gBACvErF,MAAMC,UAAUkF,aAAa;YAC/B;QACF;IACF;IAEA,MAAcC,oBAAoBjC,SAAiB,EAAE8B,KAAa,EAAiB;QACjF,MAAMmB,OAAOhG,QAAQ,IAAIiG,KAAK;QAE9B,OAAO,IAAIC,QAAc,CAACC,SAASC;YACjC,MAAMC,gBAAgB;gBACpBC,aAAaC,WAAW;gBACxBP,KAAKQ,IAAI,CAAC;gBACV5G,KAAK;YACP;YAEA,MAAM0G,eAAe5F,sBAAsB;gBAACmE;gBAAO9B;YAAS,GAAG0D,SAAS,CAAC;gBACvEC,UAAU;oBACRC,QAAQC,GAAG,CAAC,UAAUP;oBACtBL,KAAKa,OAAO,CAAC;oBACbV;gBACF;gBACAtD,OAAO,CAACiE;oBACNH,QAAQC,GAAG,CAAC,UAAUP;oBACtBL,KAAKQ,IAAI,CAAC;oBACVJ,OAAOU;gBACT;gBACAC,MAAM,CAACC;oBACL,IAAI,OAAOA,MAAMC,QAAQ,KAAK,UAAU;wBACtCjB,KAAKkB,IAAI,GAAG,CAAC,kBAAkB,EAAEF,MAAMC,QAAQ,CAAC,CAAC,CAAC;oBACpD;gBACF;YACF;YAEAN,QAAQQ,IAAI,CAAC,UAAUd;QACzB;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/commands/datasets/copy.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {Args, Flags} from '@oclif/core'\nimport {exit} from '@oclif/core/errors'\nimport {exitCodes} from '@sanity/cli-core'\nimport {subdebug} from '@sanity/cli-core/debug'\nimport {getCliExecutionContext} from '@sanity/cli-core/executionContext'\nimport {SanityCommand} from '@sanity/cli-core/SanityCommand'\nimport {spinner} from '@sanity/cli-core/ux'\nimport {Table} from 'console-table-printer'\nimport {formatDistance} from 'date-fns/formatDistance'\nimport {formatDistanceToNow} from 'date-fns/formatDistanceToNow'\nimport {parseISO} from 'date-fns/parseISO'\n\nimport {validateDatasetName} from '../../actions/dataset/validateDatasetName.js'\nimport {promptForDataset} from '../../prompts/promptForDataset.js'\nimport {promptForDatasetName} from '../../prompts/promptForDatasetName.js'\nimport {promptForProject} from '../../prompts/promptForProject.js'\nimport {\n copyDataset,\n type CopyJobProgressEvent,\n type DatasetCopyJob,\n followCopyJobProgress,\n listDatasetCopyJobs,\n listDatasets,\n} from '../../services/datasets.js'\nimport {formatCliErrorMessages} from '../../util/formatCliErrorMessages.js'\nimport {getProjectIdFlag} from '../../util/sharedFlags.js'\n\nconst copyDatasetDebug = subdebug('dataset:copy')\n\nexport class CopyDatasetCommand extends SanityCommand<typeof CopyDatasetCommand> {\n static override args = {\n source: Args.string({\n description: 'Name of the dataset to copy from',\n required: false,\n }),\n target: Args.string({\n description: 'Name of the dataset to copy to',\n required: false,\n }),\n }\n\n static override description = 'Copy a dataset or manage copy jobs'\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %>',\n description: 'Interactively copy a dataset',\n },\n {\n command: '<%= config.bin %> <%= command.id %> source-dataset',\n description: 'Copy from source-dataset (prompts for target)',\n },\n {\n command: '<%= config.bin %> <%= command.id %> source-dataset target-dataset',\n description: 'Copy from source-dataset to target-dataset',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --skip-history source target',\n description: 'Copy without preserving document history (faster for large datasets)',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --skip-content-releases source target',\n description: 'Copy without content release documents',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --detach source target',\n description: 'Start copy job without waiting for completion',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --attach <job-id>',\n description: 'Attach to a running copy job to follow progress',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --list',\n description: 'List all dataset copy jobs',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --list --offset 2 --limit 10',\n description: 'List copy jobs with pagination',\n },\n ]\n\n static override flags = {\n ...getProjectIdFlag({\n description: 'Project ID to copy dataset in',\n semantics: 'override',\n }),\n attach: Flags.string({\n description: 'Attach to the running copy process to show progress',\n exclusive: ['list', 'detach', 'skip-history'],\n required: false,\n }),\n detach: Flags.boolean({\n description: 'Start the copy without waiting for it to finish',\n exclusive: ['list', 'attach'],\n required: false,\n }),\n limit: Flags.integer({\n dependsOn: ['list'],\n description: 'Maximum number of jobs returned (default 10, max 1000)',\n max: 1000,\n required: false,\n }),\n list: Flags.boolean({\n description: 'Lists all dataset copy jobs',\n exclusive: ['attach', 'detach', 'skip-history'],\n required: false,\n }),\n offset: Flags.integer({\n dependsOn: ['list'],\n description: 'Start position in the list of jobs (default 0)',\n required: false,\n }),\n 'skip-content-releases': Flags.boolean({\n description: \"Don't copy content release documents to the target dataset\",\n exclusive: ['list', 'attach'],\n required: false,\n }),\n 'skip-history': Flags.boolean({\n description: \"Don't preserve document history on copy\",\n exclusive: ['list', 'attach'],\n required: false,\n }),\n }\n\n static override hiddenAliases: string[] = ['dataset:copy']\n\n public async run(): Promise<void> {\n const {args, flags} = await this.parse(CopyDatasetCommand)\n\n if (!flags.list && !flags.attach && this.isUnattended()) {\n const errors: string[] = []\n\n if (!args.source) {\n errors.push('Source dataset is required. Pass it as the `<source>` argument.')\n }\n if (!args.target) {\n errors.push('Target dataset is required. Pass it as the `<target>` argument.')\n }\n\n if (errors.length > 0) {\n this.output.error(formatCliErrorMessages(errors), {exit: exitCodes.USAGE_ERROR})\n }\n }\n\n const projectId = await this.getProjectId({\n fallback: () =>\n promptForProject({\n requiredPermissions: [\n {grant: 'read', permission: 'sanity.project.datasets'},\n {grant: 'create', permission: 'sanity.project.datasets'},\n ],\n }),\n })\n\n // Route to appropriate mode\n if (flags.list) {\n return this.handleListMode(projectId, flags)\n }\n\n if (flags.attach) {\n return this.handleAttachMode(projectId, flags.attach)\n }\n\n return this.handleCopyMode(projectId, args, flags)\n }\n\n private displayCopyJobsTable(jobs: DatasetCopyJob[]): void {\n const table = new Table({\n columns: [\n {alignment: 'left', name: 'id', title: 'Job ID'},\n {alignment: 'left', name: 'sourceDataset', title: 'Source Dataset'},\n {alignment: 'left', name: 'targetDataset', title: 'Target Dataset'},\n {alignment: 'left', name: 'state', title: 'State'},\n {alignment: 'left', name: 'withHistory', title: 'With history'},\n {alignment: 'left', name: 'timeStarted', title: 'Time started'},\n {alignment: 'left', name: 'timeTaken', title: 'Time taken'},\n ],\n title: 'Dataset copy jobs for this project in descending order',\n })\n\n for (const job of jobs) {\n const {createdAt, id, sourceDataset, state, targetDataset, updatedAt, withHistory} = job\n\n let timeStarted = ''\n if (createdAt !== '') {\n timeStarted = formatDistanceToNow(parseISO(createdAt))\n }\n\n let timeTaken = ''\n if (updatedAt !== '') {\n timeTaken = formatDistance(parseISO(updatedAt), parseISO(createdAt))\n }\n\n let color: '' | 'green' | 'red' | 'yellow'\n switch (state) {\n case 'completed': {\n color = 'green'\n break\n }\n case 'failed': {\n color = 'red'\n break\n }\n case 'pending': {\n color = 'yellow'\n break\n }\n default: {\n color = ''\n }\n }\n\n table.addRow(\n {\n id,\n sourceDataset,\n state,\n targetDataset,\n timeStarted: `${timeStarted} ago`,\n timeTaken,\n withHistory,\n },\n {color},\n )\n }\n\n this.output.log(table.render())\n }\n\n private async handleAttachMode(projectId: string, jobId: string): Promise<void> {\n copyDatasetDebug('Attaching to copy job %s', jobId)\n\n if (jobId.trim() === '') {\n return this.output.error('Please supply a valid jobId', {exit: exitCodes.RUNTIME_ERROR})\n }\n\n try {\n await this.subscribeToProgress(projectId, jobId)\n this.output.log(`Job ${styleText('green', jobId)} completed`)\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n copyDatasetDebug('Failed to attach to copy job: %s', message, error)\n return this.output.error(`Failed to attach to copy job: ${message}`, {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n }\n\n private async handleCopyMode(\n projectId: string,\n args: {source?: string; target?: string},\n flags: {detach?: boolean; 'skip-content-releases'?: boolean; 'skip-history'?: boolean},\n ): Promise<void> {\n copyDatasetDebug('Starting copy mode')\n\n const skipHistory = Boolean(flags['skip-history'])\n const skipContentReleases = Boolean(flags['skip-content-releases'])\n\n // Surfaced before any prompting so the flag is still actionable: a copy job\n // can't be canceled once started, so mentioning it after the job kicks off\n // leaves nothing to decide.\n if (!skipHistory) {\n this.output.log(\n `Note: You can run this command with flag '--skip-history'. The flag will reduce copy time in larger datasets.`,\n )\n }\n\n // Get and validate source dataset\n let sourceDataset = args.source\n if (sourceDataset) {\n const nameError = validateDatasetName(sourceDataset)\n if (nameError) {\n return this.output.error(nameError, {exit: exitCodes.USAGE_ERROR})\n }\n }\n\n let datasetsResponse\n try {\n datasetsResponse = await listDatasets(projectId)\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n copyDatasetDebug('Failed to fetch datasets: %s', message, error)\n return this.output.error(`Failed to fetch datasets: ${message}`, {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n\n const datasetNames = new Set(datasetsResponse.map((ds) => ds.name))\n\n // Prompt for source if not provided\n if (!sourceDataset) {\n sourceDataset = await promptForDataset({\n datasets: datasetsResponse,\n })\n }\n\n if (!datasetNames.has(sourceDataset)) {\n return this.output.error(`Source dataset \"${sourceDataset}\" doesn't exist`, {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n\n // Get and validate target dataset\n let targetDataset = args.target\n if (targetDataset) {\n const nameError = validateDatasetName(targetDataset)\n if (nameError) {\n return this.output.error(nameError, {exit: exitCodes.USAGE_ERROR})\n }\n } else {\n targetDataset = await promptForDatasetName({\n message: 'Target dataset name:',\n })\n }\n\n if (datasetNames.has(targetDataset)) {\n return this.output.error(`Target dataset \"${targetDataset}\" already exists`, {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n\n // Start the copy job\n try {\n this.output.log(\n `Copying dataset ${styleText('green', sourceDataset)} to ${styleText('green', targetDataset)}...`,\n )\n\n const response = await copyDataset({\n projectId,\n skipContentReleases,\n skipHistory,\n sourceDataset,\n targetDataset,\n })\n\n this.output.log(`Job ${styleText('green', response.jobId)} started`)\n\n if (flags.detach) {\n return\n }\n\n await this.subscribeToProgress(projectId, response.jobId)\n this.output.log(`Job ${styleText('green', response.jobId)} completed`)\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n copyDatasetDebug('Dataset copying failed: %s', message, error)\n return this.output.error(`Dataset copying failed: ${message}`, {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n }\n\n private async handleListMode(\n projectId: string,\n flags: {limit?: number; offset?: number},\n ): Promise<void> {\n copyDatasetDebug('Listing dataset copy jobs')\n\n try {\n const jobs = await listDatasetCopyJobs({\n limit: flags.limit,\n offset: flags.offset,\n projectId,\n })\n\n if (jobs.length === 0) {\n this.output.log(\"This project doesn't have any dataset copy jobs\")\n return\n }\n\n this.displayCopyJobsTable(jobs)\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n copyDatasetDebug('Failed to list dataset copy jobs: %s', message, error)\n return this.output.error(`Failed to list dataset copy jobs: ${message}`, {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n }\n\n private async subscribeToProgress(projectId: string, jobId: string): Promise<void> {\n const spin = spinner('').start()\n const hasCliExecutionContext = Boolean(getCliExecutionContext())\n\n return new Promise<void>((resolve, reject) => {\n const sigintHandler = () => {\n subscription.unsubscribe()\n spin.fail('Copy interrupted.')\n exit(130)\n }\n\n const subscription = followCopyJobProgress({jobId, projectId}).subscribe({\n complete: () => {\n if (!hasCliExecutionContext) process.off('SIGINT', sigintHandler)\n spin.succeed('Copy finished.')\n resolve()\n },\n error: (err) => {\n if (!hasCliExecutionContext) process.off('SIGINT', sigintHandler)\n spin.fail('Copy failed.')\n reject(err)\n },\n next: (event: CopyJobProgressEvent) => {\n if (typeof event.progress === 'number') {\n spin.text = `Copy in progress: ${event.progress}%`\n }\n },\n })\n\n if (!hasCliExecutionContext) process.once('SIGINT', sigintHandler)\n })\n }\n}\n"],"names":["styleText","Args","Flags","exit","exitCodes","subdebug","getCliExecutionContext","SanityCommand","spinner","Table","formatDistance","formatDistanceToNow","parseISO","validateDatasetName","promptForDataset","promptForDatasetName","promptForProject","copyDataset","followCopyJobProgress","listDatasetCopyJobs","listDatasets","formatCliErrorMessages","getProjectIdFlag","copyDatasetDebug","CopyDatasetCommand","args","source","string","description","required","target","examples","command","flags","semantics","attach","exclusive","detach","boolean","limit","integer","dependsOn","max","list","offset","hiddenAliases","run","parse","isUnattended","errors","push","length","output","error","USAGE_ERROR","projectId","getProjectId","fallback","requiredPermissions","grant","permission","handleListMode","handleAttachMode","handleCopyMode","displayCopyJobsTable","jobs","table","columns","alignment","name","title","job","createdAt","id","sourceDataset","state","targetDataset","updatedAt","withHistory","timeStarted","timeTaken","color","addRow","log","render","jobId","trim","RUNTIME_ERROR","subscribeToProgress","message","Error","String","skipHistory","Boolean","skipContentReleases","nameError","datasetsResponse","datasetNames","Set","map","ds","datasets","has","response","spin","start","hasCliExecutionContext","Promise","resolve","reject","sigintHandler","subscription","unsubscribe","fail","subscribe","complete","process","off","succeed","err","next","event","progress","text","once"],"mappings":"AAAA,SAAQA,SAAS,QAAO,YAAW;AAEnC,SAAQC,IAAI,EAAEC,KAAK,QAAO,cAAa;AACvC,SAAQC,IAAI,QAAO,qBAAoB;AACvC,SAAQC,SAAS,QAAO,mBAAkB;AAC1C,SAAQC,QAAQ,QAAO,yBAAwB;AAC/C,SAAQC,sBAAsB,QAAO,oCAAmC;AACxE,SAAQC,aAAa,QAAO,iCAAgC;AAC5D,SAAQC,OAAO,QAAO,sBAAqB;A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,QAAQ,CAAC,CAAC,CAAC;oBACpD;gBACF;YACF;YAEA,IAAI,CAAChB,wBAAwBU,QAAQQ,IAAI,CAAC,UAAUd;QACtD;IACF;AACF"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { Args, Flags } from '@oclif/core';
|
|
2
2
|
import { colorizeJson, exitCodes, getProjectCliClient, SanityCommand, subdebug } from '@sanity/cli-core';
|
|
3
|
+
import { getCliExecutionContext } from '@sanity/cli-core/executionContext';
|
|
3
4
|
import { DOCUMENTS_API_VERSION } from '../../actions/documents/constants.js';
|
|
4
5
|
import { promptForProject } from '../../prompts/promptForProject.js';
|
|
5
6
|
import { getDatasetFlag, getProjectIdFlag } from '../../util/sharedFlags.js';
|
|
@@ -44,8 +45,7 @@ export class QueryDocumentCommand extends SanityCommand {
|
|
|
44
45
|
description: 'Send the query without any authorization token'
|
|
45
46
|
}),
|
|
46
47
|
'api-version': Flags.string({
|
|
47
|
-
description: `API version to use (defaults to ${DOCUMENTS_API_VERSION})
|
|
48
|
-
env: 'SANITY_CLI_QUERY_API_VERSION'
|
|
48
|
+
description: `API version to use (defaults to ${DOCUMENTS_API_VERSION})`
|
|
49
49
|
}),
|
|
50
50
|
pretty: Flags.boolean({
|
|
51
51
|
default: false,
|
|
@@ -78,8 +78,9 @@ export class QueryDocumentCommand extends SanityCommand {
|
|
|
78
78
|
});
|
|
79
79
|
}
|
|
80
80
|
const targetDataset = dataset || cliConfig.api?.dataset;
|
|
81
|
-
const
|
|
82
|
-
|
|
81
|
+
const configuredApiVersion = apiVersion ?? (getCliExecutionContext() ? undefined : process.env.SANITY_CLI_QUERY_API_VERSION);
|
|
82
|
+
const targetApiVersion = configuredApiVersion || DOCUMENTS_API_VERSION;
|
|
83
|
+
if (!configuredApiVersion) {
|
|
83
84
|
this.warn(`--api-version not specified, using \`${DOCUMENTS_API_VERSION}\``);
|
|
84
85
|
}
|
|
85
86
|
try {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/commands/documents/query.ts"],"sourcesContent":["import {Args, Flags} from '@oclif/core'\nimport {\n colorizeJson,\n exitCodes,\n getProjectCliClient,\n SanityCommand,\n subdebug,\n} from '@sanity/cli-core'\n\nimport {DOCUMENTS_API_VERSION} from '../../actions/documents/constants.js'\nimport {promptForProject} from '../../prompts/promptForProject.js'\nimport {getDatasetFlag, getProjectIdFlag} from '../../util/sharedFlags.js'\n\nconst queryDocumentDebug = subdebug('documents:query')\n\nexport class QueryDocumentCommand extends SanityCommand<typeof QueryDocumentCommand> {\n static override args = {\n query: Args.string({\n description: 'GROQ query to run against the dataset',\n required: true,\n }),\n }\n\n static override description = 'Query for documents'\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %> \\'*[_type == \"movie\"][0..4]\\'',\n description: 'Fetch 5 documents of type \"movie\"',\n },\n {\n command:\n '<%= config.bin %> <%= command.id %> \\'*[_type == \"movie\"]|order(releaseDate asc)[0]{title}\\' --dataset staging',\n description: 'Fetch title of the oldest movie in the dataset named \"staging\"',\n },\n {\n command:\n '<%= config.bin %> <%= command.id %> \\'*[_id == \"header\"] { \"headerText\": pt::text(body) }\\' --api-version v2021-06-07',\n description: 'Use API version v2021-06-07 and do a query',\n },\n {\n command:\n '<%= config.bin %> <%= command.id %> \\'*[_type == \"post\"]\\' --project-id abc123 --dataset production',\n description: 'Query documents in a specific project and dataset',\n },\n ]\n\n static override flags = {\n ...getProjectIdFlag({description: 'Project ID to query', semantics: 'override'}),\n ...getDatasetFlag({description: 'Dataset to query', semantics: 'override'}),\n anonymous: Flags.boolean({\n default: false,\n description: 'Send the query without any authorization token',\n }),\n 'api-version': Flags.string({\n description: `API version to use (defaults to ${DOCUMENTS_API_VERSION})`,\n
|
|
1
|
+
{"version":3,"sources":["../../../src/commands/documents/query.ts"],"sourcesContent":["import {Args, Flags} from '@oclif/core'\nimport {\n colorizeJson,\n exitCodes,\n getProjectCliClient,\n SanityCommand,\n subdebug,\n} from '@sanity/cli-core'\nimport {getCliExecutionContext} from '@sanity/cli-core/executionContext'\n\nimport {DOCUMENTS_API_VERSION} from '../../actions/documents/constants.js'\nimport {promptForProject} from '../../prompts/promptForProject.js'\nimport {getDatasetFlag, getProjectIdFlag} from '../../util/sharedFlags.js'\n\nconst queryDocumentDebug = subdebug('documents:query')\n\nexport class QueryDocumentCommand extends SanityCommand<typeof QueryDocumentCommand> {\n static override args = {\n query: Args.string({\n description: 'GROQ query to run against the dataset',\n required: true,\n }),\n }\n\n static override description = 'Query for documents'\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %> \\'*[_type == \"movie\"][0..4]\\'',\n description: 'Fetch 5 documents of type \"movie\"',\n },\n {\n command:\n '<%= config.bin %> <%= command.id %> \\'*[_type == \"movie\"]|order(releaseDate asc)[0]{title}\\' --dataset staging',\n description: 'Fetch title of the oldest movie in the dataset named \"staging\"',\n },\n {\n command:\n '<%= config.bin %> <%= command.id %> \\'*[_id == \"header\"] { \"headerText\": pt::text(body) }\\' --api-version v2021-06-07',\n description: 'Use API version v2021-06-07 and do a query',\n },\n {\n command:\n '<%= config.bin %> <%= command.id %> \\'*[_type == \"post\"]\\' --project-id abc123 --dataset production',\n description: 'Query documents in a specific project and dataset',\n },\n ]\n\n static override flags = {\n ...getProjectIdFlag({description: 'Project ID to query', semantics: 'override'}),\n ...getDatasetFlag({description: 'Dataset to query', semantics: 'override'}),\n anonymous: Flags.boolean({\n default: false,\n description: 'Send the query without any authorization token',\n }),\n 'api-version': Flags.string({\n description: `API version to use (defaults to ${DOCUMENTS_API_VERSION})`,\n }),\n pretty: Flags.boolean({\n default: false,\n description: 'Colorize JSON output',\n }),\n project: Flags.string({\n deprecated: {to: 'project-id'},\n description: 'Project ID to query',\n hidden: true,\n }),\n }\n\n static override hiddenAliases: string[] = ['document:query']\n\n public async run(): Promise<void> {\n const {args, flags} = await this.parse(QueryDocumentCommand)\n const {query} = args\n const {anonymous, 'api-version': apiVersion, dataset, pretty} = flags\n\n const cliConfig = await this.tryGetCliConfig()\n\n const projectId = await this.getProjectId({\n deprecatedFlagName: 'project',\n fallback: () => promptForProject({}),\n })\n\n const requireUser = !anonymous\n\n if (!cliConfig.api?.dataset && !dataset) {\n this.error(\n 'Dataset is required. Pass it with `--dataset <name>` or configure it in `sanity.cli.ts`.',\n {exit: exitCodes.USAGE_ERROR},\n )\n }\n\n const targetDataset = dataset || cliConfig.api?.dataset\n const configuredApiVersion =\n apiVersion ??\n (getCliExecutionContext() ? undefined : process.env.SANITY_CLI_QUERY_API_VERSION)\n const targetApiVersion = configuredApiVersion || DOCUMENTS_API_VERSION\n\n if (!configuredApiVersion) {\n this.warn(`--api-version not specified, using \\`${DOCUMENTS_API_VERSION}\\``)\n }\n\n try {\n const projectClient = await getProjectCliClient({\n apiVersion: targetApiVersion,\n dataset: targetDataset,\n projectId,\n requireUser,\n })\n\n const docs = await projectClient.fetch(query)\n\n if (!docs) {\n this.error('Query returned no results', {exit: exitCodes.RUNTIME_ERROR})\n }\n\n // Output the query results\n if (pretty) {\n this.log(colorizeJson(docs))\n } else {\n this.log(JSON.stringify(docs, null, 2))\n }\n } catch (error) {\n const err = error as Error\n\n queryDocumentDebug(`Error running query: ${query}`, err)\n\n // Provide more context in error messages\n const errorMsg = err.message.toLowerCase().includes('syntax')\n ? `Invalid GROQ query syntax: ${err.message}`\n : `Failed to run query: ${err.message}`\n\n this.error(`${errorMsg}\\nQuery: ${query}`, {exit: exitCodes.RUNTIME_ERROR})\n }\n }\n}\n"],"names":["Args","Flags","colorizeJson","exitCodes","getProjectCliClient","SanityCommand","subdebug","getCliExecutionContext","DOCUMENTS_API_VERSION","promptForProject","getDatasetFlag","getProjectIdFlag","queryDocumentDebug","QueryDocumentCommand","args","query","string","description","required","examples","command","flags","semantics","anonymous","boolean","default","pretty","project","deprecated","to","hidden","hiddenAliases","run","parse","apiVersion","dataset","cliConfig","tryGetCliConfig","projectId","getProjectId","deprecatedFlagName","fallback","requireUser","api","error","exit","USAGE_ERROR","targetDataset","configuredApiVersion","undefined","process","env","SANITY_CLI_QUERY_API_VERSION","targetApiVersion","warn","projectClient","docs","fetch","RUNTIME_ERROR","log","JSON","stringify","err","errorMsg","message","toLowerCase","includes"],"mappings":"AAAA,SAAQA,IAAI,EAAEC,KAAK,QAAO,cAAa;AACvC,SACEC,YAAY,EACZC,SAAS,EACTC,mBAAmB,EACnBC,aAAa,EACbC,QAAQ,QACH,mBAAkB;AACzB,SAAQC,sBAAsB,QAAO,oCAAmC;AAExE,SAAQC,qBAAqB,QAAO,uCAAsC;AAC1E,SAAQC,gBAAgB,QAAO,oCAAmC;AAClE,SAAQC,cAAc,EAAEC,gBAAgB,QAAO,4BAA2B;AAE1E,MAAMC,qBAAqBN,SAAS;AAEpC,OAAO,MAAMO,6BAA6BR;IACxC,OAAgBS,OAAO;QACrBC,OAAOf,KAAKgB,MAAM,CAAC;YACjBC,aAAa;YACbC,UAAU;QACZ;IACF,EAAC;IAED,OAAgBD,cAAc,sBAAqB;IAEnD,OAAgBE,WAAW;QACzB;YACEC,SAAS;YACTH,aAAa;QACf;QACA;YACEG,SACE;YACFH,aAAa;QACf;QACA;YACEG,SACE;YACFH,aAAa;QACf;QACA;YACEG,SACE;YACFH,aAAa;QACf;KACD,CAAA;IAED,OAAgBI,QAAQ;QACtB,GAAGV,iBAAiB;YAACM,aAAa;YAAuBK,WAAW;QAAU,EAAE;QAChF,GAAGZ,eAAe;YAACO,aAAa;YAAoBK,WAAW;QAAU,EAAE;QAC3EC,WAAWtB,MAAMuB,OAAO,CAAC;YACvBC,SAAS;YACTR,aAAa;QACf;QACA,eAAehB,MAAMe,MAAM,CAAC;YAC1BC,aAAa,CAAC,gCAAgC,EAAET,sBAAsB,CAAC,CAAC;QAC1E;QACAkB,QAAQzB,MAAMuB,OAAO,CAAC;YACpBC,SAAS;YACTR,aAAa;QACf;QACAU,SAAS1B,MAAMe,MAAM,CAAC;YACpBY,YAAY;gBAACC,IAAI;YAAY;YAC7BZ,aAAa;YACba,QAAQ;QACV;IAC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G,GAAG,CAACC,KAAKC,SAAS,CAACL,MAAM,MAAM;YACtC;QACF,EAAE,OAAOZ,OAAO;YACd,MAAMkB,MAAMlB;YAEZhC,mBAAmB,CAAC,qBAAqB,EAAEG,OAAO,EAAE+C;YAEpD,yCAAyC;YACzC,MAAMC,WAAWD,IAAIE,OAAO,CAACC,WAAW,GAAGC,QAAQ,CAAC,YAChD,CAAC,2BAA2B,EAAEJ,IAAIE,OAAO,EAAE,GAC3C,CAAC,qBAAqB,EAAEF,IAAIE,OAAO,EAAE;YAEzC,IAAI,CAACpB,KAAK,CAAC,GAAGmB,SAAS,SAAS,EAAEhD,OAAO,EAAE;gBAAC8B,MAAM1C,UAAUuD,aAAa;YAAA;QAC3E;IACF;AACF"}
|
|
@@ -13,13 +13,9 @@ declare type InvocationSource = "mcp";
|
|
|
13
13
|
*
|
|
14
14
|
* @internal
|
|
15
15
|
*/
|
|
16
|
-
export declare function invokeSanityCli(
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
sanityEnv,
|
|
20
|
-
source,
|
|
21
|
-
token,
|
|
22
|
-
}: InvokeSanityCliOptions): Promise<InvokeSanityCliResult>;
|
|
16
|
+
export declare function invokeSanityCli(
|
|
17
|
+
options: InvokeSanityCliOptions,
|
|
18
|
+
): Promise<InvokeSanityCliResult>;
|
|
23
19
|
|
|
24
20
|
/**
|
|
25
21
|
* @internal
|
|
@@ -49,8 +45,8 @@ export declare interface InvokeSanityCliOptions {
|
|
|
49
45
|
config?: Config;
|
|
50
46
|
/**
|
|
51
47
|
* Sanity deployment environment for this invocation. Scoped to this call
|
|
52
|
-
* via the CLI execution context and defaults to
|
|
53
|
-
*
|
|
48
|
+
* via the CLI execution context and defaults to production. The embedding
|
|
49
|
+
* process's `SANITY_INTERNAL_ENV` is never consulted.
|
|
54
50
|
*/
|
|
55
51
|
sanityEnv?: SanityEnvironment;
|
|
56
52
|
}
|
|
@@ -19,22 +19,44 @@
|
|
|
19
19
|
* Help works like the regular CLI, scoped to the source's policy: `--help`
|
|
20
20
|
* (or `help`) renders root help listing the invokable topics, and a subject
|
|
21
21
|
* (`cors --help`, `cors list --help`) renders topic or command help.
|
|
22
|
-
*/ import { Config, Parser } from '@oclif/core';
|
|
22
|
+
*/ import { Config, Parser, settings } from '@oclif/core';
|
|
23
23
|
import { getHelpFlagAdditions, normalizeArgv } from '@oclif/core/help';
|
|
24
|
-
import {
|
|
24
|
+
import { exitCodes } from '@sanity/cli-core';
|
|
25
25
|
import { runWithCliExecutionContext } from '@sanity/cli-core/executionContext';
|
|
26
26
|
import { parseArgsStringToArgv } from 'string-argv';
|
|
27
27
|
import { commandPolicies } from './commandPolicies/index.js';
|
|
28
28
|
import { deny, isConditionalInvocationPolicy } from './commandPolicies/policy.js';
|
|
29
29
|
import { isHelpRequest, renderInvokableHelp } from './help.js';
|
|
30
30
|
import { prettyPrintError } from './prettyPrintError.js';
|
|
31
|
+
/**
|
|
32
|
+
* Instantiate a policy-approved command for isolated execution.
|
|
33
|
+
*
|
|
34
|
+
* Every invokable command extends `SanityCommand`, whose
|
|
35
|
+
* `runInExecutionContext()` runs the instance without oclif's static
|
|
36
|
+
* `Command.run()` — the static runner re-enters `Config.load()` (filesystem
|
|
37
|
+
* reads and a process-global config cache write) on every call. The manifest
|
|
38
|
+
* types command classes as the abstract oclif `Command`, hence the
|
|
39
|
+
* constructor cast. The method is probed rather than checked with
|
|
40
|
+
* `instanceof`, because command modules may load from the compiled build
|
|
41
|
+
* while this module runs from source, giving `SanityCommand` two identities.
|
|
42
|
+
*/ function instantiateCommand(CommandClass, argv, config) {
|
|
43
|
+
const ConcreteCommand = CommandClass;
|
|
44
|
+
const command = new ConcreteCommand(argv, config);
|
|
45
|
+
if (typeof command.runInExecutionContext !== 'function') {
|
|
46
|
+
throw new TypeError(`Command "${CommandClass.id}" does not support isolated execution`);
|
|
47
|
+
}
|
|
48
|
+
return command;
|
|
49
|
+
}
|
|
31
50
|
/**
|
|
32
51
|
* Load the oclif `Config` for this package, needed to resolve, load, and run
|
|
33
52
|
* commands. Loading it once and reusing it across invocations avoids
|
|
34
|
-
* re-reading the command manifest per call.
|
|
53
|
+
* re-reading the command manifest per call. It only reads this package's own
|
|
54
|
+
* installed files — process-lifetime initialization, not per-invocation host
|
|
55
|
+
* state — so it happens outside any execution context.
|
|
35
56
|
*/ function loadCliCommandConfig() {
|
|
36
57
|
return Config.load(import.meta.url);
|
|
37
58
|
}
|
|
59
|
+
let cachedConfig;
|
|
38
60
|
function unknownCommandResult(argv, policySet) {
|
|
39
61
|
const available = Object.entries(policySet).filter(([, policy])=>policy.kind !== 'deny').map(([id])=>id.replaceAll(':', ' ')).toSorted();
|
|
40
62
|
return {
|
|
@@ -45,7 +67,6 @@ function unknownCommandResult(argv, policySet) {
|
|
|
45
67
|
].join('\n')
|
|
46
68
|
};
|
|
47
69
|
}
|
|
48
|
-
let cachedConfig;
|
|
49
70
|
/**
|
|
50
71
|
* Unlike a shell, string-argv keeps quotes that are glued to unquoted text:
|
|
51
72
|
* `--name="my project"` tokenizes with the quotes intact. Strip a matching
|
|
@@ -63,15 +84,27 @@ let cachedConfig;
|
|
|
63
84
|
* relay them verbatim.
|
|
64
85
|
*
|
|
65
86
|
* @internal
|
|
66
|
-
*/ export async function invokeSanityCli(
|
|
67
|
-
|
|
87
|
+
*/ export async function invokeSanityCli(options) {
|
|
88
|
+
// Always load compiled command modules. Oclif's dev-mode source resolution
|
|
89
|
+
// otherwise probes tsconfigs (reading the filesystem and process.cwd) on
|
|
90
|
+
// every command load, and may register ts-node process-wide.
|
|
91
|
+
settings.enableAutoTranspile = false;
|
|
92
|
+
const resolvedConfig = options.config ?? await (cachedConfig ??= loadCliCommandConfig());
|
|
93
|
+
const output = [];
|
|
94
|
+
const sink = (line)=>output.push(line);
|
|
95
|
+
const { sanityEnv, token } = options;
|
|
96
|
+
// Establish the isolation boundary before rendering help, loading command
|
|
97
|
+
// modules, parsing, or executing. Any code reached by an external
|
|
98
|
+
// invocation can therefore fail closed on context.
|
|
99
|
+
return runWithCliExecutionContext({
|
|
100
|
+
sanityEnv,
|
|
101
|
+
stderr: sink,
|
|
102
|
+
stdout: sink,
|
|
103
|
+
token
|
|
104
|
+
}, ()=>invokeSanityCliInContext(options, resolvedConfig, output));
|
|
105
|
+
}
|
|
106
|
+
async function invokeSanityCliInContext({ args, source }, resolvedConfig, output) {
|
|
68
107
|
const policySet = commandPolicies[source];
|
|
69
|
-
// Commands log through the global telemetry store; default it to a noop
|
|
70
|
-
// store so embedding hosts need no telemetry wiring (and see no warnings),
|
|
71
|
-
// without clobbering a store the host may have installed itself.
|
|
72
|
-
if (!globalThis[CLI_TELEMETRY_SYMBOL]) {
|
|
73
|
-
setCliTelemetry(noopLogger);
|
|
74
|
-
}
|
|
75
108
|
// Pre-split argv arrays are taken verbatim; only string input goes through
|
|
76
109
|
// shell-style tokenization and quote normalization.
|
|
77
110
|
let argv = typeof args === 'string' ? parseArgsStringToArgv(args).map((t)=>stripFlagQuotes(t)) : [
|
|
@@ -149,15 +182,9 @@ let cachedConfig;
|
|
|
149
182
|
output
|
|
150
183
|
};
|
|
151
184
|
}
|
|
152
|
-
const output = [];
|
|
153
|
-
const sink = (line)=>output.push(line);
|
|
154
185
|
try {
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
stderr: sink,
|
|
158
|
-
stdout: sink,
|
|
159
|
-
token
|
|
160
|
-
}, ()=>CommandClass.run(commandArgv, resolvedConfig));
|
|
186
|
+
const command = instantiateCommand(CommandClass, commandArgv, resolvedConfig);
|
|
187
|
+
await command.runInExecutionContext();
|
|
161
188
|
return {
|
|
162
189
|
commandId,
|
|
163
190
|
exitCode: exitCodes.SUCCESS,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/exports/invokeSanityCli/index.ts"],"sourcesContent":["/**\n * Programmatic (in-process) invocation of CLI commands, e.g. from an MCP\n * server. The invokable surface is governed by a per-source command policy\n * (see ./commandPolicies): every CLI command is explicitly allowed, denied,\n * or allowed conditionally on the parsed invocation.\n *\n * {@link invokeSanityCli} handles arg parsing, policy enforcement, command\n * dispatch, per-invocation auth, and output capture.\n * ```ts\n * import {invokeSanityCli} from '@sanity/cli/invokeSanityCli'\n *\n * const {exitCode, output} = await invokeSanityCli({\n * args: 'cors list --project-id abc123',\n * source: 'mcp',\n * token: extra.authInfo.token,\n * })\n * ```\n *\n * Help works like the regular CLI, scoped to the source's policy: `--help`\n * (or `help`) renders root help listing the invokable topics, and a subject\n * (`cors --help`, `cors list --help`) renders topic or command help.\n */\nimport {Config, Parser} from '@oclif/core'\nimport {getHelpFlagAdditions, normalizeArgv} from '@oclif/core/help'\nimport {CLI_TELEMETRY_SYMBOL, exitCodes, noopLogger, setCliTelemetry} from '@sanity/cli-core'\nimport {runWithCliExecutionContext, type SanityEnvironment} from '@sanity/cli-core/executionContext'\nimport {parseArgsStringToArgv} from 'string-argv'\n\nimport {commandPolicies} from './commandPolicies/index.js'\nimport {\n type CommandPolicySet,\n deny,\n type InvocationSource,\n isConditionalInvocationPolicy,\n} from './commandPolicies/policy.js'\nimport {isHelpRequest, renderInvokableHelp} from './help.js'\nimport {prettyPrintError} from './prettyPrintError.js'\n\n/**\n * Load the oclif `Config` for this package, needed to resolve, load, and run\n * commands. Loading it once and reusing it across invocations avoids\n * re-reading the command manifest per call.\n */\nfunction loadCliCommandConfig(): Promise<Config> {\n return Config.load(import.meta.url)\n}\n\nfunction unknownCommandResult(argv: string[], policySet: CommandPolicySet): InvokeSanityCliResult {\n const available = Object.entries(policySet)\n .filter(([, policy]) => policy.kind !== 'deny')\n .map(([id]) => id.replaceAll(':', ' '))\n .toSorted()\n return {\n exitCode: exitCodes.USAGE_ERROR,\n output: [\n `Unknown or unsupported command: ${argv.slice(0, 2).join(' ') || '(none)'}`,\n `Available commands: ${available.join(', ')}`,\n ].join('\\n'),\n }\n}\n\n/**\n * @internal\n */\nexport interface InvokeSanityCliOptions {\n /**\n * Arguments after `sanity` (a leading `sanity` token is tolerated), either\n * as a single string — shell-style quoting is supported, but no shell is\n * ever executed — or as a pre-split argv array.\n */\n args: string | string[]\n\n /**\n * Where this invocation originates. Selects the command policy to enforce:\n * which commands are invokable and which invocations of them are permitted.\n */\n source: InvocationSource\n\n /**\n * Auth token for this invocation. Scoped to this call via the CLI execution\n * context: it never touches process env or the process-wide token cache, so\n * concurrent invocations with different tokens are fully isolated.\n */\n token: string\n\n /**\n * Optional oclif config override (mainly for tests). Defaults to this\n * package's config, loaded once and cached across invocations.\n */\n config?: Config\n\n /**\n * Sanity deployment environment for this invocation. Scoped to this call\n * via the CLI execution context and defaults to `SANITY_INTERNAL_ENV` (or\n * production when it is unset).\n */\n sanityEnv?: SanityEnvironment\n}\n\n/**\n * @internal\n */\nexport interface InvokeSanityCliResult {\n /** `0` on success, the command's exit code otherwise. */\n exitCode: number\n\n /** Combined stdout and stderr output, in emission order. */\n output: string\n\n /**\n * Canonical oclif command id when the invocation resolved to a command\n * exposed by the selected policy (for example, `datasets:create`).\n */\n commandId?: string\n}\n\nlet cachedConfig: Promise<Config> | undefined\n\n/**\n * Unlike a shell, string-argv keeps quotes that are glued to unquoted text:\n * `--name=\"my project\"` tokenizes with the quotes intact. Strip a matching\n * wrapping quote pair from the value side of `--flag=`-shaped tokens so the\n * common shell-style form yields the value the caller intended.\n */\nfunction stripFlagQuotes(rawToken: string): string {\n const match = /^(-{1,2}[^\\s=]+=)(['\"])([\\s\\S]*)\\2$/.exec(rawToken)\n return match ? match[1] + match[3] : rawToken\n}\n\n/**\n * Run a policy-permitted CLI command in-process and capture its result.\n *\n * Command-level failures (unknown command, bad flags, API errors) are\n * reported through `exitCode`/`output` rather than thrown, so callers can\n * relay them verbatim.\n *\n * @internal\n */\nexport async function invokeSanityCli({\n args,\n config,\n sanityEnv,\n source,\n token,\n}: InvokeSanityCliOptions): Promise<InvokeSanityCliResult> {\n const resolvedConfig = config ?? (await (cachedConfig ??= loadCliCommandConfig()))\n const policySet = commandPolicies[source]\n\n // Commands log through the global telemetry store; default it to a noop\n // store so embedding hosts need no telemetry wiring (and see no warnings),\n // without clobbering a store the host may have installed itself.\n if (!(globalThis as Record<symbol, unknown>)[CLI_TELEMETRY_SYMBOL]) {\n setCliTelemetry(noopLogger)\n }\n\n // Pre-split argv arrays are taken verbatim; only string input goes through\n // shell-style tokenization and quote normalization.\n let argv =\n typeof args === 'string'\n ? parseArgsStringToArgv(args).map((t) => stripFlagQuotes(t))\n : [...args]\n if (argv[0] === 'sanity') argv = argv.slice(1)\n\n // Help requests are routed through oclif's help system, scoped to the\n // source's policy: root help for a bare request, topic/command help when a\n // subject is given. Denied subjects get the standard unknown-command\n // response (identical to a truly unknown command, so hosts can't probe the\n // full CLI surface through help), and a help request never executes a\n // command.\n if (isHelpRequest(argv, resolvedConfig)) {\n try {\n // Drop a leading `help` so the rest is the subject, mirroring how\n // oclif's dispatch consumes the token before the help command sees argv\n const helpArgv = argv[0] === 'help' ? argv.slice(1) : argv\n const result = await renderInvokableHelp(resolvedConfig, helpArgv, policySet)\n if (result) return {...result, exitCode: exitCodes.SUCCESS}\n const helpFlags = getHelpFlagAdditions(resolvedConfig)\n return unknownCommandResult(\n helpArgv.filter((token) => !helpFlags.includes(token)),\n policySet,\n )\n } catch (err) {\n return {\n exitCode: exitCodes.RUNTIME_ERROR,\n output: err instanceof Error ? err.message : String(err),\n }\n }\n }\n\n // Resolve the command id the same way oclif's dispatch would (collating\n // space-separated topics, accepting colon-separated ids as-is), then apply\n // the policy. Denied and uncategorized ids fail closed, indistinguishable\n // from commands that don't exist.\n const [commandId = '', ...commandArgv] = normalizeArgv(resolvedConfig, argv)\n const policy = policySet[commandId] ?? deny\n const commandDefinition =\n policy.kind === 'deny' ? undefined : resolvedConfig.findCommand(commandId)\n if (!commandDefinition) return unknownCommandResult(argv, policySet)\n\n const CommandClass = await commandDefinition.load()\n\n // Parse with the command's real definitions (without executing anything) so\n // conditional policies are evaluated against typed args/flags, not tokens.\n let invocation: {args: Record<string, unknown>; flags: Record<string, unknown>}\n try {\n const parsed = await Parser.parse(commandArgv, {\n args: CommandClass.args,\n baseFlags: CommandClass.baseFlags,\n enableJsonFlag: CommandClass.enableJsonFlag,\n flags: CommandClass.flags,\n strict: CommandClass.strict,\n })\n invocation = {\n args: parsed.args as Record<string, unknown>,\n flags: parsed.flags as Record<string, unknown>,\n }\n } catch (err) {\n return {\n commandId,\n exitCode: exitCodes.USAGE_ERROR,\n output: err instanceof Error ? err.message : String(err),\n }\n }\n\n if (!policy.validate(invocation)) {\n const displayId = commandId.replaceAll(':', ' ')\n let output = `This invocation of \\`${displayId}\\` is not supported here`\n\n if (isConditionalInvocationPolicy(policy)) {\n const usedDeniedFlags = policy.deniedFlags.filter(\n (name) => invocation.flags[name] !== undefined && invocation.flags[name] !== false,\n )\n if (usedDeniedFlags.length > 0) {\n output = `\\nThe ${usedDeniedFlags.map((name) => `--${name}`).join(', ')} flag is not supported here for \\`${displayId}\\``\n }\n }\n\n return {\n commandId,\n exitCode: exitCodes.USAGE_ERROR,\n output,\n }\n }\n\n const output: string[] = []\n const sink = (line: string) => output.push(line)\n\n try {\n await runWithCliExecutionContext({sanityEnv, stderr: sink, stdout: sink, token}, () =>\n CommandClass.run(commandArgv, resolvedConfig),\n )\n return {commandId, exitCode: exitCodes.SUCCESS, output: output.join('\\n')}\n } catch (err) {\n const exit = err.oclif?.exit\n\n // `this.exit(0)` throws an ExitError but is a successful outcome\n if (exit === exitCodes.SUCCESS) {\n return {commandId, exitCode: exitCodes.SUCCESS, output: output.join('\\n')}\n }\n\n const message = prettyPrintError(err) || String(err)\n if (message) output.push(message)\n return {\n commandId,\n exitCode: typeof exit === 'number' ? exit : exitCodes.RUNTIME_ERROR,\n output: output.join('\\n'),\n }\n }\n}\n"],"names":["Config","Parser","getHelpFlagAdditions","normalizeArgv","CLI_TELEMETRY_SYMBOL","exitCodes","noopLogger","setCliTelemetry","runWithCliExecutionContext","parseArgsStringToArgv","commandPolicies","deny","isConditionalInvocationPolicy","isHelpRequest","renderInvokableHelp","prettyPrintError","loadCliCommandConfig","load","url","unknownCommandResult","argv","policySet","available","Object","entries","filter","policy","kind","map","id","replaceAll","toSorted","exitCode","USAGE_ERROR","output","slice","join","cachedConfig","stripFlagQuotes","rawToken","match","exec","invokeSanityCli","args","config","sanityEnv","source","token","resolvedConfig","globalThis","t","helpArgv","result","SUCCESS","helpFlags","includes","err","RUNTIME_ERROR","Error","message","String","commandId","commandArgv","commandDefinition","undefined","findCommand","CommandClass","invocation","parsed","parse","baseFlags","enableJsonFlag","flags","strict","validate","displayId","usedDeniedFlags","deniedFlags","name","length","sink","line","push","stderr","stdout","run","exit","oclif"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;CAqBC,GACD,SAAQA,MAAM,EAAEC,MAAM,QAAO,cAAa;AAC1C,SAAQC,oBAAoB,EAAEC,aAAa,QAAO,mBAAkB;AACpE,SAAQC,oBAAoB,EAAEC,SAAS,EAAEC,UAAU,EAAEC,eAAe,QAAO,mBAAkB;AAC7F,SAAQC,0BAA0B,QAA+B,oCAAmC;AACpG,SAAQC,qBAAqB,QAAO,cAAa;AAEjD,SAAQC,eAAe,QAAO,6BAA4B;AAC1D,SAEEC,IAAI,EAEJC,6BAA6B,QACxB,8BAA6B;AACpC,SAAQC,aAAa,EAAEC,mBAAmB,QAAO,YAAW;AAC5D,SAAQC,gBAAgB,QAAO,wBAAuB;AAEtD;;;;CAIC,GACD,SAASC;IACP,OAAOhB,OAAOiB,IAAI,CAAC,YAAYC,GAAG;AACpC;AAEA,SAASC,qBAAqBC,IAAc,EAAEC,SAA2B;IACvE,MAAMC,YAAYC,OAAOC,OAAO,CAACH,WAC9BI,MAAM,CAAC,CAAC,GAAGC,OAAO,GAAKA,OAAOC,IAAI,KAAK,QACvCC,GAAG,CAAC,CAAC,CAACC,GAAG,GAAKA,GAAGC,UAAU,CAAC,KAAK,MACjCC,QAAQ;IACX,OAAO;QACLC,UAAU3B,UAAU4B,WAAW;QAC/BC,QAAQ;YACN,CAAC,gCAAgC,EAAEd,KAA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oD,aAAa;YACnEvB,QAAQA,OAAOE,IAAI,CAAC;QACtB;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/exports/invokeSanityCli/index.ts"],"sourcesContent":["/**\n * Programmatic (in-process) invocation of CLI commands, e.g. from an MCP\n * server. The invokable surface is governed by a per-source command policy\n * (see ./commandPolicies): every CLI command is explicitly allowed, denied,\n * or allowed conditionally on the parsed invocation.\n *\n * {@link invokeSanityCli} handles arg parsing, policy enforcement, command\n * dispatch, per-invocation auth, and output capture.\n * ```ts\n * import {invokeSanityCli} from '@sanity/cli/invokeSanityCli'\n *\n * const {exitCode, output} = await invokeSanityCli({\n * args: 'cors list --project-id abc123',\n * source: 'mcp',\n * token: extra.authInfo.token,\n * })\n * ```\n *\n * Help works like the regular CLI, scoped to the source's policy: `--help`\n * (or `help`) renders root help listing the invokable topics, and a subject\n * (`cors --help`, `cors list --help`) renders topic or command help.\n */\nimport {Command, Config, Parser, settings} from '@oclif/core'\nimport {getHelpFlagAdditions, normalizeArgv} from '@oclif/core/help'\nimport {exitCodes} from '@sanity/cli-core'\nimport {runWithCliExecutionContext, type SanityEnvironment} from '@sanity/cli-core/executionContext'\nimport {type SanityCommand} from '@sanity/cli-core/SanityCommand'\nimport {parseArgsStringToArgv} from 'string-argv'\n\nimport {commandPolicies} from './commandPolicies/index.js'\nimport {\n type CommandPolicySet,\n deny,\n type InvocationSource,\n isConditionalInvocationPolicy,\n} from './commandPolicies/policy.js'\nimport {isHelpRequest, renderInvokableHelp} from './help.js'\nimport {prettyPrintError} from './prettyPrintError.js'\n\ntype InvokableCommand = Pick<SanityCommand<typeof Command>, 'runInExecutionContext'>\n\n/**\n * Instantiate a policy-approved command for isolated execution.\n *\n * Every invokable command extends `SanityCommand`, whose\n * `runInExecutionContext()` runs the instance without oclif's static\n * `Command.run()` — the static runner re-enters `Config.load()` (filesystem\n * reads and a process-global config cache write) on every call. The manifest\n * types command classes as the abstract oclif `Command`, hence the\n * constructor cast. The method is probed rather than checked with\n * `instanceof`, because command modules may load from the compiled build\n * while this module runs from source, giving `SanityCommand` two identities.\n */\nfunction instantiateCommand(\n CommandClass: Command.Class,\n argv: string[],\n config: Config,\n): InvokableCommand {\n const ConcreteCommand = CommandClass as unknown as new (argv: string[], config: Config) => Command\n const command = new ConcreteCommand(argv, config) as Command & Partial<InvokableCommand>\n if (typeof command.runInExecutionContext !== 'function') {\n throw new TypeError(`Command \"${CommandClass.id}\" does not support isolated execution`)\n }\n return command as InvokableCommand\n}\n\n/**\n * Load the oclif `Config` for this package, needed to resolve, load, and run\n * commands. Loading it once and reusing it across invocations avoids\n * re-reading the command manifest per call. It only reads this package's own\n * installed files — process-lifetime initialization, not per-invocation host\n * state — so it happens outside any execution context.\n */\nfunction loadCliCommandConfig(): Promise<Config> {\n return Config.load(import.meta.url)\n}\n\nlet cachedConfig: Promise<Config> | undefined\n\nfunction unknownCommandResult(argv: string[], policySet: CommandPolicySet): InvokeSanityCliResult {\n const available = Object.entries(policySet)\n .filter(([, policy]) => policy.kind !== 'deny')\n .map(([id]) => id.replaceAll(':', ' '))\n .toSorted()\n return {\n exitCode: exitCodes.USAGE_ERROR,\n output: [\n `Unknown or unsupported command: ${argv.slice(0, 2).join(' ') || '(none)'}`,\n `Available commands: ${available.join(', ')}`,\n ].join('\\n'),\n }\n}\n\n/**\n * @internal\n */\nexport interface InvokeSanityCliOptions {\n /**\n * Arguments after `sanity` (a leading `sanity` token is tolerated), either\n * as a single string — shell-style quoting is supported, but no shell is\n * ever executed — or as a pre-split argv array.\n */\n args: string | string[]\n\n /**\n * Where this invocation originates. Selects the command policy to enforce:\n * which commands are invokable and which invocations of them are permitted.\n */\n source: InvocationSource\n\n /**\n * Auth token for this invocation. Scoped to this call via the CLI execution\n * context: it never touches process env or the process-wide token cache, so\n * concurrent invocations with different tokens are fully isolated.\n */\n token: string\n\n /**\n * Optional oclif config override (mainly for tests). Defaults to this\n * package's config, loaded once and cached across invocations.\n */\n config?: Config\n\n /**\n * Sanity deployment environment for this invocation. Scoped to this call\n * via the CLI execution context and defaults to production. The embedding\n * process's `SANITY_INTERNAL_ENV` is never consulted.\n */\n sanityEnv?: SanityEnvironment\n}\n\n/**\n * @internal\n */\nexport interface InvokeSanityCliResult {\n /** `0` on success, the command's exit code otherwise. */\n exitCode: number\n\n /** Combined stdout and stderr output, in emission order. */\n output: string\n\n /**\n * Canonical oclif command id when the invocation resolved to a command\n * exposed by the selected policy (for example, `datasets:create`).\n */\n commandId?: string\n}\n\n/**\n * Unlike a shell, string-argv keeps quotes that are glued to unquoted text:\n * `--name=\"my project\"` tokenizes with the quotes intact. Strip a matching\n * wrapping quote pair from the value side of `--flag=`-shaped tokens so the\n * common shell-style form yields the value the caller intended.\n */\nfunction stripFlagQuotes(rawToken: string): string {\n const match = /^(-{1,2}[^\\s=]+=)(['\"])([\\s\\S]*)\\2$/.exec(rawToken)\n return match ? match[1] + match[3] : rawToken\n}\n\n/**\n * Run a policy-permitted CLI command in-process and capture its result.\n *\n * Command-level failures (unknown command, bad flags, API errors) are\n * reported through `exitCode`/`output` rather than thrown, so callers can\n * relay them verbatim.\n *\n * @internal\n */\nexport async function invokeSanityCli(\n options: InvokeSanityCliOptions,\n): Promise<InvokeSanityCliResult> {\n // Always load compiled command modules. Oclif's dev-mode source resolution\n // otherwise probes tsconfigs (reading the filesystem and process.cwd) on\n // every command load, and may register ts-node process-wide.\n settings.enableAutoTranspile = false\n\n const resolvedConfig = options.config ?? (await (cachedConfig ??= loadCliCommandConfig()))\n const output: string[] = []\n const sink = (line: string) => output.push(line)\n const {sanityEnv, token} = options\n\n // Establish the isolation boundary before rendering help, loading command\n // modules, parsing, or executing. Any code reached by an external\n // invocation can therefore fail closed on context.\n return runWithCliExecutionContext({sanityEnv, stderr: sink, stdout: sink, token}, () =>\n invokeSanityCliInContext(options, resolvedConfig, output),\n )\n}\n\nasync function invokeSanityCliInContext(\n {args, source}: InvokeSanityCliOptions,\n resolvedConfig: Config,\n output: string[],\n): Promise<InvokeSanityCliResult> {\n const policySet = commandPolicies[source]\n\n // Pre-split argv arrays are taken verbatim; only string input goes through\n // shell-style tokenization and quote normalization.\n let argv =\n typeof args === 'string'\n ? parseArgsStringToArgv(args).map((t) => stripFlagQuotes(t))\n : [...args]\n if (argv[0] === 'sanity') argv = argv.slice(1)\n\n // Help requests are routed through oclif's help system, scoped to the\n // source's policy: root help for a bare request, topic/command help when a\n // subject is given. Denied subjects get the standard unknown-command\n // response (identical to a truly unknown command, so hosts can't probe the\n // full CLI surface through help), and a help request never executes a\n // command.\n if (isHelpRequest(argv, resolvedConfig)) {\n try {\n // Drop a leading `help` so the rest is the subject, mirroring how\n // oclif's dispatch consumes the token before the help command sees argv\n const helpArgv = argv[0] === 'help' ? argv.slice(1) : argv\n const result = await renderInvokableHelp(resolvedConfig, helpArgv, policySet)\n if (result) return {...result, exitCode: exitCodes.SUCCESS}\n const helpFlags = getHelpFlagAdditions(resolvedConfig)\n return unknownCommandResult(\n helpArgv.filter((token) => !helpFlags.includes(token)),\n policySet,\n )\n } catch (err) {\n return {\n exitCode: exitCodes.RUNTIME_ERROR,\n output: err instanceof Error ? err.message : String(err),\n }\n }\n }\n\n // Resolve the command id the same way oclif's dispatch would (collating\n // space-separated topics, accepting colon-separated ids as-is), then apply\n // the policy. Denied and uncategorized ids fail closed, indistinguishable\n // from commands that don't exist.\n const [commandId = '', ...commandArgv] = normalizeArgv(resolvedConfig, argv)\n const policy = policySet[commandId] ?? deny\n const commandDefinition =\n policy.kind === 'deny' ? undefined : resolvedConfig.findCommand(commandId)\n if (!commandDefinition) return unknownCommandResult(argv, policySet)\n\n const CommandClass = await commandDefinition.load()\n\n // Parse with the command's real definitions (without executing anything) so\n // conditional policies are evaluated against typed args/flags, not tokens.\n let invocation: {args: Record<string, unknown>; flags: Record<string, unknown>}\n try {\n const parsed = await Parser.parse(commandArgv, {\n args: CommandClass.args,\n baseFlags: CommandClass.baseFlags,\n enableJsonFlag: CommandClass.enableJsonFlag,\n flags: CommandClass.flags,\n strict: CommandClass.strict,\n })\n invocation = {\n args: parsed.args as Record<string, unknown>,\n flags: parsed.flags as Record<string, unknown>,\n }\n } catch (err) {\n return {\n commandId,\n exitCode: exitCodes.USAGE_ERROR,\n output: err instanceof Error ? err.message : String(err),\n }\n }\n\n if (!policy.validate(invocation)) {\n const displayId = commandId.replaceAll(':', ' ')\n let output = `This invocation of \\`${displayId}\\` is not supported here`\n\n if (isConditionalInvocationPolicy(policy)) {\n const usedDeniedFlags = policy.deniedFlags.filter(\n (name) => invocation.flags[name] !== undefined && invocation.flags[name] !== false,\n )\n if (usedDeniedFlags.length > 0) {\n output = `\\nThe ${usedDeniedFlags.map((name) => `--${name}`).join(', ')} flag is not supported here for \\`${displayId}\\``\n }\n }\n\n return {\n commandId,\n exitCode: exitCodes.USAGE_ERROR,\n output,\n }\n }\n\n try {\n const command = instantiateCommand(CommandClass, commandArgv, resolvedConfig)\n await command.runInExecutionContext()\n return {commandId, exitCode: exitCodes.SUCCESS, output: output.join('\\n')}\n } catch (err) {\n const exit = err.oclif?.exit\n\n // `this.exit(0)` throws an ExitError but is a successful outcome\n if (exit === exitCodes.SUCCESS) {\n return {commandId, exitCode: exitCodes.SUCCESS, output: output.join('\\n')}\n }\n\n const message = prettyPrintError(err) || String(err)\n if (message) output.push(message)\n return {\n commandId,\n exitCode: typeof exit === 'number' ? exit : exitCodes.RUNTIME_ERROR,\n output: output.join('\\n'),\n }\n }\n}\n"],"names":["Config","Parser","settings","getHelpFlagAdditions","normalizeArgv","exitCodes","runWithCliExecutionContext","parseArgsStringToArgv","commandPolicies","deny","isConditionalInvocationPolicy","isHelpRequest","renderInvokableHelp","prettyPrintError","instantiateCommand","CommandClass","argv","config","ConcreteCommand","command","runInExecutionContext","TypeError","id","loadCliCommandConfig","load","url","cachedConfig","unknownCommandResult","policySet","available","Object","entries","filter","policy","kind","map","replaceAll","toSorted","exitCode","USAGE_ERROR","output","slice","join","stripFlagQuotes","rawToken","match","exec","invokeSanityCli","options","enableAutoTranspile","resolvedConfig","sink","line","push","sanityEnv","token","stderr","stdout","invokeSanityCliInContext","args","source","t","helpArgv","result","SUCCESS","helpFlags","includes","err","RUNTIME_ERROR","Error","message","String","commandId","commandArgv","commandDefinition","undefined","findCommand","invocation","parsed","parse","baseFlags","enableJsonFlag","flags","strict","validate","displayId","usedDeniedFlags","deniedFlags","name","length","exit","oclif"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;CAqBC,GACD,SAAiBA,MAAM,EAAEC,MAAM,EAAEC,QAAQ,QAAO,cAAa;AAC7D,SAAQC,oBAAoB,EAAEC,aAAa,QAAO,mBAAkB;AACpE,SAAQC,SAAS,QAAO,mBAAkB;AAC1C,SAAQC,0BAA0B,QAA+B,oCAAmC;AAEpG,SAAQC,qBAAqB,QAAO,cAAa;AAEjD,SAAQC,eAAe,QAAO,6BAA4B;AAC1D,SAEEC,IAAI,EAEJC,6BAA6B,QACxB,8BAA6B;AACpC,SAAQC,aAAa,EAAEC,mBAAmB,QAAO,YAAW;AAC5D,SAAQC,gBAAgB,QAAO,wBAAuB;AAItD;;;;;;;;;;;CAWC,GACD,SAASC,mBACPC,YAA2B,EAC3BC,IAAc,EACdC,MAAc;IAEd,MAAMC,kBAAkBH;IACxB,MAAMI,UAAU,IAAID,gBAAgBF,MAAMC;IAC1C,IAAI,OAAOE,QAAQC,qBAAqB,KAAK,YAAY;QACvD,MAAM,IAAIC,UAAU,CAAC,SAAS,EAAEN,aAAaO,EAAE,CAAC,qCAAqC,CAAC;IACxF;IACA,OAAOH;AACT;AAEA;;;;;;CAMC,GACD,SAASI;IACP,OAAOvB,OAAOwB,IAAI,CAAC,YAAYC,GAAG;AACpC;AAEA,IAAIC;AAEJ,SAASC,qBAAqBX,IAAc,EAAEY,SAA2B;IACvE,MAAMC,YAAYC,OAAOC,OAAO,CAACH,WAC9BI,MAAM,CAAC,CAAC,GAAGC,OAAO,GAAKA,OAAOC,IAAI,KAAK,QACvCC,GAAG,CAAC,CAAC,CAACb,GAAG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AiE;QACjE,IAAIA,SAASrF,UAAU2D,OAAO,EAAE;YAC9B,OAAO;gBAACQ;gBAAWlC,UAAUjC,UAAU2D,OAAO;gBAAExB,QAAQA,OAAOE,IAAI,CAAC;YAAK;QAC3E;QAEA,MAAM4B,UAAUzD,iBAAiBsD,QAAQI,OAAOJ;QAChD,IAAIG,SAAS9B,OAAOa,IAAI,CAACiB;QACzB,OAAO;YACLE;YACAlC,UAAU,OAAOoD,SAAS,WAAWA,OAAOrF,UAAU+D,aAAa;YACnE5B,QAAQA,OAAOE,IAAI,CAAC;QACtB;IACF;AACF"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
2
|
import { getCliToken, getGlobalCliClient, getUserConfig } from '@sanity/cli-core';
|
|
3
|
+
import { getCliExecutionContext } from '@sanity/cli-core/executionContext';
|
|
3
4
|
import { telemetryDebug } from '../actions/telemetry/telemetryDebug.js';
|
|
4
5
|
import { createExpiringConfig } from '../util/createExpiringConfig.js';
|
|
5
6
|
export const TELEMETRY_API_VERSION = 'v2026-01-22';
|
|
@@ -74,6 +75,9 @@ const FIVE_MINUTES = 1000 * 60 * 5;
|
|
|
74
75
|
*
|
|
75
76
|
* @internal
|
|
76
77
|
*/ export async function fetchTelemetryConsent() {
|
|
78
|
+
// Programmatic invocations must not use the host user's disk-backed consent
|
|
79
|
+
// cache. The request is already authenticated with the invocation token.
|
|
80
|
+
if (getCliExecutionContext()) return getTelemetryConsent();
|
|
77
81
|
const token = await getCliToken();
|
|
78
82
|
const cacheKey = getTelemetryConsentCacheKey(token);
|
|
79
83
|
// NOTE: createExpiringConfig is instantiated on every call, so in-flight request
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/services/telemetry.ts"],"sourcesContent":["import {createHash} from 'node:crypto'\n\nimport {getCliToken, getGlobalCliClient, getUserConfig} from '@sanity/cli-core'\nimport {type TelemetryEvent} from '@sanity/telemetry'\n\nimport {telemetryDebug} from '../actions/telemetry/telemetryDebug.js'\nimport {createExpiringConfig} from '../util/createExpiringConfig.js'\n\nexport const TELEMETRY_API_VERSION = 'v2026-01-22'\n\nexport const VALID_API_STATUSES = ['granted', 'denied', 'unset'] as const\nexport type ValidApiConsentStatus = (typeof VALID_API_STATUSES)[number]\n\nexport async function sendEvents(batch: TelemetryEvent[]) {\n const client = await getGlobalCliClient({\n apiVersion: TELEMETRY_API_VERSION,\n requireUser: true,\n })\n\n const projectId = process.env.SANITY_TELEMETRY_PROJECT_ID\n\n return client.request({\n body: {batch, projectId},\n json: true,\n method: 'POST',\n uri: '/intake/batch',\n })\n}\n\nasync function getTelemetryConsent(): Promise<{\n status: ValidApiConsentStatus\n}> {\n const client = await getGlobalCliClient({\n apiVersion: TELEMETRY_API_VERSION,\n requireUser: false,\n })\n\n return client.request({tag: 'telemetry-consent', uri: '/intake/telemetry-status'})\n}\n\n/**\n * Check if the given status is a valid consent status\n *\n * @param status - The status to check\n * @returns True if the status is valid, false otherwise\n * @internal\n */\nexport function isValidApiConsentStatus(status: string): status is ValidApiConsentStatus {\n return VALID_API_STATUSES.includes(status as ValidApiConsentStatus)\n}\n\n/**\n * Check if the given response is a valid API consent response\n *\n * @param response - The response to check\n * @returns True if the response is valid, false otherwise\n * @internal\n */\nfunction isValidApiConsentResponse(response: unknown): response is {status: ValidApiConsentStatus} {\n return (\n typeof response === 'object' &&\n response !== null &&\n 'status' in response &&\n typeof response.status === 'string' &&\n isValidApiConsentStatus(response.status)\n )\n}\n\nexport const TELEMETRY_CONSENT_CONFIG_KEY = 'telemetryConsent'\nconst FIVE_MINUTES = 1000 * 60 * 5\n\n/**\n * Get a token-scoped cache key for telemetry consent. This ensures that switching\n * users (via login/logout) always results in a cache miss, preventing one user\n * from inheriting another user's cached consent status.\n *\n * @param token - The current auth token, or undefined if not logged in\n * @returns A cache key scoped to the token\n */\nexport function getTelemetryConsentCacheKey(token: string | undefined): string {\n if (!token) {\n return TELEMETRY_CONSENT_CONFIG_KEY\n }\n\n const hash = createHash('sha256').update(token).digest('hex').slice(0, 12)\n return `${TELEMETRY_CONSENT_CONFIG_KEY}:${hash}`\n}\n\n/**\n * Fetch the telemetry consent status for the current user\n * @returns The telemetry consent status\n *\n * @internal\n */\nexport async function fetchTelemetryConsent(): Promise<{\n status: ValidApiConsentStatus\n}> {\n const token = await getCliToken()\n const cacheKey = getTelemetryConsentCacheKey(token)\n\n // NOTE: createExpiringConfig is instantiated on every call, so in-flight request\n // deduplication (via currentFetch) does not work across concurrent calls to\n // fetchTelemetryConsent(). Two concurrent callers will make two HTTP requests.\n // Consider moving to module-level instance if this becomes a bottleneck.\n const telemetryConsentConfig = createExpiringConfig<{\n status: ValidApiConsentStatus\n }>({\n fetchValue: () => getTelemetryConsent(),\n key: cacheKey,\n onCacheHit() {\n telemetryDebug('Retrieved telemetry consent status from cache')\n },\n onFetch() {\n telemetryDebug('Fetching telemetry consent status...')\n },\n onRevalidate() {\n telemetryDebug('Revalidating cached telemetry consent status...')\n },\n store: getUserConfig(),\n ttl: FIVE_MINUTES,\n validateValue: isValidApiConsentResponse,\n })\n\n return telemetryConsentConfig.get()\n}\n"],"names":["createHash","getCliToken","getGlobalCliClient","getUserConfig","telemetryDebug","createExpiringConfig","TELEMETRY_API_VERSION","VALID_API_STATUSES","sendEvents","batch","client","apiVersion","requireUser","projectId","process","env","SANITY_TELEMETRY_PROJECT_ID","request","body","json","method","uri","getTelemetryConsent","tag","isValidApiConsentStatus","status","includes","isValidApiConsentResponse","response","TELEMETRY_CONSENT_CONFIG_KEY","FIVE_MINUTES","getTelemetryConsentCacheKey","token","hash","update","digest","slice","fetchTelemetryConsent","cacheKey","telemetryConsentConfig","fetchValue","key","onCacheHit","onFetch","onRevalidate","store","ttl","validateValue","get"],"mappings":"AAAA,SAAQA,UAAU,QAAO,cAAa;AAEtC,SAAQC,WAAW,EAAEC,kBAAkB,EAAEC,aAAa,QAAO,mBAAkB;
|
|
1
|
+
{"version":3,"sources":["../../src/services/telemetry.ts"],"sourcesContent":["import {createHash} from 'node:crypto'\n\nimport {getCliToken, getGlobalCliClient, getUserConfig} from '@sanity/cli-core'\nimport {getCliExecutionContext} from '@sanity/cli-core/executionContext'\nimport {type TelemetryEvent} from '@sanity/telemetry'\n\nimport {telemetryDebug} from '../actions/telemetry/telemetryDebug.js'\nimport {createExpiringConfig} from '../util/createExpiringConfig.js'\n\nexport const TELEMETRY_API_VERSION = 'v2026-01-22'\n\nexport const VALID_API_STATUSES = ['granted', 'denied', 'unset'] as const\nexport type ValidApiConsentStatus = (typeof VALID_API_STATUSES)[number]\n\nexport async function sendEvents(batch: TelemetryEvent[]) {\n const client = await getGlobalCliClient({\n apiVersion: TELEMETRY_API_VERSION,\n requireUser: true,\n })\n\n const projectId = process.env.SANITY_TELEMETRY_PROJECT_ID\n\n return client.request({\n body: {batch, projectId},\n json: true,\n method: 'POST',\n uri: '/intake/batch',\n })\n}\n\nasync function getTelemetryConsent(): Promise<{\n status: ValidApiConsentStatus\n}> {\n const client = await getGlobalCliClient({\n apiVersion: TELEMETRY_API_VERSION,\n requireUser: false,\n })\n\n return client.request({tag: 'telemetry-consent', uri: '/intake/telemetry-status'})\n}\n\n/**\n * Check if the given status is a valid consent status\n *\n * @param status - The status to check\n * @returns True if the status is valid, false otherwise\n * @internal\n */\nexport function isValidApiConsentStatus(status: string): status is ValidApiConsentStatus {\n return VALID_API_STATUSES.includes(status as ValidApiConsentStatus)\n}\n\n/**\n * Check if the given response is a valid API consent response\n *\n * @param response - The response to check\n * @returns True if the response is valid, false otherwise\n * @internal\n */\nfunction isValidApiConsentResponse(response: unknown): response is {status: ValidApiConsentStatus} {\n return (\n typeof response === 'object' &&\n response !== null &&\n 'status' in response &&\n typeof response.status === 'string' &&\n isValidApiConsentStatus(response.status)\n )\n}\n\nexport const TELEMETRY_CONSENT_CONFIG_KEY = 'telemetryConsent'\nconst FIVE_MINUTES = 1000 * 60 * 5\n\n/**\n * Get a token-scoped cache key for telemetry consent. This ensures that switching\n * users (via login/logout) always results in a cache miss, preventing one user\n * from inheriting another user's cached consent status.\n *\n * @param token - The current auth token, or undefined if not logged in\n * @returns A cache key scoped to the token\n */\nexport function getTelemetryConsentCacheKey(token: string | undefined): string {\n if (!token) {\n return TELEMETRY_CONSENT_CONFIG_KEY\n }\n\n const hash = createHash('sha256').update(token).digest('hex').slice(0, 12)\n return `${TELEMETRY_CONSENT_CONFIG_KEY}:${hash}`\n}\n\n/**\n * Fetch the telemetry consent status for the current user\n * @returns The telemetry consent status\n *\n * @internal\n */\nexport async function fetchTelemetryConsent(): Promise<{\n status: ValidApiConsentStatus\n}> {\n // Programmatic invocations must not use the host user's disk-backed consent\n // cache. The request is already authenticated with the invocation token.\n if (getCliExecutionContext()) return getTelemetryConsent()\n\n const token = await getCliToken()\n const cacheKey = getTelemetryConsentCacheKey(token)\n\n // NOTE: createExpiringConfig is instantiated on every call, so in-flight request\n // deduplication (via currentFetch) does not work across concurrent calls to\n // fetchTelemetryConsent(). Two concurrent callers will make two HTTP requests.\n // Consider moving to module-level instance if this becomes a bottleneck.\n const telemetryConsentConfig = createExpiringConfig<{\n status: ValidApiConsentStatus\n }>({\n fetchValue: () => getTelemetryConsent(),\n key: cacheKey,\n onCacheHit() {\n telemetryDebug('Retrieved telemetry consent status from cache')\n },\n onFetch() {\n telemetryDebug('Fetching telemetry consent status...')\n },\n onRevalidate() {\n telemetryDebug('Revalidating cached telemetry consent status...')\n },\n store: getUserConfig(),\n ttl: FIVE_MINUTES,\n validateValue: isValidApiConsentResponse,\n })\n\n return telemetryConsentConfig.get()\n}\n"],"names":["createHash","getCliToken","getGlobalCliClient","getUserConfig","getCliExecutionContext","telemetryDebug","createExpiringConfig","TELEMETRY_API_VERSION","VALID_API_STATUSES","sendEvents","batch","client","apiVersion","requireUser","projectId","process","env","SANITY_TELEMETRY_PROJECT_ID","request","body","json","method","uri","getTelemetryConsent","tag","isValidApiConsentStatus","status","includes","isValidApiConsentResponse","response","TELEMETRY_CONSENT_CONFIG_KEY","FIVE_MINUTES","getTelemetryConsentCacheKey","token","hash","update","digest","slice","fetchTelemetryConsent","cacheKey","telemetryConsentConfig","fetchValue","key","onCacheHit","onFetch","onRevalidate","store","ttl","validateValue","get"],"mappings":"AAAA,SAAQA,UAAU,QAAO,cAAa;AAEtC,SAAQC,WAAW,EAAEC,kBAAkB,EAAEC,aAAa,QAAO,mBAAkB;AAC/E,SAAQC,sBAAsB,QAAO,oCAAmC;AAGxE,SAAQC,cAAc,QAAO,yCAAwC;AACrE,SAAQC,oBAAoB,QAAO,kCAAiC;AAEpE,OAAO,MAAMC,wBAAwB,cAAa;AAElD,OAAO,MAAMC,qBAAqB;IAAC;IAAW;IAAU;CAAQ,CAAS;AAGzE,OAAO,eAAeC,WAAWC,KAAuB;IACtD,MAAMC,SAAS,MAAMT,mBAAmB;QACtCU,YAAYL;QACZM,aAAa;IACf;IAEA,MAAMC,YAAYC,QAAQC,GAAG,CAACC,2BAA2B;IAEzD,OAAON,OAAOO,OAAO,CAAC;QACpBC,MAAM;YAACT;YAAOI;QAAS;QACvBM,MAAM;QACNC,QAAQ;QACRC,KAAK;IACP;AACF;AAEA,eAAeC;IAGb,MAAMZ,SAAS,MAAMT,mBAAmB;QACtCU,YAAYL;QACZM,aAAa;IACf;IAEA,OAAOF,OAAOO,OAAO,CAAC;QAACM,KAAK;QAAqBF,KAAK;IAA0B;AAClF;AAEA;;;;;;CAMC,GACD,OAAO,SAASG,wBAAwBC,MAAc;IACpD,OAAOlB,mBAAmBmB,QAAQ,CAACD;AACrC;AAEA;;;;;;CAMC,GACD,SAASE,0BAA0BC,QAAiB;IAClD,OACE,OAAOA,aAAa,YACpBA,aAAa,QACb,YAAYA,YACZ,OAAOA,SAASH,MAAM,KAAK,YAC3BD,wBAAwBI,SAASH,MAAM;AAE3C;AAEA,OAAO,MAAMI,+BAA+B,mBAAkB;AAC9D,MAAMC,eAAe,OAAO,KAAK;AAEjC;;;;;;;CAOC,GACD,OAAO,SAASC,4BAA4BC,KAAyB;IACnE,IAAI,CAACA,OAAO;QACV,OAAOH;IACT;IAEA,MAAMI,OAAOlC,WAAW,UAAUmC,MAAM,CAACF,OAAOG,MAAM,CAAC,OAAOC,KAAK,CAAC,GAAG;IACvE,OAAO,GAAGP,6BAA6B,CAAC,EAAEI,MAAM;AAClD;AAEA;;;;;CAKC,GACD,OAAO,eAAeI;IAGpB,4EAA4E;IAC5E,yEAAyE;IACzE,IAAIlC,0BAA0B,OAAOmB;IAErC,MAAMU,QAAQ,MAAMhC;IACpB,MAAMsC,WAAWP,4BAA4BC;IAE7C,iFAAiF;IACjF,4EAA4E;IAC5E,+EAA+E;IAC/E,yEAAyE;IACzE,MAAMO,yBAAyBlC,qBAE5B;QACDmC,YAAY,IAAMlB;QAClBmB,KAAKH;QACLI;YACEtC,eAAe;QACjB;QACAuC;YACEvC,eAAe;QACjB;QACAwC;YACExC,eAAe;QACjB;QACAyC,OAAO3C;QACP4C,KAAKhB;QACLiB,eAAepB;IACjB;IAEA,OAAOY,uBAAuBS,GAAG;AACnC"}
|
package/oclif.manifest.json
CHANGED
|
@@ -2743,7 +2743,6 @@
|
|
|
2743
2743
|
},
|
|
2744
2744
|
"api-version": {
|
|
2745
2745
|
"description": "API version to use (defaults to 2025-08-15)",
|
|
2746
|
-
"env": "SANITY_CLI_QUERY_API_VERSION",
|
|
2747
2746
|
"name": "api-version",
|
|
2748
2747
|
"hasDynamicHelp": false,
|
|
2749
2748
|
"multiple": false,
|
|
@@ -3409,6 +3408,45 @@
|
|
|
3409
3408
|
"logs.js"
|
|
3410
3409
|
]
|
|
3411
3410
|
},
|
|
3411
|
+
"manifest:extract": {
|
|
3412
|
+
"aliases": [],
|
|
3413
|
+
"args": {},
|
|
3414
|
+
"description": "Extract studio configuration as JSON manifest files.\n\nNote: This command is experimental and subject to change. It is currently intended for use with Create only.",
|
|
3415
|
+
"examples": [
|
|
3416
|
+
{
|
|
3417
|
+
"command": "<%= config.bin %> <%= command.id %>",
|
|
3418
|
+
"description": "Extracts manifests"
|
|
3419
|
+
},
|
|
3420
|
+
{
|
|
3421
|
+
"command": "<%= config.bin %> <%= command.id %> --path /public/static",
|
|
3422
|
+
"description": "Extracts manifests into /public/static"
|
|
3423
|
+
}
|
|
3424
|
+
],
|
|
3425
|
+
"flags": {
|
|
3426
|
+
"path": {
|
|
3427
|
+
"description": "Optional path to specify destination directory of the manifest files",
|
|
3428
|
+
"name": "path",
|
|
3429
|
+
"default": "dist/static",
|
|
3430
|
+
"hasDynamicHelp": false,
|
|
3431
|
+
"multiple": false,
|
|
3432
|
+
"type": "option"
|
|
3433
|
+
}
|
|
3434
|
+
},
|
|
3435
|
+
"hasDynamicHelp": false,
|
|
3436
|
+
"hiddenAliases": [],
|
|
3437
|
+
"id": "manifest:extract",
|
|
3438
|
+
"pluginAlias": "@sanity/cli",
|
|
3439
|
+
"pluginName": "@sanity/cli",
|
|
3440
|
+
"pluginType": "core",
|
|
3441
|
+
"strict": true,
|
|
3442
|
+
"isESM": true,
|
|
3443
|
+
"relativePath": [
|
|
3444
|
+
"dist",
|
|
3445
|
+
"commands",
|
|
3446
|
+
"manifest",
|
|
3447
|
+
"extract.js"
|
|
3448
|
+
]
|
|
3449
|
+
},
|
|
3412
3450
|
"mcp:configure": {
|
|
3413
3451
|
"aliases": [],
|
|
3414
3452
|
"args": {},
|
|
@@ -5274,45 +5312,6 @@
|
|
|
5274
5312
|
"list.js"
|
|
5275
5313
|
]
|
|
5276
5314
|
},
|
|
5277
|
-
"manifest:extract": {
|
|
5278
|
-
"aliases": [],
|
|
5279
|
-
"args": {},
|
|
5280
|
-
"description": "Extract studio configuration as JSON manifest files.\n\nNote: This command is experimental and subject to change. It is currently intended for use with Create only.",
|
|
5281
|
-
"examples": [
|
|
5282
|
-
{
|
|
5283
|
-
"command": "<%= config.bin %> <%= command.id %>",
|
|
5284
|
-
"description": "Extracts manifests"
|
|
5285
|
-
},
|
|
5286
|
-
{
|
|
5287
|
-
"command": "<%= config.bin %> <%= command.id %> --path /public/static",
|
|
5288
|
-
"description": "Extracts manifests into /public/static"
|
|
5289
|
-
}
|
|
5290
|
-
],
|
|
5291
|
-
"flags": {
|
|
5292
|
-
"path": {
|
|
5293
|
-
"description": "Optional path to specify destination directory of the manifest files",
|
|
5294
|
-
"name": "path",
|
|
5295
|
-
"default": "dist/static",
|
|
5296
|
-
"hasDynamicHelp": false,
|
|
5297
|
-
"multiple": false,
|
|
5298
|
-
"type": "option"
|
|
5299
|
-
}
|
|
5300
|
-
},
|
|
5301
|
-
"hasDynamicHelp": false,
|
|
5302
|
-
"hiddenAliases": [],
|
|
5303
|
-
"id": "manifest:extract",
|
|
5304
|
-
"pluginAlias": "@sanity/cli",
|
|
5305
|
-
"pluginName": "@sanity/cli",
|
|
5306
|
-
"pluginType": "core",
|
|
5307
|
-
"strict": true,
|
|
5308
|
-
"isESM": true,
|
|
5309
|
-
"relativePath": [
|
|
5310
|
-
"dist",
|
|
5311
|
-
"commands",
|
|
5312
|
-
"manifest",
|
|
5313
|
-
"extract.js"
|
|
5314
|
-
]
|
|
5315
|
-
},
|
|
5316
5315
|
"datasets:alias:create": {
|
|
5317
5316
|
"aliases": [],
|
|
5318
5317
|
"args": {
|
|
@@ -5830,5 +5829,5 @@
|
|
|
5830
5829
|
]
|
|
5831
5830
|
}
|
|
5832
5831
|
},
|
|
5833
|
-
"version": "7.15.
|
|
5832
|
+
"version": "7.15.1"
|
|
5834
5833
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sanity/cli",
|
|
3
|
-
"version": "7.15.
|
|
3
|
+
"version": "7.15.1",
|
|
4
4
|
"description": "Sanity CLI tool for managing Sanity projects and organizations",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cli",
|
|
@@ -62,7 +62,7 @@
|
|
|
62
62
|
"@oclif/core": "^4.11.14",
|
|
63
63
|
"@oclif/plugin-help": "^6.2.53",
|
|
64
64
|
"@oclif/plugin-not-found": "^3.2.88",
|
|
65
|
-
"@sanity/client": "^7.
|
|
65
|
+
"@sanity/client": "^7.25.0",
|
|
66
66
|
"@sanity/codegen": "^7.0.3",
|
|
67
67
|
"@sanity/descriptors": "^1.3.0",
|
|
68
68
|
"@sanity/export": "^6.2.0",
|
|
@@ -123,13 +123,13 @@
|
|
|
123
123
|
"which": "^6.0.1",
|
|
124
124
|
"yaml": "^2.9.0",
|
|
125
125
|
"zod": "^4.4.3",
|
|
126
|
-
"@sanity/cli
|
|
127
|
-
"@sanity/cli-
|
|
128
|
-
"@sanity/
|
|
126
|
+
"@sanity/workbench-cli": "^1.8.0",
|
|
127
|
+
"@sanity/cli-core": "^2.7.1",
|
|
128
|
+
"@sanity/cli-build": "^5.1.0"
|
|
129
129
|
},
|
|
130
130
|
"devDependencies": {
|
|
131
131
|
"@eslint/compat": "^2.1.0",
|
|
132
|
-
"@sanity/pkg-utils": "^11.0.
|
|
132
|
+
"@sanity/pkg-utils": "^11.0.17",
|
|
133
133
|
"@sanity/ui": "^3.5.0",
|
|
134
134
|
"@swc/cli": "^0.8.1",
|
|
135
135
|
"@swc/core": "^1.15.43",
|
|
@@ -160,7 +160,7 @@
|
|
|
160
160
|
"vitest": "^4.1.10",
|
|
161
161
|
"@repo/package.config": "0.0.1",
|
|
162
162
|
"@repo/tsconfig": "3.70.0",
|
|
163
|
-
"@sanity/cli-test": "8.0.
|
|
163
|
+
"@sanity/cli-test": "8.0.1",
|
|
164
164
|
"@sanity/eslint-config-cli": "1.1.3"
|
|
165
165
|
},
|
|
166
166
|
"peerDependencies": {
|