@sanity/cli 7.15.0 → 7.16.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 +88 -1
- package/dist/actions/build/shouldAutoUpdate.js +28 -5
- package/dist/actions/build/shouldAutoUpdate.js.map +1 -1
- package/dist/actions/deploy/deployApp.js +4 -8
- package/dist/actions/deploy/deployApp.js.map +1 -1
- package/dist/actions/deploy/deployChecks.js +49 -31
- package/dist/actions/deploy/deployChecks.js.map +1 -1
- package/dist/actions/deploy/deployRunner.js +1 -1
- package/dist/actions/deploy/deployRunner.js.map +1 -1
- package/dist/actions/deploy/deployStudio.js +12 -10
- package/dist/actions/deploy/deployStudio.js.map +1 -1
- package/dist/actions/deploy/deploymentPlan.js +2 -2
- package/dist/actions/deploy/deploymentPlan.js.map +1 -1
- package/dist/actions/deploy/resolveDeployTarget.js +13 -13
- package/dist/actions/deploy/resolveDeployTarget.js.map +1 -1
- package/dist/actions/init/bootstrapLocalTemplate.js +2 -3
- package/dist/actions/init/bootstrapLocalTemplate.js.map +1 -1
- package/dist/actions/init/createAppCliConfig.js.map +1 -1
- package/dist/actions/init/createCliConfig.js.map +1 -1
- package/dist/actions/init/initNextJs.js +1 -1
- package/dist/actions/init/initNextJs.js.map +1 -1
- package/dist/actions/init/initStudio.js +10 -6
- package/dist/actions/init/initStudio.js.map +1 -1
- package/dist/actions/init/templates/appSanityUi.js +1 -1
- package/dist/actions/init/templates/appSanityUi.js.map +1 -1
- package/dist/actions/init/templates/getStarted.js +2 -2
- package/dist/actions/init/templates/getStarted.js.map +1 -1
- package/dist/actions/init/templates/nextjs/schemaTypes/blog.js +4 -4
- package/dist/actions/init/templates/nextjs/schemaTypes/blog.js.map +1 -1
- package/dist/actions/init/templates/shopify.js +2 -2
- package/dist/actions/init/templates/shopify.js.map +1 -1
- package/dist/actions/init/templates/shopifyOnline.js +2 -2
- package/dist/actions/init/templates/shopifyOnline.js.map +1 -1
- package/dist/actions/manifest/extractCoreAppManifest.js +7 -7
- package/dist/actions/manifest/extractCoreAppManifest.js.map +1 -1
- package/dist/actions/scaffold/createFrontend.js +107 -0
- package/dist/actions/scaffold/createFrontend.js.map +1 -0
- package/dist/actions/scaffold/scaffoldProject.js +202 -0
- package/dist/actions/scaffold/scaffoldProject.js.map +1 -0
- package/dist/actions/telemetry/resolveConsent.js +4 -2
- package/dist/actions/telemetry/resolveConsent.js.map +1 -1
- package/dist/commands/backups/list.js +1 -1
- package/dist/commands/backups/list.js.map +1 -1
- package/dist/commands/datasets/copy.js +5 -3
- package/dist/commands/datasets/copy.js.map +1 -1
- package/dist/commands/documents/query.js +5 -4
- package/dist/commands/documents/query.js.map +1 -1
- package/dist/commands/migrations/list.js +1 -1
- package/dist/commands/migrations/list.js.map +1 -1
- package/dist/commands/migrations/run.js +1 -1
- package/dist/commands/migrations/run.js.map +1 -1
- package/dist/commands/new.js +309 -0
- package/dist/commands/new.js.map +1 -0
- package/dist/commands/organizations/list.js +1 -1
- package/dist/commands/organizations/list.js.map +1 -1
- package/dist/commands/projects/unclaimed.js +205 -0
- package/dist/commands/projects/unclaimed.js.map +1 -0
- package/dist/commands/tokens/list.js +1 -1
- package/dist/commands/tokens/list.js.map +1 -1
- package/dist/commands/users/list.js +5 -1
- package/dist/commands/users/list.js.map +1 -1
- package/dist/exports/invokeSanityCli/commandPolicies/mcpPolicy.js +4 -0
- package/dist/exports/invokeSanityCli/commandPolicies/mcpPolicy.js.map +1 -1
- package/dist/exports/invokeSanityCli/index.d.ts +5 -9
- package/dist/exports/invokeSanityCli/index.js +47 -20
- package/dist/exports/invokeSanityCli/index.js.map +1 -1
- package/dist/exports/runtime.d.ts +12 -0
- package/dist/exports/runtime.js.map +1 -1
- package/dist/services/mintProject.js +91 -0
- package/dist/services/mintProject.js.map +1 -0
- package/dist/services/projects.js +19 -0
- package/dist/services/projects.js.map +1 -1
- package/dist/services/telemetry.js +4 -0
- package/dist/services/telemetry.js.map +1 -1
- package/dist/util/formatClaimDeadline.js +15 -0
- package/dist/util/formatClaimDeadline.js.map +1 -0
- package/dist/util/mintProjectConstants.js +6 -0
- package/dist/util/mintProjectConstants.js.map +1 -0
- package/dist/util/newCommandSplash.js +27 -0
- package/dist/util/newCommandSplash.js.map +1 -0
- package/dist/util/packageManager/installPackages.js +57 -28
- package/dist/util/packageManager/installPackages.js.map +1 -1
- package/dist/util/unclaimedProjects.js +105 -0
- package/dist/util/unclaimedProjects.js.map +1 -0
- package/oclif.manifest.json +150 -41
- package/package.json +7 -7
- package/templates/get-started/plugins/sanity-plugin-tutorial/GetStartedTutorial.tsx +1 -1
- package/templates/shopify/components/inputs/CollectionHidden.tsx +1 -1
- package/templates/shopify/components/inputs/ProductHidden.tsx +1 -1
- package/templates/shopify/components/inputs/ProductVariantHidden.tsx +1 -1
- package/templates/shopify/components/inputs/ProxyString.tsx +1 -1
- package/templates/shopify/components/media/ShopifyDocumentStatus.tsx +3 -1
- package/templates/shopify/constants.ts +3 -1
- package/templates/shopify/plugins/customDocumentActions/shopifyDelete.tsx +1 -1
- package/templates/shopify/plugins/customDocumentActions/shopifyLink.ts +1 -1
- package/templates/shopify/schemaTypes/documents/collection.tsx +1 -1
- package/templates/shopify/schemaTypes/documents/colorTheme.tsx +1 -1
- package/templates/shopify/schemaTypes/documents/page.ts +1 -1
- package/templates/shopify/schemaTypes/documents/product.tsx +1 -1
- package/templates/shopify/schemaTypes/documents/productVariant.tsx +1 -1
- package/templates/shopify/schemaTypes/objects/collection/collectionGroupType.ts +1 -1
- package/templates/shopify/schemaTypes/objects/hotspot/imageWithProductHotspotsType.ts +1 -1
- package/templates/shopify/schemaTypes/objects/link/linkEmailType.tsx +1 -1
- package/templates/shopify/schemaTypes/objects/link/linkExternalType.tsx +1 -1
- package/templates/shopify/schemaTypes/objects/link/linkInternalType.tsx +1 -1
- package/templates/shopify/schemaTypes/objects/link/linkProductType.tsx +1 -1
- package/templates/shopify/schemaTypes/objects/module/accordionType.ts +1 -1
- package/templates/shopify/schemaTypes/objects/module/callToActionType.tsx +2 -1
- package/templates/shopify/schemaTypes/objects/module/calloutType.ts +1 -1
- package/templates/shopify/schemaTypes/objects/module/collectionReferenceType.tsx +1 -1
- package/templates/shopify/schemaTypes/objects/module/gridType.ts +1 -1
- package/templates/shopify/schemaTypes/objects/module/imageFeatureType.ts +1 -1
- package/templates/shopify/schemaTypes/objects/module/imageFeaturesType.tsx +1 -1
- package/templates/shopify/schemaTypes/objects/module/instagramType.ts +1 -1
- package/templates/shopify/schemaTypes/objects/module/productFeaturesType.tsx +1 -1
- package/templates/shopify/schemaTypes/objects/module/productReferenceType.tsx +1 -1
- package/templates/shopify/schemaTypes/objects/shopify/collectionRuleType.tsx +1 -1
- package/templates/shopify/schemaTypes/objects/shopify/optionType.tsx +1 -1
- package/templates/shopify/schemaTypes/objects/shopify/productWithVariantType.tsx +1 -1
- package/templates/shopify/schemaTypes/singletons/homeType.ts +1 -1
- package/templates/shopify/schemaTypes/singletons/settingsType.ts +5 -1
- package/templates/shopify/structure/pageStructure.ts +1 -1
- package/templates/shopify/structure/productStructure.ts +1 -1
- package/templates/shopify-online-storefront/components/inputs/CollectionHidden.tsx +1 -1
- package/templates/shopify-online-storefront/components/inputs/ProductHidden.tsx +1 -1
- package/templates/shopify-online-storefront/components/inputs/ProductVariantHidden.tsx +1 -1
- package/templates/shopify-online-storefront/components/inputs/ProxyString.tsx +1 -1
- package/templates/shopify-online-storefront/components/media/ShopifyDocumentStatus.tsx +3 -1
- package/templates/shopify-online-storefront/plugins/shopifyDocumentActions/shopifyDelete.tsx +1 -1
- package/templates/shopify-online-storefront/plugins/shopifyDocumentActions/shopifyLink.ts +1 -1
- package/templates/shopify-online-storefront/schemaTypes/documents/collection.tsx +1 -1
- package/templates/shopify-online-storefront/schemaTypes/documents/product.tsx +1 -1
- package/templates/shopify-online-storefront/schemaTypes/documents/productVariant.tsx +1 -1
- package/templates/shopify-online-storefront/schemaTypes/objects/accordion.ts +1 -1
- package/templates/shopify-online-storefront/schemaTypes/objects/callout.ts +1 -1
- package/templates/shopify-online-storefront/schemaTypes/objects/option.ts +1 -1
- package/templates/shopify-online-storefront/schemaTypes/objects/shopifyCollectionRule.tsx +1 -1
- package/templates/shopify-online-storefront/structure/productStructure.ts +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/commands/tokens/list.ts"],"sourcesContent":["import {Flags} from '@oclif/core'\nimport {exitCodes, SanityCommand, subdebug} from '@sanity/cli-core'\nimport {getErrorMessage} from '@sanity/cli-core/errors'\nimport {Table} from 'console-table-printer'\n\nimport {type Token} from '../../actions/tokens/types.js'\nimport {promptForProject} from '../../prompts/promptForProject.js'\nimport {getTokens} from '../../services/tokens.js'\nimport {getProjectIdFlag} from '../../util/sharedFlags.js'\n\nconst listTokenDebug = subdebug('tokens:list')\n\nexport class TokensListCommand extends SanityCommand<typeof TokensListCommand> {\n static override description = 'List API tokens for the project'\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %>',\n description: 'List tokens for the project',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --json',\n description: 'List tokens in JSON format',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --project-id abc123',\n description: 'List tokens for a specific project',\n },\n ]\n static override flags = {\n ...getProjectIdFlag({\n description: 'Project ID to list tokens for',\n semantics: 'override',\n }),\n json: Flags.boolean({\n default: false,\n description: 'Output tokens in JSON format',\n }),\n }\n\n static override hiddenAliases: string[] = ['token:list']\n\n public async run(): Promise<void> {\n const {flags} = await this.parse(TokensListCommand)\n const {json} = flags\n const outputJson = json ?? false\n\n // Ensure we have project context\n const projectId = await this.getProjectId({\n fallback: () =>\n promptForProject({\n requiredPermissions: [{grant: 'read', permission: 'sanity.project.tokens'}],\n }),\n })\n\n let tokens: Token[]\n try {\n tokens = await getTokens(projectId)\n } catch (error) {\n const message = getErrorMessage(error)\n listTokenDebug(`Error fetching tokens for project ${projectId}`, error)\n this.error(`Token list retrieval failed:\\n${message}`, {exit: exitCodes.RUNTIME_ERROR})\n }\n\n if (outputJson) {\n this.log(JSON.stringify(tokens, null, 2))\n return\n }\n\n if (tokens.length === 0) {\n this.log('No API tokens found for this project.')\n return\n }\n\n const table = new Table({\n columns: [\n {alignment: 'left', maxLen: 40, name: 'label', title: 'Label'},\n {alignment: 'left', maxLen: 20, name: 'id', title: 'Token ID'},\n {alignment: 'left', maxLen: 30, name: 'roles', title: 'Roles'},\n ],\n title: `Found ${tokens.length} API tokens`,\n })\n\n for (const token of tokens) {\n const roles = token.roles?.map((role) => role.title).join(', ') || 'No roles'\n const truncatedLabel =\n token.label.length > 37 ? `${token.label.slice(0, 37)}...` : token.label\n const truncatedRoles = roles.length > 27 ? `${roles.slice(0, 27)}...` : roles\n\n table.addRow({\n id: token.id,\n label: truncatedLabel,\n roles: truncatedRoles,\n })\n }\n\n table.
|
|
1
|
+
{"version":3,"sources":["../../../src/commands/tokens/list.ts"],"sourcesContent":["import {Flags} from '@oclif/core'\nimport {exitCodes, SanityCommand, subdebug} from '@sanity/cli-core'\nimport {getErrorMessage} from '@sanity/cli-core/errors'\nimport {Table} from 'console-table-printer'\n\nimport {type Token} from '../../actions/tokens/types.js'\nimport {promptForProject} from '../../prompts/promptForProject.js'\nimport {getTokens} from '../../services/tokens.js'\nimport {getProjectIdFlag} from '../../util/sharedFlags.js'\n\nconst listTokenDebug = subdebug('tokens:list')\n\nexport class TokensListCommand extends SanityCommand<typeof TokensListCommand> {\n static override description = 'List API tokens for the project'\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %>',\n description: 'List tokens for the project',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --json',\n description: 'List tokens in JSON format',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --project-id abc123',\n description: 'List tokens for a specific project',\n },\n ]\n static override flags = {\n ...getProjectIdFlag({\n description: 'Project ID to list tokens for',\n semantics: 'override',\n }),\n json: Flags.boolean({\n default: false,\n description: 'Output tokens in JSON format',\n }),\n }\n\n static override hiddenAliases: string[] = ['token:list']\n\n public async run(): Promise<void> {\n const {flags} = await this.parse(TokensListCommand)\n const {json} = flags\n const outputJson = json ?? false\n\n // Ensure we have project context\n const projectId = await this.getProjectId({\n fallback: () =>\n promptForProject({\n requiredPermissions: [{grant: 'read', permission: 'sanity.project.tokens'}],\n }),\n })\n\n let tokens: Token[]\n try {\n tokens = await getTokens(projectId)\n } catch (error) {\n const message = getErrorMessage(error)\n listTokenDebug(`Error fetching tokens for project ${projectId}`, error)\n this.error(`Token list retrieval failed:\\n${message}`, {exit: exitCodes.RUNTIME_ERROR})\n }\n\n if (outputJson) {\n this.log(JSON.stringify(tokens, null, 2))\n return\n }\n\n if (tokens.length === 0) {\n this.log('No API tokens found for this project.')\n return\n }\n\n const table = new Table({\n columns: [\n {alignment: 'left', maxLen: 40, name: 'label', title: 'Label'},\n {alignment: 'left', maxLen: 20, name: 'id', title: 'Token ID'},\n {alignment: 'left', maxLen: 30, name: 'roles', title: 'Roles'},\n ],\n title: `Found ${tokens.length} API tokens`,\n })\n\n for (const token of tokens) {\n const roles = token.roles?.map((role) => role.title).join(', ') || 'No roles'\n const truncatedLabel =\n token.label.length > 37 ? `${token.label.slice(0, 37)}...` : token.label\n const truncatedRoles = roles.length > 27 ? `${roles.slice(0, 27)}...` : roles\n\n table.addRow({\n id: token.id,\n label: truncatedLabel,\n roles: truncatedRoles,\n })\n }\n\n this.log(table.render())\n }\n}\n"],"names":["Flags","exitCodes","SanityCommand","subdebug","getErrorMessage","Table","promptForProject","getTokens","getProjectIdFlag","listTokenDebug","TokensListCommand","description","examples","command","flags","semantics","json","boolean","default","hiddenAliases","run","parse","outputJson","projectId","getProjectId","fallback","requiredPermissions","grant","permission","tokens","error","message","exit","RUNTIME_ERROR","log","JSON","stringify","length","table","columns","alignment","maxLen","name","title","token","roles","map","role","join","truncatedLabel","label","slice","truncatedRoles","addRow","id","render"],"mappings":"AAAA,SAAQA,KAAK,QAAO,cAAa;AACjC,SAAQC,SAAS,EAAEC,aAAa,EAAEC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d,IAAI,CAACY,GAAG,CAACC,KAAKC,SAAS,CAACP,QAAQ,MAAM;YACtC;QACF;QAEA,IAAIA,OAAOQ,MAAM,KAAK,GAAG;YACvB,IAAI,CAACH,GAAG,CAAC;YACT;QACF;QAEA,MAAMI,QAAQ,IAAIjC,MAAM;YACtBkC,SAAS;gBACP;oBAACC,WAAW;oBAAQC,QAAQ;oBAAIC,MAAM;oBAASC,OAAO;gBAAO;gBAC7D;oBAACH,WAAW;oBAAQC,QAAQ;oBAAIC,MAAM;oBAAMC,OAAO;gBAAU;gBAC7D;oBAACH,WAAW;oBAAQC,QAAQ;oBAAIC,MAAM;oBAASC,OAAO;gBAAO;aAC9D;YACDA,OAAO,CAAC,MAAM,EAAEd,OAAOQ,MAAM,CAAC,WAAW,CAAC;QAC5C;QAEA,KAAK,MAAMO,SAASf,OAAQ;YAC1B,MAAMgB,QAAQD,MAAMC,KAAK,EAAEC,IAAI,CAACC,OAASA,KAAKJ,KAAK,EAAEK,KAAK,SAAS;YACnE,MAAMC,iBACJL,MAAMM,KAAK,CAACb,MAAM,GAAG,KAAK,GAAGO,MAAMM,KAAK,CAACC,KAAK,CAAC,GAAG,IAAI,GAAG,CAAC,GAAGP,MAAMM,KAAK;YAC1E,MAAME,iBAAiBP,MAAMR,MAAM,GAAG,KAAK,GAAGQ,MAAMM,KAAK,CAAC,GAAG,IAAI,GAAG,CAAC,GAAGN;YAExEP,MAAMe,MAAM,CAAC;gBACXC,IAAIV,MAAMU,EAAE;gBACZJ,OAAOD;gBACPJ,OAAOO;YACT;QACF;QAEA,IAAI,CAAClB,GAAG,CAACI,MAAMiB,MAAM;IACvB;AACF"}
|
|
@@ -93,6 +93,10 @@ export class List extends SanityCommand {
|
|
|
93
93
|
includeRobots: robots,
|
|
94
94
|
projectId
|
|
95
95
|
});
|
|
96
|
+
if (members.length === 0) {
|
|
97
|
+
this.log('No members found for this project.');
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
96
100
|
const ordered = sortBy(members.map(({ date, id, name, roles })=>[
|
|
97
101
|
id,
|
|
98
102
|
name,
|
|
@@ -140,7 +144,7 @@ export class List extends SanityCommand {
|
|
|
140
144
|
roles: dimText(roles, isPending)
|
|
141
145
|
});
|
|
142
146
|
}
|
|
143
|
-
table.
|
|
147
|
+
this.log(table.render());
|
|
144
148
|
}
|
|
145
149
|
}
|
|
146
150
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/commands/users/list.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {Flags} from '@oclif/core'\nimport {SanityCommand} from '@sanity/cli-core'\nimport {Table} from 'console-table-printer'\nimport sortBy from 'lodash-es/sortBy.js'\n\nimport {getMembersForProject} from '../../actions/users/getMembersForProject.js'\nimport {promptForProject} from '../../prompts/promptForProject.js'\nimport {getProjectIdFlag} from '../../util/sharedFlags.js'\n\nconst sortFields = ['id', 'name', 'role', 'date']\n\nfunction dimText(value: string, isDim: boolean): string {\n return isDim ? styleText('dim', value) : value\n}\n\nexport class List extends SanityCommand<typeof List> {\n static override description = 'List project members'\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %>',\n description: 'List all users of the project',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --no-invitations --no-robots',\n description: 'List all users of the project, but exclude pending invitations and robots',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --sort role',\n description: 'List all users, sorted by role',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --project-id abc123',\n description: 'List users for a specific project',\n },\n ]\n static override flags = {\n ...getProjectIdFlag({\n description: 'Project ID to list users for',\n semantics: 'override',\n }),\n invitations: Flags.boolean({\n allowNo: true,\n default: true,\n description: 'Includes or excludes pending invitations',\n }),\n order: Flags.string({\n default: 'asc',\n description: 'Sort output ascending/descending',\n options: ['asc', 'desc'],\n }),\n robots: Flags.boolean({\n allowNo: true,\n default: true,\n description: 'Includes or excludes robots (token users)',\n }),\n sort: Flags.string({\n default: 'date',\n description: 'Sort users by specified column',\n options: ['id', 'name', 'role', 'date'],\n }),\n }\n\n static override hiddenAliases: string[] = ['user:list']\n\n public async run(): Promise<void> {\n const {invitations, order, robots, sort} = this.flags\n\n const projectId = await this.getProjectId({\n fallback: () =>\n promptForProject({\n requiredPermissions: [\n {grant: 'read', permission: 'sanity.project'},\n {grant: 'read', permission: 'sanity.project.members'},\n ],\n }),\n })\n\n const members = await getMembersForProject({\n includeInvitations: invitations,\n includeRobots: robots,\n projectId,\n })\n\n const ordered = sortBy(\n members.map(({date, id, name, roles}) => [\n id,\n name,\n roles\n ?.map((role) => role.title)\n .join(', ')\n .trim() || '-',\n date,\n ]),\n [sortFields.indexOf(sort)],\n )\n\n const rows = order === 'asc' ? ordered : ordered.toReversed()\n\n const table = new Table({\n columns: [\n {alignment: 'left', maxLen: 30, name: 'id', title: 'ID'},\n {alignment: 'left', maxLen: 40, name: 'name', title: 'Name'},\n {alignment: 'left', maxLen: 30, name: 'roles', title: 'Roles'},\n {alignment: 'left', maxLen: 12, name: 'date', title: 'Date'},\n ],\n rowSeparator: true,\n })\n\n for (const [id, name, roles, date] of rows) {\n const isPending = id === '<pending>'\n table.addRow({\n date: dimText(date, isPending),\n id: dimText(id, isPending),\n name: dimText(name, isPending),\n roles: dimText(roles, isPending),\n })\n }\n\n table.
|
|
1
|
+
{"version":3,"sources":["../../../src/commands/users/list.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {Flags} from '@oclif/core'\nimport {SanityCommand} from '@sanity/cli-core'\nimport {Table} from 'console-table-printer'\nimport sortBy from 'lodash-es/sortBy.js'\n\nimport {getMembersForProject} from '../../actions/users/getMembersForProject.js'\nimport {promptForProject} from '../../prompts/promptForProject.js'\nimport {getProjectIdFlag} from '../../util/sharedFlags.js'\n\nconst sortFields = ['id', 'name', 'role', 'date']\n\nfunction dimText(value: string, isDim: boolean): string {\n return isDim ? styleText('dim', value) : value\n}\n\nexport class List extends SanityCommand<typeof List> {\n static override description = 'List project members'\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %>',\n description: 'List all users of the project',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --no-invitations --no-robots',\n description: 'List all users of the project, but exclude pending invitations and robots',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --sort role',\n description: 'List all users, sorted by role',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --project-id abc123',\n description: 'List users for a specific project',\n },\n ]\n static override flags = {\n ...getProjectIdFlag({\n description: 'Project ID to list users for',\n semantics: 'override',\n }),\n invitations: Flags.boolean({\n allowNo: true,\n default: true,\n description: 'Includes or excludes pending invitations',\n }),\n order: Flags.string({\n default: 'asc',\n description: 'Sort output ascending/descending',\n options: ['asc', 'desc'],\n }),\n robots: Flags.boolean({\n allowNo: true,\n default: true,\n description: 'Includes or excludes robots (token users)',\n }),\n sort: Flags.string({\n default: 'date',\n description: 'Sort users by specified column',\n options: ['id', 'name', 'role', 'date'],\n }),\n }\n\n static override hiddenAliases: string[] = ['user:list']\n\n public async run(): Promise<void> {\n const {invitations, order, robots, sort} = this.flags\n\n const projectId = await this.getProjectId({\n fallback: () =>\n promptForProject({\n requiredPermissions: [\n {grant: 'read', permission: 'sanity.project'},\n {grant: 'read', permission: 'sanity.project.members'},\n ],\n }),\n })\n\n const members = await getMembersForProject({\n includeInvitations: invitations,\n includeRobots: robots,\n projectId,\n })\n\n if (members.length === 0) {\n this.log('No members found for this project.')\n return\n }\n\n const ordered = sortBy(\n members.map(({date, id, name, roles}) => [\n id,\n name,\n roles\n ?.map((role) => role.title)\n .join(', ')\n .trim() || '-',\n date,\n ]),\n [sortFields.indexOf(sort)],\n )\n\n const rows = order === 'asc' ? ordered : ordered.toReversed()\n\n const table = new Table({\n columns: [\n {alignment: 'left', maxLen: 30, name: 'id', title: 'ID'},\n {alignment: 'left', maxLen: 40, name: 'name', title: 'Name'},\n {alignment: 'left', maxLen: 30, name: 'roles', title: 'Roles'},\n {alignment: 'left', maxLen: 12, name: 'date', title: 'Date'},\n ],\n rowSeparator: true,\n })\n\n for (const [id, name, roles, date] of rows) {\n const isPending = id === '<pending>'\n table.addRow({\n date: dimText(date, isPending),\n id: dimText(id, isPending),\n name: dimText(name, isPending),\n roles: dimText(roles, isPending),\n })\n }\n\n this.log(table.render())\n }\n}\n"],"names":["styleText","Flags","SanityCommand","Table","sortBy","getMembersForProject","promptForProject","getProjectIdFlag","sortFields","dimText","value","isDim","List","description","examples","command","flags","semantics","invitations","boolean","allowNo","default","order","string","options","robots","sort","hiddenAliases","run","projectId","getProjectId","fallback","requiredPermissions","grant","permission","members","includeInvitations","includeRobots","length","log","ordered","map","date","id","name","roles","role","title","join","trim","indexOf","rows","toReversed","table","columns","alignment","maxLen","rowSeparator","isPending","addRow","render"],"mappings":"AAAA,SAAQA,SAAS,QAAO,YAAW;AAEnC,SAAQC,KAAK,QAAO,cAAa;AACjC,SAAQC,aAAa,QAAO,mBAAkB;AAC9C,SAAQC,KAAK,QAAO,wBAAuB;AAC3C,OAAOC,YAAY,sBAAqB;AAExC,SAAQC,oBAAoB,QAAO,8CAA6C;AAChF,SAAQC,gBAAgB,QAAO,oCAAmC;AAClE,SAAQC,gBAAgB,QAAO,4BAA2B;AAE1D,MAAMC,aAAa;IAAC;IAAM;IAAQ;IAAQ;CAAO;AAEjD,SAASC,QAAQC,KAAa,EAAEC,KAAc;IAC5C,OAAOA,QAAQX,UAAU,OAAOU,SAASA;AAC3C;AAEA,OAAO,MAAME,aAAaV;IACxB,OAAgBW,cAAc,uBAAsB;IACpD,OAAgBC,WAAW;QACzB;YACEC,SAAS;YACTF,aAAa;QACf;QACA;YACEE,SAAS;YACTF,aAAa;QACf;QACA;YACEE,SAAS;YACTF,aAAa;QACf;QACA;YACEE,SAAS;YACTF,aAAa;QACf;KACD,CAAA;IACD,OAAgBG,QAAQ;QACtB,GAAGT,iBAAiB;YAClBM,aAAa;YACbI,WAAW;QACb,EAAE;QACFC,aAAajB,MAAMkB,OAAO,CAAC;YACzBC,SAAS;YACTC,SAAS;YACTR,aAAa;QACf;QACAS,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oBAAMG,OAAO;gBAAI;gBACvD;oBAACQ,WAAW;oBAAQC,QAAQ;oBAAIZ,MAAM;oBAAQG,OAAO;gBAAM;gBAC3D;oBAACQ,WAAW;oBAAQC,QAAQ;oBAAIZ,MAAM;oBAASG,OAAO;gBAAO;gBAC7D;oBAACQ,WAAW;oBAAQC,QAAQ;oBAAIZ,MAAM;oBAAQG,OAAO;gBAAM;aAC5D;YACDU,cAAc;QAChB;QAEA,KAAK,MAAM,CAACd,IAAIC,MAAMC,OAAOH,KAAK,IAAIS,KAAM;YAC1C,MAAMO,YAAYf,OAAO;YACzBU,MAAMM,MAAM,CAAC;gBACXjB,MAAMjC,QAAQiC,MAAMgB;gBACpBf,IAAIlC,QAAQkC,IAAIe;gBAChBd,MAAMnC,QAAQmC,MAAMc;gBACpBb,OAAOpC,QAAQoC,OAAOa;YACxB;QACF;QAEA,IAAI,CAACnB,GAAG,CAACc,MAAMO,MAAM;IACvB;AACF"}
|
|
@@ -127,6 +127,8 @@ import { allow, conditionalDenyFlags, conditionalPolicy, deny } from './policy.j
|
|
|
127
127
|
'migrations:list': deny,
|
|
128
128
|
// Executes local migration code that may perform arbitrary document mutations.
|
|
129
129
|
'migrations:run': deny,
|
|
130
|
+
// Writes project setup values and scaffolds local applications.
|
|
131
|
+
new: deny,
|
|
130
132
|
// --web opens a browser on the machine running the MCP server.
|
|
131
133
|
'openapi:get': conditionalDenyFlags('web'),
|
|
132
134
|
'openapi:list': conditionalDenyFlags('web'),
|
|
@@ -139,6 +141,8 @@ import { allow, conditionalDenyFlags, conditionalPolicy, deny } from './policy.j
|
|
|
139
141
|
preview: deny,
|
|
140
142
|
'projects:create': allow,
|
|
141
143
|
'projects:list': allow,
|
|
144
|
+
// Reads locally stored claim URLs and robot tokens.
|
|
145
|
+
'projects:unclaimed': deny,
|
|
142
146
|
// Loads the local Studio configuration to resolve the datasets containing each schema.
|
|
143
147
|
'schemas:delete': deny,
|
|
144
148
|
// Loads local schema files before deploying them.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/exports/invokeSanityCli/commandPolicies/mcpPolicy.ts"],"sourcesContent":["import {\n allow,\n type CommandPolicySet,\n conditionalDenyFlags,\n conditionalPolicy,\n deny,\n} from './policy.js'\n\n/**\n * A typed `-F/--field` value of `@<file>` or `@-` makes the `api` command\n * read the host's filesystem or stdin (raw `-f` fields are always verbatim).\n */\nfunction fieldReadsFromHost(field: unknown): boolean {\n if (typeof field !== 'string') return false\n const separatorIndex = field.indexOf('=')\n return separatorIndex > 0 && field[separatorIndex + 1] === '@'\n}\n\n/** A `-H/--header` value that replaces the invocation's authentication. */\nfunction headerOverridesAuthentication(header: unknown): boolean {\n if (typeof header !== 'string') return false\n const separatorIndex = header.indexOf(':')\n return (\n separatorIndex > 0 && header.slice(0, separatorIndex).trim().toLowerCase() === 'authorization'\n )\n}\n\n/**\n * MCP programmatic mode disables local project/config discovery (see the CLI\n * execution context). Missing project or dataset values may therefore produce\n * a usage error, but cannot cause local filesystem access. Destructive remote\n * operations are allowed and do not by themselves make a command unsafe.\n *\n * Every manifest command must have exactly one policy here:\n * - allow: every valid invocation is safe\n * - conditional: safety depends on parsed arguments or flags\n * - deny: no invocation is safe\n */\nexport const mcpPolicy: CommandPolicySet = {\n // Special exception, this can be very dangerous but is also super useful\n // to expose. Refuse authentication overrides and host input channels:\n // `--token` and an Authorization header replace the MCP user's token,\n // `--input` reads the request body from the host's filesystem or stdin, and\n // `-F key=@<file>` / `-F key=@-` field values do the same.\n api: conditionalPolicy({\n deniedFlags: ['input', 'token'],\n validate: ({flags}) =>\n (!Array.isArray(flags.field) || !flags.field.some((field) => fieldReadsFromHost(field))) &&\n (!Array.isArray(flags.header) ||\n !flags.header.some((header) => headerOverridesAuthentication(header))),\n }),\n\n 'backups:disable': allow,\n // Writes a downloaded backup to the local filesystem.\n 'backups:download': deny,\n 'backups:enable': allow,\n 'backups:list': allow,\n\n // Requires a local Studio project and writes build output to disk.\n build: deny,\n\n // Reads and rewrites local source code.\n codemod: deny,\n\n 'cors:add': allow,\n 'cors:delete': allow,\n 'cors:list': allow,\n\n 'datasets:alias:create': allow,\n 'datasets:alias:delete': allow,\n 'datasets:alias:link': allow,\n 'datasets:alias:unlink': allow,\n 'datasets:copy': allow,\n 'datasets:create': allow,\n 'datasets:delete': allow,\n 'datasets:embeddings:disable': allow,\n 'datasets:embeddings:enable': allow,\n 'datasets:embeddings:status': allow,\n // Writes dataset contents and assets to the local filesystem.\n 'datasets:export': deny,\n // Reads import data from the local filesystem and may replace documents.\n 'datasets:import': deny,\n 'datasets:list': allow,\n 'datasets:visibility:get': allow,\n 'datasets:visibility:set': allow,\n\n // Inspects local project files and can print authentication secrets.\n debug: deny,\n\n // Reads, builds, and deploys a local Studio project.\n deploy: deny,\n\n // Loads a local Studio project and starts a development server.\n dev: deny,\n\n // Opens a browser on the machine running the MCP server.\n 'docs:browse': deny,\n // --web opens a browser on the machine running the MCP server.\n 'docs:read': conditionalDenyFlags('web'),\n 'docs:search': allow,\n\n // Reads and executes local project configuration for diagnostics.\n doctor: deny,\n\n // Reads document input from disk or launches a local editor.\n 'documents:create': deny,\n 'documents:delete': allow,\n 'documents:get': allow,\n 'documents:query': allow,\n // Loads a local Studio schema to validate documents.\n 'documents:validate': deny,\n\n // Executes arbitrary code in the local Studio context.\n exec: deny,\n\n // Loads a local schema and deploys a GraphQL API.\n 'graphql:deploy': deny,\n 'graphql:list': allow,\n // --api loads GraphQL definitions from the local project; explicit project/dataset flags are safe.\n 'graphql:undeploy': conditionalDenyFlags('api'),\n\n 'hooks:attempt': allow,\n 'hooks:create': allow,\n 'hooks:delete': allow,\n 'hooks:list': allow,\n 'hooks:logs': allow,\n\n // Creates or modifies a local project and may install dependencies.\n init: deny,\n\n // Installs packages into the local project.\n install: deny,\n\n // Opens a browser on the machine running the MCP server.\n learn: deny,\n\n // Performs an authentication flow.\n login: deny,\n\n // Performs an authentication operation and clears local credentials.\n logout: deny,\n\n // Reads local project configuration and opens a browser.\n manage: deny,\n\n // Loads local Studio configuration and writes manifest files.\n 'manifest:extract': deny,\n\n // Reads and writes local MCP client configuration.\n 'mcp:configure': deny,\n\n // Writes an aspect definition to the local filesystem.\n 'media:create-aspect': deny,\n 'media:delete-aspect': allow,\n // Reads a local aspect definition before deploying it.\n 'media:deploy-aspect': deny,\n // Writes media assets to the local filesystem.\n 'media:export': deny,\n // Reads media assets from the local filesystem.\n 'media:import': deny,\n\n // Creates migration source files in the local project.\n 'migrations:create': deny,\n // Reads and loads migration definitions from the local project.\n 'migrations:list': deny,\n // Executes local migration code that may perform arbitrary document mutations.\n 'migrations:run': deny,\n\n // --web opens a browser on the machine running the MCP server.\n 'openapi:get': conditionalDenyFlags('web'),\n 'openapi:list': conditionalDenyFlags('web'),\n\n 'organizations:create': allow,\n 'organizations:delete': allow,\n 'organizations:get': allow,\n 'organizations:list': allow,\n 'organizations:update': allow,\n\n // Serves a local production build.\n preview: deny,\n\n 'projects:create': allow,\n 'projects:list': allow,\n\n // Loads the local Studio configuration to resolve the datasets containing each schema.\n 'schemas:delete': deny,\n // Loads local schema files before deploying them.\n 'schemas:deploy': deny,\n // Loads local Studio configuration and writes an extracted schema to disk.\n 'schemas:extract': deny,\n // Requires a local project and loads its schema configuration.\n 'schemas:list': deny,\n // Loads and executes a local Studio schema.\n 'schemas:validate': deny,\n\n // Installs skills into local editor configuration directories.\n 'skills:install': deny,\n\n // Changes account telemetry preferences and mutates local cached configuration.\n 'telemetry:disable': deny,\n // Changes account telemetry preferences and mutates local cached configuration.\n 'telemetry:enable': deny,\n 'telemetry:status': allow,\n\n // Creates authentication credentials.\n 'tokens:create': deny,\n // Deletes authentication credentials.\n 'tokens:delete': deny,\n // Exposes authentication credential metadata.\n 'tokens:list': deny,\n\n // Loads local CLI and workbench configuration to identify the deployed Studio or application.\n undeploy: deny,\n\n // Grants a user access to a project.\n 'users:invite': deny,\n 'users:list': allow,\n\n // Reads the local project and installed package tree.\n versions: deny,\n}\n"],"names":["allow","conditionalDenyFlags","conditionalPolicy","deny","fieldReadsFromHost","field","separatorIndex","indexOf","headerOverridesAuthentication","header","slice","trim","toLowerCase","mcpPolicy","api","deniedFlags","validate","flags","Array","isArray","some","build","codemod","debug","deploy","dev","doctor","exec","init","install","learn","login","logout","manage","preview","undeploy","versions"],"mappings":"AAAA,SACEA,KAAK,EAELC,oBAAoB,EACpBC,iBAAiB,EACjBC,IAAI,QACC,cAAa;AAEpB;;;CAGC,GACD,SAASC,mBAAmBC,KAAc;IACxC,IAAI,OAAOA,UAAU,UAAU,OAAO;IACtC,MAAMC,iBAAiBD,MAAME,OAAO,CAAC;IACrC,OAAOD,iBAAiB,KAAKD,KAAK,CAACC,iBAAiB,EAAE,KAAK;AAC7D;AAEA,yEAAyE,GACzE,SAASE,8BAA8BC,MAAe;IACpD,IAAI,OAAOA,WAAW,UAAU,OAAO;IACvC,MAAMH,iBAAiBG,OAAOF,OAAO,CAAC;IACtC,OACED,iBAAiB,KAAKG,OAAOC,KAAK,CAAC,GAAGJ,gBAAgBK,IAAI,GAAGC,WAAW,OAAO;AAEnF;AAEA;;;;;;;;;;CAUC,GACD,OAAO,MAAMC,YAA8B;IACzC,yEAAyE;IACzE,sEAAsE;IACtE,sEAAsE;IACtE,4EAA4E;IAC5E,2DAA2D;IAC3DC,KAAKZ,kBAAkB;QACrBa,aAAa;YAAC;YAAS;SAAQ;QAC/BC,UAAU,CAAC,EAACC,KAAK,EAAC,GAChB,AAAC,CAAA,CAACC,MAAMC,OAAO,CAACF,MAAMZ,KAAK,KAAK,CAACY,MAAMZ,KAAK,CAACe,IAAI,CAAC,CAACf,QAAUD,mBAAmBC,OAAM,KACrF,CAAA,CAACa,MAAMC,OAAO,CAACF,MAAMR,MAAM,KAC1B,CAACQ,MAAMR,MAAM,CAACW,IAAI,CAAC,CAACX,SAAWD,8BAA8BC,QAAO;IAC1E;IAEA,mBAAmBT;IACnB,sDAAsD;IACtD,oBAAoBG;IACpB,kBAAkBH;IAClB,gBAAgBA;IAE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AAgD;IAChD,gBAAgBA;IAEhB,uDAAuD;IACvD,qBAAqBA;IACrB,gEAAgE;IAChE,mBAAmBA;IACnB,+EAA+E;IAC/E,kBAAkBA;IAElB,+DAA+D;IAC/D,eAAeF,qBAAqB;IACpC,gBAAgBA,qBAAqB;IAErC,wBAAwBD;IACxB,wBAAwBA;IACxB,qBAAqBA;IACrB,sBAAsBA;IACtB,wBAAwBA;IAExB,mCAAmC;IACnCkC,SAAS/B;IAET,mBAAmBH;IACnB,iBAAiBA;IAEjB,uFAAuF;IACvF,kBAAkBG;IAClB,kDAAkD;IAClD,kBAAkBA;IAClB,2EAA2E;IAC3E,mBAAmBA;IACnB,+DAA+D;IAC/D,gBAAgBA;IAChB,4CAA4C;IAC5C,oBAAoBA;IAEpB,+DAA+D;IAC/D,kBAAkBA;IAElB,gFAAgF;IAChF,qBAAqBA;IACrB,gFAAgF;IAChF,oBAAoBA;IACpB,oBAAoBH;IAEpB,sCAAsC;IACtC,iBAAiBG;IACjB,sCAAsC;IACtC,iBAAiBA;IACjB,8CAA8C;IAC9C,eAAeA;IAEf,8FAA8F;IAC9FgC,UAAUhC;IAEV,qCAAqC;IACrC,gBAAgBA;IAChB,cAAcH;IAEd,sDAAsD;IACtDoC,UAAUjC;AACZ,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../../src/exports/invokeSanityCli/commandPolicies/mcpPolicy.ts"],"sourcesContent":["import {\n allow,\n type CommandPolicySet,\n conditionalDenyFlags,\n conditionalPolicy,\n deny,\n} from './policy.js'\n\n/**\n * A typed `-F/--field` value of `@<file>` or `@-` makes the `api` command\n * read the host's filesystem or stdin (raw `-f` fields are always verbatim).\n */\nfunction fieldReadsFromHost(field: unknown): boolean {\n if (typeof field !== 'string') return false\n const separatorIndex = field.indexOf('=')\n return separatorIndex > 0 && field[separatorIndex + 1] === '@'\n}\n\n/** A `-H/--header` value that replaces the invocation's authentication. */\nfunction headerOverridesAuthentication(header: unknown): boolean {\n if (typeof header !== 'string') return false\n const separatorIndex = header.indexOf(':')\n return (\n separatorIndex > 0 && header.slice(0, separatorIndex).trim().toLowerCase() === 'authorization'\n )\n}\n\n/**\n * MCP programmatic mode disables local project/config discovery (see the CLI\n * execution context). Missing project or dataset values may therefore produce\n * a usage error, but cannot cause local filesystem access. Destructive remote\n * operations are allowed and do not by themselves make a command unsafe.\n *\n * Every manifest command must have exactly one policy here:\n * - allow: every valid invocation is safe\n * - conditional: safety depends on parsed arguments or flags\n * - deny: no invocation is safe\n */\nexport const mcpPolicy: CommandPolicySet = {\n // Special exception, this can be very dangerous but is also super useful\n // to expose. Refuse authentication overrides and host input channels:\n // `--token` and an Authorization header replace the MCP user's token,\n // `--input` reads the request body from the host's filesystem or stdin, and\n // `-F key=@<file>` / `-F key=@-` field values do the same.\n api: conditionalPolicy({\n deniedFlags: ['input', 'token'],\n validate: ({flags}) =>\n (!Array.isArray(flags.field) || !flags.field.some((field) => fieldReadsFromHost(field))) &&\n (!Array.isArray(flags.header) ||\n !flags.header.some((header) => headerOverridesAuthentication(header))),\n }),\n\n 'backups:disable': allow,\n // Writes a downloaded backup to the local filesystem.\n 'backups:download': deny,\n 'backups:enable': allow,\n 'backups:list': allow,\n\n // Requires a local Studio project and writes build output to disk.\n build: deny,\n\n // Reads and rewrites local source code.\n codemod: deny,\n\n 'cors:add': allow,\n 'cors:delete': allow,\n 'cors:list': allow,\n\n 'datasets:alias:create': allow,\n 'datasets:alias:delete': allow,\n 'datasets:alias:link': allow,\n 'datasets:alias:unlink': allow,\n 'datasets:copy': allow,\n 'datasets:create': allow,\n 'datasets:delete': allow,\n 'datasets:embeddings:disable': allow,\n 'datasets:embeddings:enable': allow,\n 'datasets:embeddings:status': allow,\n // Writes dataset contents and assets to the local filesystem.\n 'datasets:export': deny,\n // Reads import data from the local filesystem and may replace documents.\n 'datasets:import': deny,\n 'datasets:list': allow,\n 'datasets:visibility:get': allow,\n 'datasets:visibility:set': allow,\n\n // Inspects local project files and can print authentication secrets.\n debug: deny,\n\n // Reads, builds, and deploys a local Studio project.\n deploy: deny,\n\n // Loads a local Studio project and starts a development server.\n dev: deny,\n\n // Opens a browser on the machine running the MCP server.\n 'docs:browse': deny,\n // --web opens a browser on the machine running the MCP server.\n 'docs:read': conditionalDenyFlags('web'),\n 'docs:search': allow,\n\n // Reads and executes local project configuration for diagnostics.\n doctor: deny,\n\n // Reads document input from disk or launches a local editor.\n 'documents:create': deny,\n 'documents:delete': allow,\n 'documents:get': allow,\n 'documents:query': allow,\n // Loads a local Studio schema to validate documents.\n 'documents:validate': deny,\n\n // Executes arbitrary code in the local Studio context.\n exec: deny,\n\n // Loads a local schema and deploys a GraphQL API.\n 'graphql:deploy': deny,\n 'graphql:list': allow,\n // --api loads GraphQL definitions from the local project; explicit project/dataset flags are safe.\n 'graphql:undeploy': conditionalDenyFlags('api'),\n\n 'hooks:attempt': allow,\n 'hooks:create': allow,\n 'hooks:delete': allow,\n 'hooks:list': allow,\n 'hooks:logs': allow,\n\n // Creates or modifies a local project and may install dependencies.\n init: deny,\n\n // Installs packages into the local project.\n install: deny,\n\n // Opens a browser on the machine running the MCP server.\n learn: deny,\n\n // Performs an authentication flow.\n login: deny,\n\n // Performs an authentication operation and clears local credentials.\n logout: deny,\n\n // Reads local project configuration and opens a browser.\n manage: deny,\n\n // Loads local Studio configuration and writes manifest files.\n 'manifest:extract': deny,\n\n // Reads and writes local MCP client configuration.\n 'mcp:configure': deny,\n\n // Writes an aspect definition to the local filesystem.\n 'media:create-aspect': deny,\n 'media:delete-aspect': allow,\n // Reads a local aspect definition before deploying it.\n 'media:deploy-aspect': deny,\n // Writes media assets to the local filesystem.\n 'media:export': deny,\n // Reads media assets from the local filesystem.\n 'media:import': deny,\n\n // Creates migration source files in the local project.\n 'migrations:create': deny,\n // Reads and loads migration definitions from the local project.\n 'migrations:list': deny,\n // Executes local migration code that may perform arbitrary document mutations.\n 'migrations:run': deny,\n\n // Writes project setup values and scaffolds local applications.\n new: deny,\n\n // --web opens a browser on the machine running the MCP server.\n 'openapi:get': conditionalDenyFlags('web'),\n 'openapi:list': conditionalDenyFlags('web'),\n\n 'organizations:create': allow,\n 'organizations:delete': allow,\n 'organizations:get': allow,\n 'organizations:list': allow,\n 'organizations:update': allow,\n\n // Serves a local production build.\n preview: deny,\n\n 'projects:create': allow,\n 'projects:list': allow,\n // Reads locally stored claim URLs and robot tokens.\n 'projects:unclaimed': deny,\n\n // Loads the local Studio configuration to resolve the datasets containing each schema.\n 'schemas:delete': deny,\n // Loads local schema files before deploying them.\n 'schemas:deploy': deny,\n // Loads local Studio configuration and writes an extracted schema to disk.\n 'schemas:extract': deny,\n // Requires a local project and loads its schema configuration.\n 'schemas:list': deny,\n // Loads and executes a local Studio schema.\n 'schemas:validate': deny,\n\n // Installs skills into local editor configuration directories.\n 'skills:install': deny,\n\n // Changes account telemetry preferences and mutates local cached configuration.\n 'telemetry:disable': deny,\n // Changes account telemetry preferences and mutates local cached configuration.\n 'telemetry:enable': deny,\n 'telemetry:status': allow,\n\n // Creates authentication credentials.\n 'tokens:create': deny,\n // Deletes authentication credentials.\n 'tokens:delete': deny,\n // Exposes authentication credential metadata.\n 'tokens:list': deny,\n\n // Loads local CLI and workbench configuration to identify the deployed Studio or application.\n undeploy: deny,\n\n // Grants a user access to a project.\n 'users:invite': deny,\n 'users:list': allow,\n\n // Reads the local project and installed package tree.\n versions: deny,\n}\n"],"names":["allow","conditionalDenyFlags","conditionalPolicy","deny","fieldReadsFromHost","field","separatorIndex","indexOf","headerOverridesAuthentication","header","slice","trim","toLowerCase","mcpPolicy","api","deniedFlags","validate","flags","Array","isArray","some","build","codemod","debug","deploy","dev","doctor","exec","init","install","learn","login","logout","manage","new","preview","undeploy","versions"],"mappings":"AAAA,SACEA,KAAK,EAELC,oBAAoB,EACpBC,iBAAiB,EACjBC,IAAI,QACC,cAAa;AAEpB;;;CAGC,GACD,SAASC,mBAAmBC,KAAc;IACxC,IAAI,OAAOA,UAAU,UAAU,OAAO;IACtC,MAAMC,iBAAiBD,MAA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AsBG;IAEtB,uFAAuF;IACvF,kBAAkBA;IAClB,kDAAkD;IAClD,kBAAkBA;IAClB,2EAA2E;IAC3E,mBAAmBA;IACnB,+DAA+D;IAC/D,gBAAgBA;IAChB,4CAA4C;IAC5C,oBAAoBA;IAEpB,+DAA+D;IAC/D,kBAAkBA;IAElB,gFAAgF;IAChF,qBAAqBA;IACrB,gFAAgF;IAChF,oBAAoBA;IACpB,oBAAoBH;IAEpB,sCAAsC;IACtC,iBAAiBG;IACjB,sCAAsC;IACtC,iBAAiBA;IACjB,8CAA8C;IAC9C,eAAeA;IAEf,8FAA8F;IAC9FiC,UAAUjC;IAEV,qCAAqC;IACrC,gBAAgBA;IAChB,cAAcH;IAEd,sDAAsD;IACtDqC,UAAUlC;AACZ,EAAC"}
|
|
@@ -13,13 +13,9 @@ declare type InvocationSource = "mcp";
|
|
|
13
13
|
*
|
|
14
14
|
* @internal
|
|
15
15
|
*/
|
|
16
|
-
export declare function invokeSanityCli(
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
sanityEnv,
|
|
20
|
-
source,
|
|
21
|
-
token,
|
|
22
|
-
}: InvokeSanityCliOptions): Promise<InvokeSanityCliResult>;
|
|
16
|
+
export declare function invokeSanityCli(
|
|
17
|
+
options: InvokeSanityCliOptions,
|
|
18
|
+
): Promise<InvokeSanityCliResult>;
|
|
23
19
|
|
|
24
20
|
/**
|
|
25
21
|
* @internal
|
|
@@ -49,8 +45,8 @@ export declare interface InvokeSanityCliOptions {
|
|
|
49
45
|
config?: Config;
|
|
50
46
|
/**
|
|
51
47
|
* Sanity deployment environment for this invocation. Scoped to this call
|
|
52
|
-
* via the CLI execution context and defaults to
|
|
53
|
-
*
|
|
48
|
+
* via the CLI execution context and defaults to production. The embedding
|
|
49
|
+
* process's `SANITY_INTERNAL_ENV` is never consulted.
|
|
54
50
|
*/
|
|
55
51
|
sanityEnv?: SanityEnvironment;
|
|
56
52
|
}
|
|
@@ -19,22 +19,44 @@
|
|
|
19
19
|
* Help works like the regular CLI, scoped to the source's policy: `--help`
|
|
20
20
|
* (or `help`) renders root help listing the invokable topics, and a subject
|
|
21
21
|
* (`cors --help`, `cors list --help`) renders topic or command help.
|
|
22
|
-
*/ import { Config, Parser } from '@oclif/core';
|
|
22
|
+
*/ import { Config, Parser, settings } from '@oclif/core';
|
|
23
23
|
import { getHelpFlagAdditions, normalizeArgv } from '@oclif/core/help';
|
|
24
|
-
import {
|
|
24
|
+
import { exitCodes } from '@sanity/cli-core';
|
|
25
25
|
import { runWithCliExecutionContext } from '@sanity/cli-core/executionContext';
|
|
26
26
|
import { parseArgsStringToArgv } from 'string-argv';
|
|
27
27
|
import { commandPolicies } from './commandPolicies/index.js';
|
|
28
28
|
import { deny, isConditionalInvocationPolicy } from './commandPolicies/policy.js';
|
|
29
29
|
import { isHelpRequest, renderInvokableHelp } from './help.js';
|
|
30
30
|
import { prettyPrintError } from './prettyPrintError.js';
|
|
31
|
+
/**
|
|
32
|
+
* Instantiate a policy-approved command for isolated execution.
|
|
33
|
+
*
|
|
34
|
+
* Every invokable command extends `SanityCommand`, whose
|
|
35
|
+
* `runInExecutionContext()` runs the instance without oclif's static
|
|
36
|
+
* `Command.run()` — the static runner re-enters `Config.load()` (filesystem
|
|
37
|
+
* reads and a process-global config cache write) on every call. The manifest
|
|
38
|
+
* types command classes as the abstract oclif `Command`, hence the
|
|
39
|
+
* constructor cast. The method is probed rather than checked with
|
|
40
|
+
* `instanceof`, because command modules may load from the compiled build
|
|
41
|
+
* while this module runs from source, giving `SanityCommand` two identities.
|
|
42
|
+
*/ function instantiateCommand(CommandClass, argv, config) {
|
|
43
|
+
const ConcreteCommand = CommandClass;
|
|
44
|
+
const command = new ConcreteCommand(argv, config);
|
|
45
|
+
if (typeof command.runInExecutionContext !== 'function') {
|
|
46
|
+
throw new TypeError(`Command "${CommandClass.id}" does not support isolated execution`);
|
|
47
|
+
}
|
|
48
|
+
return command;
|
|
49
|
+
}
|
|
31
50
|
/**
|
|
32
51
|
* Load the oclif `Config` for this package, needed to resolve, load, and run
|
|
33
52
|
* commands. Loading it once and reusing it across invocations avoids
|
|
34
|
-
* re-reading the command manifest per call.
|
|
53
|
+
* re-reading the command manifest per call. It only reads this package's own
|
|
54
|
+
* installed files — process-lifetime initialization, not per-invocation host
|
|
55
|
+
* state — so it happens outside any execution context.
|
|
35
56
|
*/ function loadCliCommandConfig() {
|
|
36
57
|
return Config.load(import.meta.url);
|
|
37
58
|
}
|
|
59
|
+
let cachedConfig;
|
|
38
60
|
function unknownCommandResult(argv, policySet) {
|
|
39
61
|
const available = Object.entries(policySet).filter(([, policy])=>policy.kind !== 'deny').map(([id])=>id.replaceAll(':', ' ')).toSorted();
|
|
40
62
|
return {
|
|
@@ -45,7 +67,6 @@ function unknownCommandResult(argv, policySet) {
|
|
|
45
67
|
].join('\n')
|
|
46
68
|
};
|
|
47
69
|
}
|
|
48
|
-
let cachedConfig;
|
|
49
70
|
/**
|
|
50
71
|
* Unlike a shell, string-argv keeps quotes that are glued to unquoted text:
|
|
51
72
|
* `--name="my project"` tokenizes with the quotes intact. Strip a matching
|
|
@@ -63,15 +84,27 @@ let cachedConfig;
|
|
|
63
84
|
* relay them verbatim.
|
|
64
85
|
*
|
|
65
86
|
* @internal
|
|
66
|
-
*/ export async function invokeSanityCli(
|
|
67
|
-
|
|
87
|
+
*/ export async function invokeSanityCli(options) {
|
|
88
|
+
// Always load compiled command modules. Oclif's dev-mode source resolution
|
|
89
|
+
// otherwise probes tsconfigs (reading the filesystem and process.cwd) on
|
|
90
|
+
// every command load, and may register ts-node process-wide.
|
|
91
|
+
settings.enableAutoTranspile = false;
|
|
92
|
+
const resolvedConfig = options.config ?? await (cachedConfig ??= loadCliCommandConfig());
|
|
93
|
+
const output = [];
|
|
94
|
+
const sink = (line)=>output.push(line);
|
|
95
|
+
const { sanityEnv, token } = options;
|
|
96
|
+
// Establish the isolation boundary before rendering help, loading command
|
|
97
|
+
// modules, parsing, or executing. Any code reached by an external
|
|
98
|
+
// invocation can therefore fail closed on context.
|
|
99
|
+
return runWithCliExecutionContext({
|
|
100
|
+
sanityEnv,
|
|
101
|
+
stderr: sink,
|
|
102
|
+
stdout: sink,
|
|
103
|
+
token
|
|
104
|
+
}, ()=>invokeSanityCliInContext(options, resolvedConfig, output));
|
|
105
|
+
}
|
|
106
|
+
async function invokeSanityCliInContext({ args, source }, resolvedConfig, output) {
|
|
68
107
|
const policySet = commandPolicies[source];
|
|
69
|
-
// Commands log through the global telemetry store; default it to a noop
|
|
70
|
-
// store so embedding hosts need no telemetry wiring (and see no warnings),
|
|
71
|
-
// without clobbering a store the host may have installed itself.
|
|
72
|
-
if (!globalThis[CLI_TELEMETRY_SYMBOL]) {
|
|
73
|
-
setCliTelemetry(noopLogger);
|
|
74
|
-
}
|
|
75
108
|
// Pre-split argv arrays are taken verbatim; only string input goes through
|
|
76
109
|
// shell-style tokenization and quote normalization.
|
|
77
110
|
let argv = typeof args === 'string' ? parseArgsStringToArgv(args).map((t)=>stripFlagQuotes(t)) : [
|
|
@@ -149,15 +182,9 @@ let cachedConfig;
|
|
|
149
182
|
output
|
|
150
183
|
};
|
|
151
184
|
}
|
|
152
|
-
const output = [];
|
|
153
|
-
const sink = (line)=>output.push(line);
|
|
154
185
|
try {
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
stderr: sink,
|
|
158
|
-
stdout: sink,
|
|
159
|
-
token
|
|
160
|
-
}, ()=>CommandClass.run(commandArgv, resolvedConfig));
|
|
186
|
+
const command = instantiateCommand(CommandClass, commandArgv, resolvedConfig);
|
|
187
|
+
await command.runInExecutionContext();
|
|
161
188
|
return {
|
|
162
189
|
commandId,
|
|
163
190
|
exitCode: exitCodes.SUCCESS,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/exports/invokeSanityCli/index.ts"],"sourcesContent":["/**\n * Programmatic (in-process) invocation of CLI commands, e.g. from an MCP\n * server. The invokable surface is governed by a per-source command policy\n * (see ./commandPolicies): every CLI command is explicitly allowed, denied,\n * or allowed conditionally on the parsed invocation.\n *\n * {@link invokeSanityCli} handles arg parsing, policy enforcement, command\n * dispatch, per-invocation auth, and output capture.\n * ```ts\n * import {invokeSanityCli} from '@sanity/cli/invokeSanityCli'\n *\n * const {exitCode, output} = await invokeSanityCli({\n * args: 'cors list --project-id abc123',\n * source: 'mcp',\n * token: extra.authInfo.token,\n * })\n * ```\n *\n * Help works like the regular CLI, scoped to the source's policy: `--help`\n * (or `help`) renders root help listing the invokable topics, and a subject\n * (`cors --help`, `cors list --help`) renders topic or command help.\n */\nimport {Config, Parser} from '@oclif/core'\nimport {getHelpFlagAdditions, normalizeArgv} from '@oclif/core/help'\nimport {CLI_TELEMETRY_SYMBOL, exitCodes, noopLogger, setCliTelemetry} from '@sanity/cli-core'\nimport {runWithCliExecutionContext, type SanityEnvironment} from '@sanity/cli-core/executionContext'\nimport {parseArgsStringToArgv} from 'string-argv'\n\nimport {commandPolicies} from './commandPolicies/index.js'\nimport {\n type CommandPolicySet,\n deny,\n type InvocationSource,\n isConditionalInvocationPolicy,\n} from './commandPolicies/policy.js'\nimport {isHelpRequest, renderInvokableHelp} from './help.js'\nimport {prettyPrintError} from './prettyPrintError.js'\n\n/**\n * Load the oclif `Config` for this package, needed to resolve, load, and run\n * commands. Loading it once and reusing it across invocations avoids\n * re-reading the command manifest per call.\n */\nfunction loadCliCommandConfig(): Promise<Config> {\n return Config.load(import.meta.url)\n}\n\nfunction unknownCommandResult(argv: string[], policySet: CommandPolicySet): InvokeSanityCliResult {\n const available = Object.entries(policySet)\n .filter(([, policy]) => policy.kind !== 'deny')\n .map(([id]) => id.replaceAll(':', ' '))\n .toSorted()\n return {\n exitCode: exitCodes.USAGE_ERROR,\n output: [\n `Unknown or unsupported command: ${argv.slice(0, 2).join(' ') || '(none)'}`,\n `Available commands: ${available.join(', ')}`,\n ].join('\\n'),\n }\n}\n\n/**\n * @internal\n */\nexport interface InvokeSanityCliOptions {\n /**\n * Arguments after `sanity` (a leading `sanity` token is tolerated), either\n * as a single string — shell-style quoting is supported, but no shell is\n * ever executed — or as a pre-split argv array.\n */\n args: string | string[]\n\n /**\n * Where this invocation originates. Selects the command policy to enforce:\n * which commands are invokable and which invocations of them are permitted.\n */\n source: InvocationSource\n\n /**\n * Auth token for this invocation. Scoped to this call via the CLI execution\n * context: it never touches process env or the process-wide token cache, so\n * concurrent invocations with different tokens are fully isolated.\n */\n token: string\n\n /**\n * Optional oclif config override (mainly for tests). Defaults to this\n * package's config, loaded once and cached across invocations.\n */\n config?: Config\n\n /**\n * Sanity deployment environment for this invocation. Scoped to this call\n * via the CLI execution context and defaults to `SANITY_INTERNAL_ENV` (or\n * production when it is unset).\n */\n sanityEnv?: SanityEnvironment\n}\n\n/**\n * @internal\n */\nexport interface InvokeSanityCliResult {\n /** `0` on success, the command's exit code otherwise. */\n exitCode: number\n\n /** Combined stdout and stderr output, in emission order. */\n output: string\n\n /**\n * Canonical oclif command id when the invocation resolved to a command\n * exposed by the selected policy (for example, `datasets:create`).\n */\n commandId?: string\n}\n\nlet cachedConfig: Promise<Config> | undefined\n\n/**\n * Unlike a shell, string-argv keeps quotes that are glued to unquoted text:\n * `--name=\"my project\"` tokenizes with the quotes intact. Strip a matching\n * wrapping quote pair from the value side of `--flag=`-shaped tokens so the\n * common shell-style form yields the value the caller intended.\n */\nfunction stripFlagQuotes(rawToken: string): string {\n const match = /^(-{1,2}[^\\s=]+=)(['\"])([\\s\\S]*)\\2$/.exec(rawToken)\n return match ? match[1] + match[3] : rawToken\n}\n\n/**\n * Run a policy-permitted CLI command in-process and capture its result.\n *\n * Command-level failures (unknown command, bad flags, API errors) are\n * reported through `exitCode`/`output` rather than thrown, so callers can\n * relay them verbatim.\n *\n * @internal\n */\nexport async function invokeSanityCli({\n args,\n config,\n sanityEnv,\n source,\n token,\n}: InvokeSanityCliOptions): Promise<InvokeSanityCliResult> {\n const resolvedConfig = config ?? (await (cachedConfig ??= loadCliCommandConfig()))\n const policySet = commandPolicies[source]\n\n // Commands log through the global telemetry store; default it to a noop\n // store so embedding hosts need no telemetry wiring (and see no warnings),\n // without clobbering a store the host may have installed itself.\n if (!(globalThis as Record<symbol, unknown>)[CLI_TELEMETRY_SYMBOL]) {\n setCliTelemetry(noopLogger)\n }\n\n // Pre-split argv arrays are taken verbatim; only string input goes through\n // shell-style tokenization and quote normalization.\n let argv =\n typeof args === 'string'\n ? parseArgsStringToArgv(args).map((t) => stripFlagQuotes(t))\n : [...args]\n if (argv[0] === 'sanity') argv = argv.slice(1)\n\n // Help requests are routed through oclif's help system, scoped to the\n // source's policy: root help for a bare request, topic/command help when a\n // subject is given. Denied subjects get the standard unknown-command\n // response (identical to a truly unknown command, so hosts can't probe the\n // full CLI surface through help), and a help request never executes a\n // command.\n if (isHelpRequest(argv, resolvedConfig)) {\n try {\n // Drop a leading `help` so the rest is the subject, mirroring how\n // oclif's dispatch consumes the token before the help command sees argv\n const helpArgv = argv[0] === 'help' ? argv.slice(1) : argv\n const result = await renderInvokableHelp(resolvedConfig, helpArgv, policySet)\n if (result) return {...result, exitCode: exitCodes.SUCCESS}\n const helpFlags = getHelpFlagAdditions(resolvedConfig)\n return unknownCommandResult(\n helpArgv.filter((token) => !helpFlags.includes(token)),\n policySet,\n )\n } catch (err) {\n return {\n exitCode: exitCodes.RUNTIME_ERROR,\n output: err instanceof Error ? err.message : String(err),\n }\n }\n }\n\n // Resolve the command id the same way oclif's dispatch would (collating\n // space-separated topics, accepting colon-separated ids as-is), then apply\n // the policy. Denied and uncategorized ids fail closed, indistinguishable\n // from commands that don't exist.\n const [commandId = '', ...commandArgv] = normalizeArgv(resolvedConfig, argv)\n const policy = policySet[commandId] ?? deny\n const commandDefinition =\n policy.kind === 'deny' ? undefined : resolvedConfig.findCommand(commandId)\n if (!commandDefinition) return unknownCommandResult(argv, policySet)\n\n const CommandClass = await commandDefinition.load()\n\n // Parse with the command's real definitions (without executing anything) so\n // conditional policies are evaluated against typed args/flags, not tokens.\n let invocation: {args: Record<string, unknown>; flags: Record<string, unknown>}\n try {\n const parsed = await Parser.parse(commandArgv, {\n args: CommandClass.args,\n baseFlags: CommandClass.baseFlags,\n enableJsonFlag: CommandClass.enableJsonFlag,\n flags: CommandClass.flags,\n strict: CommandClass.strict,\n })\n invocation = {\n args: parsed.args as Record<string, unknown>,\n flags: parsed.flags as Record<string, unknown>,\n }\n } catch (err) {\n return {\n commandId,\n exitCode: exitCodes.USAGE_ERROR,\n output: err instanceof Error ? err.message : String(err),\n }\n }\n\n if (!policy.validate(invocation)) {\n const displayId = commandId.replaceAll(':', ' ')\n let output = `This invocation of \\`${displayId}\\` is not supported here`\n\n if (isConditionalInvocationPolicy(policy)) {\n const usedDeniedFlags = policy.deniedFlags.filter(\n (name) => invocation.flags[name] !== undefined && invocation.flags[name] !== false,\n )\n if (usedDeniedFlags.length > 0) {\n output = `\\nThe ${usedDeniedFlags.map((name) => `--${name}`).join(', ')} flag is not supported here for \\`${displayId}\\``\n }\n }\n\n return {\n commandId,\n exitCode: exitCodes.USAGE_ERROR,\n output,\n }\n }\n\n const output: string[] = []\n const sink = (line: string) => output.push(line)\n\n try {\n await runWithCliExecutionContext({sanityEnv, stderr: sink, stdout: sink, token}, () =>\n CommandClass.run(commandArgv, resolvedConfig),\n )\n return {commandId, exitCode: exitCodes.SUCCESS, output: output.join('\\n')}\n } catch (err) {\n const exit = err.oclif?.exit\n\n // `this.exit(0)` throws an ExitError but is a successful outcome\n if (exit === exitCodes.SUCCESS) {\n return {commandId, exitCode: exitCodes.SUCCESS, output: output.join('\\n')}\n }\n\n const message = prettyPrintError(err) || String(err)\n if (message) output.push(message)\n return {\n commandId,\n exitCode: typeof exit === 'number' ? exit : exitCodes.RUNTIME_ERROR,\n output: output.join('\\n'),\n }\n }\n}\n"],"names":["Config","Parser","getHelpFlagAdditions","normalizeArgv","CLI_TELEMETRY_SYMBOL","exitCodes","noopLogger","setCliTelemetry","runWithCliExecutionContext","parseArgsStringToArgv","commandPolicies","deny","isConditionalInvocationPolicy","isHelpRequest","renderInvokableHelp","prettyPrintError","loadCliCommandConfig","load","url","unknownCommandResult","argv","policySet","available","Object","entries","filter","policy","kind","map","id","replaceAll","toSorted","exitCode","USAGE_ERROR","output","slice","join","cachedConfig","stripFlagQuotes","rawToken","match","exec","invokeSanityCli","args","config","sanityEnv","source","token","resolvedConfig","globalThis","t","helpArgv","result","SUCCESS","helpFlags","includes","err","RUNTIME_ERROR","Error","message","String","commandId","commandArgv","commandDefinition","undefined","findCommand","CommandClass","invocation","parsed","parse","baseFlags","enableJsonFlag","flags","strict","validate","displayId","usedDeniedFlags","deniedFlags","name","length","sink","line","push","stderr","stdout","run","exit","oclif"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;CAqBC,GACD,SAAQA,MAAM,EAAEC,MAAM,QAAO,cAAa;AAC1C,SAAQC,oBAAoB,EAAEC,aAAa,QAAO,mBAAkB;AACpE,SAAQC,oBAAoB,EAAEC,SAAS,EAAEC,UAAU,EAAEC,eAAe,QAAO,mBAAkB;AAC7F,SAAQC,0BAA0B,QAA+B,oCAAmC;AACpG,SAAQC,qBAAqB,QAAO,cAAa;AAEjD,SAAQC,eAAe,QAAO,6BAA4B;AAC1D,SAEEC,IAAI,EAEJC,6BAA6B,QACxB,8BAA6B;AACpC,SAAQC,aAAa,EAAEC,mBAAmB,QAAO,YAAW;AAC5D,SAAQC,gBAAgB,QAAO,wBAAuB;AAEtD;;;;CAIC,GACD,SAASC;IACP,OAAOhB,OAAOiB,IAAI,CAAC,YAAYC,GAAG;AACpC;AAEA,SAASC,qBAAqBC,IAAc,EAAEC,SAA2B;IACvE,MAAMC,YAAYC,OAAOC,OAAO,CAACH,WAC9BI,MAAM,CAAC,CAAC,GAAGC,OAAO,GAAKA,OAAOC,IAAI,KAAK,QACvCC,GAAG,CAAC,CAAC,CAACC,GAAG,GAAKA,GAAGC,UAAU,CAAC,KAAK,MACjCC,QAAQ;IACX,OAAO;QACLC,UAAU3B,UAAU4B,WAAW;QAC/BC,QAAQ;YACN,CAAC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WAAWA,OAAOjF,UAAUoD,aAAa;YACnEvB,QAAQA,OAAOE,IAAI,CAAC;QACtB;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/exports/invokeSanityCli/index.ts"],"sourcesContent":["/**\n * Programmatic (in-process) invocation of CLI commands, e.g. from an MCP\n * server. The invokable surface is governed by a per-source command policy\n * (see ./commandPolicies): every CLI command is explicitly allowed, denied,\n * or allowed conditionally on the parsed invocation.\n *\n * {@link invokeSanityCli} handles arg parsing, policy enforcement, command\n * dispatch, per-invocation auth, and output capture.\n * ```ts\n * import {invokeSanityCli} from '@sanity/cli/invokeSanityCli'\n *\n * const {exitCode, output} = await invokeSanityCli({\n * args: 'cors list --project-id abc123',\n * source: 'mcp',\n * token: extra.authInfo.token,\n * })\n * ```\n *\n * Help works like the regular CLI, scoped to the source's policy: `--help`\n * (or `help`) renders root help listing the invokable topics, and a subject\n * (`cors --help`, `cors list --help`) renders topic or command help.\n */\nimport {Command, Config, Parser, settings} from '@oclif/core'\nimport {getHelpFlagAdditions, normalizeArgv} from '@oclif/core/help'\nimport {exitCodes} from '@sanity/cli-core'\nimport {runWithCliExecutionContext, type SanityEnvironment} from '@sanity/cli-core/executionContext'\nimport {type SanityCommand} from '@sanity/cli-core/SanityCommand'\nimport {parseArgsStringToArgv} from 'string-argv'\n\nimport {commandPolicies} from './commandPolicies/index.js'\nimport {\n type CommandPolicySet,\n deny,\n type InvocationSource,\n isConditionalInvocationPolicy,\n} from './commandPolicies/policy.js'\nimport {isHelpRequest, renderInvokableHelp} from './help.js'\nimport {prettyPrintError} from './prettyPrintError.js'\n\ntype InvokableCommand = Pick<SanityCommand<typeof Command>, 'runInExecutionContext'>\n\n/**\n * Instantiate a policy-approved command for isolated execution.\n *\n * Every invokable command extends `SanityCommand`, whose\n * `runInExecutionContext()` runs the instance without oclif's static\n * `Command.run()` — the static runner re-enters `Config.load()` (filesystem\n * reads and a process-global config cache write) on every call. The manifest\n * types command classes as the abstract oclif `Command`, hence the\n * constructor cast. The method is probed rather than checked with\n * `instanceof`, because command modules may load from the compiled build\n * while this module runs from source, giving `SanityCommand` two identities.\n */\nfunction instantiateCommand(\n CommandClass: Command.Class,\n argv: string[],\n config: Config,\n): InvokableCommand {\n const ConcreteCommand = CommandClass as unknown as new (argv: string[], config: Config) => Command\n const command = new ConcreteCommand(argv, config) as Command & Partial<InvokableCommand>\n if (typeof command.runInExecutionContext !== 'function') {\n throw new TypeError(`Command \"${CommandClass.id}\" does not support isolated execution`)\n }\n return command as InvokableCommand\n}\n\n/**\n * Load the oclif `Config` for this package, needed to resolve, load, and run\n * commands. Loading it once and reusing it across invocations avoids\n * re-reading the command manifest per call. It only reads this package's own\n * installed files — process-lifetime initialization, not per-invocation host\n * state — so it happens outside any execution context.\n */\nfunction loadCliCommandConfig(): Promise<Config> {\n return Config.load(import.meta.url)\n}\n\nlet cachedConfig: Promise<Config> | undefined\n\nfunction unknownCommandResult(argv: string[], policySet: CommandPolicySet): InvokeSanityCliResult {\n const available = Object.entries(policySet)\n .filter(([, policy]) => policy.kind !== 'deny')\n .map(([id]) => id.replaceAll(':', ' '))\n .toSorted()\n return {\n exitCode: exitCodes.USAGE_ERROR,\n output: [\n `Unknown or unsupported command: ${argv.slice(0, 2).join(' ') || '(none)'}`,\n `Available commands: ${available.join(', ')}`,\n ].join('\\n'),\n }\n}\n\n/**\n * @internal\n */\nexport interface InvokeSanityCliOptions {\n /**\n * Arguments after `sanity` (a leading `sanity` token is tolerated), either\n * as a single string — shell-style quoting is supported, but no shell is\n * ever executed — or as a pre-split argv array.\n */\n args: string | string[]\n\n /**\n * Where this invocation originates. Selects the command policy to enforce:\n * which commands are invokable and which invocations of them are permitted.\n */\n source: InvocationSource\n\n /**\n * Auth token for this invocation. Scoped to this call via the CLI execution\n * context: it never touches process env or the process-wide token cache, so\n * concurrent invocations with different tokens are fully isolated.\n */\n token: string\n\n /**\n * Optional oclif config override (mainly for tests). Defaults to this\n * package's config, loaded once and cached across invocations.\n */\n config?: Config\n\n /**\n * Sanity deployment environment for this invocation. Scoped to this call\n * via the CLI execution context and defaults to production. The embedding\n * process's `SANITY_INTERNAL_ENV` is never consulted.\n */\n sanityEnv?: SanityEnvironment\n}\n\n/**\n * @internal\n */\nexport interface InvokeSanityCliResult {\n /** `0` on success, the command's exit code otherwise. */\n exitCode: number\n\n /** Combined stdout and stderr output, in emission order. */\n output: string\n\n /**\n * Canonical oclif command id when the invocation resolved to a command\n * exposed by the selected policy (for example, `datasets:create`).\n */\n commandId?: string\n}\n\n/**\n * Unlike a shell, string-argv keeps quotes that are glued to unquoted text:\n * `--name=\"my project\"` tokenizes with the quotes intact. Strip a matching\n * wrapping quote pair from the value side of `--flag=`-shaped tokens so the\n * common shell-style form yields the value the caller intended.\n */\nfunction stripFlagQuotes(rawToken: string): string {\n const match = /^(-{1,2}[^\\s=]+=)(['\"])([\\s\\S]*)\\2$/.exec(rawToken)\n return match ? match[1] + match[3] : rawToken\n}\n\n/**\n * Run a policy-permitted CLI command in-process and capture its result.\n *\n * Command-level failures (unknown command, bad flags, API errors) are\n * reported through `exitCode`/`output` rather than thrown, so callers can\n * relay them verbatim.\n *\n * @internal\n */\nexport async function invokeSanityCli(\n options: InvokeSanityCliOptions,\n): Promise<InvokeSanityCliResult> {\n // Always load compiled command modules. Oclif's dev-mode source resolution\n // otherwise probes tsconfigs (reading the filesystem and process.cwd) on\n // every command load, and may register ts-node process-wide.\n settings.enableAutoTranspile = false\n\n const resolvedConfig = options.config ?? (await (cachedConfig ??= loadCliCommandConfig()))\n const output: string[] = []\n const sink = (line: string) => output.push(line)\n const {sanityEnv, token} = options\n\n // Establish the isolation boundary before rendering help, loading command\n // modules, parsing, or executing. Any code reached by an external\n // invocation can therefore fail closed on context.\n return runWithCliExecutionContext({sanityEnv, stderr: sink, stdout: sink, token}, () =>\n invokeSanityCliInContext(options, resolvedConfig, output),\n )\n}\n\nasync function invokeSanityCliInContext(\n {args, source}: InvokeSanityCliOptions,\n resolvedConfig: Config,\n output: string[],\n): Promise<InvokeSanityCliResult> {\n const policySet = commandPolicies[source]\n\n // Pre-split argv arrays are taken verbatim; only string input goes through\n // shell-style tokenization and quote normalization.\n let argv =\n typeof args === 'string'\n ? parseArgsStringToArgv(args).map((t) => stripFlagQuotes(t))\n : [...args]\n if (argv[0] === 'sanity') argv = argv.slice(1)\n\n // Help requests are routed through oclif's help system, scoped to the\n // source's policy: root help for a bare request, topic/command help when a\n // subject is given. Denied subjects get the standard unknown-command\n // response (identical to a truly unknown command, so hosts can't probe the\n // full CLI surface through help), and a help request never executes a\n // command.\n if (isHelpRequest(argv, resolvedConfig)) {\n try {\n // Drop a leading `help` so the rest is the subject, mirroring how\n // oclif's dispatch consumes the token before the help command sees argv\n const helpArgv = argv[0] === 'help' ? argv.slice(1) : argv\n const result = await renderInvokableHelp(resolvedConfig, helpArgv, policySet)\n if (result) return {...result, exitCode: exitCodes.SUCCESS}\n const helpFlags = getHelpFlagAdditions(resolvedConfig)\n return unknownCommandResult(\n helpArgv.filter((token) => !helpFlags.includes(token)),\n policySet,\n )\n } catch (err) {\n return {\n exitCode: exitCodes.RUNTIME_ERROR,\n output: err instanceof Error ? err.message : String(err),\n }\n }\n }\n\n // Resolve the command id the same way oclif's dispatch would (collating\n // space-separated topics, accepting colon-separated ids as-is), then apply\n // the policy. Denied and uncategorized ids fail closed, indistinguishable\n // from commands that don't exist.\n const [commandId = '', ...commandArgv] = normalizeArgv(resolvedConfig, argv)\n const policy = policySet[commandId] ?? deny\n const commandDefinition =\n policy.kind === 'deny' ? undefined : resolvedConfig.findCommand(commandId)\n if (!commandDefinition) return unknownCommandResult(argv, policySet)\n\n const CommandClass = await commandDefinition.load()\n\n // Parse with the command's real definitions (without executing anything) so\n // conditional policies are evaluated against typed args/flags, not tokens.\n let invocation: {args: Record<string, unknown>; flags: Record<string, unknown>}\n try {\n const parsed = await Parser.parse(commandArgv, {\n args: CommandClass.args,\n baseFlags: CommandClass.baseFlags,\n enableJsonFlag: CommandClass.enableJsonFlag,\n flags: CommandClass.flags,\n strict: CommandClass.strict,\n })\n invocation = {\n args: parsed.args as Record<string, unknown>,\n flags: parsed.flags as Record<string, unknown>,\n }\n } catch (err) {\n return {\n commandId,\n exitCode: exitCodes.USAGE_ERROR,\n output: err instanceof Error ? err.message : String(err),\n }\n }\n\n if (!policy.validate(invocation)) {\n const displayId = commandId.replaceAll(':', ' ')\n let output = `This invocation of \\`${displayId}\\` is not supported here`\n\n if (isConditionalInvocationPolicy(policy)) {\n const usedDeniedFlags = policy.deniedFlags.filter(\n (name) => invocation.flags[name] !== undefined && invocation.flags[name] !== false,\n )\n if (usedDeniedFlags.length > 0) {\n output = `\\nThe ${usedDeniedFlags.map((name) => `--${name}`).join(', ')} flag is not supported here for \\`${displayId}\\``\n }\n }\n\n return {\n commandId,\n exitCode: exitCodes.USAGE_ERROR,\n output,\n }\n }\n\n try {\n const command = instantiateCommand(CommandClass, commandArgv, resolvedConfig)\n await command.runInExecutionContext()\n return {commandId, exitCode: exitCodes.SUCCESS, output: output.join('\\n')}\n } catch (err) {\n const exit = err.oclif?.exit\n\n // `this.exit(0)` throws an ExitError but is a successful outcome\n if (exit === exitCodes.SUCCESS) {\n return {commandId, exitCode: exitCodes.SUCCESS, output: output.join('\\n')}\n }\n\n const message = prettyPrintError(err) || String(err)\n if (message) output.push(message)\n return {\n commandId,\n exitCode: typeof exit === 'number' ? exit : exitCodes.RUNTIME_ERROR,\n output: output.join('\\n'),\n }\n }\n}\n"],"names":["Config","Parser","settings","getHelpFlagAdditions","normalizeArgv","exitCodes","runWithCliExecutionContext","parseArgsStringToArgv","commandPolicies","deny","isConditionalInvocationPolicy","isHelpRequest","renderInvokableHelp","prettyPrintError","instantiateCommand","CommandClass","argv","config","ConcreteCommand","command","runInExecutionContext","TypeError","id","loadCliCommandConfig","load","url","cachedConfig","unknownCommandResult","policySet","available","Object","entries","filter","policy","kind","map","replaceAll","toSorted","exitCode","USAGE_ERROR","output","slice","join","stripFlagQuotes","rawToken","match","exec","invokeSanityCli","options","enableAutoTranspile","resolvedConfig","sink","line","push","sanityEnv","token","stderr","stdout","invokeSanityCliInContext","args","source","t","helpArgv","result","SUCCESS","helpFlags","includes","err","RUNTIME_ERROR","Error","message","String","commandId","commandArgv","commandDefinition","undefined","findCommand","invocation","parsed","parse","baseFlags","enableJsonFlag","flags","strict","validate","displayId","usedDeniedFlags","deniedFlags","name","length","exit","oclif"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;CAqBC,GACD,SAAiBA,MAAM,EAAEC,MAAM,EAAEC,QAAQ,QAAO,cAAa;AAC7D,SAAQC,oBAAoB,EAAEC,aAAa,QAAO,mBAAkB;AACpE,SAAQC,SAAS,QAAO,mBAAkB;AAC1C,SAAQC,0BAA0B,QAA+B,oCAAmC;AAEpG,SAAQC,qBAAqB,QAAO,cAAa;AAEjD,SAAQC,eAAe,QAAO,6BAA4B;AAC1D,SAEEC,IAAI,EAEJC,6BAA6B,QACxB,8BAA6B;AACpC,SAAQC,aAAa,EAAEC,mBAAmB,QAAO,YAAW;AAC5D,SAAQC,gBAAgB,QAAO,wBAAuB;AAItD;;;;;;;;;;;CAWC,GACD,SAASC,mBACPC,YAA2B,EAC3BC,IAAc,EACdC,MAAc;IAEd,MAAMC,kBAAkBH;IACxB,MAAMI,UAAU,IAAID,gBAAgBF,MAAMC;IAC1C,IAAI,OAAOE,QAAQC,qBAAqB,KAAK,YAAY;QACvD,MAAM,IAAIC,UAAU,CAAC,SAAS,EAAEN,aAAaO,EAAE,CAAC,qCAAqC,CAAC;IACxF;IACA,OAAOH;AACT;AAEA;;;;;;CAMC,GACD,SAASI;IACP,OAAOvB,OAAOwB,IAAI,CAAC,YAAYC,GAAG;AACpC;AAEA,IAAIC;AAEJ,SAASC,qBAAqBX,IAAc,EAAEY,SAA2B;IACvE,MAAMC,YAAYC,OAAOC,OAAO,CAACH,WAC9BI,MAAM,CAAC,CAAC,GAAGC,OAAO,GAAKA,OAAOC,IAAI,KAAK,QACvCC,GAAG,CA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AAK,EAAED;QAExB,iEAAiE;QACjE,IAAIA,SAASrF,UAAU2D,OAAO,EAAE;YAC9B,OAAO;gBAACQ;gBAAWlC,UAAUjC,UAAU2D,OAAO;gBAAExB,QAAQA,OAAOE,IAAI,CAAC;YAAK;QAC3E;QAEA,MAAM4B,UAAUzD,iBAAiBsD,QAAQI,OAAOJ;QAChD,IAAIG,SAAS9B,OAAOa,IAAI,CAACiB;QACzB,OAAO;YACLE;YACAlC,UAAU,OAAOoD,SAAS,WAAWA,OAAOrF,UAAU+D,aAAa;YACnE5B,QAAQA,OAAOE,IAAI,CAAC;QACtB;IACF;AACF"}
|
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
import { AssetSource } from "@sanity/types";
|
|
2
|
+
import { AssetSourceComponent } from "@sanity/workbench-cli";
|
|
3
|
+
import { AssetSourceComponentProps } from "@sanity/types";
|
|
4
|
+
import { AssetSourceViewComponents } from "@sanity/workbench-cli";
|
|
1
5
|
import { DefinedService } from "@sanity/workbench-cli";
|
|
2
6
|
import { DefinedView } from "@sanity/workbench-cli";
|
|
3
7
|
import { InterfaceType } from "@sanity/workbench-cli";
|
|
@@ -12,6 +16,14 @@ import { unstable_defineService } from "@sanity/workbench-cli";
|
|
|
12
16
|
import { unstable_defineView } from "@sanity/workbench-cli";
|
|
13
17
|
import { ViewComponentsByType } from "@sanity/workbench-cli";
|
|
14
18
|
|
|
19
|
+
export { AssetSource };
|
|
20
|
+
|
|
21
|
+
export { AssetSourceComponent };
|
|
22
|
+
|
|
23
|
+
export { AssetSourceComponentProps };
|
|
24
|
+
|
|
25
|
+
export { AssetSourceViewComponents };
|
|
26
|
+
|
|
15
27
|
export { DefinedService };
|
|
16
28
|
|
|
17
29
|
export { DefinedView };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/exports/runtime.ts"],"sourcesContent":["// Browser-safe runtime authoring helpers for the module-federation extension API.\n//\n// View/service src files bundle to the browser, so this entry re-exports ONLY\n// from dependency-light, browser-safe modules — it must never import\n// `@sanity/cli-core` or anything Node-only, or it would drag the CLI into the\n// frontend bundle. The `sanity` runtime package re-exports from here, so the\n// same constraint protects it.\n//\n// `unstable_defineApp` is config-time (Node) and stays on the main `@sanity/cli`\n// entry; only the runtime helpers live here.\nexport type {\n DefinedService,\n DefinedView,\n InterfaceType,\n PanelComponent,\n PanelViewComponents,\n PanelViewProps,\n ServiceCallback,\n ServiceContext,\n ServiceInfo,\n ServiceType,\n ViewComponentsByType,\n} from '@sanity/workbench-cli'\nexport {unstable_defineService, unstable_defineView} from '@sanity/workbench-cli'\n"],"names":["unstable_defineService","unstable_defineView"],"mappings":"AAAA,kFAAkF;AAClF,EAAE;AACF,8EAA8E;AAC9E,qEAAqE;AACrE,8EAA8E;AAC9E,6EAA6E;AAC7E,+BAA+B;AAC/B,EAAE;AACF,iFAAiF;AACjF,6CAA6C;
|
|
1
|
+
{"version":3,"sources":["../../src/exports/runtime.ts"],"sourcesContent":["// Browser-safe runtime authoring helpers for the module-federation extension API.\n//\n// View/service src files bundle to the browser, so this entry re-exports ONLY\n// from dependency-light, browser-safe modules — it must never import\n// `@sanity/cli-core` or anything Node-only, or it would drag the CLI into the\n// frontend bundle. The `sanity` runtime package re-exports from here, so the\n// same constraint protects it.\n//\n// `unstable_defineApp` is config-time (Node) and stays on the main `@sanity/cli`\n// entry; only the runtime helpers live here.\nexport type {AssetSource, AssetSourceComponentProps} from '@sanity/types'\nexport type {\n AssetSourceComponent,\n AssetSourceViewComponents,\n DefinedService,\n DefinedView,\n InterfaceType,\n PanelComponent,\n PanelViewComponents,\n PanelViewProps,\n ServiceCallback,\n ServiceContext,\n ServiceInfo,\n ServiceType,\n ViewComponentsByType,\n} from '@sanity/workbench-cli'\nexport {unstable_defineService, unstable_defineView} from '@sanity/workbench-cli'\n"],"names":["unstable_defineService","unstable_defineView"],"mappings":"AAAA,kFAAkF;AAClF,EAAE;AACF,8EAA8E;AAC9E,qEAAqE;AACrE,8EAA8E;AAC9E,6EAA6E;AAC7E,+BAA+B;AAC/B,EAAE;AACF,iFAAiF;AACjF,6CAA6C;AAiB7C,SAAQA,sBAAsB,EAAEC,mBAAmB,QAAO,wBAAuB"}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { subdebug } from '@sanity/cli-core/debug';
|
|
2
|
+
import { createRequester } from '@sanity/cli-core/request';
|
|
3
|
+
import { isStaging } from '@sanity/cli-core/util';
|
|
4
|
+
import { TERMS_OF_SERVICE_FALLBACK_NOTICE, TERMS_OF_SERVICE_FALLBACK_URL } from '../util/mintProjectConstants.js';
|
|
5
|
+
const debug = subdebug('new:provision');
|
|
6
|
+
/** Provision API version for minting unclaimed projects. */ export const PROVISION_API_VERSION = 'v2026-06-23';
|
|
7
|
+
const request = createRequester({
|
|
8
|
+
middleware: {
|
|
9
|
+
httpErrors: false,
|
|
10
|
+
promise: {
|
|
11
|
+
onlyBody: false
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
});
|
|
15
|
+
function getProvisionApiBase() {
|
|
16
|
+
const override = process.env.SANITY_API_HOST;
|
|
17
|
+
if (override) return override.replace(/\/$/u, '');
|
|
18
|
+
return isStaging() ? 'https://api.sanity.work' : 'https://api.sanity.io';
|
|
19
|
+
}
|
|
20
|
+
function parseJsonBody(body) {
|
|
21
|
+
if (typeof body !== 'string') return body;
|
|
22
|
+
try {
|
|
23
|
+
return JSON.parse(body);
|
|
24
|
+
} catch {
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
function getString(value) {
|
|
29
|
+
return typeof value === 'string' && value.length > 0 ? value : undefined;
|
|
30
|
+
}
|
|
31
|
+
function parseProvisionResponse(body) {
|
|
32
|
+
const data = parseJsonBody(body);
|
|
33
|
+
const response = data && typeof data === 'object' && !Array.isArray(data) ? data : {};
|
|
34
|
+
const links = response.links && typeof response.links === 'object' && !Array.isArray(response.links) ? response.links : {};
|
|
35
|
+
const terms = response.terms && typeof response.terms === 'object' && !Array.isArray(response.terms) ? response.terms : {};
|
|
36
|
+
const minted = {
|
|
37
|
+
apiHost: getString(response.apiHost),
|
|
38
|
+
claimApiUrl: getString(links.claimApiUrl),
|
|
39
|
+
claimToken: getString(response.claimToken),
|
|
40
|
+
claimUrl: getString(links.claimUrl),
|
|
41
|
+
datasetName: getString(response.datasetName),
|
|
42
|
+
expiresAt: getString(response.expiresAt),
|
|
43
|
+
resourceId: getString(response.resourceId),
|
|
44
|
+
token: getString(response.token)
|
|
45
|
+
};
|
|
46
|
+
const missing = Object.entries(minted).filter(([, value])=>value === undefined).map(([key])=>key);
|
|
47
|
+
if (response.resourceType !== 'project') {
|
|
48
|
+
missing.push('resourceType');
|
|
49
|
+
}
|
|
50
|
+
if (missing.length > 0) {
|
|
51
|
+
throw new Error(`Project creation response is missing or invalid: ${missing.join(', ')}`);
|
|
52
|
+
}
|
|
53
|
+
return {
|
|
54
|
+
...minted,
|
|
55
|
+
termsNotice: getString(terms.notice) ?? TERMS_OF_SERVICE_FALLBACK_NOTICE,
|
|
56
|
+
termsUrl: getString(terms.url) ?? TERMS_OF_SERVICE_FALLBACK_URL
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Mint an unclaimed Sanity project through the public provision endpoint.
|
|
61
|
+
*/ export async function mintUnclaimedProject(options) {
|
|
62
|
+
const displayName = options.displayName.trim();
|
|
63
|
+
if (!displayName || displayName.length > 80) {
|
|
64
|
+
throw new Error('Project name must be 1-80 characters.');
|
|
65
|
+
}
|
|
66
|
+
const url = `${getProvisionApiBase()}/${PROVISION_API_VERSION}/provision`;
|
|
67
|
+
debug('minting unclaimed project at %s', url);
|
|
68
|
+
const response = await request({
|
|
69
|
+
body: JSON.stringify({
|
|
70
|
+
displayName,
|
|
71
|
+
resourceType: 'project'
|
|
72
|
+
}),
|
|
73
|
+
headers: {
|
|
74
|
+
'Content-Type': 'application/json'
|
|
75
|
+
},
|
|
76
|
+
method: 'POST',
|
|
77
|
+
url
|
|
78
|
+
});
|
|
79
|
+
if (response.statusCode === 404) {
|
|
80
|
+
throw new Error('Creating projects without an account is currently unavailable. Try again later, or run `sanity login` and `sanity init`.');
|
|
81
|
+
}
|
|
82
|
+
if (response.statusCode === 429) {
|
|
83
|
+
throw new Error('Project creation rate limit reached for this machine. Try again later.');
|
|
84
|
+
}
|
|
85
|
+
if (response.statusCode < 200 || response.statusCode >= 300) {
|
|
86
|
+
throw new Error(`Project creation failed (HTTP ${response.statusCode}). Try again later.`);
|
|
87
|
+
}
|
|
88
|
+
return parseProvisionResponse(response.body);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
//# sourceMappingURL=mintProject.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/services/mintProject.ts"],"sourcesContent":["import {subdebug} from '@sanity/cli-core/debug'\nimport {createRequester} from '@sanity/cli-core/request'\nimport {isStaging} from '@sanity/cli-core/util'\n\nimport {\n TERMS_OF_SERVICE_FALLBACK_NOTICE,\n TERMS_OF_SERVICE_FALLBACK_URL,\n} from '../util/mintProjectConstants.js'\n\nconst debug = subdebug('new:provision')\n\n/** Provision API version for minting unclaimed projects. */\nexport const PROVISION_API_VERSION = 'v2026-06-23'\n\nconst request = createRequester({middleware: {httpErrors: false, promise: {onlyBody: false}}})\n\nexport interface MintedProject {\n apiHost: string\n claimApiUrl: string\n claimToken: string\n claimUrl: string\n datasetName: string\n expiresAt: string\n resourceId: string\n /** Terms of Service accepted by using the project. Falls back to the bundled constants. */\n termsNotice: string\n termsUrl: string\n token: string\n}\n\nfunction getProvisionApiBase(): string {\n const override = process.env.SANITY_API_HOST\n if (override) return override.replace(/\\/$/u, '')\n return isStaging() ? 'https://api.sanity.work' : 'https://api.sanity.io'\n}\n\nfunction parseJsonBody(body: unknown): unknown {\n if (typeof body !== 'string') return body\n\n try {\n return JSON.parse(body)\n } catch {\n return undefined\n }\n}\n\nfunction getString(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n\nfunction parseProvisionResponse(body: unknown): MintedProject {\n const data = parseJsonBody(body)\n const response =\n data && typeof data === 'object' && !Array.isArray(data)\n ? (data as Record<string, unknown>)\n : {}\n const links =\n response.links && typeof response.links === 'object' && !Array.isArray(response.links)\n ? (response.links as Record<string, unknown>)\n : {}\n const terms =\n response.terms && typeof response.terms === 'object' && !Array.isArray(response.terms)\n ? (response.terms as Record<string, unknown>)\n : {}\n\n const minted = {\n apiHost: getString(response.apiHost),\n claimApiUrl: getString(links.claimApiUrl),\n claimToken: getString(response.claimToken),\n claimUrl: getString(links.claimUrl),\n datasetName: getString(response.datasetName),\n expiresAt: getString(response.expiresAt),\n resourceId: getString(response.resourceId),\n token: getString(response.token),\n }\n const missing = Object.entries(minted)\n .filter(([, value]) => value === undefined)\n .map(([key]) => key)\n\n if (response.resourceType !== 'project') {\n missing.push('resourceType')\n }\n if (missing.length > 0) {\n throw new Error(`Project creation response is missing or invalid: ${missing.join(', ')}`)\n }\n\n return {\n ...(minted as Omit<MintedProject, 'termsNotice' | 'termsUrl'>),\n termsNotice: getString(terms.notice) ?? TERMS_OF_SERVICE_FALLBACK_NOTICE,\n termsUrl: getString(terms.url) ?? TERMS_OF_SERVICE_FALLBACK_URL,\n }\n}\n\n/**\n * Mint an unclaimed Sanity project through the public provision endpoint.\n */\nexport async function mintUnclaimedProject(options: {displayName: string}): Promise<MintedProject> {\n const displayName = options.displayName.trim()\n if (!displayName || displayName.length > 80) {\n throw new Error('Project name must be 1-80 characters.')\n }\n\n const url = `${getProvisionApiBase()}/${PROVISION_API_VERSION}/provision`\n debug('minting unclaimed project at %s', url)\n\n const response = await request({\n body: JSON.stringify({displayName, resourceType: 'project'}),\n headers: {'Content-Type': 'application/json'},\n method: 'POST',\n url,\n })\n\n if (response.statusCode === 404) {\n throw new Error(\n 'Creating projects without an account is currently unavailable. Try again later, or run `sanity login` and `sanity init`.',\n )\n }\n if (response.statusCode === 429) {\n throw new Error('Project creation rate limit reached for this machine. Try again later.')\n }\n if (response.statusCode < 200 || response.statusCode >= 300) {\n throw new Error(`Project creation failed (HTTP ${response.statusCode}). Try again later.`)\n }\n\n return parseProvisionResponse(response.body)\n}\n"],"names":["subdebug","createRequester","isStaging","TERMS_OF_SERVICE_FALLBACK_NOTICE","TERMS_OF_SERVICE_FALLBACK_URL","debug","PROVISION_API_VERSION","request","middleware","httpErrors","promise","onlyBody","getProvisionApiBase","override","process","env","SANITY_API_HOST","replace","parseJsonBody","body","JSON","parse","undefined","getString","value","length","parseProvisionResponse","data","response","Array","isArray","links","terms","minted","apiHost","claimApiUrl","claimToken","claimUrl","datasetName","expiresAt","resourceId","token","missing","Object","entries","filter","map","key","resourceType","push","Error","join","termsNotice","notice","termsUrl","url","mintUnclaimedProject","options","displayName","trim","stringify","headers","method","statusCode"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,yBAAwB;AAC/C,SAAQC,eAAe,QAAO,2BAA0B;AACxD,SAAQC,SAAS,QAAO,wBAAuB;AAE/C,SACEC,gCAAgC,EAChCC,6BAA6B,QACxB,kCAAiC;AAExC,MAAMC,QAAQL,SAAS;AAEvB,0DAA0D,GAC1D,OAAO,MAAMM,wBAAwB,cAAa;AAElD,MAAMC,UAAUN,gBAAgB;IAACO,YAAY;QAACC,YAAY;QAAOC,SAAS;YAACC,UAAU;QAAK;IAAC;AAAC;AAgB5F,SAASC;IACP,MAAMC,WAAWC,QAAQC,GAAG,CAACC,eAAe;IAC5C,IAAIH,UAAU,OAAOA,SAASI,OAAO,CAAC,QAAQ;IAC9C,OAAOf,cAAc,4BAA4B;AACnD;AAEA,SAASgB,cAAcC,IAAa;IAClC,IAAI,OAAOA,SAAS,UAAU,OAAOA;IAErC,IAAI;QACF,OAAOC,KAAKC,KAAK,CAACF;IACpB,EAAE,OAAM;QACN,OAAOG;IACT;AACF;AAEA,SAASC,UAAUC,KAAc;IAC/B,OAAO,OAAOA,UAAU,YAAYA,MAAMC,MAAM,GAAG,IAAID,QAAQF;AACjE;AAEA,S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IACvE,MAAMC,cAAcD,QAAQC,WAAW,CAACC,IAAI;IAC5C,IAAI,CAACD,eAAeA,YAAYjC,MAAM,GAAG,IAAI;QAC3C,MAAM,IAAIyB,MAAM;IAClB;IAEA,MAAMK,MAAM,GAAG3C,sBAAsB,CAAC,EAAEN,sBAAsB,UAAU,CAAC;IACzED,MAAM,mCAAmCkD;IAEzC,MAAM3B,WAAW,MAAMrB,QAAQ;QAC7BY,MAAMC,KAAKwC,SAAS,CAAC;YAACF;YAAaV,cAAc;QAAS;QAC1Da,SAAS;YAAC,gBAAgB;QAAkB;QAC5CC,QAAQ;QACRP;IACF;IAEA,IAAI3B,SAASmC,UAAU,KAAK,KAAK;QAC/B,MAAM,IAAIb,MACR;IAEJ;IACA,IAAItB,SAASmC,UAAU,KAAK,KAAK;QAC/B,MAAM,IAAIb,MAAM;IAClB;IACA,IAAItB,SAASmC,UAAU,GAAG,OAAOnC,SAASmC,UAAU,IAAI,KAAK;QAC3D,MAAM,IAAIb,MAAM,CAAC,8BAA8B,EAAEtB,SAASmC,UAAU,CAAC,mBAAmB,CAAC;IAC3F;IAEA,OAAOrC,uBAAuBE,SAAST,IAAI;AAC7C"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { debug, getGlobalCliClient, getProjectCliClient } from '@sanity/cli-core';
|
|
2
2
|
export const PROJECTS_API_VERSION = '2025-09-22';
|
|
3
3
|
export const CREATE_PROJECT_API_VERSION = 'v2025-05-14';
|
|
4
|
+
const UNCLAIMED_PROJECT_ORGANIZATION_ID = 'oSystemUnclaimed';
|
|
4
5
|
/**
|
|
5
6
|
* Create a new Sanity project
|
|
6
7
|
*/ export async function createProject(options) {
|
|
@@ -37,6 +38,24 @@ export async function getProjectById(projectId) {
|
|
|
37
38
|
});
|
|
38
39
|
return client.projects.getById(projectId);
|
|
39
40
|
}
|
|
41
|
+
export async function getProjectClaimStatus(projectId, token) {
|
|
42
|
+
try {
|
|
43
|
+
const client = await getProjectCliClient({
|
|
44
|
+
apiVersion: PROJECTS_API_VERSION,
|
|
45
|
+
projectId,
|
|
46
|
+
requireUser: true,
|
|
47
|
+
token
|
|
48
|
+
});
|
|
49
|
+
const project = await client.projects.getById(projectId);
|
|
50
|
+
if (typeof project.organizationId !== 'string' || project.organizationId.length === 0) {
|
|
51
|
+
return 'unknown';
|
|
52
|
+
}
|
|
53
|
+
return project.organizationId === UNCLAIMED_PROJECT_ORGANIZATION_ID ? 'unclaimed' : 'claimed';
|
|
54
|
+
} catch (error) {
|
|
55
|
+
debug('failed to check claim status for project %s: %s', projectId, error instanceof Error ? error.message : `${error}`);
|
|
56
|
+
return 'unknown';
|
|
57
|
+
}
|
|
58
|
+
}
|
|
40
59
|
export async function getProjectRoles(projectId) {
|
|
41
60
|
const client = await getGlobalCliClient({
|
|
42
61
|
apiVersion: PROJECTS_API_VERSION,
|