@sanity/cli 8.23.0 → 8.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +401 -87
- package/bin/run.js +7 -1
- package/dist/actions/codemods/dashboard.js +136 -8
- package/dist/actions/codemods/dashboard.js.map +1 -1
- package/dist/actions/codemods/types.js.map +1 -1
- package/dist/actions/dev/devAction.js +48 -44
- package/dist/actions/dev/devAction.js.map +1 -1
- package/dist/actions/init/initHelpers.js +1 -1
- package/dist/actions/init/initHelpers.js.map +1 -1
- package/dist/actions/init/initStudio.js +1 -1
- package/dist/actions/init/initStudio.js.map +1 -1
- package/dist/actions/init/project/getOrCreateDataset.js +10 -12
- package/dist/actions/init/project/getOrCreateDataset.js.map +1 -1
- package/dist/actions/init/project/getOrCreateProject.js +7 -5
- package/dist/actions/init/project/getOrCreateProject.js.map +1 -1
- package/dist/actions/init/project/promptUserForOrganization.js +6 -4
- package/dist/actions/init/project/promptUserForOrganization.js.map +1 -1
- package/dist/commands/api.js +1 -1
- package/dist/commands/api.js.map +1 -1
- package/dist/commands/assets/upload.js +1 -1
- package/dist/commands/assets/upload.js.map +1 -1
- package/dist/commands/codemod.js +1 -0
- package/dist/commands/codemod.js.map +1 -1
- package/dist/commands/cors/add.js +1 -1
- package/dist/commands/cors/add.js.map +1 -1
- package/dist/commands/cors/delete.js +1 -1
- package/dist/commands/cors/delete.js.map +1 -1
- package/dist/commands/cors/list.js +1 -1
- package/dist/commands/cors/list.js.map +1 -1
- package/dist/commands/datasets/alias/create.js +1 -1
- package/dist/commands/datasets/alias/create.js.map +1 -1
- package/dist/commands/datasets/import.js +0 -8
- package/dist/commands/datasets/import.js.map +1 -1
- package/dist/commands/datasets/list.js +1 -1
- package/dist/commands/datasets/list.js.map +1 -1
- package/dist/commands/documents/create.js +1 -1
- package/dist/commands/documents/create.js.map +1 -1
- package/dist/commands/documents/delete.js +1 -1
- package/dist/commands/documents/delete.js.map +1 -1
- package/dist/commands/documents/get.js +1 -1
- package/dist/commands/documents/get.js.map +1 -1
- package/dist/commands/documents/query.js +1 -9
- package/dist/commands/documents/query.js.map +1 -1
- package/dist/commands/documents/validate.js +2 -2
- package/dist/commands/documents/validate.js.map +1 -1
- package/dist/commands/graphql/list.js +1 -1
- package/dist/commands/graphql/list.js.map +1 -1
- package/dist/commands/graphql/undeploy.js +1 -11
- package/dist/commands/graphql/undeploy.js.map +1 -1
- package/dist/commands/hooks/attempt.js +1 -1
- package/dist/commands/hooks/attempt.js.map +1 -1
- package/dist/commands/hooks/create.js +1 -1
- package/dist/commands/hooks/create.js.map +1 -1
- package/dist/commands/hooks/delete.js +1 -1
- package/dist/commands/hooks/delete.js.map +1 -1
- package/dist/commands/hooks/list.js +1 -1
- package/dist/commands/hooks/list.js.map +1 -1
- package/dist/commands/hooks/logs.js +1 -1
- package/dist/commands/hooks/logs.js.map +1 -1
- package/dist/commands/init.js +3 -5
- package/dist/commands/init.js.map +1 -1
- package/dist/commands/migrations/run.js +5 -5
- package/dist/commands/migrations/run.js.map +1 -1
- package/dist/commands/projects/unclaimed.js +6 -5
- package/dist/commands/projects/unclaimed.js.map +1 -1
- package/dist/commands/tokens/create.js +4 -4
- package/dist/commands/tokens/create.js.map +1 -1
- package/dist/commands/tokens/delete.js +2 -2
- package/dist/commands/tokens/delete.js.map +1 -1
- package/dist/commands/tokens/list.js +2 -2
- package/dist/commands/tokens/list.js.map +1 -1
- package/dist/commands/users/invite.js +1 -1
- package/dist/commands/users/invite.js.map +1 -1
- package/dist/commands/users/list.js +1 -1
- package/dist/commands/users/list.js.map +1 -1
- package/dist/exports/invokeSanityCli/index.js +1 -1
- package/dist/exports/invokeSanityCli/index.js.map +1 -1
- package/dist/hooks/prerun/injectEnvVariables.js +1 -1
- package/dist/hooks/prerun/injectEnvVariables.js.map +1 -1
- package/dist/util/searchChoices.js +52 -0
- package/dist/util/searchChoices.js.map +1 -0
- package/dist/util/sharedFlags.js +8 -4
- package/dist/util/sharedFlags.js.map +1 -1
- package/dist/util/warnOnNonProductionEnvironment.js +4 -3
- package/dist/util/warnOnNonProductionEnvironment.js.map +1 -1
- package/oclif.manifest.json +515 -351
- package/package.json +8 -8
- package/dist/util/getSanityEnv.js +0 -8
- package/dist/util/getSanityEnv.js.map +0 -1
- package/templates/shopify/.gitignore +0 -26
|
@@ -25,7 +25,7 @@ export class CreateAliasCommand extends SanityCommand {
|
|
|
25
25
|
static description = 'Create a dataset alias for the project';
|
|
26
26
|
static examples = [
|
|
27
27
|
{
|
|
28
|
-
command: '<%= config.bin %> <%= command.id %> --project
|
|
28
|
+
command: '<%= config.bin %> <%= command.id %> --project abc123 conference conf-2025',
|
|
29
29
|
description: 'Create alias in a specific project'
|
|
30
30
|
},
|
|
31
31
|
{
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/commands/datasets/alias/create.ts"],"sourcesContent":["import {Args} from '@oclif/core'\nimport {CLIError} from '@oclif/core/errors'\nimport {exitCodes, SanityCommand, subdebug} from '@sanity/cli-core'\n\nimport {validateDatasetAliasName} from '../../../actions/dataset/validateDatasetAliasName.js'\nimport {validateDatasetName} from '../../../actions/dataset/validateDatasetName.js'\nimport {promptForDatasetAliasName} from '../../../prompts/promptForDatasetAliasName.js'\nimport {promptForProject} from '../../../prompts/promptForProject.js'\nimport {selectDataset} from '../../../prompts/selectDataset.js'\nimport {ALIAS_PREFIX, createAlias, listAliases} from '../../../services/datasetAliases.js'\nimport {listDatasets} from '../../../services/datasets.js'\nimport {getProjectFeatures} from '../../../services/getProjectFeatures.js'\nimport {getProjectIdFlag} from '../../../util/sharedFlags.js'\n\nconst createAliasDebug = subdebug('dataset:alias:create')\n\nexport class CreateAliasCommand extends SanityCommand<typeof CreateAliasCommand> {\n static override args = {\n aliasName: Args.string({\n description: 'Dataset alias name to create',\n required: false,\n }),\n targetDataset: Args.string({\n description: 'Target dataset name to link the alias to',\n required: false,\n }),\n }\n\n static override description = 'Create a dataset alias for the project'\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %> --project
|
|
1
|
+
{"version":3,"sources":["../../../../src/commands/datasets/alias/create.ts"],"sourcesContent":["import {Args} from '@oclif/core'\nimport {CLIError} from '@oclif/core/errors'\nimport {exitCodes, SanityCommand, subdebug} from '@sanity/cli-core'\n\nimport {validateDatasetAliasName} from '../../../actions/dataset/validateDatasetAliasName.js'\nimport {validateDatasetName} from '../../../actions/dataset/validateDatasetName.js'\nimport {promptForDatasetAliasName} from '../../../prompts/promptForDatasetAliasName.js'\nimport {promptForProject} from '../../../prompts/promptForProject.js'\nimport {selectDataset} from '../../../prompts/selectDataset.js'\nimport {ALIAS_PREFIX, createAlias, listAliases} from '../../../services/datasetAliases.js'\nimport {listDatasets} from '../../../services/datasets.js'\nimport {getProjectFeatures} from '../../../services/getProjectFeatures.js'\nimport {getProjectIdFlag} from '../../../util/sharedFlags.js'\n\nconst createAliasDebug = subdebug('dataset:alias:create')\n\nexport class CreateAliasCommand extends SanityCommand<typeof CreateAliasCommand> {\n static override args = {\n aliasName: Args.string({\n description: 'Dataset alias name to create',\n required: false,\n }),\n targetDataset: Args.string({\n description: 'Target dataset name to link the alias to',\n required: false,\n }),\n }\n\n static override description = 'Create a dataset alias for the project'\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %> --project abc123 conference conf-2025',\n description: 'Create alias in a specific project',\n },\n {\n command: '<%= config.bin %> <%= command.id %>',\n description: 'Create an alias with interactive prompts',\n },\n {\n command: '<%= config.bin %> <%= command.id %> conference',\n description: 'Create alias named \"conference\" with interactive dataset selection',\n },\n {\n command: '<%= config.bin %> <%= command.id %> conference conf-2025',\n description: 'Create alias \"conference\" linked to \"conf-2025\" dataset',\n },\n ]\n\n static override flags = {\n ...getProjectIdFlag({\n description: 'Project ID to create dataset alias in',\n semantics: 'override',\n }),\n }\n\n static override hiddenAliases: string[] = ['dataset:alias:create']\n\n public async run(): Promise<void> {\n const {args} = await this.parse(CreateAliasCommand)\n\n if (!args.aliasName && this.isUnattended()) {\n this.error('Dataset alias name is required. Pass it as the `<aliasName>` argument.', {\n exit: exitCodes.USAGE_ERROR,\n })\n }\n\n if (args.aliasName) {\n const nameError = validateDatasetAliasName(args.aliasName)\n if (nameError) {\n this.error(nameError, {exit: exitCodes.USAGE_ERROR})\n }\n }\n\n if (args.targetDataset) {\n const datasetErr = validateDatasetName(args.targetDataset)\n if (datasetErr) {\n this.error(datasetErr, {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 let canCreateAlias = false\n try {\n const features = await getProjectFeatures(projectId)\n canCreateAlias = features.includes('advancedDatasetManagement')\n } catch (error) {\n createAliasDebug(`Error getting project features`, error)\n this.error('Failed to get project features', {exit: exitCodes.RUNTIME_ERROR})\n }\n if (!canCreateAlias) {\n this.error('This project cannot create a dataset alias - see https://www.sanity.io/pricing', {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n\n try {\n const [datasetsResponse, aliases] = await Promise.all([\n listDatasets(projectId),\n listAliases(projectId),\n ])\n\n const datasets = datasetsResponse.map((ds: {name: string}) => ds.name)\n const existingAliases = aliases.map((alias: {name: string}) => alias.name)\n\n let aliasName = args.aliasName || (await promptForDatasetAliasName())\n let aliasOutputName = aliasName\n\n if (aliasName.startsWith(ALIAS_PREFIX)) {\n aliasName = aliasName.slice(1)\n } else {\n aliasOutputName = `${ALIAS_PREFIX}${aliasName}`\n }\n\n if (existingAliases.includes(aliasName)) {\n this.error(`Dataset alias \"${aliasOutputName}\" already exists`, {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n\n const targetDataset =\n args.targetDataset ||\n (!this.isUnattended() && datasets.length > 0 ? await selectDataset(datasets) : null)\n\n if (targetDataset && !datasets.includes(targetDataset)) {\n this.error(\n `Dataset \"${targetDataset}\" does not exist. Available datasets: ${datasets.join(', ')}`,\n {exit: exitCodes.RUNTIME_ERROR},\n )\n }\n\n await createAlias(projectId, aliasName, targetDataset)\n\n const linkMessage = targetDataset ? ` and linked to ${targetDataset}` : ''\n this.log(`Dataset alias ${aliasOutputName} created${linkMessage} successfully`)\n } catch (error) {\n if (error instanceof CLIError) throw error\n createAliasDebug(`Error creating dataset alias`, error)\n this.error(\n `Dataset alias creation failed: ${error instanceof Error ? error.message : String(error)}`,\n {exit: exitCodes.RUNTIME_ERROR},\n )\n }\n }\n}\n"],"names":["Args","CLIError","exitCodes","SanityCommand","subdebug","validateDatasetAliasName","validateDatasetName","promptForDatasetAliasName","promptForProject","selectDataset","ALIAS_PREFIX","createAlias","listAliases","listDatasets","getProjectFeatures","getProjectIdFlag","createAliasDebug","CreateAliasCommand","args","aliasName","string","description","required","targetDataset","examples","command","flags","semantics","hiddenAliases","run","parse","isUnattended","error","exit","USAGE_ERROR","nameError","datasetErr","projectId","getProjectId","fallback","requiredPermissions","grant","permission","canCreateAlias","features","includes","RUNTIME_ERROR","datasetsResponse","aliases","Promise","all","datasets","map","ds","name","existingAliases","alias","aliasOutputName","startsWith","slice","length","join","linkMessage","log","Error","message","String"],"mappings":"AAAA,SAAQA,IAAI,QAAO,cAAa;AAChC,SAAQC,QAAQ,QAAO,qBAAoB;AAC3C,SAAQC,SAAS,EAAEC,aAAa,EAAEC,QAAQ,QAAO,mBAAkB;AAEnE,SAAQC,wBAAwB,QAAO,uDAAsD;AAC7F,SAAQC,mBAAmB,QAAO,kDAAiD;AACnF,SAAQC,yBAAyB,QAAO,gDAA+C;AACvF,SAAQC,gBAAgB,QAAO,uCAAsC;AACrE,SAAQC,aAAa,QAAO,oCAAmC;AAC/D,SAAQC,YAAY,EAAEC,WAAW,EAAEC,WAAW,QAAO,sCAAqC;AAC1F,SAAQC,YAAY,QAAO,gCAA+B;AAC1D,SAAQC,kBAAkB,QAAO,0CAAyC;AAC1E,SAAQC,gBAAgB,QAAO,+BAA8B;AAE7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MAAMnD,cAAc0C,YAAY,IAAG;YAEpF,IAAI5B,iBAAiB,CAAC4B,SAASN,QAAQ,CAACtB,gBAAgB;gBACtD,IAAI,CAACS,KAAK,CACR,CAAC,SAAS,EAAET,cAAc,sCAAsC,EAAE4B,SAASU,IAAI,CAAC,OAAO,EACvF;oBAAC5B,MAAM/B,UAAU4C,aAAa;gBAAA;YAElC;YAEA,MAAMnC,YAAY0B,WAAWlB,WAAWI;YAExC,MAAMuC,cAAcvC,gBAAgB,CAAC,eAAe,EAAEA,eAAe,GAAG;YACxE,IAAI,CAACwC,GAAG,CAAC,CAAC,cAAc,EAAEN,gBAAgB,QAAQ,EAAEK,YAAY,aAAa,CAAC;QAChF,EAAE,OAAO9B,OAAO;YACd,IAAIA,iBAAiB/B,UAAU,MAAM+B;YACrChB,iBAAiB,CAAC,4BAA4B,CAAC,EAAEgB;YACjD,IAAI,CAACA,KAAK,CACR,CAAC,+BAA+B,EAAEA,iBAAiBgC,QAAQhC,MAAMiC,OAAO,GAAGC,OAAOlC,QAAQ,EAC1F;gBAACC,MAAM/B,UAAU4C,aAAa;YAAA;QAElC;IACF;AACF"}
|
|
@@ -113,13 +113,6 @@ export class ImportDatasetCommand extends SanityCommand {
|
|
|
113
113
|
description: 'Project ID to import to',
|
|
114
114
|
semantics: 'override'
|
|
115
115
|
}),
|
|
116
|
-
project: Flags.string({
|
|
117
|
-
deprecated: {
|
|
118
|
-
to: 'project-id'
|
|
119
|
-
},
|
|
120
|
-
description: 'Project ID to import to',
|
|
121
|
-
hidden: true
|
|
122
|
-
}),
|
|
123
116
|
replace: Flags.boolean({
|
|
124
117
|
default: false,
|
|
125
118
|
description: 'Replace documents with the same IDs',
|
|
@@ -159,7 +152,6 @@ export class ImportDatasetCommand extends SanityCommand {
|
|
|
159
152
|
const { args, flags } = await this.parse(ImportDatasetCommand);
|
|
160
153
|
const { 'allow-assets-in-different-dataset': allowAssetsInDifferentDataset, 'allow-failing-assets': allowFailingAssets, 'allow-replacement-characters': allowReplacementCharacters, 'allow-system-documents': allowSystemDocuments, 'asset-concurrency': assetConcurrency, dataset: datasetFlag, missing, replace, 'replace-assets': replaceAssets, 'skip-cross-dataset-references': skipCrossDatasetReferences, token } = flags;
|
|
161
154
|
const projectId = await this.getProjectId({
|
|
162
|
-
deprecatedFlagName: 'project',
|
|
163
155
|
fallback: ()=>promptForProject({})
|
|
164
156
|
});
|
|
165
157
|
const { source, targetDataset: targetDatasetArg } = args;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/commands/datasets/import.ts"],"sourcesContent":["import fs from 'node:fs'\nimport path from 'node:path'\n\nimport {Args, Flags} from '@oclif/core'\nimport {exitCodes, getProjectCliClient, SanityCommand, subdebug} from '@sanity/cli-core'\nimport {createRequester, nodeReadableFromWeb} from '@sanity/cli-core/request'\nimport {spinner} from '@sanity/cli-core/ux'\nimport {sanityImport} from '@sanity/import'\nimport prettyMs from 'pretty-ms'\n\nimport {NEW_DATASET_VALUE, promptForDataset} from '../../prompts/promptForDataset.js'\nimport {promptForDatasetName} from '../../prompts/promptForDatasetName.js'\nimport {promptForProject} from '../../prompts/promptForProject.js'\nimport {createDataset, listDatasets} from '../../services/datasets.js'\nimport {getDatasetFlag, getProjectIdFlag} from '../../util/sharedFlags.js'\n\nconst importDebug = subdebug('dataset:import')\n\ninterface ProgressEvent {\n step: string\n\n current?: number\n total?: number\n update?: string\n}\n\nfunction getAssetsBase(source: string): string | undefined {\n if (/^https?:\\/\\//i.test(source) || source === '-') {\n return undefined\n }\n\n try {\n const fileStats = fs.statSync(source)\n const sourceIsFolder = fileStats.isDirectory()\n return sourceIsFolder ? source : path.dirname(source)\n } catch {\n return undefined\n }\n}\n\nasync function getUriStream(uri: string): Promise<NodeJS.ReadableStream> {\n const request = createRequester()\n\n try {\n // No timeout: large dataset exports may stream for longer than get-it's\n // default request timeout, which would abort the body mid-transfer.\n const response = await request({as: 'stream', timeout: false, url: uri})\n return nodeReadableFromWeb(response.body)\n } catch (err) {\n throw new Error(`Error fetching source:\\n${(err as Error).message}`, {cause: err})\n }\n}\n\nfunction getPercentage(opts: ProgressEvent): string {\n if (!opts.total) {\n return ''\n }\n\n const percent = Math.floor(((opts.current || 0) / opts.total) * 100)\n return `[${percent}%] `\n}\n\nexport class ImportDatasetCommand extends SanityCommand<typeof ImportDatasetCommand> {\n static override args = {\n source: Args.string({\n description: 'Source file (use \"-\" for stdin)',\n required: true,\n }),\n targetDataset: Args.string({\n description: 'Target dataset (prefer --dataset flag instead)',\n required: false,\n }),\n }\n\n static override description = 'Import documents to a Sanity dataset'\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %> -d staging my-dataset.ndjson',\n description: 'Import \"./my-dataset.ndjson\" into dataset \"staging\"',\n },\n {\n command: 'cat my-dataset.ndjson | <%= config.bin %> <%= command.id %> -d test -',\n description: 'Import into dataset \"test\" from stdin',\n },\n {\n command: '<%= config.bin %> <%= command.id %> -p projectId -d staging my-dataset.ndjson',\n description: 'Import with explicit project ID (overrides CLI configuration)',\n },\n {\n command:\n '<%= config.bin %> <%= command.id %> -d staging -t someSecretToken my-dataset.ndjson',\n description: 'Import with an explicit token (e.g. for CI/CD)',\n },\n ]\n\n static override flags = {\n 'allow-assets-in-different-dataset': Flags.boolean({\n default: false,\n description: 'Allow asset documents to reference different project/dataset',\n }),\n 'allow-failing-assets': Flags.boolean({\n default: false,\n description: 'Skip assets that cannot be fetched/uploaded',\n }),\n 'allow-replacement-characters': Flags.boolean({\n default: false,\n description: 'Allow unicode replacement characters in imported documents',\n }),\n 'allow-system-documents': Flags.boolean({\n default: false,\n description: 'Imports system documents',\n }),\n 'asset-concurrency': Flags.integer({\n description: 'Number of parallel asset imports',\n }),\n ...getDatasetFlag({\n description: 'Dataset to import to',\n semantics: 'specify',\n }),\n missing: Flags.boolean({\n default: false,\n description: 'Skip documents that already exist',\n exclusive: ['replace'],\n }),\n ...getProjectIdFlag({\n description: 'Project ID to import to',\n semantics: 'override',\n }),\n project: Flags.string({\n deprecated: {to: 'project-id'},\n description: 'Project ID to import to',\n hidden: true,\n }),\n replace: Flags.boolean({\n default: false,\n description: 'Replace documents with the same IDs',\n exclusive: ['missing'],\n }),\n 'replace-assets': Flags.boolean({\n default: false,\n description: 'Skip reuse of existing assets',\n }),\n 'skip-cross-dataset-references': Flags.boolean({\n default: false,\n description: 'Skips references to other datasets',\n }),\n token: Flags.string({\n char: 't',\n description: 'Token to authenticate with',\n env: 'SANITY_IMPORT_TOKEN',\n required: false,\n }),\n }\n\n static override hiddenAliases: string[] = ['dataset:import']\n\n private currentProgress?: ReturnType<typeof spinner>\n private currentStep?: string\n private spinInterval?: NodeJS.Timeout | null\n private stepStart?: number\n\n private static async getStream(source: string): Promise<NodeJS.ReadableStream> {\n if (/^https?:\\/\\//i.test(source)) {\n return getUriStream(source)\n }\n\n return source === '-' ? process.stdin : fs.createReadStream(source)\n }\n\n public async run(): Promise<void> {\n const {args, flags} = await this.parse(ImportDatasetCommand)\n\n const {\n 'allow-assets-in-different-dataset': allowAssetsInDifferentDataset,\n 'allow-failing-assets': allowFailingAssets,\n 'allow-replacement-characters': allowReplacementCharacters,\n 'allow-system-documents': allowSystemDocuments,\n 'asset-concurrency': assetConcurrency,\n dataset: datasetFlag,\n missing,\n replace,\n 'replace-assets': replaceAssets,\n 'skip-cross-dataset-references': skipCrossDatasetReferences,\n token,\n } = flags\n\n const projectId = await this.getProjectId({\n deprecatedFlagName: 'project',\n fallback: () => promptForProject({}),\n })\n\n const {source, targetDataset: targetDatasetArg} = args\n\n if (targetDatasetArg && !datasetFlag) {\n this.output.warn(\n 'Positional dataset argument is deprecated. Use the --dataset flag instead: --dataset <name>',\n )\n }\n\n let dataset = datasetFlag ?? targetDatasetArg\n if (!dataset) {\n if (this.isUnattended()) {\n return this.output.error('Dataset is required. Pass it with `--dataset <name>`.', {\n exit: exitCodes.USAGE_ERROR,\n })\n }\n\n const datasets = await listDatasets(projectId)\n dataset = await promptForDataset({allowCreation: true, datasets})\n\n if (dataset === NEW_DATASET_VALUE) {\n const newDatasetName = await promptForDatasetName()\n\n try {\n await createDataset({datasetName: newDatasetName, projectId})\n dataset = newDatasetName\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n importDebug(`Failed to create dataset ${newDatasetName}: ${message}`, error)\n return this.output.error(`Failed to create dataset ${newDatasetName}: ${message}`, {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n }\n }\n\n let operation: 'create' | 'createIfNotExists' | 'createOrReplace' = 'create'\n let releasesOperation: 'fail' | 'ignore' | 'replace' = 'fail'\n\n if (replace || missing) {\n operation = replace ? 'createOrReplace' : 'createIfNotExists'\n releasesOperation = replace ? 'replace' : 'ignore'\n }\n\n const client = await getProjectCliClient({\n apiVersion: 'v2025-02-19',\n dataset,\n projectId,\n requireUser: true,\n ...(token ? {token} : {}),\n })\n\n try {\n const stream = await ImportDatasetCommand.getStream(source)\n const assetsBase = getAssetsBase(source)\n\n const importOptions = {\n allowAssetsInDifferentDataset,\n allowFailingAssets,\n allowReplacementCharacters,\n allowSystemDocuments,\n client,\n onProgress: this.onProgress.bind(this),\n operation,\n releasesOperation,\n replaceAssets,\n skipCrossDatasetReferences,\n tag: 'sanity.import',\n targetDataset: dataset,\n targetProjectId: projectId,\n ...(assetsBase ? {assetsBase} : {}),\n ...(assetConcurrency === undefined ? {} : {assetConcurrency}),\n }\n\n const {numDocs, warnings} = await sanityImport(stream, importOptions)\n\n if (this.stepStart) {\n const timeSpent = prettyMs(Date.now() - this.stepStart, {secondsDecimalDigits: 2})\n if (this.currentProgress) {\n if (this.spinInterval) {\n clearInterval(this.spinInterval)\n this.spinInterval = null\n }\n this.currentProgress.text = `[100%] ${this.currentStep} (${timeSpent})`\n this.currentProgress.succeed()\n }\n }\n\n this.output.log('Done! Imported %d documents to dataset \"%s\"\\n', numDocs, dataset)\n this.printWarnings(warnings)\n } catch (err) {\n if (this.spinInterval) {\n clearInterval(this.spinInterval)\n this.spinInterval = null\n }\n\n if (this.currentProgress) {\n this.currentProgress.fail()\n }\n\n return (err as Error).name === 'ReplacementCharError'\n ? this.output.error(\n `Import failed due to unicode replacement characters in the data.\\n${(err as Error).message}\\n\\nIf you are certain you want to proceed with the import despite potentially corrupt data, re-run the import with the \\`--allow-replacement-characters\\` flag set.`,\n {exit: exitCodes.RUNTIME_ERROR},\n )\n : this.output.error((err as Error).stack || (err as Error).message, {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n }\n\n private onProgress(opts: ProgressEvent): void {\n const lengthComputable = opts.total\n const sameStep = opts.step === this.currentStep\n const percent = getPercentage(opts)\n\n if (lengthComputable && opts.total === opts.current && this.spinInterval) {\n clearInterval(this.spinInterval)\n this.spinInterval = null\n }\n\n if (sameStep && !lengthComputable) {\n return\n }\n\n if (sameStep) {\n if (this.stepStart) {\n const timeSpent = prettyMs(Date.now() - this.stepStart, {secondsDecimalDigits: 2})\n if (this.currentProgress) {\n this.currentProgress.text = `${percent}${opts.step} (${timeSpent})`\n this.currentProgress.render()\n }\n }\n return\n }\n\n // Moved to a new step\n const prevStep = this.currentStep\n const prevStepStart = this.stepStart\n this.stepStart = Date.now()\n this.currentStep = opts.step\n\n if (this.spinInterval) {\n clearInterval(this.spinInterval)\n this.spinInterval = null\n }\n\n if (this.currentProgress && this.currentProgress.succeed && prevStepStart) {\n const timeSpent = prettyMs(Date.now() - prevStepStart, {\n secondsDecimalDigits: 2,\n })\n this.currentProgress.text = `[100%] ${prevStep} (${timeSpent})`\n this.currentProgress.succeed()\n }\n\n this.currentProgress = spinner(`[0%] ${opts.step} (0.00s)`).start()\n\n if (!lengthComputable) {\n this.spinInterval = setInterval(() => {\n if (this.stepStart && this.currentProgress) {\n const timeSpent = prettyMs(Date.now() - this.stepStart, {\n secondsDecimalDigits: 2,\n })\n this.currentProgress.text = `${percent}${opts.step} (${timeSpent})`\n this.currentProgress.render()\n }\n }, 60)\n }\n }\n\n private printWarnings(warnings: Array<{message: string; type?: string; url?: string}>): void {\n const assetFails = warnings.filter((warn) => warn.type === 'asset')\n\n if (assetFails.length === 0) {\n return\n }\n\n this.output.warn(\n `Failed to import the following ${assetFails.length > 1 ? 'assets' : 'asset'}:`,\n )\n\n for (const warning of assetFails) {\n if (warning.url) {\n this.output.warn(` ${warning.url}`)\n }\n }\n }\n}\n"],"names":["fs","path","Args","Flags","exitCodes","getProjectCliClient","SanityCommand","subdebug","createRequester","nodeReadableFromWeb","spinner","sanityImport","prettyMs","NEW_DATASET_VALUE","promptForDataset","promptForDatasetName","promptForProject","createDataset","listDatasets","getDatasetFlag","getProjectIdFlag","importDebug","getAssetsBase","source","test","undefined","fileStats","statSync","sourceIsFolder","isDirectory","dirname","getUriStream","uri","request","response","as","timeout","url","body","err","Error","message","cause","getPercentage","opts","total","percent","Math","floor","current","ImportDatasetCommand","args","string","description","required","targetDataset","examples","command","flags","boolean","default","integer","semantics","missing","exclusive","project","deprecated","to","hidden","replace","token","char","env","hiddenAliases","currentProgress","currentStep","spinInterval","stepStart","getStream","process","stdin","createReadStream","run","parse","allowAssetsInDifferentDataset","allowFailingAssets","allowReplacementCharacters","allowSystemDocuments","assetConcurrency","dataset","datasetFlag","replaceAssets","skipCrossDatasetReferences","projectId","getProjectId","deprecatedFlagName","fallback","targetDatasetArg","output","warn","isUnattended","error","exit","USAGE_ERROR","datasets","allowCreation","newDatasetName","datasetName","String","RUNTIME_ERROR","operation","releasesOperation","client","apiVersion","requireUser","stream","assetsBase","importOptions","onProgress","bind","tag","targetProjectId","numDocs","warnings","timeSpent","Date","now","secondsDecimalDigits","clearInterval","text","succeed","log","printWarnings","fail","name","stack","lengthComputable","sameStep","step","render","prevStep","prevStepStart","start","setInterval","assetFails","filter","type","length","warning"],"mappings":"AAAA,OAAOA,QAAQ,UAAS;AACxB,OAAOC,UAAU,YAAW;AAE5B,SAAQC,IAAI,EAAEC,KAAK,QAAO,cAAa;AACvC,SAAQC,SAAS,EAAEC,mBAAmB,EAAEC,aAAa,EAAEC,QAAQ,QAAO,mBAAkB;AACxF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BACrDd,sBAAsB;YACxB;YACA,IAAI,CAACrD,eAAe,CAACuD,IAAI,GAAG,CAAC,OAAO,EAAEW,SAAS,EAAE,EAAEhB,UAAU,CAAC,CAAC;YAC/D,IAAI,CAAClD,eAAe,CAACwD,OAAO;QAC9B;QAEA,IAAI,CAACxD,eAAe,GAAGhE,QAAQ,CAAC,KAAK,EAAEkC,KAAK8F,IAAI,CAAC,QAAQ,CAAC,EAAEI,KAAK;QAEjE,IAAI,CAACN,kBAAkB;YACrB,IAAI,CAAC5D,YAAY,GAAGmE,YAAY;gBAC9B,IAAI,IAAI,CAAClE,SAAS,IAAI,IAAI,CAACH,eAAe,EAAE;oBAC1C,MAAMkD,YAAYhH,SAASiH,KAAKC,GAAG,KAAK,IAAI,CAACjD,SAAS,EAAE;wBACtDkD,sBAAsB;oBACxB;oBACA,IAAI,CAACrD,eAAe,CAACuD,IAAI,GAAG,GAAGnF,UAAUF,KAAK8F,IAAI,CAAC,EAAE,EAAEd,UAAU,CAAC,CAAC;oBACnE,IAAI,CAAClD,eAAe,CAACiE,MAAM;gBAC7B;YACF,GAAG;QACL;IACF;IAEQP,cAAcT,QAA+D,EAAQ;QAC3F,MAAMqB,aAAarB,SAASsB,MAAM,CAAC,CAAC9C,OAASA,KAAK+C,IAAI,KAAK;QAE3D,IAAIF,WAAWG,MAAM,KAAK,GAAG;YAC3B;QACF;QAEA,IAAI,CAACjD,MAAM,CAACC,IAAI,CACd,CAAC,+BAA+B,EAAE6C,WAAWG,MAAM,GAAG,IAAI,WAAW,QAAQ,CAAC,CAAC;QAGjF,KAAK,MAAMC,WAAWJ,WAAY;YAChC,IAAII,QAAQ/G,GAAG,EAAE;gBACf,IAAI,CAAC6D,MAAM,CAACC,IAAI,CAAC,CAAC,EAAE,EAAEiD,QAAQ/G,GAAG,EAAE;YACrC;QACF;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/commands/datasets/import.ts"],"sourcesContent":["import fs from 'node:fs'\nimport path from 'node:path'\n\nimport {Args, Flags} from '@oclif/core'\nimport {exitCodes, getProjectCliClient, SanityCommand, subdebug} from '@sanity/cli-core'\nimport {createRequester, nodeReadableFromWeb} from '@sanity/cli-core/request'\nimport {spinner} from '@sanity/cli-core/ux'\nimport {sanityImport} from '@sanity/import'\nimport prettyMs from 'pretty-ms'\n\nimport {NEW_DATASET_VALUE, promptForDataset} from '../../prompts/promptForDataset.js'\nimport {promptForDatasetName} from '../../prompts/promptForDatasetName.js'\nimport {promptForProject} from '../../prompts/promptForProject.js'\nimport {createDataset, listDatasets} from '../../services/datasets.js'\nimport {getDatasetFlag, getProjectIdFlag} from '../../util/sharedFlags.js'\n\nconst importDebug = subdebug('dataset:import')\n\ninterface ProgressEvent {\n step: string\n\n current?: number\n total?: number\n update?: string\n}\n\nfunction getAssetsBase(source: string): string | undefined {\n if (/^https?:\\/\\//i.test(source) || source === '-') {\n return undefined\n }\n\n try {\n const fileStats = fs.statSync(source)\n const sourceIsFolder = fileStats.isDirectory()\n return sourceIsFolder ? source : path.dirname(source)\n } catch {\n return undefined\n }\n}\n\nasync function getUriStream(uri: string): Promise<NodeJS.ReadableStream> {\n const request = createRequester()\n\n try {\n // No timeout: large dataset exports may stream for longer than get-it's\n // default request timeout, which would abort the body mid-transfer.\n const response = await request({as: 'stream', timeout: false, url: uri})\n return nodeReadableFromWeb(response.body)\n } catch (err) {\n throw new Error(`Error fetching source:\\n${(err as Error).message}`, {cause: err})\n }\n}\n\nfunction getPercentage(opts: ProgressEvent): string {\n if (!opts.total) {\n return ''\n }\n\n const percent = Math.floor(((opts.current || 0) / opts.total) * 100)\n return `[${percent}%] `\n}\n\nexport class ImportDatasetCommand extends SanityCommand<typeof ImportDatasetCommand> {\n static override args = {\n source: Args.string({\n description: 'Source file (use \"-\" for stdin)',\n required: true,\n }),\n targetDataset: Args.string({\n description: 'Target dataset (prefer --dataset flag instead)',\n required: false,\n }),\n }\n\n static override description = 'Import documents to a Sanity dataset'\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %> -d staging my-dataset.ndjson',\n description: 'Import \"./my-dataset.ndjson\" into dataset \"staging\"',\n },\n {\n command: 'cat my-dataset.ndjson | <%= config.bin %> <%= command.id %> -d test -',\n description: 'Import into dataset \"test\" from stdin',\n },\n {\n command: '<%= config.bin %> <%= command.id %> -p projectId -d staging my-dataset.ndjson',\n description: 'Import with explicit project ID (overrides CLI configuration)',\n },\n {\n command:\n '<%= config.bin %> <%= command.id %> -d staging -t someSecretToken my-dataset.ndjson',\n description: 'Import with an explicit token (e.g. for CI/CD)',\n },\n ]\n\n static override flags = {\n 'allow-assets-in-different-dataset': Flags.boolean({\n default: false,\n description: 'Allow asset documents to reference different project/dataset',\n }),\n 'allow-failing-assets': Flags.boolean({\n default: false,\n description: 'Skip assets that cannot be fetched/uploaded',\n }),\n 'allow-replacement-characters': Flags.boolean({\n default: false,\n description: 'Allow unicode replacement characters in imported documents',\n }),\n 'allow-system-documents': Flags.boolean({\n default: false,\n description: 'Imports system documents',\n }),\n 'asset-concurrency': Flags.integer({\n description: 'Number of parallel asset imports',\n }),\n ...getDatasetFlag({\n description: 'Dataset to import to',\n semantics: 'specify',\n }),\n missing: Flags.boolean({\n default: false,\n description: 'Skip documents that already exist',\n exclusive: ['replace'],\n }),\n ...getProjectIdFlag({\n description: 'Project ID to import to',\n semantics: 'override',\n }),\n replace: Flags.boolean({\n default: false,\n description: 'Replace documents with the same IDs',\n exclusive: ['missing'],\n }),\n 'replace-assets': Flags.boolean({\n default: false,\n description: 'Skip reuse of existing assets',\n }),\n 'skip-cross-dataset-references': Flags.boolean({\n default: false,\n description: 'Skips references to other datasets',\n }),\n token: Flags.string({\n char: 't',\n description: 'Token to authenticate with',\n env: 'SANITY_IMPORT_TOKEN',\n required: false,\n }),\n }\n\n static override hiddenAliases: string[] = ['dataset:import']\n\n private currentProgress?: ReturnType<typeof spinner>\n private currentStep?: string\n private spinInterval?: NodeJS.Timeout | null\n private stepStart?: number\n\n private static async getStream(source: string): Promise<NodeJS.ReadableStream> {\n if (/^https?:\\/\\//i.test(source)) {\n return getUriStream(source)\n }\n\n return source === '-' ? process.stdin : fs.createReadStream(source)\n }\n\n public async run(): Promise<void> {\n const {args, flags} = await this.parse(ImportDatasetCommand)\n\n const {\n 'allow-assets-in-different-dataset': allowAssetsInDifferentDataset,\n 'allow-failing-assets': allowFailingAssets,\n 'allow-replacement-characters': allowReplacementCharacters,\n 'allow-system-documents': allowSystemDocuments,\n 'asset-concurrency': assetConcurrency,\n dataset: datasetFlag,\n missing,\n replace,\n 'replace-assets': replaceAssets,\n 'skip-cross-dataset-references': skipCrossDatasetReferences,\n token,\n } = flags\n\n const projectId = await this.getProjectId({\n fallback: () => promptForProject({}),\n })\n\n const {source, targetDataset: targetDatasetArg} = args\n\n if (targetDatasetArg && !datasetFlag) {\n this.output.warn(\n 'Positional dataset argument is deprecated. Use the --dataset flag instead: --dataset <name>',\n )\n }\n\n let dataset = datasetFlag ?? targetDatasetArg\n if (!dataset) {\n if (this.isUnattended()) {\n return this.output.error('Dataset is required. Pass it with `--dataset <name>`.', {\n exit: exitCodes.USAGE_ERROR,\n })\n }\n\n const datasets = await listDatasets(projectId)\n dataset = await promptForDataset({allowCreation: true, datasets})\n\n if (dataset === NEW_DATASET_VALUE) {\n const newDatasetName = await promptForDatasetName()\n\n try {\n await createDataset({datasetName: newDatasetName, projectId})\n dataset = newDatasetName\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n importDebug(`Failed to create dataset ${newDatasetName}: ${message}`, error)\n return this.output.error(`Failed to create dataset ${newDatasetName}: ${message}`, {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n }\n }\n\n let operation: 'create' | 'createIfNotExists' | 'createOrReplace' = 'create'\n let releasesOperation: 'fail' | 'ignore' | 'replace' = 'fail'\n\n if (replace || missing) {\n operation = replace ? 'createOrReplace' : 'createIfNotExists'\n releasesOperation = replace ? 'replace' : 'ignore'\n }\n\n const client = await getProjectCliClient({\n apiVersion: 'v2025-02-19',\n dataset,\n projectId,\n requireUser: true,\n ...(token ? {token} : {}),\n })\n\n try {\n const stream = await ImportDatasetCommand.getStream(source)\n const assetsBase = getAssetsBase(source)\n\n const importOptions = {\n allowAssetsInDifferentDataset,\n allowFailingAssets,\n allowReplacementCharacters,\n allowSystemDocuments,\n client,\n onProgress: this.onProgress.bind(this),\n operation,\n releasesOperation,\n replaceAssets,\n skipCrossDatasetReferences,\n tag: 'sanity.import',\n targetDataset: dataset,\n targetProjectId: projectId,\n ...(assetsBase ? {assetsBase} : {}),\n ...(assetConcurrency === undefined ? {} : {assetConcurrency}),\n }\n\n const {numDocs, warnings} = await sanityImport(stream, importOptions)\n\n if (this.stepStart) {\n const timeSpent = prettyMs(Date.now() - this.stepStart, {secondsDecimalDigits: 2})\n if (this.currentProgress) {\n if (this.spinInterval) {\n clearInterval(this.spinInterval)\n this.spinInterval = null\n }\n this.currentProgress.text = `[100%] ${this.currentStep} (${timeSpent})`\n this.currentProgress.succeed()\n }\n }\n\n this.output.log('Done! Imported %d documents to dataset \"%s\"\\n', numDocs, dataset)\n this.printWarnings(warnings)\n } catch (err) {\n if (this.spinInterval) {\n clearInterval(this.spinInterval)\n this.spinInterval = null\n }\n\n if (this.currentProgress) {\n this.currentProgress.fail()\n }\n\n return (err as Error).name === 'ReplacementCharError'\n ? this.output.error(\n `Import failed due to unicode replacement characters in the data.\\n${(err as Error).message}\\n\\nIf you are certain you want to proceed with the import despite potentially corrupt data, re-run the import with the \\`--allow-replacement-characters\\` flag set.`,\n {exit: exitCodes.RUNTIME_ERROR},\n )\n : this.output.error((err as Error).stack || (err as Error).message, {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n }\n\n private onProgress(opts: ProgressEvent): void {\n const lengthComputable = opts.total\n const sameStep = opts.step === this.currentStep\n const percent = getPercentage(opts)\n\n if (lengthComputable && opts.total === opts.current && this.spinInterval) {\n clearInterval(this.spinInterval)\n this.spinInterval = null\n }\n\n if (sameStep && !lengthComputable) {\n return\n }\n\n if (sameStep) {\n if (this.stepStart) {\n const timeSpent = prettyMs(Date.now() - this.stepStart, {secondsDecimalDigits: 2})\n if (this.currentProgress) {\n this.currentProgress.text = `${percent}${opts.step} (${timeSpent})`\n this.currentProgress.render()\n }\n }\n return\n }\n\n // Moved to a new step\n const prevStep = this.currentStep\n const prevStepStart = this.stepStart\n this.stepStart = Date.now()\n this.currentStep = opts.step\n\n if (this.spinInterval) {\n clearInterval(this.spinInterval)\n this.spinInterval = null\n }\n\n if (this.currentProgress && this.currentProgress.succeed && prevStepStart) {\n const timeSpent = prettyMs(Date.now() - prevStepStart, {\n secondsDecimalDigits: 2,\n })\n this.currentProgress.text = `[100%] ${prevStep} (${timeSpent})`\n this.currentProgress.succeed()\n }\n\n this.currentProgress = spinner(`[0%] ${opts.step} (0.00s)`).start()\n\n if (!lengthComputable) {\n this.spinInterval = setInterval(() => {\n if (this.stepStart && this.currentProgress) {\n const timeSpent = prettyMs(Date.now() - this.stepStart, {\n secondsDecimalDigits: 2,\n })\n this.currentProgress.text = `${percent}${opts.step} (${timeSpent})`\n this.currentProgress.render()\n }\n }, 60)\n }\n }\n\n private printWarnings(warnings: Array<{message: string; type?: string; url?: string}>): void {\n const assetFails = warnings.filter((warn) => warn.type === 'asset')\n\n if (assetFails.length === 0) {\n return\n }\n\n this.output.warn(\n `Failed to import the following ${assetFails.length > 1 ? 'assets' : 'asset'}:`,\n )\n\n for (const warning of assetFails) {\n if (warning.url) {\n this.output.warn(` ${warning.url}`)\n }\n }\n }\n}\n"],"names":["fs","path","Args","Flags","exitCodes","getProjectCliClient","SanityCommand","subdebug","createRequester","nodeReadableFromWeb","spinner","sanityImport","prettyMs","NEW_DATASET_VALUE","promptForDataset","promptForDatasetName","promptForProject","createDataset","listDatasets","getDatasetFlag","getProjectIdFlag","importDebug","getAssetsBase","source","test","undefined","fileStats","statSync","sourceIsFolder","isDirectory","dirname","getUriStream","uri","request","response","as","timeout","url","body","err","Error","message","cause","getPercentage","opts","total","percent","Math","floor","current","ImportDatasetCommand","args","string","description","required","targetDataset","examples","command","flags","boolean","default","integer","semantics","missing","exclusive","replace","token","char","env","hiddenAliases","currentProgress","currentStep","spinInterval","stepStart","getStream","process","stdin","createReadStream","run","parse","allowAssetsInDifferentDataset","allowFailingAssets","allowReplacementCharacters","allowSystemDocuments","assetConcurrency","dataset","datasetFlag","replaceAssets","skipCrossDatasetReferences","projectId","getProjectId","fallback","targetDatasetArg","output","warn","isUnattended","error","exit","USAGE_ERROR","datasets","allowCreation","newDatasetName","datasetName","String","RUNTIME_ERROR","operation","releasesOperation","client","apiVersion","requireUser","stream","assetsBase","importOptions","onProgress","bind","tag","targetProjectId","numDocs","warnings","timeSpent","Date","now","secondsDecimalDigits","clearInterval","text","succeed","log","printWarnings","fail","name","stack","lengthComputable","sameStep","step","render","prevStep","prevStepStart","start","setInterval","assetFails","filter","type","length","warning"],"mappings":"AAAA,OAAOA,QAAQ,UAAS;AACxB,OAAOC,UAAU,YAAW;AAE5B,SAAQC,IAAI,EAAEC,KAAK,QAAO,cAAa;AACvC,SAAQC,SAAS,EAAEC,mBAAmB,EAAEC,aAAa,EAAEC,QAAQ,QAAO,mBAAkB;AACxF,SAAQC,eAAe,EAAEC,mBAAmB,QAAO,2BAA0B;AAC7E,SAAQC,OAAO,QAAO,sBAAqB;AAC3C,SAAQC,YAAY,QAAO,iBAAgB;AAC3C,OAAOC,cAAc,YAAW;AAEhC,SAAQC,iBAAiB,EAAEC,gBAAgB,QAAO,oCAAmC;AACrF,SAAQC,oBAAoB,QAAO,wCAAuC;AAC1E,SAAQC,gBAAgB,QAAO,oCAAmC;AAClE,SAAQC,aAAa,EAAEC,YAAY,QAAO,6BAA4B;AACtE,SAAQC,cAAc,EAAEC,gBAAgB,QAAO,4BAA2B;AAE1E,MAAMC,cAAcd,SAAS;AAU7B,SAASe,cAAcC,MAAc;IACnC,IAAI,gBAAgBC,IAAI,CAACD,WAAWA,WAAW,KAAK;QAClD,OAAOE;IACT;IAEA,IAAI;QACF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AAI,CAACjD,eAAe,CAACgE,MAAM;gBAC7B;YACF,GAAG;QACL;IACF;IAEQP,cAAcT,QAA+D,EAAQ;QAC3F,MAAMqB,aAAarB,SAASsB,MAAM,CAAC,CAAC9C,OAASA,KAAK+C,IAAI,KAAK;QAE3D,IAAIF,WAAWG,MAAM,KAAK,GAAG;YAC3B;QACF;QAEA,IAAI,CAACjD,MAAM,CAACC,IAAI,CACd,CAAC,+BAA+B,EAAE6C,WAAWG,MAAM,GAAG,IAAI,WAAW,QAAQ,CAAC,CAAC;QAGjF,KAAK,MAAMC,WAAWJ,WAAY;YAChC,IAAII,QAAQ1G,GAAG,EAAE;gBACf,IAAI,CAACwD,MAAM,CAACC,IAAI,CAAC,CAAC,EAAE,EAAEiD,QAAQ1G,GAAG,EAAE;YACrC;QACF;IACF;AACF"}
|
|
@@ -11,7 +11,7 @@ export class ListDatasetCommand extends SanityCommand {
|
|
|
11
11
|
description: 'List datasets for the project'
|
|
12
12
|
},
|
|
13
13
|
{
|
|
14
|
-
command: '<%= config.bin %> <%= command.id %> --project
|
|
14
|
+
command: '<%= config.bin %> <%= command.id %> --project abc123',
|
|
15
15
|
description: 'List datasets for a specific project'
|
|
16
16
|
}
|
|
17
17
|
];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/commands/datasets/list.ts"],"sourcesContent":["import {exitCodes, SanityCommand, subdebug} from '@sanity/cli-core'\n\nimport {promptForProject} from '../../prompts/promptForProject.js'\nimport {listDatasetAliases, listDatasets} from '../../services/datasets.js'\nimport {getProjectIdFlag} from '../../util/sharedFlags.js'\n\nconst listDatasetDebug = subdebug('dataset:list')\n\nexport class ListDatasetCommand extends SanityCommand<typeof ListDatasetCommand> {\n static override description = 'List datasets for the project'\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %>',\n description: 'List datasets for the project',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --project
|
|
1
|
+
{"version":3,"sources":["../../../src/commands/datasets/list.ts"],"sourcesContent":["import {exitCodes, SanityCommand, subdebug} from '@sanity/cli-core'\n\nimport {promptForProject} from '../../prompts/promptForProject.js'\nimport {listDatasetAliases, listDatasets} from '../../services/datasets.js'\nimport {getProjectIdFlag} from '../../util/sharedFlags.js'\n\nconst listDatasetDebug = subdebug('dataset:list')\n\nexport class ListDatasetCommand extends SanityCommand<typeof ListDatasetCommand> {\n static override description = 'List datasets for the project'\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %>',\n description: 'List datasets for the project',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --project abc123',\n description: 'List datasets for a specific project',\n },\n ]\n\n static override flags = {\n ...getProjectIdFlag({\n description: 'Project ID to list datasets for',\n semantics: 'override',\n }),\n }\n\n static override hiddenAliases: string[] = ['dataset:list']\n\n public async run(): Promise<void> {\n const projectId = await this.getProjectId({\n fallback: () =>\n promptForProject({\n requiredPermissions: [{grant: 'read', permission: 'sanity.project.datasets'}],\n }),\n })\n\n const [datasets, aliases] = await Promise.allSettled([\n listDatasets(projectId),\n listDatasetAliases(projectId),\n ])\n\n if (datasets.status === 'rejected') {\n const err = datasets.reason as Error\n listDatasetDebug(`Error listing datasets for project ${projectId}`, err)\n this.error(`Dataset list retrieval failed: ${err.message}`, {exit: exitCodes.RUNTIME_ERROR})\n }\n\n const datasetList = datasets.value\n if (datasetList.length === 0) {\n this.log('No datasets found for this project.')\n } else {\n for (const dataset of datasetList) {\n this.log(dataset.name)\n }\n }\n\n if (aliases.status === 'fulfilled' && aliases.value.length > 0) {\n for (const alias of aliases.value) {\n const targetDataset = alias.datasetName || '<unlinked>'\n this.log(`~${alias.name} -> ${targetDataset}`)\n }\n } else if (aliases.status === 'rejected') {\n listDatasetDebug(`Warning: Could not fetch aliases for project ${projectId}`, aliases.reason)\n }\n }\n}\n"],"names":["exitCodes","SanityCommand","subdebug","promptForProject","listDatasetAliases","listDatasets","getProjectIdFlag","listDatasetDebug","ListDatasetCommand","description","examples","command","flags","semantics","hiddenAliases","run","projectId","getProjectId","fallback","requiredPermissions","grant","permission","datasets","aliases","Promise","allSettled","status","err","reason","error","message","exit","RUNTIME_ERROR","datasetList","value","length","log","dataset","name","alias","targetDataset","datasetName"],"mappings":"AAAA,SAAQA,SAAS,EAAEC,aAAa,EAAEC,QAAQ,QAAO,mBAAkB;AAEnE,SAAQC,gBAAgB,QAAO,oCAAmC;AAClE,SAAQC,kBAAkB,EAAEC,YAAY,QAAO,6BAA4B;AAC3E,SAAQC,gBAAgB,QAAO,4BAA2B;AAE1D,MAAMC,mBAAmBL,SAAS;AAElC,OAAO,MAAMM,2BAA2BP;IACtC,OAAgBQ,cAAc,gCAA+B;IAE7D,OAAgBC,WAAW;QACzB;YACEC,SAAS;YACTF,aAAa;QACf;QACA;YACEE,SAAS;YACTF,aAAa;QACf;KACD,CAAA;IAED,OAAgBG,QAAQ;QACtB,GAAGN,iBAAiB;YAClBG,aAAa;YACbI,WAAW;QACb,EAAE;IACJ,EAAC;IAED,OAAgBC,gBAA0B;QAAC;KAAe,CAAA;IAE1D,MAAaC,MAAqB;QAChC,MAAMC,YAAY,MAAM,IAAI,CAACC,YAAY,CAAC;YACxCC,UAAU,IACRf,iBAAiB;oBACfgB,qBAAqB;wBAAC;4BAACC,OAAO;4BAAQC,YAAY;wBAAyB;qBAAE;gBAC/E;QACJ;QAEA,MAAM,CAACC,UAAUC,QAAQ,GAAG,MAAMC,QAAQC,UAAU,CAAC;YACnDpB,aAAaW;YACbZ,mBAAmBY;SACpB;QAED,IAAIM,SAASI,MAAM,KAAK,YAAY;YAClC,MAAMC,MAAML,SAASM,MAAM;YAC3BrB,iBAAiB,CAAC,mCAAmC,EAAES,WAAW,EAAEW;YACpE,IAAI,CAACE,KAAK,CAAC,CAAC,+BAA+B,EAAEF,IAAIG,OAAO,EAAE,EAAE;gBAACC,MAAM/B,UAAUgC,aAAa;YAAA;QAC5F;QAEA,MAAMC,cAAcX,SAASY,KAAK;QAClC,IAAID,YAAYE,MAAM,KAAK,GAAG;YAC5B,IAAI,CAACC,GAAG,CAAC;QACX,OAAO;YACL,KAAK,MAAMC,WAAWJ,YAAa;gBACjC,IAAI,CAACG,GAAG,CAACC,QAAQC,IAAI;YACvB;QACF;QAEA,IAAIf,QAAQG,MAAM,KAAK,eAAeH,QAAQW,KAAK,CAACC,MAAM,GAAG,GAAG;YAC9D,KAAK,MAAMI,SAAShB,QAAQW,KAAK,CAAE;gBACjC,MAAMM,gBAAgBD,MAAME,WAAW,IAAI;gBAC3C,IAAI,CAACL,GAAG,CAAC,CAAC,CAAC,EAAEG,MAAMD,IAAI,CAAC,IAAI,EAAEE,eAAe;YAC/C;QACF,OAAO,IAAIjB,QAAQG,MAAM,KAAK,YAAY;YACxCnB,iBAAiB,CAAC,6CAA6C,EAAES,WAAW,EAAEO,QAAQK,MAAM;QAC9F;IACF;AACF"}
|
|
@@ -41,7 +41,7 @@ export class CreateDocumentCommand extends SanityCommand {
|
|
|
41
41
|
description: 'Open configured $EDITOR and replace the document with the given content on each save. Use JSON5 file extension and parser for simplified syntax.'
|
|
42
42
|
},
|
|
43
43
|
{
|
|
44
|
-
command: '<%= config.bin %> <%= command.id %> myDocument.json --project
|
|
44
|
+
command: '<%= config.bin %> <%= command.id %> myDocument.json --project abc123',
|
|
45
45
|
description: 'Create documents in a specific project'
|
|
46
46
|
}
|
|
47
47
|
];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/commands/documents/create.ts"],"sourcesContent":["import {randomUUID} from 'node:crypto'\nimport fs from 'node:fs/promises'\nimport os from 'node:os'\nimport path from 'node:path'\nimport {isDeepStrictEqual} from 'node:util'\n\nimport {Args, Flags} from '@oclif/core'\nimport {exitCodes, getProjectCliClient, SanityCommand, subdebug} from '@sanity/cli-core'\nimport {isRecord} from '@sanity/cli-core/util'\nimport {type MultipleMutationResult, type Mutation} from '@sanity/client'\nimport {watch as chokidarWatch} from 'chokidar'\nimport {execa, execaSync} from 'execa'\nimport json5 from 'json5'\n\nimport {DOCUMENTS_API_VERSION} from '../../actions/documents/constants.js'\nimport {getEditor, registerUnlinkOnSigInt} from '../../actions/documents/editor.js'\nimport {promptForProject} from '../../prompts/promptForProject.js'\nimport {isIdentifiedSanityDocument, isSanityDocumentish} from '../../util/isSanityDocumentish.js'\nimport {getDatasetFlag, getProjectIdFlag} from '../../util/sharedFlags.js'\n\nexport type MutationOperationName = 'create' | 'createIfNotExists' | 'createOrReplace'\n\nconst createDocumentDebug = subdebug('documents:create')\n\nexport class CreateDocumentCommand extends SanityCommand<typeof CreateDocumentCommand> {\n static override args = {\n file: Args.string({\n description: 'JSON file to create document(s) from',\n required: false,\n }),\n }\n\n static override description = 'Create one or more documents'\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %> myDocument.json',\n description: 'Create the document specified in \"myDocument.json\"',\n },\n {\n command: '<%= config.bin %> <%= command.id %>',\n description: 'Open configured $EDITOR and create the specified document(s)',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --id myDocId --replace',\n description:\n 'Fetch document with the ID \"myDocId\" and open configured $EDITOR with the current document content (if any). Replace document with the edited version when the editor closes',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --id myDocId --watch --replace --json5',\n description:\n 'Open configured $EDITOR and replace the document with the given content on each save. Use JSON5 file extension and parser for simplified syntax.',\n },\n {\n command: '<%= config.bin %> <%= command.id %> myDocument.json --project-id abc123',\n description: 'Create documents in a specific project',\n },\n ]\n\n static override flags = {\n ...getProjectIdFlag({\n description: 'Project ID to create document(s) in',\n semantics: 'override',\n }),\n ...getDatasetFlag({\n description: 'Dataset to create document(s) in',\n semantics: 'override',\n }),\n id: Flags.string({\n description:\n 'Specify a document ID to use. Will fetch remote document ID and populate editor.',\n }),\n json5: Flags.boolean({\n description: 'Use JSON5 file type to allow a \"simplified\" version of JSON',\n }),\n missing: Flags.boolean({\n description: \"On duplicate document IDs, don't modify the target document(s)\",\n }),\n replace: Flags.boolean({\n description:\n 'On duplicate document IDs, replace existing document with specified document(s)',\n }),\n watch: Flags.boolean({\n description: 'Write the documents whenever the target file or buffer changes',\n }),\n }\n\n static override hiddenAliases: string[] = ['document:create']\n\n private client!: Awaited<ReturnType<typeof getProjectCliClient>>\n\n public async run(): Promise<void> {\n const {args, flags} = await this.parse(CreateDocumentCommand)\n const {file} = args\n const {dataset, id, json5: useJson5, missing, replace, watch} = flags\n\n if (!file && this.isUnattended()) {\n this.error(\n 'Document input is required in unattended mode. Pass it as the `<file>` argument.',\n {exit: exitCodes.USAGE_ERROR},\n )\n }\n\n if (replace && missing) {\n this.error(\n 'Cannot use `--replace` and `--missing` together. Remove one flag and try again.',\n {\n exit: exitCodes.USAGE_ERROR,\n },\n )\n }\n\n if (id && file) {\n this.error(\n 'Cannot use `--id` with the `<file>` argument. Remove `--id` or omit `<file>` and try again.',\n {exit: exitCodes.USAGE_ERROR},\n )\n }\n\n const cliConfig = await this.tryGetCliConfig()\n\n const projectId = await this.getProjectId({fallback: () => promptForProject({})})\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\n this.client = await getProjectCliClient({\n apiVersion: DOCUMENTS_API_VERSION,\n dataset: targetDataset,\n projectId,\n requireUser: true,\n })\n\n let operation: MutationOperationName = 'create'\n if (replace || missing) {\n operation = replace ? 'createOrReplace' : 'createIfNotExists'\n }\n\n if (file) {\n try {\n const contentPath = path.resolve(process.cwd(), file)\n const content = json5.parse(await fs.readFile(contentPath, 'utf8'))\n const result = await this.writeDocuments(content, operation)\n this.log(this.getResultMessage(result, operation))\n return\n } catch (error) {\n const err = error as Error\n createDocumentDebug(`Error creating documents from file ${file}`, err)\n this.error(`Failed to create documents: ${err.message}`, {exit: exitCodes.RUNTIME_ERROR})\n }\n }\n\n try {\n // Create a temporary file and use that as source, opening an editor on it\n const docId = id || randomUUID()\n const ext = useJson5 ? 'json5' : 'json'\n // Add UUID prefix to prevent predictable file names and potential conflicts\n const tmpFile = path.join(os.tmpdir(), 'sanity-cli', `${randomUUID()}-${docId}.${ext}`)\n const stringify = useJson5 ? json5.stringify : JSON.stringify\n const defaultValue = (id && (await this.client.getDocument(id))) || {\n _id: docId,\n _type: 'specify-me',\n }\n\n // Create temp directory with restricted permissions (owner only)\n const tempDir = path.join(os.tmpdir(), 'sanity-cli')\n await fs.mkdir(tempDir, {\n mode: 0o700, // rwx------ (owner read/write/execute only)\n recursive: true,\n })\n\n // Write file with restricted permissions (owner read/write only)\n await fs.writeFile(tmpFile, stringify(defaultValue, null, 2), {\n encoding: 'utf8',\n mode: 0o600, // rw------- (owner read/write only)\n })\n\n const editor = getEditor()\n const readAndPerformCreatesFromFile = this.readAndPerformCreatesFromFile.bind(this, operation)\n\n if (watch) {\n // If we're in watch mode, we want to run the creation on each change (if it validates)\n registerUnlinkOnSigInt(tmpFile)\n this.log(`Watch mode: ${tmpFile}`)\n this.log('Watch mode: Will write documents on each save.')\n this.log('Watch mode: Press Ctrl + C to cancel watch mode.')\n\n // Add race condition protection\n let isProcessing = false\n chokidarWatch(tmpFile).on('change', async () => {\n if (isProcessing) {\n return // Skip if already processing\n }\n isProcessing = true\n\n this.log('')\n try {\n await readAndPerformCreatesFromFile(tmpFile, defaultValue)\n } finally {\n isProcessing = false\n }\n })\n execa(editor.bin, [...editor.args, tmpFile], {stdio: 'inherit'})\n } else {\n // While in normal mode, we just want to wait for the editor to close and run the thing once\n execaSync(editor.bin, [...editor.args, tmpFile], {stdio: 'inherit'})\n await readAndPerformCreatesFromFile(tmpFile, defaultValue)\n await fs.unlink(tmpFile).catch(() => {})\n }\n } catch (error) {\n const err = error as Error\n createDocumentDebug('Error in editor workflow', err)\n this.error(`Failed to create documents: ${err.message}`, {exit: exitCodes.RUNTIME_ERROR})\n }\n }\n\n private getErrorMessage(message: string, index: number, isSingle: boolean): string {\n return isSingle ? `Document ${message}` : `Document at index ${index} ${message}`\n }\n\n /**\n * Formats the result message for document operations\n */\n private getResultMessage(\n result: MultipleMutationResult,\n operation: MutationOperationName,\n ): string {\n const joiner = '\\n - '\n if (operation === 'createOrReplace') {\n return `Upserted:\\n - ${result.results.map((res) => res.id).join(joiner)}`\n }\n\n if (operation === 'create') {\n return `Created:\\n - ${result.results.map((res) => res.id).join(joiner)}`\n }\n\n // \"Missing\" (createIfNotExists)\n const created: string[] = []\n const skipped: string[] = []\n for (const res of result.results) {\n if (res.operation === 'update') {\n skipped.push(res.id)\n } else {\n created.push(res.id)\n }\n }\n\n if (created.length > 0 && skipped.length > 0) {\n return [\n `Created:\\n - ${created.join(joiner)}`,\n `Skipped (already exists):${joiner}${skipped.join(joiner)}`,\n ].join('\\n\\n')\n } else if (created.length > 0) {\n return `Created:\\n - ${created.join(joiner)}`\n }\n\n return `Skipped (already exists):\\n - ${skipped.join(joiner)}`\n }\n\n /**\n * Reads and processes documents from a file for creation\n */\n private async readAndPerformCreatesFromFile(\n operation: MutationOperationName,\n filePath: string,\n defaultValue: unknown,\n ): Promise<void> {\n let content\n try {\n content = json5.parse(await fs.readFile(filePath, 'utf8'))\n } catch (err) {\n const error = err as Error\n createDocumentDebug(`Failed to read input file ${filePath}`, error)\n this.log(`Failed to read input: ${error.message}`)\n return\n }\n\n if (isDeepStrictEqual(content, defaultValue)) {\n this.log('Value not modified, doing nothing.')\n this.log('Modify document to trigger creation.')\n return\n }\n\n try {\n const writeResult = await this.writeDocuments(content, operation)\n this.log(this.getResultMessage(writeResult, operation))\n } catch (err) {\n const error = err as Error\n createDocumentDebug(`Failed to write documents`, error)\n let errorMessage = `Failed to write documents: ${error.message}`\n if (error.message.includes('already exists')) {\n errorMessage += '\\nPerhaps you want to use `--replace` or `--missing`?'\n }\n this.error(errorMessage, {exit: exitCodes.RUNTIME_ERROR})\n }\n }\n\n /**\n * Validates a document for Sanity requirements\n */\n private validateDocument(doc: unknown, index: number, arr: unknown[]): void {\n const isSingle = arr.length === 1\n\n if (!isRecord(doc)) {\n throw new Error(this.getErrorMessage('must be an object', index, isSingle))\n }\n\n if (!isSanityDocumentish(doc)) {\n throw new Error(\n this.getErrorMessage('must have a `_type` property of type string', index, isSingle),\n )\n }\n\n // Enhanced validations for Sanity document constraints\n const docObj = doc as Record<string, unknown>\n\n // Validate _type is non-empty\n const typeValue = docObj._type?.toString().trim()\n if (!typeValue) {\n throw new Error(this.getErrorMessage('_type cannot be empty', index, isSingle))\n }\n\n // Validate _type format (alphanumeric, underscore, hyphen, dot)\n if (!/^[a-zA-Z][a-zA-Z0-9_.-]*$/.test(typeValue)) {\n throw new Error(\n this.getErrorMessage(\n '_type must start with a letter and contain only alphanumeric characters, underscores, hyphens, and dots',\n index,\n isSingle,\n ),\n )\n }\n\n // Validate _id format if present\n if (docObj._id && typeof docObj._id === 'string') {\n const idValue = docObj._id.trim()\n if (!idValue) {\n throw new Error(this.getErrorMessage('_id cannot be empty', index, isSingle))\n }\n\n // Sanity document IDs can contain alphanumeric chars, hyphens, underscores, and dots\n if (!/^[a-zA-Z0-9_.-]+$/.test(idValue)) {\n throw new Error(\n this.getErrorMessage(\n '_id can only contain alphanumeric characters, underscores, hyphens, and dots',\n index,\n isSingle,\n ),\n )\n }\n\n // Check length constraints (Sanity has reasonable limits)\n if (idValue.length > 200) {\n throw new Error(\n this.getErrorMessage('_id cannot be longer than 200 characters', index, isSingle),\n )\n }\n }\n\n // Warn about reserved fields (these are managed by Sanity)\n const reservedFields = ['_rev', '_updatedAt', '_createdAt']\n for (const field of reservedFields) {\n if (field in docObj) {\n // Note: We don't throw an error here as these might be present in fetched documents\n // that are being re-uploaded, but we could add a debug warning\n createDocumentDebug(\n `Warning: Document ${index} contains reserved field '${field}' which will be ignored by Sanity`,\n )\n }\n }\n }\n\n /**\n * Writes documents to Sanity using the specified operation\n */\n private async writeDocuments(\n documents: {_id?: string; _type: string} | {_id?: string; _type: string}[],\n operation: MutationOperationName,\n ): Promise<MultipleMutationResult> {\n const docs = Array.isArray(documents) ? documents : [documents]\n if (docs.length === 0) {\n throw new Error('No documents provided')\n }\n\n const mutations = docs.map((doc, index): Mutation => {\n this.validateDocument(doc, index, docs)\n if (operation === 'create') {\n return {create: doc}\n }\n\n if (operation === 'createIfNotExists') {\n if (isIdentifiedSanityDocument(doc)) {\n return {createIfNotExists: doc}\n }\n\n throw new Error(`Missing required _id attribute for ${operation}`)\n }\n\n if (operation === 'createOrReplace') {\n if (isIdentifiedSanityDocument(doc)) {\n return {createOrReplace: doc}\n }\n\n throw new Error(`Missing required _id attribute for ${operation}`)\n }\n\n throw new Error(`Unsupported operation ${operation}`)\n })\n\n return this.client.transaction(mutations).commit()\n }\n}\n"],"names":["randomUUID","fs","os","path","isDeepStrictEqual","Args","Flags","exitCodes","getProjectCliClient","SanityCommand","subdebug","isRecord","watch","chokidarWatch","execa","execaSync","json5","DOCUMENTS_API_VERSION","getEditor","registerUnlinkOnSigInt","promptForProject","isIdentifiedSanityDocument","isSanityDocumentish","getDatasetFlag","getProjectIdFlag","createDocumentDebug","CreateDocumentCommand","args","file","string","description","required","examples","command","flags","semantics","id","boolean","missing","replace","hiddenAliases","client","run","parse","dataset","useJson5","isUnattended","error","exit","USAGE_ERROR","cliConfig","tryGetCliConfig","projectId","getProjectId","fallback","api","targetDataset","apiVersion","requireUser","operation","contentPath","resolve","process","cwd","content","readFile","result","writeDocuments","log","getResultMessage","err","message","RUNTIME_ERROR","docId","ext","tmpFile","join","tmpdir","stringify","JSON","defaultValue","getDocument","_id","_type","tempDir","mkdir","mode","recursive","writeFile","encoding","editor","readAndPerformCreatesFromFile","bind","isProcessing","on","bin","stdio","unlink","catch","getErrorMessage","index","isSingle","joiner","results","map","res","created","skipped","push","length","filePath","writeResult","errorMessage","includes","validateDocument","doc","arr","Error","docObj","typeValue","toString","trim","test","idValue","reservedFields","field","documents","docs","Array","isArray","mutations","create","createIfNotExists","createOrReplace","transaction","commit"],"mappings":"AAAA,SAAQA,UAAU,QAAO,cAAa;AACtC,OAAOC,QAAQ,mB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B;QAEA,MAAMa,YAAYH,KAAKvB,GAAG,CAAC,CAACW,KAAKf;YAC/B,IAAI,CAACc,gBAAgB,CAACC,KAAKf,OAAO2B;YAClC,IAAIpE,cAAc,UAAU;gBAC1B,OAAO;oBAACwE,QAAQhB;gBAAG;YACrB;YAEA,IAAIxD,cAAc,qBAAqB;gBACrC,IAAItC,2BAA2B8F,MAAM;oBACnC,OAAO;wBAACiB,mBAAmBjB;oBAAG;gBAChC;gBAEA,MAAM,IAAIE,MAAM,CAAC,mCAAmC,EAAE1D,WAAW;YACnE;YAEA,IAAIA,cAAc,mBAAmB;gBACnC,IAAItC,2BAA2B8F,MAAM;oBACnC,OAAO;wBAACkB,iBAAiBlB;oBAAG;gBAC9B;gBAEA,MAAM,IAAIE,MAAM,CAAC,mCAAmC,EAAE1D,WAAW;YACnE;YAEA,MAAM,IAAI0D,MAAM,CAAC,sBAAsB,EAAE1D,WAAW;QACtD;QAEA,OAAO,IAAI,CAAClB,MAAM,CAAC6F,WAAW,CAACJ,WAAWK,MAAM;IAClD;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/commands/documents/create.ts"],"sourcesContent":["import {randomUUID} from 'node:crypto'\nimport fs from 'node:fs/promises'\nimport os from 'node:os'\nimport path from 'node:path'\nimport {isDeepStrictEqual} from 'node:util'\n\nimport {Args, Flags} from '@oclif/core'\nimport {exitCodes, getProjectCliClient, SanityCommand, subdebug} from '@sanity/cli-core'\nimport {isRecord} from '@sanity/cli-core/util'\nimport {type MultipleMutationResult, type Mutation} from '@sanity/client'\nimport {watch as chokidarWatch} from 'chokidar'\nimport {execa, execaSync} from 'execa'\nimport json5 from 'json5'\n\nimport {DOCUMENTS_API_VERSION} from '../../actions/documents/constants.js'\nimport {getEditor, registerUnlinkOnSigInt} from '../../actions/documents/editor.js'\nimport {promptForProject} from '../../prompts/promptForProject.js'\nimport {isIdentifiedSanityDocument, isSanityDocumentish} from '../../util/isSanityDocumentish.js'\nimport {getDatasetFlag, getProjectIdFlag} from '../../util/sharedFlags.js'\n\nexport type MutationOperationName = 'create' | 'createIfNotExists' | 'createOrReplace'\n\nconst createDocumentDebug = subdebug('documents:create')\n\nexport class CreateDocumentCommand extends SanityCommand<typeof CreateDocumentCommand> {\n static override args = {\n file: Args.string({\n description: 'JSON file to create document(s) from',\n required: false,\n }),\n }\n\n static override description = 'Create one or more documents'\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %> myDocument.json',\n description: 'Create the document specified in \"myDocument.json\"',\n },\n {\n command: '<%= config.bin %> <%= command.id %>',\n description: 'Open configured $EDITOR and create the specified document(s)',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --id myDocId --replace',\n description:\n 'Fetch document with the ID \"myDocId\" and open configured $EDITOR with the current document content (if any). Replace document with the edited version when the editor closes',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --id myDocId --watch --replace --json5',\n description:\n 'Open configured $EDITOR and replace the document with the given content on each save. Use JSON5 file extension and parser for simplified syntax.',\n },\n {\n command: '<%= config.bin %> <%= command.id %> myDocument.json --project abc123',\n description: 'Create documents in a specific project',\n },\n ]\n\n static override flags = {\n ...getProjectIdFlag({\n description: 'Project ID to create document(s) in',\n semantics: 'override',\n }),\n ...getDatasetFlag({\n description: 'Dataset to create document(s) in',\n semantics: 'override',\n }),\n id: Flags.string({\n description:\n 'Specify a document ID to use. Will fetch remote document ID and populate editor.',\n }),\n json5: Flags.boolean({\n description: 'Use JSON5 file type to allow a \"simplified\" version of JSON',\n }),\n missing: Flags.boolean({\n description: \"On duplicate document IDs, don't modify the target document(s)\",\n }),\n replace: Flags.boolean({\n description:\n 'On duplicate document IDs, replace existing document with specified document(s)',\n }),\n watch: Flags.boolean({\n description: 'Write the documents whenever the target file or buffer changes',\n }),\n }\n\n static override hiddenAliases: string[] = ['document:create']\n\n private client!: Awaited<ReturnType<typeof getProjectCliClient>>\n\n public async run(): Promise<void> {\n const {args, flags} = await this.parse(CreateDocumentCommand)\n const {file} = args\n const {dataset, id, json5: useJson5, missing, replace, watch} = flags\n\n if (!file && this.isUnattended()) {\n this.error(\n 'Document input is required in unattended mode. Pass it as the `<file>` argument.',\n {exit: exitCodes.USAGE_ERROR},\n )\n }\n\n if (replace && missing) {\n this.error(\n 'Cannot use `--replace` and `--missing` together. Remove one flag and try again.',\n {\n exit: exitCodes.USAGE_ERROR,\n },\n )\n }\n\n if (id && file) {\n this.error(\n 'Cannot use `--id` with the `<file>` argument. Remove `--id` or omit `<file>` and try again.',\n {exit: exitCodes.USAGE_ERROR},\n )\n }\n\n const cliConfig = await this.tryGetCliConfig()\n\n const projectId = await this.getProjectId({fallback: () => promptForProject({})})\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\n this.client = await getProjectCliClient({\n apiVersion: DOCUMENTS_API_VERSION,\n dataset: targetDataset,\n projectId,\n requireUser: true,\n })\n\n let operation: MutationOperationName = 'create'\n if (replace || missing) {\n operation = replace ? 'createOrReplace' : 'createIfNotExists'\n }\n\n if (file) {\n try {\n const contentPath = path.resolve(process.cwd(), file)\n const content = json5.parse(await fs.readFile(contentPath, 'utf8'))\n const result = await this.writeDocuments(content, operation)\n this.log(this.getResultMessage(result, operation))\n return\n } catch (error) {\n const err = error as Error\n createDocumentDebug(`Error creating documents from file ${file}`, err)\n this.error(`Failed to create documents: ${err.message}`, {exit: exitCodes.RUNTIME_ERROR})\n }\n }\n\n try {\n // Create a temporary file and use that as source, opening an editor on it\n const docId = id || randomUUID()\n const ext = useJson5 ? 'json5' : 'json'\n // Add UUID prefix to prevent predictable file names and potential conflicts\n const tmpFile = path.join(os.tmpdir(), 'sanity-cli', `${randomUUID()}-${docId}.${ext}`)\n const stringify = useJson5 ? json5.stringify : JSON.stringify\n const defaultValue = (id && (await this.client.getDocument(id))) || {\n _id: docId,\n _type: 'specify-me',\n }\n\n // Create temp directory with restricted permissions (owner only)\n const tempDir = path.join(os.tmpdir(), 'sanity-cli')\n await fs.mkdir(tempDir, {\n mode: 0o700, // rwx------ (owner read/write/execute only)\n recursive: true,\n })\n\n // Write file with restricted permissions (owner read/write only)\n await fs.writeFile(tmpFile, stringify(defaultValue, null, 2), {\n encoding: 'utf8',\n mode: 0o600, // rw------- (owner read/write only)\n })\n\n const editor = getEditor()\n const readAndPerformCreatesFromFile = this.readAndPerformCreatesFromFile.bind(this, operation)\n\n if (watch) {\n // If we're in watch mode, we want to run the creation on each change (if it validates)\n registerUnlinkOnSigInt(tmpFile)\n this.log(`Watch mode: ${tmpFile}`)\n this.log('Watch mode: Will write documents on each save.')\n this.log('Watch mode: Press Ctrl + C to cancel watch mode.')\n\n // Add race condition protection\n let isProcessing = false\n chokidarWatch(tmpFile).on('change', async () => {\n if (isProcessing) {\n return // Skip if already processing\n }\n isProcessing = true\n\n this.log('')\n try {\n await readAndPerformCreatesFromFile(tmpFile, defaultValue)\n } finally {\n isProcessing = false\n }\n })\n execa(editor.bin, [...editor.args, tmpFile], {stdio: 'inherit'})\n } else {\n // While in normal mode, we just want to wait for the editor to close and run the thing once\n execaSync(editor.bin, [...editor.args, tmpFile], {stdio: 'inherit'})\n await readAndPerformCreatesFromFile(tmpFile, defaultValue)\n await fs.unlink(tmpFile).catch(() => {})\n }\n } catch (error) {\n const err = error as Error\n createDocumentDebug('Error in editor workflow', err)\n this.error(`Failed to create documents: ${err.message}`, {exit: exitCodes.RUNTIME_ERROR})\n }\n }\n\n private getErrorMessage(message: string, index: number, isSingle: boolean): string {\n return isSingle ? `Document ${message}` : `Document at index ${index} ${message}`\n }\n\n /**\n * Formats the result message for document operations\n */\n private getResultMessage(\n result: MultipleMutationResult,\n operation: MutationOperationName,\n ): string {\n const joiner = '\\n - '\n if (operation === 'createOrReplace') {\n return `Upserted:\\n - ${result.results.map((res) => res.id).join(joiner)}`\n }\n\n if (operation === 'create') {\n return `Created:\\n - ${result.results.map((res) => res.id).join(joiner)}`\n }\n\n // \"Missing\" (createIfNotExists)\n const created: string[] = []\n const skipped: string[] = []\n for (const res of result.results) {\n if (res.operation === 'update') {\n skipped.push(res.id)\n } else {\n created.push(res.id)\n }\n }\n\n if (created.length > 0 && skipped.length > 0) {\n return [\n `Created:\\n - ${created.join(joiner)}`,\n `Skipped (already exists):${joiner}${skipped.join(joiner)}`,\n ].join('\\n\\n')\n } else if (created.length > 0) {\n return `Created:\\n - ${created.join(joiner)}`\n }\n\n return `Skipped (already exists):\\n - ${skipped.join(joiner)}`\n }\n\n /**\n * Reads and processes documents from a file for creation\n */\n private async readAndPerformCreatesFromFile(\n operation: MutationOperationName,\n filePath: string,\n defaultValue: unknown,\n ): Promise<void> {\n let content\n try {\n content = json5.parse(await fs.readFile(filePath, 'utf8'))\n } catch (err) {\n const error = err as Error\n createDocumentDebug(`Failed to read input file ${filePath}`, error)\n this.log(`Failed to read input: ${error.message}`)\n return\n }\n\n if (isDeepStrictEqual(content, defaultValue)) {\n this.log('Value not modified, doing nothing.')\n this.log('Modify document to trigger creation.')\n return\n }\n\n try {\n const writeResult = await this.writeDocuments(content, operation)\n this.log(this.getResultMessage(writeResult, operation))\n } catch (err) {\n const error = err as Error\n createDocumentDebug(`Failed to write documents`, error)\n let errorMessage = `Failed to write documents: ${error.message}`\n if (error.message.includes('already exists')) {\n errorMessage += '\\nPerhaps you want to use `--replace` or `--missing`?'\n }\n this.error(errorMessage, {exit: exitCodes.RUNTIME_ERROR})\n }\n }\n\n /**\n * Validates a document for Sanity requirements\n */\n private validateDocument(doc: unknown, index: number, arr: unknown[]): void {\n const isSingle = arr.length === 1\n\n if (!isRecord(doc)) {\n throw new Error(this.getErrorMessage('must be an object', index, isSingle))\n }\n\n if (!isSanityDocumentish(doc)) {\n throw new Error(\n this.getErrorMessage('must have a `_type` property of type string', index, isSingle),\n )\n }\n\n // Enhanced validations for Sanity document constraints\n const docObj = doc as Record<string, unknown>\n\n // Validate _type is non-empty\n const typeValue = docObj._type?.toString().trim()\n if (!typeValue) {\n throw new Error(this.getErrorMessage('_type cannot be empty', index, isSingle))\n }\n\n // Validate _type format (alphanumeric, underscore, hyphen, dot)\n if (!/^[a-zA-Z][a-zA-Z0-9_.-]*$/.test(typeValue)) {\n throw new Error(\n this.getErrorMessage(\n '_type must start with a letter and contain only alphanumeric characters, underscores, hyphens, and dots',\n index,\n isSingle,\n ),\n )\n }\n\n // Validate _id format if present\n if (docObj._id && typeof docObj._id === 'string') {\n const idValue = docObj._id.trim()\n if (!idValue) {\n throw new Error(this.getErrorMessage('_id cannot be empty', index, isSingle))\n }\n\n // Sanity document IDs can contain alphanumeric chars, hyphens, underscores, and dots\n if (!/^[a-zA-Z0-9_.-]+$/.test(idValue)) {\n throw new Error(\n this.getErrorMessage(\n '_id can only contain alphanumeric characters, underscores, hyphens, and dots',\n index,\n isSingle,\n ),\n )\n }\n\n // Check length constraints (Sanity has reasonable limits)\n if (idValue.length > 200) {\n throw new Error(\n this.getErrorMessage('_id cannot be longer than 200 characters', index, isSingle),\n )\n }\n }\n\n // Warn about reserved fields (these are managed by Sanity)\n const reservedFields = ['_rev', '_updatedAt', '_createdAt']\n for (const field of reservedFields) {\n if (field in docObj) {\n // Note: We don't throw an error here as these might be present in fetched documents\n // that are being re-uploaded, but we could add a debug warning\n createDocumentDebug(\n `Warning: Document ${index} contains reserved field '${field}' which will be ignored by Sanity`,\n )\n }\n }\n }\n\n /**\n * Writes documents to Sanity using the specified operation\n */\n private async writeDocuments(\n documents: {_id?: string; _type: string} | {_id?: string; _type: string}[],\n operation: MutationOperationName,\n ): Promise<MultipleMutationResult> {\n const docs = Array.isArray(documents) ? documents : [documents]\n if (docs.length === 0) {\n throw new Error('No documents provided')\n }\n\n const mutations = docs.map((doc, index): Mutation => {\n this.validateDocument(doc, index, docs)\n if (operation === 'create') {\n return {create: doc}\n }\n\n if (operation === 'createIfNotExists') {\n if (isIdentifiedSanityDocument(doc)) {\n return {createIfNotExists: doc}\n }\n\n throw new Error(`Missing required _id attribute for ${operation}`)\n }\n\n if (operation === 'createOrReplace') {\n if (isIdentifiedSanityDocument(doc)) {\n return {createOrReplace: doc}\n }\n\n throw new Error(`Missing required _id attribute for ${operation}`)\n }\n\n throw new Error(`Unsupported operation ${operation}`)\n })\n\n return this.client.transaction(mutations).commit()\n }\n}\n"],"names":["randomUUID","fs","os","path","isDeepStrictEqual","Args","Flags","exitCodes","getProjectCliClient","SanityCommand","subdebug","isRecord","watch","chokidarWatch","execa","execaSync","json5","DOCUMENTS_API_VERSION","getEditor","registerUnlinkOnSigInt","promptForProject","isIdentifiedSanityDocument","isSanityDocumentish","getDatasetFlag","getProjectIdFlag","createDocumentDebug","CreateDocumentCommand","args","file","string","description","required","examples","command","flags","semantics","id","boolean","missing","replace","hiddenAliases","client","run","parse","dataset","useJson5","isUnattended","error","exit","USAGE_ERROR","cliConfig","tryGetCliConfig","projectId","getProjectId","fallback","api","targetDataset","apiVersion","requireUser","operation","contentPath","resolve","process","cwd","content","readFile","result","writeDocuments","log","getResultMessage","err","message","RUNTIME_ERROR","docId","ext","tmpFile","join","tmpdir","stringify","JSON","defaultValue","getDocument","_id","_type","tempDir","mkdir","mode","recursive","writeFile","encoding","editor","readAndPerformCreatesFromFile","bind","isProcessing","on","bin","stdio","unlink","catch","getErrorMessage","index","isSingle","joiner","results","map","res","created","skipped","push","length","filePath","writeResult","errorMessage","includes","validateDocument","doc","arr","Error","docObj","typeValue","toString","trim","test","idValue","reservedFields","field","documents","docs","Array","isArray","mutations","create","createIfNotExists","createOrReplace","transaction","commit"],"mappings":"AAAA,SAAQA,UAAU,QAAO,cAAa;AACtC,OAAOC,QAAQ,mBAAkB;AACjC,OAAOC,QAAQ,UAAS;AACxB,OAAOC,UAAU,YAAW;AAC5B,SAAQC,iBAAiB,QAAO,YAAW;AAE3C,SAAQC,IAAI,EAAEC,KAAK,QAAO,cAAa;AACvC,SAAQC,SAAS,EAAEC,mBAAmB,EAAEC,aAAa,EAAEC,QAAQ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BAAqB;gBACrC,IAAItC,2BAA2B8F,MAAM;oBACnC,OAAO;wBAACiB,mBAAmBjB;oBAAG;gBAChC;gBAEA,MAAM,IAAIE,MAAM,CAAC,mCAAmC,EAAE1D,WAAW;YACnE;YAEA,IAAIA,cAAc,mBAAmB;gBACnC,IAAItC,2BAA2B8F,MAAM;oBACnC,OAAO;wBAACkB,iBAAiBlB;oBAAG;gBAC9B;gBAEA,MAAM,IAAIE,MAAM,CAAC,mCAAmC,EAAE1D,WAAW;YACnE;YAEA,MAAM,IAAI0D,MAAM,CAAC,sBAAsB,EAAE1D,WAAW;QACtD;QAEA,OAAO,IAAI,CAAClB,MAAM,CAAC6F,WAAW,CAACJ,WAAWK,MAAM;IAClD;AACF"}
|
|
@@ -34,7 +34,7 @@ export class DeleteDocumentCommand extends SanityCommand {
|
|
|
34
34
|
description: 'Delete the document with ID "doc1" and "doc2"'
|
|
35
35
|
},
|
|
36
36
|
{
|
|
37
|
-
command: '<%= config.bin %> <%= command.id %> myDocId --project
|
|
37
|
+
command: '<%= config.bin %> <%= command.id %> myDocId --project abc123',
|
|
38
38
|
description: 'Delete a document from a specific project'
|
|
39
39
|
}
|
|
40
40
|
];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/commands/documents/delete.ts"],"sourcesContent":["import {Args} from '@oclif/core'\nimport {exitCodes, getProjectCliClient, SanityCommand, subdebug} 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 deleteDocumentDebug = subdebug('documents:delete')\n\nexport class DeleteDocumentCommand extends SanityCommand<typeof DeleteDocumentCommand> {\n static override args = {\n id: Args.string({\n description: 'Document ID to delete',\n required: true,\n }),\n ids: Args.string({\n description: 'Additional document IDs to delete',\n required: false,\n }),\n }\n\n static override description = \"Delete one or more documents from the project's configured dataset\"\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %> myDocId',\n description: 'Delete the document with the ID \"myDocId\"',\n },\n {\n command: \"<%= config.bin %> <%= command.id %> 'myDocId'\",\n description: 'ID wrapped in double or single quote works equally well',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --dataset=blog someDocId',\n description: 'Delete document with ID \"someDocId\" from dataset \"blog\"',\n },\n {\n command: '<%= config.bin %> <%= command.id %> doc1 doc2',\n description: 'Delete the document with ID \"doc1\" and \"doc2\"',\n },\n {\n command: '<%= config.bin %> <%= command.id %> myDocId --project
|
|
1
|
+
{"version":3,"sources":["../../../src/commands/documents/delete.ts"],"sourcesContent":["import {Args} from '@oclif/core'\nimport {exitCodes, getProjectCliClient, SanityCommand, subdebug} 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 deleteDocumentDebug = subdebug('documents:delete')\n\nexport class DeleteDocumentCommand extends SanityCommand<typeof DeleteDocumentCommand> {\n static override args = {\n id: Args.string({\n description: 'Document ID to delete',\n required: true,\n }),\n ids: Args.string({\n description: 'Additional document IDs to delete',\n required: false,\n }),\n }\n\n static override description = \"Delete one or more documents from the project's configured dataset\"\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %> myDocId',\n description: 'Delete the document with the ID \"myDocId\"',\n },\n {\n command: \"<%= config.bin %> <%= command.id %> 'myDocId'\",\n description: 'ID wrapped in double or single quote works equally well',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --dataset=blog someDocId',\n description: 'Delete document with ID \"someDocId\" from dataset \"blog\"',\n },\n {\n command: '<%= config.bin %> <%= command.id %> doc1 doc2',\n description: 'Delete the document with ID \"doc1\" and \"doc2\"',\n },\n {\n command: '<%= config.bin %> <%= command.id %> myDocId --project abc123',\n description: 'Delete a document from a specific project',\n },\n ]\n\n static override flags = {\n ...getProjectIdFlag({description: 'Project ID to delete from', semantics: 'override'}),\n ...getDatasetFlag({description: 'Dataset to delete from', semantics: 'override'}),\n }\n\n static override hiddenAliases: string[] = ['document:delete']\n\n // Disable strict mode to allow for more flexible input\n // This is needed for supporting multiple document IDs\n static override strict = false\n\n public async run(): Promise<void> {\n const {args, argv, flags} = await this.parse(DeleteDocumentCommand)\n const {id} = args\n const {dataset} = flags\n\n // Collect all document IDs from args and argv\n const ids = [id, ...argv.slice(1)].filter(Boolean) as string[]\n\n if (ids.length === 0) {\n this.error('Document ID must be specified', {exit: exitCodes.RUNTIME_ERROR})\n }\n\n // Get project configuration (may not exist when running outside a project directory)\n const cliConfig = await this.tryGetCliConfig()\n\n const projectId = await this.getProjectId({fallback: () => promptForProject({})})\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\n try {\n const projectClient = await getProjectCliClient({\n apiVersion: DOCUMENTS_API_VERSION,\n dataset: targetDataset,\n projectId,\n requireUser: true,\n })\n\n const transaction = projectClient.transaction()\n for (const id of ids) {\n transaction.delete(id)\n }\n const {results} = await transaction.commit()\n const deleted = results.filter((res) => res.operation === 'delete').map((res) => res.id)\n const notFound = ids.filter((id) => !deleted.includes(id))\n\n if (deleted.length > 0) {\n this.log(`Deleted ${deleted.length} ${deleted.length === 1 ? 'document' : 'documents'}`)\n }\n\n if (notFound.length > 0) {\n this.error(\n `${notFound.length === 1 ? 'Document' : 'Documents'} not found: ${notFound.join(', ')}`,\n {\n exit: exitCodes.RUNTIME_ERROR,\n },\n )\n }\n } catch (error) {\n const err = error as Error\n deleteDocumentDebug(`Error deleting documents ${ids.join(', ')}`, err)\n this.error(\n `Failed to delete ${ids.length} ${ids.length === 1 ? 'document' : 'documents'}: ${err.message}`,\n {\n exit: exitCodes.RUNTIME_ERROR,\n },\n )\n }\n }\n}\n"],"names":["Args","exitCodes","getProjectCliClient","SanityCommand","subdebug","DOCUMENTS_API_VERSION","promptForProject","getDatasetFlag","getProjectIdFlag","deleteDocumentDebug","DeleteDocumentCommand","args","id","string","description","required","ids","examples","command","flags","semantics","hiddenAliases","strict","run","argv","parse","dataset","slice","filter","Boolean","length","error","exit","RUNTIME_ERROR","cliConfig","tryGetCliConfig","projectId","getProjectId","fallback","api","USAGE_ERROR","targetDataset","projectClient","apiVersion","requireUser","transaction","delete","results","commit","deleted","res","operation","map","notFound","includes","log","join","err","message"],"mappings":"AAAA,SAAQA,IAAI,QAAO,cAAa;AAChC,SAAQC,SAAS,EAAEC,mBAAmB,EAAEC,aAAa,EAAEC,QAAQ,QAAO,mBAAkB;AAExF,SAAQC,qBAAqB,QAAO,uCAAsC;AAC1E,SAAQC,gBAAgB,QAAO,oCAAmC;AAClE,SAAQC,cAAc,EAAEC,gBAAgB,QAAO,4BAA2B;AAE1E,MAAMC,sBAAsBL,SAAS;AAErC,OAAO,MAAMM,8BAA8BP;IACzC,OAAgBQ,OAAO;QACrBC,IAAIZ,KAAKa,MAAM,CAAC;YACdC,aAAa;YACbC,UAAU;QACZ;QACAC,KAAKhB,KAAKa,MAAM,CAAC;YACfC,aAAa;YACbC,UAAU;QACZ;IACF,EAAC;IAED,OAAgBD,cAAc,qEAAoE;IAElG,OAAgBG,WAAW;QACzB;YACEC,SAAS;YACTJ,aAAa;QACf;QACA;YACEI,SAAS;YACTJ,aAAa;QACf;QACA;YACEI,SAAS;YACTJ,aAAa;QACf;QACA;YACEI,SAAS;YACTJ,aAAa;QACf;QACA;YACEI,SAAS;YACTJ,aAAa;QACf;KACD,CAAA;IAED,OAAgBK,QAAQ;QACtB,GAAGX,iBAAiB;YAACM,aAAa;YAA6BM,WAAW;QAAU,EAAE;QACtF,GAAGb,eAAe;YAACO,aAAa;YAA0BM,WAAW;QAAU,EAAE;IACnF,EAAC;IAED,OAAgBC,gBAA0B;QAAC;KAAkB,CA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M,CAAC,CAAChB,KAAO,CAACqC,QAAQK,QAAQ,CAAC1C;YAEtD,IAAIqC,QAAQnB,MAAM,GAAG,GAAG;gBACtB,IAAI,CAACyB,GAAG,CAAC,CAAC,QAAQ,EAAEN,QAAQnB,MAAM,CAAC,CAAC,EAAEmB,QAAQnB,MAAM,KAAK,IAAI,aAAa,aAAa;YACzF;YAEA,IAAIuB,SAASvB,MAAM,GAAG,GAAG;gBACvB,IAAI,CAACC,KAAK,CACR,GAAGsB,SAASvB,MAAM,KAAK,IAAI,aAAa,YAAY,YAAY,EAAEuB,SAASG,IAAI,CAAC,OAAO,EACvF;oBACExB,MAAM/B,UAAUgC,aAAa;gBAC/B;YAEJ;QACF,EAAE,OAAOF,OAAO;YACd,MAAM0B,MAAM1B;YACZtB,oBAAoB,CAAC,yBAAyB,EAAEO,IAAIwC,IAAI,CAAC,OAAO,EAAEC;YAClE,IAAI,CAAC1B,KAAK,CACR,CAAC,iBAAiB,EAAEf,IAAIc,MAAM,CAAC,CAAC,EAAEd,IAAIc,MAAM,KAAK,IAAI,aAAa,YAAY,EAAE,EAAE2B,IAAIC,OAAO,EAAE,EAC/F;gBACE1B,MAAM/B,UAAUgC,aAAa;YAC/B;QAEJ;IACF;AACF"}
|
|
@@ -26,7 +26,7 @@ export class GetDocumentCommand extends SanityCommand {
|
|
|
26
26
|
description: 'Get document from a specific dataset'
|
|
27
27
|
},
|
|
28
28
|
{
|
|
29
|
-
command: '<%= config.bin %> <%= command.id %> myDocId --project
|
|
29
|
+
command: '<%= config.bin %> <%= command.id %> myDocId --project abc123',
|
|
30
30
|
description: 'Get a document from a specific project'
|
|
31
31
|
}
|
|
32
32
|
];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/commands/documents/get.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 getDocumentDebug = subdebug('documents:get')\n\nexport class GetDocumentCommand extends SanityCommand<typeof GetDocumentCommand> {\n static override args = {\n documentId: Args.string({\n description: 'Document ID to retrieve',\n required: true,\n }),\n }\n\n static override description = 'Get and print a document by ID'\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %> myDocId',\n description: 'Get the document with ID \"myDocId\"',\n },\n {\n command: '<%= config.bin %> <%= command.id %> myDocId --pretty',\n description: 'Get document with colorized JSON output',\n },\n {\n command: '<%= config.bin %> <%= command.id %> myDocId --dataset production',\n description: 'Get document from a specific dataset',\n },\n {\n command: '<%= config.bin %> <%= command.id %> myDocId --project
|
|
1
|
+
{"version":3,"sources":["../../../src/commands/documents/get.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 getDocumentDebug = subdebug('documents:get')\n\nexport class GetDocumentCommand extends SanityCommand<typeof GetDocumentCommand> {\n static override args = {\n documentId: Args.string({\n description: 'Document ID to retrieve',\n required: true,\n }),\n }\n\n static override description = 'Get and print a document by ID'\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %> myDocId',\n description: 'Get the document with ID \"myDocId\"',\n },\n {\n command: '<%= config.bin %> <%= command.id %> myDocId --pretty',\n description: 'Get document with colorized JSON output',\n },\n {\n command: '<%= config.bin %> <%= command.id %> myDocId --dataset production',\n description: 'Get document from a specific dataset',\n },\n {\n command: '<%= config.bin %> <%= command.id %> myDocId --project abc123',\n description: 'Get a document from a specific project',\n },\n ]\n\n static override flags = {\n ...getProjectIdFlag({\n description: 'Project ID to get document from',\n semantics: 'override',\n }),\n ...getDatasetFlag({description: 'Dataset to get document from', semantics: 'override'}),\n pretty: Flags.boolean({\n default: false,\n description: 'Colorize JSON output',\n }),\n }\n\n static override hiddenAliases: string[] = ['document:get']\n\n public async run(): Promise<void> {\n const {args, flags} = await this.parse(GetDocumentCommand)\n const {documentId} = args\n const {dataset, pretty} = flags\n\n const cliConfig = await this.tryGetCliConfig()\n\n const projectId = await this.getProjectId({fallback: () => promptForProject({})})\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\n try {\n const projectClient = await getProjectCliClient({\n apiVersion: DOCUMENTS_API_VERSION,\n dataset: targetDataset,\n projectId,\n requireUser: true,\n })\n\n const doc = await projectClient.getDocument(documentId)\n\n if (!doc) {\n this.error(`Document \"${documentId}\" not found in dataset \"${targetDataset}\"`, {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n\n // Output the document\n if (pretty) {\n this.log(colorizeJson(doc))\n } else {\n this.log(JSON.stringify(doc, null, 2))\n }\n } catch (error) {\n const err = error as Error\n\n getDocumentDebug(`Error fetching document ${documentId}`, err)\n this.error(`Failed to fetch document: ${err.message}`, {exit: exitCodes.RUNTIME_ERROR})\n }\n }\n}\n"],"names":["Args","Flags","colorizeJson","exitCodes","getProjectCliClient","SanityCommand","subdebug","DOCUMENTS_API_VERSION","promptForProject","getDatasetFlag","getProjectIdFlag","getDocumentDebug","GetDocumentCommand","args","documentId","string","description","required","examples","command","flags","semantics","pretty","boolean","default","hiddenAliases","run","parse","dataset","cliConfig","tryGetCliConfig","projectId","getProjectId","fallback","api","error","exit","USAGE_ERROR","targetDataset","projectClient","apiVersion","requireUser","doc","getDocument","RUNTIME_ERROR","log","JSON","stringify","err","message"],"mappings":"AA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,SAAS;YACvC,IAAI,CAACO,KAAK,CACR,4FACA;gBAACC,MAAMjC,UAAUkC,WAAW;YAAA;QAEhC;QAEA,MAAMC,gBAAgBV,WAAWC,UAAUK,GAAG,EAAEN;QAEhD,IAAI;YACF,MAAMW,gBAAgB,MAAMnC,oBAAoB;gBAC9CoC,YAAYjC;gBACZqB,SAASU;gBACTP;gBACAU,aAAa;YACf;YAEA,MAAMC,MAAM,MAAMH,cAAcI,WAAW,CAAC7B;YAE5C,IAAI,CAAC4B,KAAK;gBACR,IAAI,CAACP,KAAK,CAAC,CAAC,UAAU,EAAErB,WAAW,wBAAwB,EAAEwB,cAAc,CAAC,CAAC,EAAE;oBAC7EF,MAAMjC,UAAUyC,aAAa;gBAC/B;YACF;YAEA,sBAAsB;YACtB,IAAItB,QAAQ;gBACV,IAAI,CAACuB,GAAG,CAAC3C,aAAawC;YACxB,OAAO;gBACL,IAAI,CAACG,GAAG,CAACC,KAAKC,SAAS,CAACL,KAAK,MAAM;YACrC;QACF,EAAE,OAAOP,OAAO;YACd,MAAMa,MAAMb;YAEZxB,iBAAiB,CAAC,wBAAwB,EAAEG,YAAY,EAAEkC;YAC1D,IAAI,CAACb,KAAK,CAAC,CAAC,0BAA0B,EAAEa,IAAIC,OAAO,EAAE,EAAE;gBAACb,MAAMjC,UAAUyC,aAAa;YAAA;QACvF;IACF;AACF"}
|
|
@@ -27,7 +27,7 @@ export class QueryDocumentCommand extends SanityCommand {
|
|
|
27
27
|
description: 'Use API version v2021-06-07 and do a query'
|
|
28
28
|
},
|
|
29
29
|
{
|
|
30
|
-
command: '<%= config.bin %> <%= command.id %> \'*[_type == "post"]\' --project
|
|
30
|
+
command: '<%= config.bin %> <%= command.id %> \'*[_type == "post"]\' --project abc123 --dataset production',
|
|
31
31
|
description: 'Query documents in a specific project and dataset'
|
|
32
32
|
}
|
|
33
33
|
];
|
|
@@ -50,13 +50,6 @@ export class QueryDocumentCommand extends SanityCommand {
|
|
|
50
50
|
pretty: Flags.boolean({
|
|
51
51
|
default: false,
|
|
52
52
|
description: 'Colorize JSON output'
|
|
53
|
-
}),
|
|
54
|
-
project: Flags.string({
|
|
55
|
-
deprecated: {
|
|
56
|
-
to: 'project-id'
|
|
57
|
-
},
|
|
58
|
-
description: 'Project ID to query',
|
|
59
|
-
hidden: true
|
|
60
53
|
})
|
|
61
54
|
};
|
|
62
55
|
static hiddenAliases = [
|
|
@@ -68,7 +61,6 @@ export class QueryDocumentCommand extends SanityCommand {
|
|
|
68
61
|
const { anonymous, 'api-version': apiVersion, dataset, pretty } = flags;
|
|
69
62
|
const cliConfig = await this.tryGetCliConfig();
|
|
70
63
|
const projectId = await this.getProjectId({
|
|
71
|
-
deprecatedFlagName: 'project',
|
|
72
64
|
fallback: ()=>promptForProject({})
|
|
73
65
|
});
|
|
74
66
|
const requireUser = !anonymous;
|
|
@@ -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'\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
|
|
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 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 }\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 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","hiddenAliases","run","parse","apiVersion","dataset","cliConfig","tryGetCliConfig","projectId","getProjectId","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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aAAa;gBAAA;YACxE;YAEA,2BAA2B;YAC3B,IAAI3B,QAAQ;gBACV,IAAI,CAAC4B,GAAG,CAACpD,aAAaiD;YACxB,OAAO;gBACL,IAAI,CAACG,GAAG,CAACC,KAAKC,SAAS,CAACL,MAAM,MAAM;YACtC;QACF,EAAE,OAAOZ,OAAO;YACd,MAAMkB,MAAMlB;YAEZ3B,mBAAmB,CAAC,qBAAqB,EAAEG,OAAO,EAAE0C;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,EAAE3C,OAAO,EAAE;gBAACyB,MAAMrC,UAAUkD,aAAa;YAAA;QAC3E;IACF;AACF"}
|
|
@@ -29,7 +29,7 @@ export class ValidateDocumentsCommand extends SanityCommand {
|
|
|
29
29
|
description: 'Report out info level validation markers too'
|
|
30
30
|
},
|
|
31
31
|
{
|
|
32
|
-
command: '<%= config.bin %> <%= command.id %> --project
|
|
32
|
+
command: '<%= config.bin %> <%= command.id %> --project abc123 --dataset production',
|
|
33
33
|
description: 'Validate documents in a specific project and dataset'
|
|
34
34
|
}
|
|
35
35
|
];
|
|
@@ -84,7 +84,7 @@ export class ValidateDocumentsCommand extends SanityCommand {
|
|
|
84
84
|
];
|
|
85
85
|
async run() {
|
|
86
86
|
const { flags } = await this.parse(ValidateDocumentsCommand);
|
|
87
|
-
const { dataset, file, format, level, 'max-custom-validation-concurrency': maxCustomValidationConcurrency, 'max-fetch-concurrency': maxFetchConcurrency,
|
|
87
|
+
const { dataset, file, format, level, 'max-custom-validation-concurrency': maxCustomValidationConcurrency, 'max-fetch-concurrency': maxFetchConcurrency, project: projectId, workspace } = flags;
|
|
88
88
|
const unattendedMode = this.isUnattended();
|
|
89
89
|
let workDir;
|
|
90
90
|
let cliConfig;
|