@sanity/cli 8.34.0 → 8.36.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.
Files changed (46) hide show
  1. package/dist/actions/build/buildApp.js +1 -4
  2. package/dist/actions/build/buildApp.js.map +1 -1
  3. package/dist/actions/build/buildStudio.js +1 -0
  4. package/dist/actions/build/buildStudio.js.map +1 -1
  5. package/dist/actions/deploy/deployApp.js +17 -9
  6. package/dist/actions/deploy/deployApp.js.map +1 -1
  7. package/dist/actions/deploy/deployDashboardConfig.js +118 -0
  8. package/dist/actions/deploy/deployDashboardConfig.js.map +1 -0
  9. package/dist/actions/deploy/deployStudio.js +3 -2
  10. package/dist/actions/deploy/deployStudio.js.map +1 -1
  11. package/dist/actions/dev/servers/getDevServerConfig.js +2 -5
  12. package/dist/actions/dev/servers/getDevServerConfig.js.map +1 -1
  13. package/dist/actions/graphql/extractGraphQLAPIs.js +13 -6
  14. package/dist/actions/graphql/extractGraphQLAPIs.js.map +1 -1
  15. package/dist/actions/graphql/extractGraphQLAPIs.worker.js +2 -1
  16. package/dist/actions/graphql/extractGraphQLAPIs.worker.js.map +1 -1
  17. package/dist/actions/init/initAction.js +30 -3
  18. package/dist/actions/init/initAction.js.map +1 -1
  19. package/dist/actions/init/initBlueprint.js +66 -0
  20. package/dist/actions/init/initBlueprint.js.map +1 -0
  21. package/dist/actions/init/types.js +2 -1
  22. package/dist/actions/init/types.js.map +1 -1
  23. package/dist/actions/preview/previewAction.js +2 -2
  24. package/dist/actions/preview/previewAction.js.map +1 -1
  25. package/dist/actions/undeploy/runUndeploy.js +16 -4
  26. package/dist/actions/undeploy/runUndeploy.js.map +1 -1
  27. package/dist/actions/undeploy/undeployPlan.js +2 -2
  28. package/dist/actions/undeploy/undeployPlan.js.map +1 -1
  29. package/dist/commands/deploy.js +15 -3
  30. package/dist/commands/deploy.js.map +1 -1
  31. package/dist/commands/init.js +10 -0
  32. package/dist/commands/init.js.map +1 -1
  33. package/dist/commands/media/prune-aspect-data.js +1 -1
  34. package/dist/commands/media/prune-aspect-data.js.map +1 -1
  35. package/dist/commands/media/pull-aspects.js +1 -1
  36. package/dist/commands/media/pull-aspects.js.map +1 -1
  37. package/dist/exports/index.d.ts +2 -2
  38. package/dist/exports/index.js +1 -1
  39. package/dist/exports/index.js.map +1 -1
  40. package/dist/exports/runtime.d.ts +2 -2
  41. package/dist/exports/runtime.js +1 -1
  42. package/dist/exports/runtime.js.map +1 -1
  43. package/dist/generated/apiRoutes.js +52 -0
  44. package/dist/generated/apiRoutes.js.map +1 -1
  45. package/oclif.manifest.json +3019 -3006
  46. package/package.json +16 -15
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/commands/init.ts"],"sourcesContent":["import {Args, Command, Flags} from '@oclif/core'\nimport {CLIError} from '@oclif/core/errors'\nimport {SanityCommand} from '@sanity/cli-core'\n\nimport {initAction} from '../actions/init/initAction.js'\nimport {InitError} from '../actions/init/initError.js'\nimport {flagsToInitOptions} from '../actions/init/types.js'\nimport {getProjectIdFlag} from '../util/sharedFlags.js'\nimport {defineCommandTelemetry} from '../util/telemetry/commandTelemetry.js'\n\nexport class InitCommand extends SanityCommand<typeof InitCommand> {\n static override args = {type: Args.string({hidden: true})}\n static override description = 'Initialize a new Sanity Studio, project and/or app'\n static override enableJsonFlag = true\n\n static override examples = [\n '<%= config.bin %> <%= command.id %>',\n {\n command: '<%= config.bin %> <%= command.id %> --dataset-default',\n description: 'Initialize a new project with a public dataset named \"production\"',\n },\n {\n command:\n '<%= config.bin %> <%= command.id %> -y --project abc123 --dataset production --output-path ~/myproj',\n description: 'Initialize a project with the given project ID and dataset to the given path',\n },\n {\n command:\n '<%= config.bin %> <%= command.id %> -y --project abc123 --dataset staging --template moviedb --output-path .',\n description:\n 'Initialize a project with the given project ID and dataset using the moviedb template to the given path',\n },\n {\n command:\n '<%= config.bin %> <%= command.id %> -y --project-name \"Movies Unlimited\" --dataset moviedb --visibility private --template moviedb --output-path /Users/espenh/movies-unlimited',\n description: 'Create a brand new project with name \"Movies Unlimited\"',\n },\n ] satisfies Array<Command.Example>\n\n static override flags = {\n 'auto-updates': Flags.boolean({\n allowNo: true,\n default: true,\n description: 'Enable auto updates of studio versions',\n exclusive: ['bare'],\n }),\n bare: Flags.boolean({\n description:\n 'Skip the Studio initialization and only print the selected project ID and dataset name to stdout',\n }),\n coupon: Flags.string({\n description:\n 'Optionally select a coupon for a new project (cannot be used with --project-plan)',\n exclusive: ['project-plan'],\n helpValue: '<code>',\n }),\n 'create-project': Flags.string({\n deprecated: {message: 'Use --project-name instead'},\n description: 'Create a new project with the given name',\n helpValue: '<name>',\n hidden: true,\n }),\n dashboard: Flags.boolean({\n description: 'Set up the project to run in the Sanity Dashboard (beta)',\n exclusive: ['bare', 'env'],\n }),\n dataset: Flags.string({\n description: 'Dataset name for the studio',\n exclusive: ['dataset-default'],\n helpValue: '<name>',\n }),\n 'dataset-default': Flags.boolean({\n description: 'Set up a project with a public dataset named \"production\"',\n }),\n env: Flags.string({\n description: 'Write environment variables to file',\n exclusive: ['bare'],\n helpValue: '<filename>',\n parse: async (input) => {\n if (!input.startsWith('.env')) {\n throw new CLIError('Env filename (`--env`) must start with `.env`')\n }\n return input\n },\n }),\n 'from-create': Flags.boolean({\n description: 'Internal flag to indicate that the command is run from create-sanity',\n hidden: true,\n }),\n git: Flags.string({\n default: undefined,\n description: 'Specify a commit message for initial commit, or disable git init',\n exclusive: ['bare'],\n // oclif doesn't indent correctly with custom help labels, thus leading space :/\n helpLabel: ' --[no-]git',\n helpValue: '<message>',\n }),\n 'import-dataset': Flags.boolean({\n allowNo: true,\n default: undefined,\n description: 'Import template sample dataset',\n }),\n install: Flags.boolean({\n allowNo: true,\n default: true,\n description: 'Install dependencies after scaffolding',\n exclusive: ['bare'],\n }),\n mcp: Flags.boolean({\n allowNo: true,\n default: true,\n description: 'Enable AI editor integration (MCP) setup',\n }),\n 'nextjs-add-config-files': Flags.boolean({\n allowNo: true,\n default: undefined,\n description: 'Add config files to Next.js project',\n helpGroup: 'Next.js',\n }),\n 'nextjs-append-env': Flags.boolean({\n allowNo: true,\n default: undefined,\n description: 'Append project ID and dataset to .env file',\n helpGroup: 'Next.js',\n }),\n 'nextjs-embed-studio': Flags.boolean({\n allowNo: true,\n default: undefined,\n description: 'Embed the Studio in Next.js application',\n helpGroup: 'Next.js',\n }),\n // oclif doesn't support a boolean/string flag combination, but listing both a\n // `--git` and a `--no-git` flag in help breaks conventions, so we hide this one,\n // but use it to \"combine\" the two in the actual logic.\n 'no-git': Flags.boolean({\n description: 'Disable git initialization',\n exclusive: ['git'],\n hidden: true,\n }),\n organization: Flags.string({\n description:\n 'Organization ID to use for the project (required for unattended project creation)',\n helpValue: '<id>',\n }),\n 'output-path': Flags.string({\n description: 'Path to write studio project to',\n exclusive: ['bare'],\n helpValue: '<path>',\n }),\n 'overwrite-files': Flags.boolean({\n allowNo: true,\n default: undefined,\n description: 'Overwrite existing files',\n }),\n 'package-manager': Flags.string({\n description: 'Specify which package manager to use [allowed: npm, yarn, pnpm]',\n exclusive: ['bare'],\n helpValue: '<manager>',\n options: ['npm', 'yarn', 'pnpm'],\n }),\n ...getProjectIdFlag({\n description: 'Project ID to use for the studio',\n exclusive: ['create-project', 'project-name'],\n semantics: 'specify',\n }),\n 'project-name': Flags.string({\n description: 'Create a new project with the given name',\n exclusive: ['project', 'create-project'],\n helpValue: '<name>',\n }),\n 'project-plan': Flags.string({\n description: 'Optionally select a plan for a new project',\n helpValue: '<name>',\n }),\n provider: Flags.string({\n description: 'Login provider to use',\n helpValue: '<provider>',\n }),\n quickstart: Flags.boolean({\n deprecated: true,\n description:\n 'Used for initializing a project from a server schema that is saved in the Journey API',\n hidden: true,\n }),\n reconfigure: Flags.boolean({\n deprecated: {\n message: 'This flag is no longer supported',\n version: '3.0.0',\n },\n description: 'Reconfigure an existing project',\n hidden: true,\n }),\n skills: Flags.boolean({\n allowNo: true,\n default: true,\n description: 'Install Sanity agent skills globally for detected AI editors',\n }),\n template: Flags.string({\n description: 'Project template to use [default: \"clean\"]',\n exclusive: ['bare'],\n helpValue: '<template>',\n }),\n // Porting over a beta flag\n // Oclif doesn't seem to support something in beta so hiding for now\n 'template-token': Flags.string({\n description: 'Used for accessing private GitHub repo templates',\n hidden: true,\n }),\n typescript: Flags.boolean({\n allowNo: true,\n default: undefined,\n description: 'Enable TypeScript support',\n exclusive: ['bare'],\n }),\n visibility: Flags.string({\n description: 'Visibility mode for dataset',\n helpValue: '<mode>',\n options: ['public', 'private'],\n }),\n yes: Flags.boolean({\n char: 'y',\n default: false,\n description:\n 'Unattended mode, answers \"yes\" to any \"yes/no\" prompt and otherwise uses defaults',\n }),\n }\n\n static telemetry = defineCommandTelemetry(this.flags, {\n redact: [\n 'template-token',\n 'template',\n 'git',\n 'env',\n 'output-path',\n 'project-name',\n 'create-project',\n 'coupon',\n ],\n })\n\n public async run(): Promise<void> {\n let mcpMode: 'auto' | 'prompt' | 'skip' = 'prompt'\n if (!this.flags.mcp || !this.resolveIsInteractive()) {\n mcpMode = 'skip'\n } else if (this.isUnattended()) {\n // Any unattended run (e.g. --yes, --json) configures MCP with defaults rather than prompting\n mcpMode = 'auto'\n }\n\n // Mirror MCP's environment gating: skip install in test environments\n // ensure e2e / CI tests don't run the bundled skills CLI.\n let skillsMode: 'auto' | 'prompt' | 'skip' = 'auto'\n if (!this.flags.skills || !this.resolveIsInteractive()) {\n skillsMode = 'skip'\n }\n\n try {\n await initAction(\n flagsToInitOptions(this.flags, this.isUnattended(), this.args, mcpMode, skillsMode),\n {\n output: this.output,\n telemetry: this.telemetry,\n workDir: process.cwd(),\n },\n )\n } catch (error) {\n if (error instanceof InitError) {\n this.error(error.message, {exit: error.exitCode})\n }\n throw error\n }\n }\n}\n"],"names":["Args","Flags","CLIError","SanityCommand","initAction","InitError","flagsToInitOptions","getProjectIdFlag","defineCommandTelemetry","InitCommand","args","type","string","hidden","description","enableJsonFlag","examples","command","flags","boolean","allowNo","default","exclusive","bare","coupon","helpValue","deprecated","message","dashboard","dataset","env","parse","input","startsWith","git","undefined","helpLabel","install","mcp","helpGroup","organization","options","semantics","provider","quickstart","reconfigure","version","skills","template","typescript","visibility","yes","char","telemetry","redact","run","mcpMode","resolveIsInteractive","isUnattended","skillsMode","output","workDir","process","cwd","error","exit","exitCode"],"mappings":"AAAA,SAAQA,IAAI,EAAWC,KAAK,QAAO,cAAa;AAChD,SAAQC,QAAQ,QAAO,qBAAoB;AAC3C,SAAQC,aAAa,QAAO,mBAAkB;AAE9C,SAAQC,UAAU,QAAO,gCAA+B;AACxD,SAAQC,SAAS,QAAO,+BAA8B;AACtD,SAAQC,kBAAkB,QAAO,2BAA0B;AAC3D,SAAQC,gBAAgB,QAAO,yBAAwB;AACvD,SAAQC,sBAAsB,QAAO,wCAAuC;AAE5E,OAAO,MAAMC,oBAAoBN;IAC/B,OAAgBO,OAAO;QAACC,MAAMX,KAAKY,MAAM,CAAC;YAACC,QAAQ;QAAI;IAAE,EAAC;IAC1D,OAAgBC,cAAc,qDAAoD;IAClF,OAAgBC,iBAAiB,KAAI;IAErC,OAAgBC,WAAW;QACzB;QACA;YACEC,SAAS;YACTH,aAAa;QACf;QACA;YACEG,SACE;YACFH,aAAa;QACf;QACA;YACEG,SACE;YACFH,aACE;QACJ;QACA;YACEG,SACE;YACFH,aAAa;QACf;KACD,CAAiC;IAElC,OAAgBI,QAAQ;QACtB,gBAAgBjB,MAAMkB,OAAO,CAAC;YAC5BC,SAAS;YACTC,SAAS;YACTP,aAAa;YACbQ,WAAW;gBAAC;aAAO;QACrB;QACAC,MAAMtB,MAAMkB,OAAO,CAAC;YAClBL,aACE;QACJ;QACAU,QAAQvB,MAAMW,MAAM,CAAC;YACnBE,aACE;YACFQ,WAAW;gBAAC;aAAe;YAC3BG,WAAW;QACb;QACA,kBAAkBxB,MAAMW,MAAM,CAAC;YAC7Bc,YAAY;gBAACC,SAAS;YAA4B;YAClDb,aAAa;YACbW,WAAW;YACXZ,QAAQ;QACV;QACAe,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"}
1
+ {"version":3,"sources":["../../src/commands/init.ts"],"sourcesContent":["import {Args, Command, Flags} from '@oclif/core'\nimport {CLIError} from '@oclif/core/errors'\nimport {SanityCommand} from '@sanity/cli-core'\n\nimport {initAction} from '../actions/init/initAction.js'\nimport {InitError} from '../actions/init/initError.js'\nimport {flagsToInitOptions} from '../actions/init/types.js'\nimport {getProjectIdFlag} from '../util/sharedFlags.js'\nimport {defineCommandTelemetry} from '../util/telemetry/commandTelemetry.js'\n\nexport class InitCommand extends SanityCommand<typeof InitCommand> {\n static override args = {type: Args.string({hidden: true})}\n static override description = 'Initialize a new Sanity Studio, project and/or app'\n static override enableJsonFlag = true\n\n static override examples = [\n '<%= config.bin %> <%= command.id %>',\n {\n command: '<%= config.bin %> <%= command.id %> --dataset-default',\n description: 'Initialize a new project with a public dataset named \"production\"',\n },\n {\n command:\n '<%= config.bin %> <%= command.id %> -y --project abc123 --dataset production --output-path ~/myproj',\n description: 'Initialize a project with the given project ID and dataset to the given path',\n },\n {\n command:\n '<%= config.bin %> <%= command.id %> -y --project abc123 --dataset staging --template moviedb --output-path .',\n description:\n 'Initialize a project with the given project ID and dataset using the moviedb template to the given path',\n },\n {\n command:\n '<%= config.bin %> <%= command.id %> -y --project-name \"Movies Unlimited\" --dataset moviedb --visibility private --template moviedb --output-path /Users/espenh/movies-unlimited',\n description: 'Create a brand new project with name \"Movies Unlimited\"',\n },\n ] satisfies Array<Command.Example>\n\n static override flags = {\n 'auto-updates': Flags.boolean({\n allowNo: true,\n default: true,\n description: 'Enable auto updates of studio versions',\n exclusive: ['bare'],\n }),\n bare: Flags.boolean({\n description:\n 'Skip the Studio initialization and only print the selected project ID and dataset name to stdout',\n }),\n coupon: Flags.string({\n description:\n 'Optionally select a coupon for a new project (cannot be used with --project-plan)',\n exclusive: ['project-plan'],\n helpValue: '<code>',\n }),\n 'create-project': Flags.string({\n deprecated: {message: 'Use --project-name instead'},\n description: 'Create a new project with the given name',\n helpValue: '<name>',\n hidden: true,\n }),\n dashboard: Flags.boolean({\n description: 'Set up the project to run in the Sanity Dashboard (beta)',\n exclusive: ['bare', 'env'],\n }),\n dataset: Flags.string({\n description: 'Dataset name for the studio',\n exclusive: ['dataset-default'],\n helpValue: '<name>',\n }),\n 'dataset-default': Flags.boolean({\n description: 'Set up a project with a public dataset named \"production\"',\n }),\n env: Flags.string({\n description: 'Write environment variables to file',\n exclusive: ['bare'],\n helpValue: '<filename>',\n parse: async (input) => {\n if (!input.startsWith('.env')) {\n throw new CLIError('Env filename (`--env`) must start with `.env`')\n }\n return input\n },\n }),\n 'from-create': Flags.boolean({\n description: 'Internal flag to indicate that the command is run from create-sanity',\n hidden: true,\n }),\n git: Flags.string({\n default: undefined,\n description: 'Specify a commit message for initial commit, or disable git init',\n exclusive: ['bare'],\n // oclif doesn't indent correctly with custom help labels, thus leading space :/\n helpLabel: ' --[no-]git',\n helpValue: '<message>',\n }),\n 'import-dataset': Flags.boolean({\n allowNo: true,\n default: undefined,\n description: 'Import template sample dataset',\n }),\n install: Flags.boolean({\n allowNo: true,\n default: true,\n description: 'Install dependencies after scaffolding',\n exclusive: ['bare'],\n }),\n mcp: Flags.boolean({\n allowNo: true,\n default: true,\n description: 'Enable AI editor integration (MCP) setup',\n }),\n 'nextjs-add-config-files': Flags.boolean({\n allowNo: true,\n default: undefined,\n description: 'Add config files to Next.js project',\n helpGroup: 'Next.js',\n }),\n 'nextjs-append-env': Flags.boolean({\n allowNo: true,\n default: undefined,\n description: 'Append project ID and dataset to .env file',\n helpGroup: 'Next.js',\n }),\n 'nextjs-embed-studio': Flags.boolean({\n allowNo: true,\n default: undefined,\n description: 'Embed the Studio in Next.js application',\n helpGroup: 'Next.js',\n }),\n // oclif doesn't support a boolean/string flag combination, but listing both a\n // `--git` and a `--no-git` flag in help breaks conventions, so we hide this one,\n // but use it to \"combine\" the two in the actual logic.\n 'no-git': Flags.boolean({\n description: 'Disable git initialization',\n exclusive: ['git'],\n hidden: true,\n }),\n organization: Flags.string({\n description:\n 'Organization ID to use for the project (required for unattended project creation)',\n helpValue: '<id>',\n }),\n 'output-path': Flags.string({\n description: 'Path to write studio project to',\n exclusive: ['bare'],\n helpValue: '<path>',\n }),\n 'overwrite-files': Flags.boolean({\n allowNo: true,\n default: undefined,\n description: 'Overwrite existing files',\n }),\n 'package-manager': Flags.string({\n description: 'Specify which package manager to use [allowed: npm, yarn, pnpm]',\n exclusive: ['bare'],\n helpValue: '<manager>',\n options: ['npm', 'yarn', 'pnpm'],\n }),\n ...getProjectIdFlag({\n description: 'Project ID to use for the studio',\n exclusive: ['create-project', 'project-name'],\n semantics: 'specify',\n }),\n 'project-name': Flags.string({\n description: 'Create a new project with the given name',\n exclusive: ['project', 'create-project'],\n helpValue: '<name>',\n }),\n 'project-plan': Flags.string({\n description: 'Optionally select a plan for a new project',\n helpValue: '<name>',\n }),\n provider: Flags.string({\n description: 'Login provider to use',\n helpValue: '<provider>',\n }),\n quickstart: Flags.boolean({\n deprecated: true,\n description:\n 'Used for initializing a project from a server schema that is saved in the Journey API',\n hidden: true,\n }),\n reconfigure: Flags.boolean({\n deprecated: {\n message: 'This flag is no longer supported',\n version: '3.0.0',\n },\n description: 'Reconfigure an existing project',\n hidden: true,\n }),\n skills: Flags.boolean({\n allowNo: true,\n default: true,\n description: 'Install Sanity agent skills globally for detected AI editors',\n }),\n template: Flags.string({\n description: 'Project template to use [default: \"clean\"]',\n exclusive: ['bare'],\n helpValue: '<template>',\n }),\n // Porting over a beta flag\n // Oclif doesn't seem to support something in beta so hiding for now\n 'template-token': Flags.string({\n description: 'Used for accessing private GitHub repo templates',\n hidden: true,\n }),\n typescript: Flags.boolean({\n allowNo: true,\n default: undefined,\n description: 'Enable TypeScript support',\n exclusive: ['bare'],\n }),\n visibility: Flags.string({\n description: 'Visibility mode for dataset',\n helpValue: '<mode>',\n options: ['public', 'private'],\n }),\n 'with-blueprints': Flags.boolean({\n description: 'Set up a Blueprint workspace',\n exclusive: ['bare', 'dashboard', 'env', 'template'],\n hidden: true,\n }),\n yes: Flags.boolean({\n char: 'y',\n default: false,\n description:\n 'Unattended mode, answers \"yes\" to any \"yes/no\" prompt and otherwise uses defaults',\n }),\n }\n\n static telemetry = defineCommandTelemetry(this.flags, {\n redact: [\n 'template-token',\n 'template',\n 'git',\n 'env',\n 'output-path',\n 'project-name',\n 'create-project',\n 'coupon',\n ],\n })\n\n public async run(): Promise<void> {\n let mcpMode: 'auto' | 'prompt' | 'skip' = 'prompt'\n if (!this.flags.mcp || !this.resolveIsInteractive()) {\n mcpMode = 'skip'\n } else if (this.isUnattended()) {\n // Any unattended run (e.g. --yes, --json) configures MCP with defaults rather than prompting\n mcpMode = 'auto'\n }\n\n // Mirror MCP's environment gating: skip install in test environments\n // ensure e2e / CI tests don't run the bundled skills CLI.\n let skillsMode: 'auto' | 'prompt' | 'skip' = 'auto'\n if (!this.flags.skills || !this.resolveIsInteractive()) {\n skillsMode = 'skip'\n }\n\n try {\n await initAction(\n flagsToInitOptions(this.flags, this.isUnattended(), this.args, mcpMode, skillsMode),\n {\n output: this.output,\n telemetry: this.telemetry,\n workDir: process.cwd(),\n },\n )\n } catch (error) {\n if (error instanceof InitError) {\n this.error(error.message, {exit: error.exitCode})\n }\n throw error\n }\n }\n}\n"],"names":["Args","Flags","CLIError","SanityCommand","initAction","InitError","flagsToInitOptions","getProjectIdFlag","defineCommandTelemetry","InitCommand","args","type","string","hidden","description","enableJsonFlag","examples","command","flags","boolean","allowNo","default","exclusive","bare","coupon","helpValue","deprecated","message","dashboard","dataset","env","parse","input","startsWith","git","undefined","helpLabel","install","mcp","helpGroup","organization","options","semantics","provider","quickstart","reconfigure","version","skills","template","typescript","visibility","yes","char","telemetry","redact","run","mcpMode","resolveIsInteractive","isUnattended","skillsMode","output","workDir","process","cwd","error","exit","exitCode"],"mappings":"AAAA,SAAQA,IAAI,EAAWC,KAAK,QAAO,cAAa;AAChD,SAAQC,QAAQ,QAAO,qBAAoB;AAC3C,SAAQC,aAAa,QAAO,mBAAkB;AAE9C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;aAAW;YACnDT,QAAQ;QACV;QACAsC,KAAKlD,MAAMkB,OAAO,CAAC;YACjBiC,MAAM;YACN/B,SAAS;YACTP,aACE;QACJ;IACF,EAAC;IAED,OAAOuC,YAAY7C,uBAAuB,IAAI,CAACU,KAAK,EAAE;QACpDoC,QAAQ;YACN;YACA;YACA;YACA;YACA;YACA;YACA;YACA;SACD;IACH,GAAE;IAEF,MAAaC,MAAqB;QAChC,IAAIC,UAAsC;QAC1C,IAAI,CAAC,IAAI,CAACtC,KAAK,CAACoB,GAAG,IAAI,CAAC,IAAI,CAACmB,oBAAoB,IAAI;YACnDD,UAAU;QACZ,OAAO,IAAI,IAAI,CAACE,YAAY,IAAI;YAC9B,6FAA6F;YAC7FF,UAAU;QACZ;QAEA,qEAAqE;QACrE,0DAA0D;QAC1D,IAAIG,aAAyC;QAC7C,IAAI,CAAC,IAAI,CAACzC,KAAK,CAAC6B,MAAM,IAAI,CAAC,IAAI,CAACU,oBAAoB,IAAI;YACtDE,aAAa;QACf;QAEA,IAAI;YACF,MAAMvD,WACJE,mBAAmB,IAAI,CAACY,KAAK,EAAE,IAAI,CAACwC,YAAY,IAAI,IAAI,CAAChD,IAAI,EAAE8C,SAASG,aACxE;gBACEC,QAAQ,IAAI,CAACA,MAAM;gBACnBP,WAAW,IAAI,CAACA,SAAS;gBACzBQ,SAASC,QAAQC,GAAG;YACtB;QAEJ,EAAE,OAAOC,OAAO;YACd,IAAIA,iBAAiB3D,WAAW;gBAC9B,IAAI,CAAC2D,KAAK,CAACA,MAAMrC,OAAO,EAAE;oBAACsC,MAAMD,MAAME,QAAQ;gBAAA;YACjD;YACA,MAAMF;QACR;IACF;AACF"}
@@ -73,7 +73,7 @@ const NOT_A_CONFIG_APP = 'This command must be run inside a Media Library config
73
73
  throw err;
74
74
  }
75
75
  const config = resolveWorkbenchConfig(cliConfig);
76
- if (!config) {
76
+ if (config?.appType !== 'media-library') {
77
77
  this.error(NOT_A_CONFIG_APP, {
78
78
  exit: exitCodes.RUNTIME_ERROR
79
79
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/commands/media/prune-aspect-data.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {Args, Flags} from '@oclif/core'\nimport {\n type CliConfig,\n exitCodes,\n ProjectRootNotFoundError,\n SanityCommand,\n subdebug,\n} from '@sanity/cli-core'\nimport {getErrorMessage} from '@sanity/cli-core/errors'\nimport {logSymbols, spinner} from '@sanity/cli-core/ux'\nimport {resolveWorkbenchConfig} from '@sanity/workbench-cli/deploy'\n\nimport {VALID_ASPECT_NAME} from '../../actions/media/aspectName.js'\nimport {resolveMediaLibraryId} from '../../actions/media/resolveMediaLibraryId.js'\nimport {\n getAspectDataCarrierIds,\n getStoredAspectIds,\n unsetAspectData,\n} from '../../services/mediaLibraries.js'\nimport {pluralize} from '../../util/pluralize.js'\n\nconst pruneAspectDataDebug = subdebug('media:prune-aspect-data')\n\nconst NOT_A_CONFIG_APP =\n 'This command must be run inside a Media Library config app — a project whose ' +\n '`sanity.cli.ts` declares `unstable_defineMediaLibrary(...)`. Scaffold one with ' +\n '`sanity init --template media-library-config`.'\n\n/** Unset-patch batch size per mutate request. */\nconst BATCH_SIZE = 100\n\n/** How many carrier ids the report lists before truncating. */\nconst SAMPLE_SIZE = 10\n\n/**\n * The deliberate, explicitly-invoked counterpart to the deploy-time aspect\n * sync: deploying a config only mirrors aspect *definitions* — `aspects.<name>`\n * values on assets are never touched and resurface if a matching field comes\n * back. This command removes that data. Irreversible fan-out mutation, so it\n * never asks for confirmation: without `--yes` it only reports what would change.\n */\nexport class MediaPruneAspectDataCommand extends SanityCommand<typeof MediaPruneAspectDataCommand> {\n static override args = {\n aspectName: Args.string({\n description: 'Name of the aspect whose data to remove from all assets',\n required: true,\n }),\n }\n\n static override description =\n \"Irreversibly remove an aspect's data (aspects.<name> values) from every asset of a media library\"\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %> legacyAspect',\n description: 'Report which assets carry aspects.legacyAspect (changes nothing)',\n },\n {\n command: '<%= config.bin %> <%= command.id %> legacyAspect --yes',\n description: 'Remove aspects.legacyAspect from every asset that carries it',\n },\n ]\n\n static override flags = {\n 'media-library-id': Flags.string({\n description:\n 'The id of the media library to prune (defaults to the single active library of the configured organization)',\n }),\n yes: Flags.boolean({\n char: 'y',\n description:\n 'Execute the prune. Without this flag the command only reports what would change',\n }),\n }\n\n // Part of the beta config-app flow: the command requires a config app to\n // resolve its organization, so listing it in the general help would only\n // route legacy-flow users into the beta paradigm. The prune itself is\n // paradigm-neutral (it only unsets asset data) — when there is demand from\n // the legacy flow, ungate it from the config app and unhide it.\n static override hidden = true\n\n public async run(): Promise<void> {\n const {aspectName} = this.args\n const {'media-library-id': mediaLibraryIdFlag, yes = false} = this.flags\n\n // The name rule shared with the sync contract; also makes the\n // interpolation into the carrier GROQ filter injection-safe.\n if (!VALID_ASPECT_NAME.test(aspectName)) {\n this.error(`\"${aspectName}\" is not a valid aspect name (${VALID_ASPECT_NAME})`, {\n exit: exitCodes.USAGE_ERROR,\n })\n }\n\n let cliConfig: CliConfig\n try {\n cliConfig = await this.getCliConfig()\n } catch (err) {\n if (err instanceof ProjectRootNotFoundError) {\n this.error(NOT_A_CONFIG_APP, {exit: exitCodes.RUNTIME_ERROR})\n }\n throw err\n }\n\n const config = resolveWorkbenchConfig(cliConfig)\n if (!config) {\n this.error(NOT_A_CONFIG_APP, {exit: exitCodes.RUNTIME_ERROR})\n }\n\n try {\n // Not `isUnattended()`: that treats `--yes` as unattended, but here\n // `--yes` consents to the prune, not to skipping prompts — the report\n // path literally instructs \"Re-run with --yes\", and that run must still\n // offer the library picker in a multi-library organization. Only a\n // genuinely non-interactive run (CI, piped stdin) must not prompt.\n const mediaLibraryId = await resolveMediaLibraryId({\n mediaLibraryIdFlag,\n organizationId: config.organizationId,\n unattended: !this.resolveIsInteractive(),\n })\n\n const spin = spinner('Finding assets that carry the aspect').start()\n let storedIds: string[]\n let carriers: string[]\n try {\n storedIds = await getStoredAspectIds(mediaLibraryId, 'prune-aspect-data')\n carriers = await getAspectDataCarrierIds(mediaLibraryId, aspectName)\n } finally {\n // Also on failure — a spinner left running garbles the error output.\n spin.stop()\n }\n\n // Guardrails, not gates: pruning while either is true can be deliberate\n // (e.g. clearing data before re-shaping a field), so warn and continue.\n if (config.fields.some((field) => field.name === aspectName)) {\n this.warn(\n `\"${aspectName}\" is still declared in sanity.cli.ts — its data is likely in active use and will grow back.`,\n )\n }\n if (storedIds.includes(aspectName)) {\n this.warn(\n `Aspect definition \"${aspectName}\" still exists in the library — this only removes data, not the definition.`,\n )\n }\n\n if (carriers.length === 0) {\n this.log(\n `No assets in media library ${styleText('bold', mediaLibraryId)} carry ${styleText(\n 'bold',\n `aspects.${aspectName}`,\n )} — nothing to prune.`,\n )\n return\n }\n\n const sample = carriers.slice(0, SAMPLE_SIZE)\n // \"documents\", not \"assets\": under the raw perspective drafts and\n // release versions are separate ids, so an asset count would overstate.\n this.log(\n `${styleText('bold', String(carriers.length))} ${pluralize(\n 'document',\n carriers.length,\n )} in media library ${styleText('bold', mediaLibraryId)} ${\n carriers.length === 1 ? 'carries' : 'carry'\n } ${styleText('bold', `aspects.${aspectName}`)}:`,\n )\n for (const id of sample) {\n this.log(` - ${id}`)\n }\n if (carriers.length > sample.length) {\n this.log(styleText('dim', ` … and ${carriers.length - sample.length} more`))\n }\n\n if (!yes) {\n this.log('')\n this.log(\n `This would ${styleText(\n 'bold',\n 'irreversibly',\n )} unset aspects.${aspectName} on all of them. Re-run with ${styleText(\n 'bold',\n '--yes',\n )} to execute.`,\n )\n return\n }\n\n let pruned = 0\n for (let offset = 0; offset < carriers.length; offset += BATCH_SIZE) {\n const batch = carriers.slice(offset, offset + BATCH_SIZE)\n try {\n await unsetAspectData({aspectName, assetIds: batch, mediaLibraryId})\n } catch (batchError) {\n // The progress made so far must survive into the error: re-running\n // is safe (pruned assets no longer match the carrier query), so the\n // message says how far it got and that a retry finishes the rest.\n throw new Error(\n `Removed aspects.${aspectName} from ${pruned} of ${carriers.length} ${pluralize(\n 'document',\n carriers.length,\n )} before a batch failed: ${getErrorMessage(batchError)}\\n` +\n `Re-running the command with --yes is safe — already-pruned documents no longer ` +\n `match and only the remaining ${carriers.length - pruned} will be mutated.`,\n {cause: batchError},\n )\n }\n pruned += batch.length\n this.log(styleText('dim', ` pruned ${pruned}/${carriers.length}`))\n }\n\n this.log('')\n this.log(\n `${logSymbols.success} aspects.${aspectName} removed from ${pruned} ${pluralize(\n 'document',\n pruned,\n )}.`,\n )\n } catch (error) {\n const err = error as Error\n // Ctrl+C in the library prompt and errors that already carry their exit\n // story (`this.error`, CLIError from the resolver) pass through to\n // `SanityCommand.catch` instead of being re-wrapped here.\n if (err.name === 'ExitPromptError' || 'oclif' in err) {\n throw err\n }\n pruneAspectDataDebug('Failed to prune aspect data', {\n aspectName,\n error: err,\n })\n this.error(\n styleText('bold', 'Failed to prune aspect data') + `\\n\\n${styleText('red', err.message)}`,\n {exit: exitCodes.RUNTIME_ERROR},\n )\n }\n }\n}\n"],"names":["styleText","Args","Flags","exitCodes","ProjectRootNotFoundError","SanityCommand","subdebug","getErrorMessage","logSymbols","spinner","resolveWorkbenchConfig","VALID_ASPECT_NAME","resolveMediaLibraryId","getAspectDataCarrierIds","getStoredAspectIds","unsetAspectData","pluralize","pruneAspectDataDebug","NOT_A_CONFIG_APP","BATCH_SIZE","SAMPLE_SIZE","MediaPruneAspectDataCommand","args","aspectName","string","description","required","examples","command","flags","yes","boolean","char","hidden","run","mediaLibraryIdFlag","test","error","exit","USAGE_ERROR","cliConfig","getCliConfig","err","RUNTIME_ERROR","config","mediaLibraryId","organizationId","unattended","resolveIsInteractive","spin","start","storedIds","carriers","stop","fields","some","field","name","warn","includes","length","log","sample","slice","String","id","pruned","offset","batch","assetIds","batchError","Error","cause","success","message"],"mappings":"AAAA,SAAQA,SAAS,QAAO,YAAW;AAEnC,SAAQC,IAAI,EAAEC,KAAK,QAAO,cAAa;AACvC,SAEEC,SAAS,EACT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{styleText} from 'node:util'\n\nimport {Args, Flags} from '@oclif/core'\nimport {\n type CliConfig,\n exitCodes,\n ProjectRootNotFoundError,\n SanityCommand,\n subdebug,\n} from '@sanity/cli-core'\nimport {getErrorMessage} from '@sanity/cli-core/errors'\nimport {logSymbols, spinner} from '@sanity/cli-core/ux'\nimport {resolveWorkbenchConfig} from '@sanity/workbench-cli/deploy'\n\nimport {VALID_ASPECT_NAME} from '../../actions/media/aspectName.js'\nimport {resolveMediaLibraryId} from '../../actions/media/resolveMediaLibraryId.js'\nimport {\n getAspectDataCarrierIds,\n getStoredAspectIds,\n unsetAspectData,\n} from '../../services/mediaLibraries.js'\nimport {pluralize} from '../../util/pluralize.js'\n\nconst pruneAspectDataDebug = subdebug('media:prune-aspect-data')\n\nconst NOT_A_CONFIG_APP =\n 'This command must be run inside a Media Library config app — a project whose ' +\n '`sanity.cli.ts` declares `unstable_defineMediaLibrary(...)`. Scaffold one with ' +\n '`sanity init --template media-library-config`.'\n\n/** Unset-patch batch size per mutate request. */\nconst BATCH_SIZE = 100\n\n/** How many carrier ids the report lists before truncating. */\nconst SAMPLE_SIZE = 10\n\n/**\n * The deliberate, explicitly-invoked counterpart to the deploy-time aspect\n * sync: deploying a config only mirrors aspect *definitions* — `aspects.<name>`\n * values on assets are never touched and resurface if a matching field comes\n * back. This command removes that data. Irreversible fan-out mutation, so it\n * never asks for confirmation: without `--yes` it only reports what would change.\n */\nexport class MediaPruneAspectDataCommand extends SanityCommand<typeof MediaPruneAspectDataCommand> {\n static override args = {\n aspectName: Args.string({\n description: 'Name of the aspect whose data to remove from all assets',\n required: true,\n }),\n }\n\n static override description =\n \"Irreversibly remove an aspect's data (aspects.<name> values) from every asset of a media library\"\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %> legacyAspect',\n description: 'Report which assets carry aspects.legacyAspect (changes nothing)',\n },\n {\n command: '<%= config.bin %> <%= command.id %> legacyAspect --yes',\n description: 'Remove aspects.legacyAspect from every asset that carries it',\n },\n ]\n\n static override flags = {\n 'media-library-id': Flags.string({\n description:\n 'The id of the media library to prune (defaults to the single active library of the configured organization)',\n }),\n yes: Flags.boolean({\n char: 'y',\n description:\n 'Execute the prune. Without this flag the command only reports what would change',\n }),\n }\n\n // Part of the beta config-app flow: the command requires a config app to\n // resolve its organization, so listing it in the general help would only\n // route legacy-flow users into the beta paradigm. The prune itself is\n // paradigm-neutral (it only unsets asset data) — when there is demand from\n // the legacy flow, ungate it from the config app and unhide it.\n static override hidden = true\n\n public async run(): Promise<void> {\n const {aspectName} = this.args\n const {'media-library-id': mediaLibraryIdFlag, yes = false} = this.flags\n\n // The name rule shared with the sync contract; also makes the\n // interpolation into the carrier GROQ filter injection-safe.\n if (!VALID_ASPECT_NAME.test(aspectName)) {\n this.error(`\"${aspectName}\" is not a valid aspect name (${VALID_ASPECT_NAME})`, {\n exit: exitCodes.USAGE_ERROR,\n })\n }\n\n let cliConfig: CliConfig\n try {\n cliConfig = await this.getCliConfig()\n } catch (err) {\n if (err instanceof ProjectRootNotFoundError) {\n this.error(NOT_A_CONFIG_APP, {exit: exitCodes.RUNTIME_ERROR})\n }\n throw err\n }\n\n const config = resolveWorkbenchConfig(cliConfig)\n if (config?.appType !== 'media-library') {\n this.error(NOT_A_CONFIG_APP, {exit: exitCodes.RUNTIME_ERROR})\n }\n\n try {\n // Not `isUnattended()`: that treats `--yes` as unattended, but here\n // `--yes` consents to the prune, not to skipping prompts — the report\n // path literally instructs \"Re-run with --yes\", and that run must still\n // offer the library picker in a multi-library organization. Only a\n // genuinely non-interactive run (CI, piped stdin) must not prompt.\n const mediaLibraryId = await resolveMediaLibraryId({\n mediaLibraryIdFlag,\n organizationId: config.organizationId,\n unattended: !this.resolveIsInteractive(),\n })\n\n const spin = spinner('Finding assets that carry the aspect').start()\n let storedIds: string[]\n let carriers: string[]\n try {\n storedIds = await getStoredAspectIds(mediaLibraryId, 'prune-aspect-data')\n carriers = await getAspectDataCarrierIds(mediaLibraryId, aspectName)\n } finally {\n // Also on failure — a spinner left running garbles the error output.\n spin.stop()\n }\n\n // Guardrails, not gates: pruning while either is true can be deliberate\n // (e.g. clearing data before re-shaping a field), so warn and continue.\n if (config.fields.some((field) => field.name === aspectName)) {\n this.warn(\n `\"${aspectName}\" is still declared in sanity.cli.ts — its data is likely in active use and will grow back.`,\n )\n }\n if (storedIds.includes(aspectName)) {\n this.warn(\n `Aspect definition \"${aspectName}\" still exists in the library — this only removes data, not the definition.`,\n )\n }\n\n if (carriers.length === 0) {\n this.log(\n `No assets in media library ${styleText('bold', mediaLibraryId)} carry ${styleText(\n 'bold',\n `aspects.${aspectName}`,\n )} — nothing to prune.`,\n )\n return\n }\n\n const sample = carriers.slice(0, SAMPLE_SIZE)\n // \"documents\", not \"assets\": under the raw perspective drafts and\n // release versions are separate ids, so an asset count would overstate.\n this.log(\n `${styleText('bold', String(carriers.length))} ${pluralize(\n 'document',\n carriers.length,\n )} in media library ${styleText('bold', mediaLibraryId)} ${\n carriers.length === 1 ? 'carries' : 'carry'\n } ${styleText('bold', `aspects.${aspectName}`)}:`,\n )\n for (const id of sample) {\n this.log(` - ${id}`)\n }\n if (carriers.length > sample.length) {\n this.log(styleText('dim', ` … and ${carriers.length - sample.length} more`))\n }\n\n if (!yes) {\n this.log('')\n this.log(\n `This would ${styleText(\n 'bold',\n 'irreversibly',\n )} unset aspects.${aspectName} on all of them. Re-run with ${styleText(\n 'bold',\n '--yes',\n )} to execute.`,\n )\n return\n }\n\n let pruned = 0\n for (let offset = 0; offset < carriers.length; offset += BATCH_SIZE) {\n const batch = carriers.slice(offset, offset + BATCH_SIZE)\n try {\n await unsetAspectData({aspectName, assetIds: batch, mediaLibraryId})\n } catch (batchError) {\n // The progress made so far must survive into the error: re-running\n // is safe (pruned assets no longer match the carrier query), so the\n // message says how far it got and that a retry finishes the rest.\n throw new Error(\n `Removed aspects.${aspectName} from ${pruned} of ${carriers.length} ${pluralize(\n 'document',\n carriers.length,\n )} before a batch failed: ${getErrorMessage(batchError)}\\n` +\n `Re-running the command with --yes is safe — already-pruned documents no longer ` +\n `match and only the remaining ${carriers.length - pruned} will be mutated.`,\n {cause: batchError},\n )\n }\n pruned += batch.length\n this.log(styleText('dim', ` pruned ${pruned}/${carriers.length}`))\n }\n\n this.log('')\n this.log(\n `${logSymbols.success} aspects.${aspectName} removed from ${pruned} ${pluralize(\n 'document',\n pruned,\n )}.`,\n )\n } catch (error) {\n const err = error as Error\n // Ctrl+C in the library prompt and errors that already carry their exit\n // story (`this.error`, CLIError from the resolver) pass through to\n // `SanityCommand.catch` instead of being re-wrapped here.\n if (err.name === 'ExitPromptError' || 'oclif' in err) {\n throw err\n }\n pruneAspectDataDebug('Failed to prune aspect data', {\n aspectName,\n error: err,\n })\n this.error(\n styleText('bold', 'Failed to prune aspect data') + `\\n\\n${styleText('red', err.message)}`,\n {exit: exitCodes.RUNTIME_ERROR},\n )\n }\n }\n}\n"],"names":["styleText","Args","Flags","exitCodes","ProjectRootNotFoundError","SanityCommand","subdebug","getErrorMessage","logSymbols","spinner","resolveWorkbenchConfig","VALID_ASPECT_NAME","resolveMediaLibraryId","getAspectDataCarrierIds","getStoredAspectIds","unsetAspectData","pluralize","pruneAspectDataDebug","NOT_A_CONFIG_APP","BATCH_SIZE","SAMPLE_SIZE","MediaPruneAspectDataCommand","args","aspectName","string","description","required","examples","command","flags","yes","boolean","char","hidden","run","mediaLibraryIdFlag","test","error","exit","USAGE_ERROR","cliConfig","getCliConfig","err","RUNTIME_ERROR","config","appType","mediaLibraryId","organizationId","unattended","resolveIsInteractive","spin","start","storedIds","carriers","stop","fields","some","field","name","warn","includes","length","log","sample","slice","String","id","pruned","offset","batch","assetIds","batchError","Error","cause","success","message"],"mappings":"AAAA,SAAQA,SAAS,QAAO,YAAW;AAEnC,SAAQC,IAAI,EAAEC,KAAK,QAAO,cAAa;AACvC,SAEEC,SAAS,EACTC,wBAAwB,EACxBC,aAAa,EACbC,QAAQ,QACH,mBAAkB;AACzB,SAAQC,eAAe,QAAO,0BA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vB;oBAAc;gBACpE,EAAE,OAAOyB,YAAY;oBACnB,mEAAmE;oBACnE,oEAAoE;oBACpE,kEAAkE;oBAClE,MAAM,IAAIC,MACR,CAAC,gBAAgB,EAAEjD,WAAW,MAAM,EAAE4C,OAAO,IAAI,EAAEd,SAASQ,MAAM,CAAC,CAAC,EAAE7C,UACpE,YACAqC,SAASQ,MAAM,EACf,wBAAwB,EAAEtD,gBAAgBgE,YAAY,EAAE,CAAC,GACzD,CAAC,+EAA+E,CAAC,GACjF,CAAC,6BAA6B,EAAElB,SAASQ,MAAM,GAAGM,OAAO,iBAAiB,CAAC,EAC7E;wBAACM,OAAOF;oBAAU;gBAEtB;gBACAJ,UAAUE,MAAMR,MAAM;gBACtB,IAAI,CAACC,GAAG,CAAC9D,UAAU,OAAO,CAAC,SAAS,EAAEmE,OAAO,CAAC,EAAEd,SAASQ,MAAM,EAAE;YACnE;YAEA,IAAI,CAACC,GAAG,CAAC;YACT,IAAI,CAACA,GAAG,CACN,GAAGtD,WAAWkE,OAAO,CAAC,SAAS,EAAEnD,WAAW,cAAc,EAAE4C,OAAO,CAAC,EAAEnD,UACpE,YACAmD,QACA,CAAC,CAAC;QAER,EAAE,OAAO9B,OAAO;YACd,MAAMK,MAAML;YACZ,wEAAwE;YACxE,mEAAmE;YACnE,0DAA0D;YAC1D,IAAIK,IAAIgB,IAAI,KAAK,qBAAqB,WAAWhB,KAAK;gBACpD,MAAMA;YACR;YACAzB,qBAAqB,+BAA+B;gBAClDM;gBACAc,OAAOK;YACT;YACA,IAAI,CAACL,KAAK,CACRrC,UAAU,QAAQ,iCAAiC,CAAC,IAAI,EAAEA,UAAU,OAAO0C,IAAIiC,OAAO,GAAG,EACzF;gBAACrC,MAAMnC,UAAUwC,aAAa;YAAA;QAElC;IACF;AACF"}
@@ -67,7 +67,7 @@ export class MediaPullAspectsCommand extends SanityCommand {
67
67
  throw err;
68
68
  }
69
69
  const config = resolveWorkbenchConfig(cliConfig);
70
- if (!config) {
70
+ if (config?.appType !== 'media-library') {
71
71
  this.error(NOT_A_CONFIG_APP, {
72
72
  exit: exitCodes.RUNTIME_ERROR
73
73
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/commands/media/pull-aspects.ts"],"sourcesContent":["import {access, mkdir, readFile, writeFile} from 'node:fs/promises'\nimport path from 'node:path'\nimport {styleText} from 'node:util'\n\nimport {Flags} from '@oclif/core'\nimport {\n type CliConfig,\n exitCodes,\n ProjectRootNotFoundError,\n SanityCommand,\n subdebug,\n} from '@sanity/cli-core'\nimport {confirm, logSymbols, spinner} from '@sanity/cli-core/ux'\nimport {resolveWorkbenchConfig} from '@sanity/workbench-cli/deploy'\n\nimport {appendFieldEntries} from '../../actions/media/cliConfigFields.js'\nimport {\n convertAspectDocuments,\n formatFieldEntries,\n type GeneratedFieldModule,\n type SkippedAspect,\n} from '../../actions/media/pullAspects.js'\nimport {resolveMediaLibraryId} from '../../actions/media/resolveMediaLibraryId.js'\nimport {getAspects} from '../../services/mediaLibraries.js'\nimport {pluralize} from '../../util/pluralize.js'\nimport {defineCommandTelemetry} from '../../util/telemetry/commandTelemetry.js'\n\nconst pullAspectsDebug = subdebug('media:pull-aspects')\n\nconst NOT_A_CONFIG_APP =\n 'This command must be run inside a Media Library config app — a project whose ' +\n '`sanity.cli.ts` declares `unstable_defineMediaLibrary(...)`. Scaffold one with ' +\n '`sanity init --template media-library-config`.'\n\nconst flags = {\n 'media-library-id': Flags.string({\n description:\n 'The id of the media library to pull from (defaults to the single active library of the configured organization)',\n }),\n 'out-dir': Flags.string({\n default: 'src/fields',\n description: 'Directory to write the generated field modules to, relative to the project root',\n }),\n overwrite: Flags.boolean({\n description:\n 'Overwrite existing field modules and re-generate fields already declared in the config',\n }),\n 'update-config': Flags.boolean({\n allowNo: true,\n description:\n 'Declare the generated fields in sanity.cli.ts (--no-update-config to skip). Prompted when omitted; unattended runs only print the entries',\n }),\n}\n\n/**\n * The outcome of offering to declare the generated fields in `sanity.cli.ts`:\n * written, turned down (flag, prompt, or unattended), or not writable (the\n * config shape could not be edited safely — the `reason` says why).\n */\ntype Registration = 'added' | 'declined' | {reason: string}\n\nexport class MediaPullAspectsCommand extends SanityCommand<typeof MediaPullAspectsCommand> {\n static override description =\n \"Generate field modules from a media library's stored aspect documents\"\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %>',\n description: 'Generate src/fields/<name>.tsx modules from the stored aspects',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --media-library-id ml123 --overwrite',\n description: 'Pull from a specific media library, overwriting existing modules',\n },\n ]\n\n static override flags = flags\n\n // Part of the beta config-app flow: only usable inside a config app (like\n // the unlisted media-library-config init template, which points to it), and\n // listing it next to the legacy aspect commands would mix the two\n // paradigms. Unhide when the config app leaves beta.\n static override hidden = true\n\n // --out-dir is a local filesystem path.\n static telemetry = defineCommandTelemetry(flags, {redact: ['out-dir']})\n\n public async run(): Promise<void> {\n const {\n 'media-library-id': mediaLibraryIdFlag,\n 'out-dir': outDir,\n overwrite = false,\n } = this.flags\n\n let cliConfig: CliConfig\n try {\n cliConfig = await this.getCliConfig()\n } catch (err) {\n if (err instanceof ProjectRootNotFoundError) {\n this.error(NOT_A_CONFIG_APP, {exit: exitCodes.RUNTIME_ERROR})\n }\n throw err\n }\n\n const config = resolveWorkbenchConfig(cliConfig)\n if (!config) {\n this.error(NOT_A_CONFIG_APP, {exit: exitCodes.RUNTIME_ERROR})\n }\n\n const root = await this.getProjectRoot()\n // The generated `src:` entries and the ownership story both assume the\n // modules live inside the project; a path escaping the root is a mistake.\n // `outDirRelative` (not the raw flag) feeds the report so an absolute\n // --out-dir inside the root still prints proper relative `src:` entries.\n const outDirAbsolute = path.resolve(root.directory, outDir)\n const outDirRelative = path.relative(root.directory, outDirAbsolute)\n if (\n path.isAbsolute(outDirRelative) ||\n outDirRelative === '..' ||\n outDirRelative.startsWith(`..${path.sep}`)\n ) {\n this.error(`--out-dir must stay inside the project root (got \"${outDir}\")`, {\n exit: exitCodes.USAGE_ERROR,\n })\n }\n\n try {\n const mediaLibraryId = await resolveMediaLibraryId({\n mediaLibraryIdFlag,\n organizationId: config.organizationId,\n unattended: this.isUnattended(),\n })\n\n const spin = spinner('Fetching stored aspect documents').start()\n let documents: Awaited<ReturnType<typeof getAspects>>\n try {\n documents = await getAspects(mediaLibraryId)\n } finally {\n // Also on failure — a spinner left running garbles the error output.\n spin.stop()\n }\n\n if (documents.length === 0) {\n this.log(\n `Media library ${styleText('bold', mediaLibraryId)} has no stored aspects — nothing to pull.`,\n )\n return\n }\n\n // Names already declared in the config are owned by existing field\n // modules; pulling the stored mirror back over them would regress local\n // edits, so they are skipped unless --overwrite says otherwise.\n const configuredNames = new Set(config.fields.map((field) => field.name))\n const configuredSrcByName = new Map(config.fields.map((field) => [field.name, field.src]))\n\n // One module per field name; name collisions and invalid documents are skipped.\n const {modules: winners, skipped} = convertAspectDocuments(documents)\n\n const generated: GeneratedFieldModule[] = []\n // Module name -> written path relative to the project root, so the\n // report shows where each module actually landed.\n const writtenPaths = new Map<string, string>()\n // Module name -> path of a module skipped because it already exists on\n // disk. Those fields may still be undeclared and need registration.\n const existingPaths = new Map<string, string>()\n for (const module of winners) {\n if (!overwrite && configuredNames.has(module.name)) {\n skipped.push({\n id: module.name,\n reasons: ['Already declared in sanity.cli.ts (pass --overwrite to re-generate)'],\n status: 'skipped',\n validationErrors: [],\n })\n continue\n }\n\n const defaultDestination = path.join(outDirAbsolute, module.filename)\n // The pull generates `.tsx`, but a hand-written module for the same\n // field may be plain `.ts` — treat both as taken.\n const existing = await firstExisting([\n defaultDestination,\n defaultDestination.replace(/\\.tsx$/, '.ts'),\n ])\n if (!overwrite && existing) {\n // The file is left alone, but the field is undeclared (declared\n // names were skipped above) — so it still joins the registration\n // offer below. An on-disk module without a config entry is exactly\n // the state the next deploy punishes, however the file got there.\n existingPaths.set(module.name, path.relative(root.directory, existing))\n skipped.push({\n id: module.name,\n reasons: [\n `A file already exists at ${path.relative(root.directory, existing)} (pass --overwrite to replace it)`,\n ],\n status: 'skipped',\n validationErrors: [],\n })\n continue\n }\n\n // When overwriting a field the config already declares, the module\n // must land at the declared `src` path — writing <out-dir>/<name>.tsx\n // instead would orphan the new file while deploy keeps evaluating the\n // old one. Failing that, replace the module found on disk (which may\n // be the .ts variant), and only then fall back to the default.\n const declaredSrc = overwrite ? configuredSrcByName.get(module.name) : undefined\n const destination = declaredSrc\n ? await resolveDeclaredSrc(path.resolve(root.directory, declaredSrc), module.filename)\n : (existing ?? defaultDestination)\n\n await mkdir(path.dirname(destination), {recursive: true})\n await writeFile(destination, module.source)\n writtenPaths.set(module.name, path.relative(root.directory, destination))\n generated.push(module)\n }\n\n // Fields present locally — written this run or already on disk — but not\n // declared get offered for registration: the deploy mirrors config to\n // stored documents, so an undeclared stored aspect is deleted by the\n // next deploy — leaving the entries unpasted is a data hazard, not just\n // friction. Existing files count because a prior pull may have been\n // declined (or edited by hand): the file being there does not make the\n // field declared.\n const entryPaths = new Map([...writtenPaths, ...existingPaths])\n const newEntries = winners.filter(\n (module) => !configuredNames.has(module.name) && entryPaths.has(module.name),\n )\n const entryLines =\n newEntries.length > 0\n ? formatFieldEntries(newEntries, outDirRelative, entryPaths).split('\\n')\n : []\n const registration =\n newEntries.length > 0\n ? await this.maybeRegisterFields({configPath: root.path, entryLines})\n : null\n\n this.report({\n configuredNames,\n entryLines,\n generated,\n newEntries,\n outDir: outDirRelative,\n registration,\n skipped,\n writtenPaths,\n })\n } catch (error) {\n // Ctrl+C on the library prompt and errors that already carry their exit\n // code (`this.error` inside helpers) pass through to SanityCommand.catch.\n if (error instanceof Error && error.name === 'ExitPromptError') throw error\n if (error && typeof error === 'object' && 'oclif' in error) throw error\n const err = error as Error\n pullAspectsDebug('Failed to pull aspects', {error: err, mediaLibraryId: mediaLibraryIdFlag})\n this.error(\n styleText('bold', 'Failed to pull aspects') + `\\n\\n${styleText('red', err.message)}`,\n {exit: exitCodes.RUNTIME_ERROR},\n )\n }\n }\n\n /**\n * Offer to declare the generated fields in `sanity.cli.ts`. `--update-config`\n * / `--no-update-config` decide outright; otherwise an interactive run\n * prompts (default yes) and an unattended run leaves the config alone.\n */\n private async maybeRegisterFields({\n configPath,\n entryLines,\n }: {\n configPath: string\n entryLines: string[]\n }): Promise<Registration> {\n const flag = this.flags['update-config']\n const shouldUpdate =\n flag ??\n (this.isUnattended()\n ? false\n : await confirm({\n default: true,\n message: `Declare the ${entryLines.length} pulled ${pluralize('field', entryLines.length)} in sanity.cli.ts?`,\n }))\n if (!shouldUpdate) return 'declined'\n\n const source = await readFile(configPath, 'utf8')\n const result = appendFieldEntries(source, entryLines)\n if (!result.ok) return {reason: result.reason}\n await writeFile(configPath, result.updated)\n return 'added'\n }\n\n private report({\n configuredNames,\n entryLines,\n generated,\n newEntries,\n outDir,\n registration,\n skipped,\n writtenPaths,\n }: {\n configuredNames: Set<string>\n entryLines: string[]\n generated: GeneratedFieldModule[]\n newEntries: GeneratedFieldModule[]\n outDir: string\n registration: Registration | null\n skipped: SkippedAspect[]\n writtenPaths: Map<string, string>\n }): void {\n if (skipped.length > 0) {\n this.logToStderr('')\n this.warn(\n styleText('bold', `Skipped ${skipped.length} ${pluralize('aspect', skipped.length)}`),\n )\n for (const aspect of skipped) {\n const errors = aspect.validationErrors.flatMap((group) => group.map(({message}) => message))\n const reasons = [...aspect.reasons, ...errors]\n this.logToStderr(` - ${aspect.id} ${styleText('dim', reasons.join('; '))}`)\n }\n }\n\n // No modules written and nothing to declare: done. Skipped-but-undeclared\n // fields keep the report alive — their registration outcome still matters.\n if (generated.length === 0 && newEntries.length === 0) {\n this.log('')\n this.log('No field modules generated.')\n return\n }\n\n if (generated.length === 0) {\n this.log('')\n this.log('No field modules generated.')\n } else {\n this.log('')\n this.log(\n `${logSymbols.success} ${styleText('bold', `Generated ${generated.length} field ${pluralize('module', generated.length)}`)}`,\n )\n for (const module of generated) {\n const location = writtenPaths.get(module.name) ?? path.join(outDir, module.filename)\n this.log(` - ${module.name} ${styleText('dim', location)}`)\n for (const warning of module.warnings) {\n this.log(` ${logSymbols.warning} ${warning}`)\n }\n }\n }\n\n if (newEntries.length > 0 && registration === 'added') {\n this.log('')\n this.log(\n `${logSymbols.success} Declared ${newEntries.length} ${pluralize('field', newEntries.length)} in ${styleText('bold', 'sanity.cli.ts')}`,\n )\n } else if (newEntries.length > 0) {\n if (registration !== null && typeof registration === 'object') {\n this.warn(`Could not update sanity.cli.ts automatically: ${registration.reason}`)\n }\n this.log('')\n this.log(\n configuredNames.size > 0\n ? `Add the pulled ${pluralize('field', newEntries.length)} to the \\`fields\\` array in ${styleText('bold', 'sanity.cli.ts')}:`\n : `Declare the pulled ${pluralize('field', newEntries.length)} in ${styleText('bold', 'sanity.cli.ts')}:`,\n )\n this.log('')\n this.log(entryLines.map((line) => ` ${line}`).join('\\n'))\n // The deploy mirrors config into stored documents; a pulled-but-undeclared\n // field reads as stale there, so leaving the entries out is destructive.\n this.warn(\n '`sanity deploy` deletes the stored definition of any field not declared in sanity.cli.ts.',\n )\n }\n\n this.log('')\n this.log(\n 'Once declared in sanity.cli.ts, the config app owns these definitions — deploying the',\n )\n this.log('config overwrites the stored documents this pull read from. Stored definitions')\n this.log('not declared in sanity.cli.ts are deleted on deploy.')\n }\n}\n\n/**\n * The write target for a declared `src` path. A declared path may omit the\n * extension — the bundler and jiti both resolve `./src/fields/notes` to\n * `notes.ts(x)` — so writing it literally would create an extensionless file\n * next to the module deploy actually evaluates. Resolve to the existing\n * module file; if none exists, append the generated module's extension.\n */\nasync function resolveDeclaredSrc(declaredPath: string, moduleFilename: string): Promise<string> {\n if (path.extname(declaredPath) !== '') return declaredPath\n const existing = await firstExisting([`${declaredPath}.ts`, `${declaredPath}.tsx`])\n return existing ?? `${declaredPath}${path.extname(moduleFilename)}`\n}\n\n/** The first path in `paths` that exists, or `undefined`. */\nasync function firstExisting(paths: string[]): Promise<string | undefined> {\n for (const filePath of paths) {\n const exists = await access(filePath).then(\n () => true,\n () => false,\n )\n if (exists) return filePath\n }\n return undefined\n}\n"],"names":["access","mkdir","readFile","writeFile","path","styleText","Flags","exitCodes","ProjectRootNotFoundError","SanityCommand","subdebug","confirm","logSymbols","spinner","resolveWorkbenchConfig","appendFieldEntries","convertAspectDocuments","formatFieldEntries","resolveMediaLibraryId","getAspects","pluralize","defineCommandTelemetry","pullAspectsDebug","NOT_A_CONFIG_APP","flags","string","description","default","overwrite","boolean","allowNo","MediaPullAspectsCommand","examples","command","hidden","telemetry","redact","run","mediaLibraryIdFlag","outDir","cliConfig","getCliConfig","err","error","exit","RUNTIME_ERROR","config","root","getProjectRoot","outDirAbsolute","resolve","directory","outDirRelative","relative","isAbsolute","startsWith","sep","USAGE_ERROR","mediaLibraryId","organizationId","unattended","isUnattended","spin","start","documents","stop","length","log","configuredNames","Set","fields","map","field","name","configuredSrcByName","Map","src","modules","winners","skipped","generated","writtenPaths","existingPaths","module","has","push","id","reasons","status","validationErrors","defaultDestination","join","filename","existing","firstExisting","replace","set","declaredSrc","get","undefined","destination","resolveDeclaredSrc","dirname","recursive","source","entryPaths","newEntries","filter","entryLines","split","registration","maybeRegisterFields","configPath","report","Error","message","flag","shouldUpdate","result","ok","reason","updated","logToStderr","warn","aspect","errors","flatMap","group","success","location","warning","warnings","size","line","declaredPath","moduleFilename","extname","paths","filePath","exists","then"],"mappings":"AAAA,SAAQA,MAAM,EAAEC,KAAK,EAAEC,QAAQ,EAAEC,SAAS,QAAO,mBAAkB;AACnE,OAAOC,UAAU,YAAW;AAC5B,SAAQC,SAAS,QAAO,YAAW;AAEnC,SAAQC,KAAK,QAAO,cAAa;AACjC,SAEEC,SAAS,EACTC,wBAAwB,EACxBC,aAAa,EACbC,QAAQ,QACH,mBAAkB;AACzB,SAAQC,OAAO,EAAEC,UAAU,EAAEC,OAAO,QAAO,sBAAqB;AAChE,SAAQC,sBAAsB,QAAO,+BAA8B;AAEnE,SAAQC,kBAAkB,QAAO,yCAAwC;AACzE,SACEC,sBAAsB,EACtBC,kBAAkB,QAGb,qCAAoC;AA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cAAc;QAAC,GAAGwC,aAAa,GAAG,CAAC;QAAE,GAAGA,aAAa,IAAI,CAAC;KAAC;IAClF,OAAOzC,YAAY,GAAGyC,eAAelI,KAAKoI,OAAO,CAACD,iBAAiB;AACrE;AAEA,2DAA2D,GAC3D,eAAezC,cAAc2C,KAAe;IAC1C,KAAK,MAAMC,YAAYD,MAAO;QAC5B,MAAME,SAAS,MAAM3I,OAAO0I,UAAUE,IAAI,CACxC,IAAM,MACN,IAAM;QAER,IAAID,QAAQ,OAAOD;IACrB;IACA,OAAOvC;AACT"}
1
+ {"version":3,"sources":["../../../src/commands/media/pull-aspects.ts"],"sourcesContent":["import {access, mkdir, readFile, writeFile} from 'node:fs/promises'\nimport path from 'node:path'\nimport {styleText} from 'node:util'\n\nimport {Flags} from '@oclif/core'\nimport {\n type CliConfig,\n exitCodes,\n ProjectRootNotFoundError,\n SanityCommand,\n subdebug,\n} from '@sanity/cli-core'\nimport {confirm, logSymbols, spinner} from '@sanity/cli-core/ux'\nimport {resolveWorkbenchConfig} from '@sanity/workbench-cli/deploy'\n\nimport {appendFieldEntries} from '../../actions/media/cliConfigFields.js'\nimport {\n convertAspectDocuments,\n formatFieldEntries,\n type GeneratedFieldModule,\n type SkippedAspect,\n} from '../../actions/media/pullAspects.js'\nimport {resolveMediaLibraryId} from '../../actions/media/resolveMediaLibraryId.js'\nimport {getAspects} from '../../services/mediaLibraries.js'\nimport {pluralize} from '../../util/pluralize.js'\nimport {defineCommandTelemetry} from '../../util/telemetry/commandTelemetry.js'\n\nconst pullAspectsDebug = subdebug('media:pull-aspects')\n\nconst NOT_A_CONFIG_APP =\n 'This command must be run inside a Media Library config app — a project whose ' +\n '`sanity.cli.ts` declares `unstable_defineMediaLibrary(...)`. Scaffold one with ' +\n '`sanity init --template media-library-config`.'\n\nconst flags = {\n 'media-library-id': Flags.string({\n description:\n 'The id of the media library to pull from (defaults to the single active library of the configured organization)',\n }),\n 'out-dir': Flags.string({\n default: 'src/fields',\n description: 'Directory to write the generated field modules to, relative to the project root',\n }),\n overwrite: Flags.boolean({\n description:\n 'Overwrite existing field modules and re-generate fields already declared in the config',\n }),\n 'update-config': Flags.boolean({\n allowNo: true,\n description:\n 'Declare the generated fields in sanity.cli.ts (--no-update-config to skip). Prompted when omitted; unattended runs only print the entries',\n }),\n}\n\n/**\n * The outcome of offering to declare the generated fields in `sanity.cli.ts`:\n * written, turned down (flag, prompt, or unattended), or not writable (the\n * config shape could not be edited safely — the `reason` says why).\n */\ntype Registration = 'added' | 'declined' | {reason: string}\n\nexport class MediaPullAspectsCommand extends SanityCommand<typeof MediaPullAspectsCommand> {\n static override description =\n \"Generate field modules from a media library's stored aspect documents\"\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %>',\n description: 'Generate src/fields/<name>.tsx modules from the stored aspects',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --media-library-id ml123 --overwrite',\n description: 'Pull from a specific media library, overwriting existing modules',\n },\n ]\n\n static override flags = flags\n\n // Part of the beta config-app flow: only usable inside a config app (like\n // the unlisted media-library-config init template, which points to it), and\n // listing it next to the legacy aspect commands would mix the two\n // paradigms. Unhide when the config app leaves beta.\n static override hidden = true\n\n // --out-dir is a local filesystem path.\n static telemetry = defineCommandTelemetry(flags, {redact: ['out-dir']})\n\n public async run(): Promise<void> {\n const {\n 'media-library-id': mediaLibraryIdFlag,\n 'out-dir': outDir,\n overwrite = false,\n } = this.flags\n\n let cliConfig: CliConfig\n try {\n cliConfig = await this.getCliConfig()\n } catch (err) {\n if (err instanceof ProjectRootNotFoundError) {\n this.error(NOT_A_CONFIG_APP, {exit: exitCodes.RUNTIME_ERROR})\n }\n throw err\n }\n\n const config = resolveWorkbenchConfig(cliConfig)\n if (config?.appType !== 'media-library') {\n this.error(NOT_A_CONFIG_APP, {exit: exitCodes.RUNTIME_ERROR})\n }\n\n const root = await this.getProjectRoot()\n // The generated `src:` entries and the ownership story both assume the\n // modules live inside the project; a path escaping the root is a mistake.\n // `outDirRelative` (not the raw flag) feeds the report so an absolute\n // --out-dir inside the root still prints proper relative `src:` entries.\n const outDirAbsolute = path.resolve(root.directory, outDir)\n const outDirRelative = path.relative(root.directory, outDirAbsolute)\n if (\n path.isAbsolute(outDirRelative) ||\n outDirRelative === '..' ||\n outDirRelative.startsWith(`..${path.sep}`)\n ) {\n this.error(`--out-dir must stay inside the project root (got \"${outDir}\")`, {\n exit: exitCodes.USAGE_ERROR,\n })\n }\n\n try {\n const mediaLibraryId = await resolveMediaLibraryId({\n mediaLibraryIdFlag,\n organizationId: config.organizationId,\n unattended: this.isUnattended(),\n })\n\n const spin = spinner('Fetching stored aspect documents').start()\n let documents: Awaited<ReturnType<typeof getAspects>>\n try {\n documents = await getAspects(mediaLibraryId)\n } finally {\n // Also on failure — a spinner left running garbles the error output.\n spin.stop()\n }\n\n if (documents.length === 0) {\n this.log(\n `Media library ${styleText('bold', mediaLibraryId)} has no stored aspects — nothing to pull.`,\n )\n return\n }\n\n // Names already declared in the config are owned by existing field\n // modules; pulling the stored mirror back over them would regress local\n // edits, so they are skipped unless --overwrite says otherwise.\n const configuredNames = new Set(config.fields.map((field) => field.name))\n const configuredSrcByName = new Map(config.fields.map((field) => [field.name, field.src]))\n\n // One module per field name; name collisions and invalid documents are skipped.\n const {modules: winners, skipped} = convertAspectDocuments(documents)\n\n const generated: GeneratedFieldModule[] = []\n // Module name -> written path relative to the project root, so the\n // report shows where each module actually landed.\n const writtenPaths = new Map<string, string>()\n // Module name -> path of a module skipped because it already exists on\n // disk. Those fields may still be undeclared and need registration.\n const existingPaths = new Map<string, string>()\n for (const module of winners) {\n if (!overwrite && configuredNames.has(module.name)) {\n skipped.push({\n id: module.name,\n reasons: ['Already declared in sanity.cli.ts (pass --overwrite to re-generate)'],\n status: 'skipped',\n validationErrors: [],\n })\n continue\n }\n\n const defaultDestination = path.join(outDirAbsolute, module.filename)\n // The pull generates `.tsx`, but a hand-written module for the same\n // field may be plain `.ts` — treat both as taken.\n const existing = await firstExisting([\n defaultDestination,\n defaultDestination.replace(/\\.tsx$/, '.ts'),\n ])\n if (!overwrite && existing) {\n // The file is left alone, but the field is undeclared (declared\n // names were skipped above) — so it still joins the registration\n // offer below. An on-disk module without a config entry is exactly\n // the state the next deploy punishes, however the file got there.\n existingPaths.set(module.name, path.relative(root.directory, existing))\n skipped.push({\n id: module.name,\n reasons: [\n `A file already exists at ${path.relative(root.directory, existing)} (pass --overwrite to replace it)`,\n ],\n status: 'skipped',\n validationErrors: [],\n })\n continue\n }\n\n // When overwriting a field the config already declares, the module\n // must land at the declared `src` path — writing <out-dir>/<name>.tsx\n // instead would orphan the new file while deploy keeps evaluating the\n // old one. Failing that, replace the module found on disk (which may\n // be the .ts variant), and only then fall back to the default.\n const declaredSrc = overwrite ? configuredSrcByName.get(module.name) : undefined\n const destination = declaredSrc\n ? await resolveDeclaredSrc(path.resolve(root.directory, declaredSrc), module.filename)\n : (existing ?? defaultDestination)\n\n await mkdir(path.dirname(destination), {recursive: true})\n await writeFile(destination, module.source)\n writtenPaths.set(module.name, path.relative(root.directory, destination))\n generated.push(module)\n }\n\n // Fields present locally — written this run or already on disk — but not\n // declared get offered for registration: the deploy mirrors config to\n // stored documents, so an undeclared stored aspect is deleted by the\n // next deploy — leaving the entries unpasted is a data hazard, not just\n // friction. Existing files count because a prior pull may have been\n // declined (or edited by hand): the file being there does not make the\n // field declared.\n const entryPaths = new Map([...writtenPaths, ...existingPaths])\n const newEntries = winners.filter(\n (module) => !configuredNames.has(module.name) && entryPaths.has(module.name),\n )\n const entryLines =\n newEntries.length > 0\n ? formatFieldEntries(newEntries, outDirRelative, entryPaths).split('\\n')\n : []\n const registration =\n newEntries.length > 0\n ? await this.maybeRegisterFields({configPath: root.path, entryLines})\n : null\n\n this.report({\n configuredNames,\n entryLines,\n generated,\n newEntries,\n outDir: outDirRelative,\n registration,\n skipped,\n writtenPaths,\n })\n } catch (error) {\n // Ctrl+C on the library prompt and errors that already carry their exit\n // code (`this.error` inside helpers) pass through to SanityCommand.catch.\n if (error instanceof Error && error.name === 'ExitPromptError') throw error\n if (error && typeof error === 'object' && 'oclif' in error) throw error\n const err = error as Error\n pullAspectsDebug('Failed to pull aspects', {error: err, mediaLibraryId: mediaLibraryIdFlag})\n this.error(\n styleText('bold', 'Failed to pull aspects') + `\\n\\n${styleText('red', err.message)}`,\n {exit: exitCodes.RUNTIME_ERROR},\n )\n }\n }\n\n /**\n * Offer to declare the generated fields in `sanity.cli.ts`. `--update-config`\n * / `--no-update-config` decide outright; otherwise an interactive run\n * prompts (default yes) and an unattended run leaves the config alone.\n */\n private async maybeRegisterFields({\n configPath,\n entryLines,\n }: {\n configPath: string\n entryLines: string[]\n }): Promise<Registration> {\n const flag = this.flags['update-config']\n const shouldUpdate =\n flag ??\n (this.isUnattended()\n ? false\n : await confirm({\n default: true,\n message: `Declare the ${entryLines.length} pulled ${pluralize('field', entryLines.length)} in sanity.cli.ts?`,\n }))\n if (!shouldUpdate) return 'declined'\n\n const source = await readFile(configPath, 'utf8')\n const result = appendFieldEntries(source, entryLines)\n if (!result.ok) return {reason: result.reason}\n await writeFile(configPath, result.updated)\n return 'added'\n }\n\n private report({\n configuredNames,\n entryLines,\n generated,\n newEntries,\n outDir,\n registration,\n skipped,\n writtenPaths,\n }: {\n configuredNames: Set<string>\n entryLines: string[]\n generated: GeneratedFieldModule[]\n newEntries: GeneratedFieldModule[]\n outDir: string\n registration: Registration | null\n skipped: SkippedAspect[]\n writtenPaths: Map<string, string>\n }): void {\n if (skipped.length > 0) {\n this.logToStderr('')\n this.warn(\n styleText('bold', `Skipped ${skipped.length} ${pluralize('aspect', skipped.length)}`),\n )\n for (const aspect of skipped) {\n const errors = aspect.validationErrors.flatMap((group) => group.map(({message}) => message))\n const reasons = [...aspect.reasons, ...errors]\n this.logToStderr(` - ${aspect.id} ${styleText('dim', reasons.join('; '))}`)\n }\n }\n\n // No modules written and nothing to declare: done. Skipped-but-undeclared\n // fields keep the report alive — their registration outcome still matters.\n if (generated.length === 0 && newEntries.length === 0) {\n this.log('')\n this.log('No field modules generated.')\n return\n }\n\n if (generated.length === 0) {\n this.log('')\n this.log('No field modules generated.')\n } else {\n this.log('')\n this.log(\n `${logSymbols.success} ${styleText('bold', `Generated ${generated.length} field ${pluralize('module', generated.length)}`)}`,\n )\n for (const module of generated) {\n const location = writtenPaths.get(module.name) ?? path.join(outDir, module.filename)\n this.log(` - ${module.name} ${styleText('dim', location)}`)\n for (const warning of module.warnings) {\n this.log(` ${logSymbols.warning} ${warning}`)\n }\n }\n }\n\n if (newEntries.length > 0 && registration === 'added') {\n this.log('')\n this.log(\n `${logSymbols.success} Declared ${newEntries.length} ${pluralize('field', newEntries.length)} in ${styleText('bold', 'sanity.cli.ts')}`,\n )\n } else if (newEntries.length > 0) {\n if (registration !== null && typeof registration === 'object') {\n this.warn(`Could not update sanity.cli.ts automatically: ${registration.reason}`)\n }\n this.log('')\n this.log(\n configuredNames.size > 0\n ? `Add the pulled ${pluralize('field', newEntries.length)} to the \\`fields\\` array in ${styleText('bold', 'sanity.cli.ts')}:`\n : `Declare the pulled ${pluralize('field', newEntries.length)} in ${styleText('bold', 'sanity.cli.ts')}:`,\n )\n this.log('')\n this.log(entryLines.map((line) => ` ${line}`).join('\\n'))\n // The deploy mirrors config into stored documents; a pulled-but-undeclared\n // field reads as stale there, so leaving the entries out is destructive.\n this.warn(\n '`sanity deploy` deletes the stored definition of any field not declared in sanity.cli.ts.',\n )\n }\n\n this.log('')\n this.log(\n 'Once declared in sanity.cli.ts, the config app owns these definitions — deploying the',\n )\n this.log('config overwrites the stored documents this pull read from. Stored definitions')\n this.log('not declared in sanity.cli.ts are deleted on deploy.')\n }\n}\n\n/**\n * The write target for a declared `src` path. A declared path may omit the\n * extension — the bundler and jiti both resolve `./src/fields/notes` to\n * `notes.ts(x)` — so writing it literally would create an extensionless file\n * next to the module deploy actually evaluates. Resolve to the existing\n * module file; if none exists, append the generated module's extension.\n */\nasync function resolveDeclaredSrc(declaredPath: string, moduleFilename: string): Promise<string> {\n if (path.extname(declaredPath) !== '') return declaredPath\n const existing = await firstExisting([`${declaredPath}.ts`, `${declaredPath}.tsx`])\n return existing ?? `${declaredPath}${path.extname(moduleFilename)}`\n}\n\n/** The first path in `paths` that exists, or `undefined`. */\nasync function firstExisting(paths: string[]): Promise<string | undefined> {\n for (const filePath of paths) {\n const exists = await access(filePath).then(\n () => true,\n () => false,\n )\n if (exists) return filePath\n }\n return undefined\n}\n"],"names":["access","mkdir","readFile","writeFile","path","styleText","Flags","exitCodes","ProjectRootNotFoundError","SanityCommand","subdebug","confirm","logSymbols","spinner","resolveWorkbenchConfig","appendFieldEntries","convertAspectDocuments","formatFieldEntries","resolveMediaLibraryId","getAspects","pluralize","defineCommandTelemetry","pullAspectsDebug","NOT_A_CONFIG_APP","flags","string","description","default","overwrite","boolean","allowNo","MediaPullAspectsCommand","examples","command","hidden","telemetry","redact","run","mediaLibraryIdFlag","outDir","cliConfig","getCliConfig","err","error","exit","RUNTIME_ERROR","config","appType","root","getProjectRoot","outDirAbsolute","resolve","directory","outDirRelative","relative","isAbsolute","startsWith","sep","USAGE_ERROR","mediaLibraryId","organizationId","unattended","isUnattended","spin","start","documents","stop","length","log","configuredNames","Set","fields","map","field","name","configuredSrcByName","Map","src","modules","winners","skipped","generated","writtenPaths","existingPaths","module","has","push","id","reasons","status","validationErrors","defaultDestination","join","filename","existing","firstExisting","replace","set","declaredSrc","get","undefined","destination","resolveDeclaredSrc","dirname","recursive","source","entryPaths","newEntries","filter","entryLines","split","registration","maybeRegisterFields","configPath","report","Error","message","flag","shouldUpdate","result","ok","reason","updated","logToStderr","warn","aspect","errors","flatMap","group","success","location","warning","warnings","size","line","declaredPath","moduleFilename","extname","paths","filePath","exists","then"],"mappings":"AAAA,SAAQA,MAAM,EAAEC,KAAK,EAAEC,QAAQ,EAAEC,SAAS,QAAO,mBAAkB;AACnE,OAAOC,UAAU,YAAW;AAC5B,SAAQC,SAAS,QAAO,YAAW;AAEnC,SAAQC,KAAK,QAAO,cAAa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,IAAI,CAACxD,GAAG,CAAC;QACT,IAAI,CAACA,GAAG,CACN;QAEF,IAAI,CAACA,GAAG,CAAC;QACT,IAAI,CAACA,GAAG,CAAC;IACX;AACF;AAEA;;;;;;CAMC,GACD,eAAekC,mBAAmBiC,YAAoB,EAAEC,cAAsB;IAC5E,IAAIpI,KAAKqI,OAAO,CAACF,kBAAkB,IAAI,OAAOA;IAC9C,MAAMzC,WAAW,MAAMC,cAAc;QAAC,GAAGwC,aAAa,GAAG,CAAC;QAAE,GAAGA,aAAa,IAAI,CAAC;KAAC;IAClF,OAAOzC,YAAY,GAAGyC,eAAenI,KAAKqI,OAAO,CAACD,iBAAiB;AACrE;AAEA,2DAA2D,GAC3D,eAAezC,cAAc2C,KAAe;IAC1C,KAAK,MAAMC,YAAYD,MAAO;QAC5B,MAAME,SAAS,MAAM5I,OAAO2I,UAAUE,IAAI,CACxC,IAAM,MACN,IAAM;QAER,IAAID,QAAQ,OAAOD;IACrB;IACA,OAAOvC;AACT"}
@@ -2,7 +2,7 @@ import "@sanity/types";
2
2
  import { CliConfig, CliConfig as CliConfig$1, UserViteConfig } from "@sanity/cli-core";
3
3
  import { ClientConfig, SanityClient } from "@sanity/client";
4
4
  import { loadEnv } from "vite";
5
- import { AssetSourceView, DefineAppInput, DefineAssetSourceViewInput, DefineMediaLibraryInput, DefinePanelViewInput, DefineTileViewInput, DefineWebWorkerInput, DefineWindowViewInput, MediaLibraryField, PanelView, TileView, ViewDeclaration, WebWorker, WindowView, defineApplication, defineApplication as unstable_defineApp, defineAssetSourceView, definePanelView, defineTileView, defineWebWorker, defineWindowView, unstable_defineMediaLibrary } from "@sanity/workbench-cli";
5
+ import { AssetSourceViewDeclaration, DefineAppInput, DefineAssetSourceViewInput, DefineDashboardInput, DefineMediaLibraryInput, DefinePanelViewInput, DefineTileViewInput, DefineWebWorkerInput, DefineWindowViewInput, MediaLibraryField, PanelViewDeclaration, TileViewDeclaration, ViewDeclaration, WebWorkerDeclaration, WindowViewDeclaration, defineApplication, defineApplication as unstable_defineApp, defineAssetSourceView, defineDashboard, definePanelView, defineTileView, defineWebWorker, defineWindowView, unstable_defineMediaLibrary } from "@sanity/workbench-cli";
6
6
  /**
7
7
  * @public
8
8
  */
@@ -94,5 +94,5 @@ type CliClientGetter = ((options?: CliClientOptions) => SanityClient) & {
94
94
  */
95
95
  __internal__getToken: () => string | undefined;
96
96
  };
97
- export { type AssetSourceView, type CliApiConfig, type CliClientOptions, type CliConfig, type DefineAppInput, type DefineAssetSourceViewInput, type DefineMediaLibraryInput, type DefinePanelViewInput, type DefineTileViewInput, type DefineWebWorkerInput, type DefineWindowViewInput, type GraphQLAPIConfig, type MediaLibraryField, type PanelView, type TileView, type UserViteConfig, type ViewDeclaration, type WebWorker, type WindowView, createCliConfig, defineApplication, defineAssetSourceView, defineCliConfig, definePanelView, defineTileView, defineWebWorker, defineWindowView, getCliClient, loadEnv, unstable_defineApp, unstable_defineMediaLibrary };
97
+ export { type AssetSourceViewDeclaration, type CliApiConfig, type CliClientOptions, type CliConfig, type DefineAppInput, type DefineAssetSourceViewInput, type DefineDashboardInput, type DefineMediaLibraryInput, type DefinePanelViewInput, type DefineTileViewInput, type DefineWebWorkerInput, type DefineWindowViewInput, type GraphQLAPIConfig, type MediaLibraryField, type PanelViewDeclaration, type TileViewDeclaration, type UserViteConfig, type ViewDeclaration, type WebWorkerDeclaration, type WindowViewDeclaration, createCliConfig, defineApplication, defineAssetSourceView, defineCliConfig, defineDashboard, definePanelView, defineTileView, defineWebWorker, defineWindowView, getCliClient, loadEnv, unstable_defineApp, unstable_defineMediaLibrary };
98
98
  //# sourceMappingURL=index.d.ts.map
@@ -2,7 +2,7 @@ export { createCliConfig } from '../config/createCliConfig.js';
2
2
  export { defineCliConfig } from '../config/defineCliConfig.js';
3
3
  export { getCliClient } from '../util/cliClient.js';
4
4
  export { loadEnv } from '../util/loadEnv.js';
5
- export { defineApplication, defineAssetSourceView, definePanelView, defineTileView, defineWebWorker, defineWindowView, // Older `sanity/cli` versions import this compatibility name from `@sanity/cli`.
5
+ export { defineApplication, defineAssetSourceView, defineDashboard, definePanelView, defineTileView, defineWebWorker, defineWindowView, // Older `sanity/cli` versions import this compatibility name from `@sanity/cli`.
6
6
  defineApplication as unstable_defineApp, unstable_defineMediaLibrary } from '@sanity/workbench-cli';
7
7
 
8
8
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/exports/index.ts"],"sourcesContent":["export type {GraphQLAPIConfig} from '../actions/graphql/types.js'\nexport {createCliConfig} from '../config/createCliConfig.js'\nexport {defineCliConfig} from '../config/defineCliConfig.js'\nexport type {CliApiConfig} from '../types.js'\nexport {type CliClientOptions, getCliClient} from '../util/cliClient.js'\nexport {loadEnv} from '../util/loadEnv.js'\nexport type {CliConfig, UserViteConfig} from '@sanity/cli-core'\n\nexport {\n type AssetSourceView,\n type DefineAppInput,\n defineApplication,\n defineAssetSourceView,\n type DefineAssetSourceViewInput,\n type DefineMediaLibraryInput,\n definePanelView,\n type DefinePanelViewInput,\n defineTileView,\n type DefineTileViewInput,\n defineWebWorker,\n type DefineWebWorkerInput,\n defineWindowView,\n type DefineWindowViewInput,\n type MediaLibraryField,\n type PanelView,\n type TileView,\n // Older `sanity/cli` versions import this compatibility name from `@sanity/cli`.\n defineApplication as unstable_defineApp,\n unstable_defineMediaLibrary,\n type ViewDeclaration,\n type WebWorker,\n type WindowView,\n} from '@sanity/workbench-cli'\n"],"names":["createCliConfig","defineCliConfig","getCliClient","loadEnv","defineApplication","defineAssetSourceView","definePanelView","defineTileView","defineWebWorker","defineWindowView","unstable_defineApp","unstable_defineMediaLibrary"],"mappings":"AACA,SAAQA,eAAe,QAAO,+BAA8B;AAC5D,SAAQC,eAAe,QAAO,+BAA8B;AAE5D,SAA+BC,YAAY,QAAO,uBAAsB;AACxE,SAAQC,OAAO,QAAO,qBAAoB;AAG1C,SAGEC,iBAAiB,EACjBC,qBAAqB,EAGrBC,eAAe,EAEfC,cAAc,EAEdC,eAAe,EAEfC,gBAAgB,EAKhB,iFAAiF;AACjFL,qBAAqBM,kBAAkB,EACvCC,2BAA2B,QAItB,wBAAuB"}
1
+ {"version":3,"sources":["../../src/exports/index.ts"],"sourcesContent":["export type {GraphQLAPIConfig} from '../actions/graphql/types.js'\nexport {createCliConfig} from '../config/createCliConfig.js'\nexport {defineCliConfig} from '../config/defineCliConfig.js'\nexport type {CliApiConfig} from '../types.js'\nexport {type CliClientOptions, getCliClient} from '../util/cliClient.js'\nexport {loadEnv} from '../util/loadEnv.js'\nexport type {CliConfig, UserViteConfig} from '@sanity/cli-core'\n\nexport {\n type AssetSourceViewDeclaration,\n type DefineAppInput,\n defineApplication,\n defineAssetSourceView,\n type DefineAssetSourceViewInput,\n defineDashboard,\n type DefineDashboardInput,\n type DefineMediaLibraryInput,\n definePanelView,\n type DefinePanelViewInput,\n defineTileView,\n type DefineTileViewInput,\n defineWebWorker,\n type DefineWebWorkerInput,\n defineWindowView,\n type DefineWindowViewInput,\n type MediaLibraryField,\n type PanelViewDeclaration,\n type TileViewDeclaration,\n // Older `sanity/cli` versions import this compatibility name from `@sanity/cli`.\n defineApplication as unstable_defineApp,\n unstable_defineMediaLibrary,\n type ViewDeclaration,\n type WebWorkerDeclaration,\n type WindowViewDeclaration,\n} from '@sanity/workbench-cli'\n"],"names":["createCliConfig","defineCliConfig","getCliClient","loadEnv","defineApplication","defineAssetSourceView","defineDashboard","definePanelView","defineTileView","defineWebWorker","defineWindowView","unstable_defineApp","unstable_defineMediaLibrary"],"mappings":"AACA,SAAQA,eAAe,QAAO,+BAA8B;AAC5D,SAAQC,eAAe,QAAO,+BAA8B;AAE5D,SAA+BC,YAAY,QAAO,uBAAsB;AACxE,SAAQC,OAAO,QAAO,qBAAoB;AAG1C,SAGEC,iBAAiB,EACjBC,qBAAqB,EAErBC,eAAe,EAGfC,eAAe,EAEfC,cAAc,EAEdC,eAAe,EAEfC,gBAAgB,EAKhB,iFAAiF;AACjFN,qBAAqBO,kBAAkB,EACvCC,2BAA2B,QAItB,wBAAuB"}
@@ -1,3 +1,3 @@
1
1
  import { AssetSource, AssetSourceComponentProps } from "@sanity/types";
2
- import { AssetSourceComponent, AssetSourceViewComponents, DefinedService, DefinedView, PanelComponent, PanelViewComponents, PanelViewProps, ServiceBus, ServiceCallback, ServiceContext, ServiceInfo, ServiceType, TileComponent, TileSize, TileViewComponents, TileViewProps, ViewComponentsBySurface, ViewSurface, WebWorkerBus, WebWorkerInfo, WebWorkerProps, WebWorkerType, unstable_defineService, unstable_defineView } from "@sanity/workbench-cli";
3
- export { type AssetSource, type AssetSourceComponent, type AssetSourceComponentProps, type AssetSourceViewComponents, type DefinedService, type DefinedView, type PanelComponent, type PanelViewComponents, type PanelViewProps, type ServiceBus, type ServiceCallback, type ServiceContext, type ServiceInfo, type ServiceType, type TileComponent, type TileSize, type TileViewComponents, type TileViewProps, type ViewComponentsBySurface, type ViewSurface, type WebWorkerBus, type WebWorkerInfo, type WebWorkerProps, type WebWorkerType, unstable_defineService, unstable_defineView };
2
+ import { AssetSourceComponent, AssetSourceViewComponents, DefinedService, DefinedView, PanelComponent, PanelViewComponents, PanelViewProps, ServiceBus, ServiceCallback, ServiceContext, ServiceInfo, ServiceType, TileComponent, TileSize, TileViewComponents, TileViewProps, ViewComponentsBySurface, ViewSurface, WebWorkerBus, WebWorkerInfo, WebWorkerProps, WebWorkerType, defineDashboardConfig, unstable_defineService, unstable_defineView } from "@sanity/workbench-cli";
3
+ export { type AssetSource, type AssetSourceComponent, type AssetSourceComponentProps, type AssetSourceViewComponents, type DefinedService, type DefinedView, type PanelComponent, type PanelViewComponents, type PanelViewProps, type ServiceBus, type ServiceCallback, type ServiceContext, type ServiceInfo, type ServiceType, type TileComponent, type TileSize, type TileViewComponents, type TileViewProps, type ViewComponentsBySurface, type ViewSurface, type WebWorkerBus, type WebWorkerInfo, type WebWorkerProps, type WebWorkerType, defineDashboardConfig, unstable_defineService, unstable_defineView };
@@ -8,6 +8,6 @@
8
8
  //
9
9
  // `defineApplication` is config-time (Node) and stays on the main `@sanity/cli`
10
10
  // entry; only the runtime helpers live here.
11
- export { unstable_defineService, unstable_defineView } from '@sanity/workbench-cli';
11
+ export { defineDashboardConfig, unstable_defineService, unstable_defineView } from '@sanity/workbench-cli';
12
12
 
13
13
  //# sourceMappingURL=runtime.js.map
@@ -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/web worker src files bundle to the browser, so this entry re-exports ONLY\n// from dependency-light, browser-safe modules — it must never import\n// `@sanity/cli-core` or anything Node-only, or it would drag the CLI into the\n// frontend bundle. The `sanity` runtime package re-exports from here, so the\n// same constraint protects it.\n//\n// `defineApplication` is config-time (Node) and stays on the main `@sanity/cli`\n// entry; only the runtime helpers live here.\nexport type {AssetSource, AssetSourceComponentProps} from '@sanity/types'\nexport type {\n AssetSourceComponent,\n AssetSourceViewComponents,\n DefinedService,\n DefinedView,\n PanelComponent,\n PanelViewComponents,\n PanelViewProps,\n ServiceBus,\n ServiceCallback,\n ServiceContext,\n ServiceInfo,\n ServiceType,\n TileComponent,\n TileSize,\n TileViewComponents,\n TileViewProps,\n ViewComponentsBySurface,\n ViewSurface,\n WebWorkerBus,\n WebWorkerInfo,\n WebWorkerProps,\n WebWorkerType,\n} from '@sanity/workbench-cli'\nexport {unstable_defineService, unstable_defineView} from '@sanity/workbench-cli'\n"],"names":["unstable_defineService","unstable_defineView"],"mappings":"AAAA,kFAAkF;AAClF,EAAE;AACF,iFAAiF;AACjF,qEAAqE;AACrE,8EAA8E;AAC9E,6EAA6E;AAC7E,+BAA+B;AAC/B,EAAE;AACF,gFAAgF;AAChF,6CAA6C;AA0B7C,SAAQA,sBAAsB,EAAEC,mBAAmB,QAAO,wBAAuB"}
1
+ {"version":3,"sources":["../../src/exports/runtime.ts"],"sourcesContent":["// Browser-safe runtime authoring helpers for the module-federation extension API.\n//\n// View/web worker src files bundle to the browser, so this entry re-exports ONLY\n// from dependency-light, browser-safe modules — it must never import\n// `@sanity/cli-core` or anything Node-only, or it would drag the CLI into the\n// frontend bundle. The `sanity` runtime package re-exports from here, so the\n// same constraint protects it.\n//\n// `defineApplication` is config-time (Node) and stays on the main `@sanity/cli`\n// entry; only the runtime helpers live here.\nexport type {AssetSource, AssetSourceComponentProps} from '@sanity/types'\nexport type {\n AssetSourceComponent,\n AssetSourceViewComponents,\n DefinedService,\n DefinedView,\n PanelComponent,\n PanelViewComponents,\n PanelViewProps,\n ServiceBus,\n ServiceCallback,\n ServiceContext,\n ServiceInfo,\n ServiceType,\n TileComponent,\n TileSize,\n TileViewComponents,\n TileViewProps,\n ViewComponentsBySurface,\n ViewSurface,\n WebWorkerBus,\n WebWorkerInfo,\n WebWorkerProps,\n WebWorkerType,\n} from '@sanity/workbench-cli'\nexport {\n defineDashboardConfig,\n unstable_defineService,\n unstable_defineView,\n} from '@sanity/workbench-cli'\n"],"names":["defineDashboardConfig","unstable_defineService","unstable_defineView"],"mappings":"AAAA,kFAAkF;AAClF,EAAE;AACF,iFAAiF;AACjF,qEAAqE;AACrE,8EAA8E;AAC9E,6EAA6E;AAC7E,+BAA+B;AAC/B,EAAE;AACF,gFAAgF;AAChF,6CAA6C;AA0B7C,SACEA,qBAAqB,EACrBC,sBAAsB,EACtBC,mBAAmB,QACd,wBAAuB"}
@@ -77,6 +77,10 @@
77
77
  host: 'global',
78
78
  pathPatterns: [
79
79
  'applications',
80
+ 'applications/dashboards',
81
+ 'applications/dashboards/{dashboardId}',
82
+ 'applications/dashboards/{dashboardId}/configs',
83
+ 'applications/dashboards/{dashboardId}/configs/{configId}',
80
84
  'applications/{applicationId}',
81
85
  'applications/{applicationId}/access',
82
86
  'applications/{applicationId}/deployments',
@@ -84,6 +88,7 @@
84
88
  'applications/{applicationId}/icon',
85
89
  'applications/{applicationId}/installations',
86
90
  'applications/{applicationId}/interfaces',
91
+ 'applications/{applicationId}/interfaces/{interfaceId}/icon',
87
92
  'applications/{applicationId}/workspaces',
88
93
  'deploy',
89
94
  'deploy/quickstart',
@@ -120,6 +125,10 @@
120
125
  host: 'project',
121
126
  pathPatterns: [
122
127
  'applications',
128
+ 'applications/dashboards',
129
+ 'applications/dashboards/{dashboardId}',
130
+ 'applications/dashboards/{dashboardId}/configs',
131
+ 'applications/dashboards/{dashboardId}/configs/{configId}',
123
132
  'applications/{applicationId}',
124
133
  'applications/{applicationId}/access',
125
134
  'applications/{applicationId}/deployments',
@@ -127,6 +136,7 @@
127
136
  'applications/{applicationId}/icon',
128
137
  'applications/{applicationId}/installations',
129
138
  'applications/{applicationId}/interfaces',
139
+ 'applications/{applicationId}/interfaces/{interfaceId}/icon',
130
140
  'applications/{applicationId}/workspaces',
131
141
  'deploy',
132
142
  'deploy/quickstart',
@@ -231,6 +241,43 @@
231
241
  slug: 'content-agent',
232
242
  title: 'Content Agent API reference'
233
243
  },
244
+ {
245
+ host: 'global',
246
+ pathPatterns: [
247
+ 'context/knowledge-bases',
248
+ 'context/knowledge-bases/{knowledgeBaseId}',
249
+ 'context/knowledge-bases/{knowledgeBaseId}/apply',
250
+ 'context/knowledge-bases/{knowledgeBaseId}/build',
251
+ 'context/knowledge-bases/{knowledgeBaseId}/build/cancel',
252
+ 'context/knowledge-bases/{knowledgeBaseId}/discard',
253
+ 'context/knowledge-bases/{knowledgeBaseId}/documents',
254
+ 'context/knowledge-bases/{knowledgeBaseId}/documents/{documentId}',
255
+ 'context/knowledge-bases/{knowledgeBaseId}/documents/{documentId}/content',
256
+ 'context/knowledge-bases/{knowledgeBaseId}/entries/{entryPath}/rebuild',
257
+ 'context/knowledge-bases/{knowledgeBaseId}/instructions',
258
+ 'context/knowledge-bases/{knowledgeBaseId}/instructions/check',
259
+ 'context/knowledge-bases/{knowledgeBaseId}/instructions/draft',
260
+ 'context/knowledge-bases/{knowledgeBaseId}/instructions/{instructionId}',
261
+ 'context/knowledge-bases/{knowledgeBaseId}/issues/apply',
262
+ 'context/knowledge-bases/{knowledgeBaseId}/issues/{issueId}/dismiss',
263
+ 'context/knowledge-bases/{knowledgeBaseId}/issues/{issueId}/reopen',
264
+ 'context/knowledge-bases/{knowledgeBaseId}/issues/{issueId}/resolve',
265
+ 'context/knowledge-bases/{knowledgeBaseId}/jobs/{jobId}',
266
+ 'context/knowledge-bases/{knowledgeBaseId}/sources',
267
+ 'context/knowledge-bases/{knowledgeBaseId}/sources/{sourceId}',
268
+ 'context/knowledge-bases/{knowledgeBaseId}/sources/{sourceId}/syncs',
269
+ 'context/knowledge-bases/{knowledgeBaseId}/sources/{sourceId}/syncs/{syncId}',
270
+ 'context/knowledge-bases/{knowledgeBaseId}/sources/{sourceId}/uploads',
271
+ 'context/knowledge-bases/{knowledgeBaseId}/sync',
272
+ 'context/organizations/{organizationId}/conversations/{threadId}',
273
+ 'context/organizations/{organizationId}/mcp',
274
+ 'context/organizations/{organizationId}/mcp/{mcpEndpoint}',
275
+ 'context/organizations/{organizationId}/mcp/{mcpEndpoint}/initial-context',
276
+ 'context/organizations/{organizationId}/mcp/{mcpEndpoint}/status'
277
+ ],
278
+ slug: 'context-api',
279
+ title: 'Context API reference'
280
+ },
234
281
  {
235
282
  defaultApiVersion: 'v2025-02-19',
236
283
  host: 'global',
@@ -274,6 +321,11 @@
274
321
  host: 'global',
275
322
  pathPatterns: [
276
323
  'functions',
324
+ 'functions/durables/callback/{callbackId}/failure',
325
+ 'functions/durables/callback/{callbackId}/success',
326
+ 'functions/durables/{functionId}/executions',
327
+ 'functions/durables/{functionId}/executions/{executionId}',
328
+ 'functions/durables/{functionId}/executions/{executionId}/stop',
277
329
  'functions/{functionId}',
278
330
  'functions/{functionId}/envvars',
279
331
  'functions/{functionId}/envvars/{envVarKey}',