@sanity/cli-core 3.10.0 → 3.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,7 +2,7 @@ import { n as ProjectCliClientOptions, t as GlobalCliClientOptions } from "./api
2
2
  import { r as CliConfig } from "./cliConfig-BZgn8ge1.js";
3
3
  import { t as ProjectRootResult } from "./recursivelyResolveProjectRoot-BE54uEP6.js";
4
4
  import { t as CLITelemetryStore } from "./types-ZNH3prAd.js";
5
- import { t as Output } from "./types-CwJLTYDj.js";
5
+ import { t as Output } from "./types-ii6VUp6a.js";
6
6
  import { Command, Interfaces } from "@oclif/core";
7
7
  import { CommandError, Input, ParserOutput } from "@oclif/core/interfaces";
8
8
  type Flags<T extends typeof Command> = Interfaces.InferredFlags<(typeof SanityCommand)['baseFlags'] & T['flags']>;
@@ -114,12 +114,31 @@ declare abstract class SanityCommand<T extends typeof Command> extends Command i
114
114
  * output (a caller parsing JSON can't answer a prompt).
115
115
  */
116
116
  isUnattended(): boolean;
117
+ /**
118
+ * Whether this run should emit JSON.
119
+ *
120
+ * oclif's own check also treats `SANITY_CONTENT_TYPE=json` as a request for
121
+ * JSON. That reads the host process's environment, so it is consulted only
122
+ * for a real command line: a programmatic invocation must decide from its own
123
+ * arguments, never from whatever the embedding process happens to export.
124
+ */
125
+ jsonEnabled(): boolean;
117
126
  /**
118
127
  * Write to stdout — or, when running under an execution context (e.g. from
119
128
  * an MCP server), to the context's `stdout` sink. Mirrors oclif's `log`
120
129
  * semantics: suppressed when `--json` is enabled, printf-style formatting.
121
130
  */
122
131
  log(message?: string, ...args: unknown[]): void;
132
+ /**
133
+ * Write a diagnostic that stays visible in JSON mode.
134
+ *
135
+ * `log`, `warn` and `logToStderr` are all suppressed once `--json` is on, so
136
+ * a command that skipped part of its work would report the remainder as a
137
+ * complete result. stderr carries it instead, where it cannot corrupt the
138
+ * payload: JSON mode is reachable only from a real command line, since
139
+ * programmatic invocations drop the flag.
140
+ */
141
+ logDiagnostic(message: string): void;
123
142
  /**
124
143
  * Pretty-print JSON to stdout — or plain (un-colorized) JSON to the
125
144
  * execution context's `stdout` sink, so programmatic callers don't have to
@@ -144,6 +163,12 @@ declare abstract class SanityCommand<T extends typeof Command> extends Command i
144
163
  * which programmatic invocations must not repeat per request.
145
164
  */
146
165
  runInExecutionContext<TResult>(): Promise<TResult>;
166
+ /**
167
+ * A command-specific report wins; otherwise oclif's envelope, trimmed to a
168
+ * bounded set of properties when a programmatic caller will relay it. See
169
+ * {@link toRelayableErrorJson} for why the untrimmed form is unsafe there.
170
+ */
171
+ toErrorJson(err: unknown): unknown;
147
172
  /**
148
173
  * Get the CLI config, returning an empty config if no project root is found.
149
174
  *
@@ -1,11 +1,13 @@
1
1
  import { format, styleText } from 'node:util';
2
- import { Command } from '@oclif/core';
2
+ import { Command, ux } from '@oclif/core';
3
+ import { CLIError, ExitError } from '@oclif/core/errors';
3
4
  import { subdebug } from './_exports/debug.js';
4
5
  import { resolveUnattendedFlagRequirements } from './_exports/flags.js';
5
6
  import { getGlobalCliClient, getProjectCliClient } from './apiClient.js';
6
7
  import { getCliConfig } from './config/cli/getCliConfig.js';
7
8
  import { findProjectRoot } from './config/findProjectRoot.js';
8
9
  import { enrichAuthError } from './errors/enrichAuthError.js';
10
+ import { JsonOutputError } from './errors/JsonOutputError.js';
9
11
  import { NonInteractiveError } from './errors/NonInteractiveError.js';
10
12
  import { ProjectRootNotFoundError } from './errors/ProjectRootNotFoundError.js';
11
13
  import { getCliExecutionContext } from './executionContext.js';
@@ -13,6 +15,7 @@ import { exitCodes } from './exitCodes.js';
13
15
  import { getCliTelemetry, reportCliTraceError } from './telemetry/getCliTelemetry.js';
14
16
  import { isInteractive } from './util/isInteractive.js';
15
17
  import { isUnattendedInvocation, isUnattended as resolveIsUnattended } from './util/isUnattended.js';
18
+ import { hasJsonFlagInArgv, toRelayableErrorJson } from './util/jsonInvocation.js';
16
19
  const debug = subdebug('sanityCommand');
17
20
  export class SanityCommand extends Command {
18
21
  args;
@@ -45,6 +48,8 @@ export class SanityCommand extends Command {
45
48
  */ output = {
46
49
  error: this.error.bind(this),
47
50
  log: this.log.bind(this),
51
+ logDiagnostic: this.logDiagnostic.bind(this),
52
+ logJson: this.logJson.bind(this),
48
53
  warn: this.warn.bind(this)
49
54
  };
50
55
  /**
@@ -59,25 +64,39 @@ export class SanityCommand extends Command {
59
64
  */ async catch(err) {
60
65
  // ExitPromptError is thrown by `@inquirer/prompts` when the user cancels a prompt
61
66
  // The `message === 'SIGINT'` check matches oclif's own convention (see handle.js in @oclif/core)
62
- if (err.name === 'ExitPromptError' || err.message === 'SIGINT') {
63
- this.logToStderr(styleText('yellow', '\u{203A}') + ' Aborted by user');
64
- return this.exit(exitCodes.SIGINT);
67
+ const isUserAbort = err.name === 'ExitPromptError' || err.message === 'SIGINT';
68
+ if (isUserAbort) {
69
+ if (!this.jsonEnabled()) {
70
+ this.logToStderr(styleText('yellow', '\u{203A}') + ' Aborted by user');
71
+ return this.exit(exitCodes.SIGINT);
72
+ }
73
+ err = new CLIError('Aborted by user', {
74
+ exit: exitCodes.SIGINT
75
+ });
76
+ }
77
+ if (err instanceof ExitError) {
78
+ if (err.oclif.exit !== exitCodes.SUCCESS) reportCliTraceError(err);
79
+ if (getCliExecutionContext() || !this.jsonEnabled()) throw err;
80
+ process.exitCode = err.oclif.exit;
81
+ return;
65
82
  }
66
83
  // 401s carry login/membership guidance in their message. Applied here
67
84
  // rather than in transport middleware since client v8 dropped custom
68
85
  // requesters.
69
86
  enrichAuthError(err);
70
87
  // In other cases, we _do_ want to report the error
71
- reportCliTraceError(err);
88
+ if (!isUserAbort) reportCliTraceError(err);
72
89
  // oclif's base `catch` sets `process.exitCode` as a side effect
73
90
  // we do not want to write to the host's own exit status.
74
91
  if (getCliExecutionContext()) {
75
92
  if (this.jsonEnabled()) {
76
93
  this.logJson(this.toErrorJson(err));
77
- return;
78
94
  }
79
95
  throw err;
80
96
  }
97
+ if (this.jsonEnabled()) {
98
+ process.exitCode = err instanceof CLIError ? err.oclif.exit : err.exitCode ?? exitCodes.RUNTIME_ERROR;
99
+ }
81
100
  return super.catch(err);
82
101
  }
83
102
  /**
@@ -195,6 +214,22 @@ export class SanityCommand extends Command {
195
214
  });
196
215
  }
197
216
  /**
217
+ * Whether this run should emit JSON.
218
+ *
219
+ * oclif's own check also treats `SANITY_CONTENT_TYPE=json` as a request for
220
+ * JSON. That reads the host process's environment, so it is consulted only
221
+ * for a real command line: a programmatic invocation must decide from its own
222
+ * arguments, never from whatever the embedding process happens to export.
223
+ */ jsonEnabled() {
224
+ if (!this.ctor.enableJsonFlag) return false;
225
+ if (this.flags) return Boolean(this.flags.json);
226
+ if (!getCliExecutionContext() && super.jsonEnabled()) return true;
227
+ return hasJsonFlagInArgv(this.argv, {
228
+ ...this.ctor.baseFlags,
229
+ ...this.ctor.flags
230
+ });
231
+ }
232
+ /**
198
233
  * Write to stdout — or, when running under an execution context (e.g. from
199
234
  * an MCP server), to the context's `stdout` sink. Mirrors oclif's `log`
200
235
  * semantics: suppressed when `--json` is enabled, printf-style formatting.
@@ -207,6 +242,22 @@ export class SanityCommand extends Command {
207
242
  if (!this.jsonEnabled()) context.stdout(format(message, ...args));
208
243
  }
209
244
  /**
245
+ * Write a diagnostic that stays visible in JSON mode.
246
+ *
247
+ * `log`, `warn` and `logToStderr` are all suppressed once `--json` is on, so
248
+ * a command that skipped part of its work would report the remainder as a
249
+ * complete result. stderr carries it instead, where it cannot corrupt the
250
+ * payload: JSON mode is reachable only from a real command line, since
251
+ * programmatic invocations drop the flag.
252
+ */ logDiagnostic(message) {
253
+ const context = getCliExecutionContext();
254
+ if (context?.stderr) {
255
+ context.stderr(message);
256
+ return;
257
+ }
258
+ ux.stderr(message);
259
+ }
260
+ /**
210
261
  * Pretty-print JSON to stdout — or plain (un-colorized) JSON to the
211
262
  * execution context's `stdout` sink, so programmatic callers don't have to
212
263
  * strip ANSI codes.
@@ -228,21 +279,28 @@ export class SanityCommand extends Command {
228
279
  }
229
280
  if (!this.jsonEnabled()) context.stderr(format(message, ...args));
230
281
  }
231
- parse(options, argv = this.argv) {
232
- // If no flags defined, exit to default parser early
233
- if (!options?.flags) return super.parse(options, argv);
234
- // Resolve the actual required flags based on the current unattended mode value
235
- const resolvedFlags = resolveUnattendedFlagRequirements(options.flags, isUnattendedInvocation({
236
- argv,
237
- isInteractive: this.resolveIsInteractive()
238
- }));
239
- // If flags weren't modified, use original options object
240
- // Otherwise create a new options object with the resolved flag values
241
- const resolvedOptions = resolvedFlags === options.flags ? options : {
242
- ...options,
243
- flags: resolvedFlags
282
+ async parse(options, argv = this.argv) {
283
+ let resolvedOptions = options;
284
+ const jsonEnabled = this.jsonEnabled();
285
+ if (options?.flags) {
286
+ const resolvedFlags = resolveUnattendedFlagRequirements(options.flags, jsonEnabled || isUnattendedInvocation({
287
+ argv,
288
+ isInteractive: this.resolveIsInteractive()
289
+ }));
290
+ if (resolvedFlags !== options.flags) {
291
+ resolvedOptions = {
292
+ ...options,
293
+ flags: resolvedFlags
294
+ };
295
+ }
296
+ }
297
+ const parsed = await super.parse(resolvedOptions, argv);
298
+ const jsonFlag = Boolean(parsed.flags.json) || jsonEnabled;
299
+ parsed.flags = {
300
+ ...parsed.flags,
301
+ json: jsonFlag
244
302
  };
245
- return super.parse(resolvedOptions, argv);
303
+ return parsed;
246
304
  }
247
305
  /**
248
306
  * Resolver for checking if the terminal is interactive. Override in tests to provide mock values.
@@ -263,6 +321,15 @@ export class SanityCommand extends Command {
263
321
  return this._run();
264
322
  }
265
323
  /**
324
+ * A command-specific report wins; otherwise oclif's envelope, trimmed to a
325
+ * bounded set of properties when a programmatic caller will relay it. See
326
+ * {@link toRelayableErrorJson} for why the untrimmed form is unsafe there.
327
+ */ toErrorJson(err) {
328
+ if (err instanceof JsonOutputError) return err.payload;
329
+ if (getCliExecutionContext()) return toRelayableErrorJson(err);
330
+ return super.toErrorJson(err);
331
+ }
332
+ /**
266
333
  * Get the CLI config, returning an empty config if no project root is found.
267
334
  *
268
335
  * Use this instead of `getCliConfig()` in commands that can operate without a
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/SanityCommand.ts"],"sourcesContent":["import {format, styleText} from 'node:util'\n\nimport {Command, Interfaces} from '@oclif/core'\nimport {type CommandError, type Input, type ParserOutput} from '@oclif/core/interfaces'\n\nimport {subdebug} from './_exports/debug.js'\nimport {resolveUnattendedFlagRequirements} from './_exports/flags.js'\nimport {\n getGlobalCliClient,\n getProjectCliClient,\n type GlobalCliClientOptions,\n type ProjectCliClientOptions,\n} from './apiClient.js'\nimport {getCliConfig} from './config/cli/getCliConfig.js'\nimport {type CliConfig} from './config/cli/types/cliConfig.js'\nimport {findProjectRoot} from './config/findProjectRoot.js'\nimport {type ProjectRootResult} from './config/util/recursivelyResolveProjectRoot.js'\nimport {enrichAuthError} from './errors/enrichAuthError.js'\nimport {NonInteractiveError} from './errors/NonInteractiveError.js'\nimport {ProjectRootNotFoundError} from './errors/ProjectRootNotFoundError.js'\nimport {getCliExecutionContext} from './executionContext.js'\nimport {exitCodes} from './exitCodes.js'\nimport {getCliTelemetry, reportCliTraceError} from './telemetry/getCliTelemetry.js'\nimport {type CLITelemetryStore} from './telemetry/types.js'\nimport {type Output} from './types.js'\nimport {isInteractive} from './util/isInteractive.js'\nimport {isUnattendedInvocation, isUnattended as resolveIsUnattended} from './util/isUnattended.js'\n\ntype Flags<T extends typeof Command> = Interfaces.InferredFlags<\n (typeof SanityCommand)['baseFlags'] & T['flags']\n>\n\ntype Args<T extends typeof Command> = Interfaces.InferredArgs<T['args']>\n\ntype ParserValues = Record<string, unknown>\n\nconst debug = subdebug('sanityCommand')\n\n/**\n * Interface for `SanityCommand`, a wrapper around OCLIF's Command class.\n * Important to keep updated as `SanityCommand` evolves so that its mock implementation (enabling fast unit tests) stays up to date as well.\n * @see https://oclif.io/docs/base_class/\n */\nexport interface SanityCommandInterface {\n getCliConfig: () => Promise<CliConfig>\n getProjectId: (options?: {\n deprecatedFlagName?: string\n fallback?: () => Promise<string>\n }) => Promise<string>\n getProjectRoot: () => Promise<ProjectRootResult>\n isUnattended: () => boolean\n output: Output\n resolveIsInteractive: () => boolean\n}\n\nexport abstract class SanityCommand<T extends typeof Command>\n extends Command\n implements SanityCommandInterface\n{\n protected args!: Args<T>\n protected flags!: Flags<T>\n\n /**\n * Get the global API client.\n *\n * @param args - The global API client options.\n * @returns The global API client.\n *\n * @deprecated use `getGlobalCliClient` function directly instead.\n */\n protected getGlobalApiClient = (args: GlobalCliClientOptions) => getGlobalCliClient(args)\n\n /**\n * Get the project API client.\n *\n * @param args - The project API client options.\n * @returns The project API client.\n *\n * @deprecated use `getProjectCliClient` function directly instead.\n */\n protected getProjectApiClient = (args: ProjectCliClientOptions) => getProjectCliClient(args)\n\n /**\n * Helper for outputting to the console.\n *\n * @example\n * ```ts\n * this.output.log('Hello')\n * this.output.warn('Warning')\n * this.output.error('Error')\n * ```\n */\n public output: Output = {\n error: this.error.bind(this),\n log: this.log.bind(this),\n warn: this.warn.bind(this),\n }\n\n /**\n * The telemetry store.\n *\n * @returns The telemetry store.\n */\n protected telemetry!: CLITelemetryStore\n\n /**\n * Report real command errors to the CLI command trace.\n * User aborts (SIGINT, ExitPromptError) are not reported — the trace is left\n * incomplete, which accurately represents that the command was interrupted.\n */\n protected override async catch(err: CommandError): Promise<void> {\n // ExitPromptError is thrown by `@inquirer/prompts` when the user cancels a prompt\n // The `message === 'SIGINT'` check matches oclif's own convention (see handle.js in @oclif/core)\n if (err.name === 'ExitPromptError' || err.message === 'SIGINT') {\n this.logToStderr(styleText('yellow', '\\u{203A}') + ' Aborted by user')\n return this.exit(exitCodes.SIGINT)\n }\n\n // 401s carry login/membership guidance in their message. Applied here\n // rather than in transport middleware since client v8 dropped custom\n // requesters.\n enrichAuthError(err)\n\n // In other cases, we _do_ want to report the error\n reportCliTraceError(err)\n\n // oclif's base `catch` sets `process.exitCode` as a side effect\n // we do not want to write to the host's own exit status.\n if (getCliExecutionContext()) {\n if (this.jsonEnabled()) {\n this.logJson(this.toErrorJson(err))\n return\n }\n throw err\n }\n\n return super.catch(err)\n }\n\n /**\n * Get the CLI config.\n *\n * @returns The CLI config.\n */\n public async getCliConfig(): Promise<CliConfig> {\n const root = await this.getProjectRoot()\n\n debug(`Using project root`, root)\n return getCliConfig(root.directory)\n }\n\n /**\n * Get the project ID from passed flags or (if not provided) the CLI config.\n *\n * Optionally accepts a `fallback` function that is called when no project ID\n * can be determined from flags or config. This allows commands to provide\n * interactive project selection while keeping the prompt logic in the CLI package.\n *\n * If the fallback throws a `NonInteractiveError` (e.g. because the terminal is\n * not interactive), it falls through to the standard error with suggestions.\n *\n * Optionally accepts a `deprecatedFlagName` for commands that have a deprecated\n * flag (e.g. `--project`) that should be checked after `--project-id` but before\n * the CLI config.\n *\n * @returns The project ID.\n */\n public async getProjectId(options?: {\n deprecatedFlagName?: string\n fallback?: () => Promise<string>\n }): Promise<string> {\n const hasProjectFlag = this.ctor.flags != null && 'project-id' in this.ctor.flags\n\n // Check --project-id flag first\n if (hasProjectFlag) {\n const flagProjectId =\n 'project-id' in this.flags && typeof this.flags['project-id'] === 'string'\n ? this.flags['project-id']\n : undefined\n\n if (flagProjectId) return flagProjectId\n }\n\n // Check deprecated flag (e.g. --project) before CLI config\n if (options?.deprecatedFlagName) {\n const deprecatedValue =\n options.deprecatedFlagName in this.flags &&\n typeof this.flags[options.deprecatedFlagName] === 'string'\n ? (this.flags[options.deprecatedFlagName] as string)\n : undefined\n\n if (deprecatedValue) return deprecatedValue\n }\n\n // Fall back to CLI config\n try {\n const config = await this.getCliConfig()\n const configProjectId = config.api?.projectId\n if (configProjectId) return configProjectId\n } catch (err) {\n if (!(err instanceof ProjectRootNotFoundError)) throw err\n // No project root — fall through to fallback/error\n }\n\n // Offer interactive selection if a fallback was provided\n if (options?.fallback) {\n try {\n return await options.fallback()\n } catch (err) {\n if (!(err instanceof NonInteractiveError)) throw err\n // Non-interactive: throw with actionable suggestions\n throw new ProjectRootNotFoundError('Unable to determine project ID', {\n cause: err,\n suggestions: [\n ...(hasProjectFlag ? ['Providing a project ID: --project-id <project-id>'] : []),\n 'Running this command from within a Sanity project directory',\n 'Running in an interactive terminal to get a project selection prompt',\n ],\n })\n }\n }\n\n throw new ProjectRootNotFoundError('Unable to determine project ID', {\n suggestions: [\n ...(hasProjectFlag ? ['Providing a project ID: --project-id <project-id>'] : []),\n 'Running this command from within a Sanity project directory',\n ],\n })\n }\n\n /**\n * Get the project's root directory by resolving the config\n *\n * @returns The project root result.\n */\n public getProjectRoot(): Promise<ProjectRootResult> {\n if (getCliExecutionContext()) {\n throw new ProjectRootNotFoundError(\n 'Project root resolution from the filesystem is disabled for programmatic invocations',\n )\n }\n return findProjectRoot(process.cwd())\n }\n\n public async init(): Promise<void> {\n const {args, flags} = await this.parse({\n args: this.ctor.args,\n baseFlags: (super.ctor as typeof SanityCommand).baseFlags,\n enableJsonFlag: this.ctor.enableJsonFlag,\n flags: this.ctor.flags,\n strict: this.ctor.strict,\n })\n\n this.args = args as Args<T>\n this.flags = flags as Flags<T>\n this.telemetry = getCliTelemetry()\n\n await super.init()\n }\n\n /**\n * Check if the command is running in unattended mode.\n *\n * This means the command should not ask for user input, instead using defaults where\n * possible, and if that does not make sense (eg there's missing information), then we\n * should error out (remember to exit with a non-zero code).\n *\n * Most commands should take an explicit `--yes` flag to enable unattended mode, but\n * some commands may also be run in unattended mode if `process.stdin` is not a TTY\n * (eg when running in a CI environment), or when `--json` asks for machine-readable\n * output (a caller parsing JSON can't answer a prompt).\n */\n public isUnattended(): boolean {\n return resolveIsUnattended({\n isInteractive: this.resolveIsInteractive(),\n json: this.flags.json,\n yes: this.flags.yes,\n })\n }\n\n /**\n * Write to stdout — or, when running under an execution context (e.g. from\n * an MCP server), to the context's `stdout` sink. Mirrors oclif's `log`\n * semantics: suppressed when `--json` is enabled, printf-style formatting.\n */\n public override log(message = '', ...args: unknown[]): void {\n const context = getCliExecutionContext()\n if (!context?.stdout) {\n super.log(message, ...args)\n return\n }\n if (!this.jsonEnabled()) context.stdout(format(message, ...args))\n }\n\n /**\n * Pretty-print JSON to stdout — or plain (un-colorized) JSON to the\n * execution context's `stdout` sink, so programmatic callers don't have to\n * strip ANSI codes.\n */\n public override logJson(json: unknown): void {\n const context = getCliExecutionContext()\n if (!context?.stdout) {\n super.logJson(json)\n return\n }\n context.stdout(JSON.stringify(json, null, 2))\n }\n\n /**\n * Like `log`, but for stderr / the context's `stderr` sink.\n */\n public override logToStderr(message = '', ...args: unknown[]): void {\n const context = getCliExecutionContext()\n if (!context?.stderr) {\n super.logToStderr(message, ...args)\n return\n }\n if (!this.jsonEnabled()) context.stderr(format(message, ...args))\n }\n\n protected override parse<F extends ParserValues, B extends ParserValues, A extends ParserValues>(\n options?: Input<F, B, A>,\n argv: string[] = this.argv,\n ): Promise<ParserOutput<F, B, A>> {\n // If no flags defined, exit to default parser early\n if (!options?.flags) return super.parse(options, argv)\n\n // Resolve the actual required flags based on the current unattended mode value\n const resolvedFlags = resolveUnattendedFlagRequirements(\n options.flags,\n isUnattendedInvocation({argv, isInteractive: this.resolveIsInteractive()}),\n )\n // If flags weren't modified, use original options object\n // Otherwise create a new options object with the resolved flag values\n const resolvedOptions =\n resolvedFlags === options.flags\n ? options\n : {...options, flags: resolvedFlags as Interfaces.FlagInput<F>}\n\n return super.parse(resolvedOptions, argv)\n }\n\n /**\n * Resolver for checking if the terminal is interactive. Override in tests to provide mock values.\n *\n * @returns Whether the terminal is interactive.\n */\n public resolveIsInteractive(): boolean {\n return isInteractive()\n }\n\n /**\n * Execute an already-constructed command without oclif's static runner:\n * `Command.run()` performs a full `Config.load()` — filesystem reads, env\n * consultation, and a process-global config cache write — on every call,\n * which programmatic invocations must not repeat per request.\n */\n public runInExecutionContext<TResult>(): Promise<TResult> {\n if (!getCliExecutionContext()) {\n throw new Error('runInExecutionContext requires a CLI execution context')\n }\n return this._run<TResult>()\n }\n\n /**\n * Get the CLI config, returning an empty config if no project root is found.\n *\n * Use this instead of `getCliConfig()` in commands that can operate without a\n * project directory (e.g. when `--project-id` and `--dataset` flags are provided).\n *\n * @returns The CLI config, or an empty config object if no project root is found.\n */\n protected async tryGetCliConfig(): Promise<CliConfig> {\n try {\n return await this.getCliConfig()\n } catch (err) {\n if (!(err instanceof ProjectRootNotFoundError)) throw err\n return {}\n }\n }\n\n /**\n * Emit a warning — routed to the execution context's `stderr` sink when one\n * is active, otherwise through oclif's standard warning printer.\n */\n public override warn(input: Error | string): Error | string {\n const context = getCliExecutionContext()\n if (!context?.stderr) return super.warn(input)\n\n if (!this.jsonEnabled()) {\n context.stderr(`Warning: ${input instanceof Error ? input.message : input}`)\n }\n return input\n }\n}\n"],"names":["format","styleText","Command","subdebug","resolveUnattendedFlagRequirements","getGlobalCliClient","getProjectCliClient","getCliConfig","findProjectRoot","enrichAuthError","NonInteractiveError","ProjectRootNotFoundError","getCliExecutionContext","exitCodes","getCliTelemetry","reportCliTraceError","isInteractive","isUnattendedInvocation","isUnattended","resolveIsUnattended","debug","SanityCommand","args","flags","getGlobalApiClient","getProjectApiClient","output","error","bind","log","warn","telemetry","catch","err","name","message","logToStderr","exit","SIGINT","jsonEnabled","logJson","toErrorJson","root","getProjectRoot","directory","getProjectId","options","hasProjectFlag","ctor","flagProjectId","undefined","deprecatedFlagName","deprecatedValue","config","configProjectId","api","projectId","fallback","cause","suggestions","process","cwd","init","parse","baseFlags","enableJsonFlag","strict","resolveIsInteractive","json","yes","context","stdout","JSON","stringify","stderr","argv","resolvedFlags","resolvedOptions","runInExecutionContext","Error","_run","tryGetCliConfig","input"],"mappings":"AAAA,SAAQA,MAAM,EAAEC,SAAS,QAAO,YAAW;AAE3C,SAAQC,OAAO,QAAmB,cAAa;AAG/C,SAAQC,QAAQ,QAAO,sBAAqB;AAC5C,SAAQC,iCAAiC,QAAO,sBAAqB;AACrE,SACEC,kBAAkB,EAClBC,mBAAmB,QAGd,iBAAgB;AACvB,SAAQC,YAAY,QAAO,+BAA8B;AAEzD,SAA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K,CAACb,MAAMc,iBAAiBF;IACtC;IAEA;;;;GAIC,GACD,AAAOR,uBAAgC;QACrC,OAAOnD;IACT;IAEA;;;;;GAKC,GACD,AAAO8D,wBAAmD;QACxD,IAAI,CAAClE,0BAA0B;YAC7B,MAAM,IAAImE,MAAM;QAClB;QACA,OAAO,IAAI,CAACC,IAAI;IAClB;IAEA;;;;;;;GAOC,GACD,MAAgBC,kBAAsC;QACpD,IAAI;YACF,OAAO,MAAM,IAAI,CAAC1E,YAAY;QAChC,EAAE,OAAO0B,KAAK;YACZ,IAAI,CAAEA,CAAAA,eAAetB,wBAAuB,GAAI,MAAMsB;YACtD,OAAO,CAAC;QACV;IACF;IAEA;;;GAGC,GACD,AAAgBH,KAAKoD,KAAqB,EAAkB;QAC1D,MAAMZ,UAAU1D;QAChB,IAAI,CAAC0D,SAASI,QAAQ,OAAO,KAAK,CAAC5C,KAAKoD;QAExC,IAAI,CAAC,IAAI,CAAC3C,WAAW,IAAI;YACvB+B,QAAQI,MAAM,CAAC,CAAC,SAAS,EAAEQ,iBAAiBH,QAAQG,MAAM/C,OAAO,GAAG+C,OAAO;QAC7E;QACA,OAAOA;IACT;AACF"}
1
+ {"version":3,"sources":["../src/SanityCommand.ts"],"sourcesContent":["import {format, styleText} from 'node:util'\n\nimport {Command, Interfaces, ux} from '@oclif/core'\nimport {CLIError, ExitError} from '@oclif/core/errors'\nimport {type CommandError, type Input, type ParserOutput} from '@oclif/core/interfaces'\n\nimport {subdebug} from './_exports/debug.js'\nimport {resolveUnattendedFlagRequirements} from './_exports/flags.js'\nimport {\n getGlobalCliClient,\n getProjectCliClient,\n type GlobalCliClientOptions,\n type ProjectCliClientOptions,\n} from './apiClient.js'\nimport {getCliConfig} from './config/cli/getCliConfig.js'\nimport {type CliConfig} from './config/cli/types/cliConfig.js'\nimport {findProjectRoot} from './config/findProjectRoot.js'\nimport {type ProjectRootResult} from './config/util/recursivelyResolveProjectRoot.js'\nimport {enrichAuthError} from './errors/enrichAuthError.js'\nimport {JsonOutputError} from './errors/JsonOutputError.js'\nimport {NonInteractiveError} from './errors/NonInteractiveError.js'\nimport {ProjectRootNotFoundError} from './errors/ProjectRootNotFoundError.js'\nimport {getCliExecutionContext} from './executionContext.js'\nimport {exitCodes} from './exitCodes.js'\nimport {getCliTelemetry, reportCliTraceError} from './telemetry/getCliTelemetry.js'\nimport {type CLITelemetryStore} from './telemetry/types.js'\nimport {type Output} from './types.js'\nimport {isInteractive} from './util/isInteractive.js'\nimport {isUnattendedInvocation, isUnattended as resolveIsUnattended} from './util/isUnattended.js'\nimport {hasJsonFlagInArgv, toRelayableErrorJson} from './util/jsonInvocation.js'\n\ntype Flags<T extends typeof Command> = Interfaces.InferredFlags<\n (typeof SanityCommand)['baseFlags'] & T['flags']\n>\n\ntype Args<T extends typeof Command> = Interfaces.InferredArgs<T['args']>\n\ntype ParserValues = Record<string, unknown>\n\nconst debug = subdebug('sanityCommand')\n\n/**\n * Interface for `SanityCommand`, a wrapper around OCLIF's Command class.\n * Important to keep updated as `SanityCommand` evolves so that its mock implementation (enabling fast unit tests) stays up to date as well.\n * @see https://oclif.io/docs/base_class/\n */\nexport interface SanityCommandInterface {\n getCliConfig: () => Promise<CliConfig>\n getProjectId: (options?: {\n deprecatedFlagName?: string\n fallback?: () => Promise<string>\n }) => Promise<string>\n getProjectRoot: () => Promise<ProjectRootResult>\n isUnattended: () => boolean\n output: Output\n resolveIsInteractive: () => boolean\n}\n\nexport abstract class SanityCommand<T extends typeof Command>\n extends Command\n implements SanityCommandInterface\n{\n protected args!: Args<T>\n protected flags!: Flags<T>\n\n /**\n * Get the global API client.\n *\n * @param args - The global API client options.\n * @returns The global API client.\n *\n * @deprecated use `getGlobalCliClient` function directly instead.\n */\n protected getGlobalApiClient = (args: GlobalCliClientOptions) => getGlobalCliClient(args)\n\n /**\n * Get the project API client.\n *\n * @param args - The project API client options.\n * @returns The project API client.\n *\n * @deprecated use `getProjectCliClient` function directly instead.\n */\n protected getProjectApiClient = (args: ProjectCliClientOptions) => getProjectCliClient(args)\n\n /**\n * Helper for outputting to the console.\n *\n * @example\n * ```ts\n * this.output.log('Hello')\n * this.output.warn('Warning')\n * this.output.error('Error')\n * ```\n */\n public output: Output = {\n error: this.error.bind(this),\n log: this.log.bind(this),\n logDiagnostic: this.logDiagnostic.bind(this),\n logJson: this.logJson.bind(this),\n warn: this.warn.bind(this),\n }\n\n /**\n * The telemetry store.\n *\n * @returns The telemetry store.\n */\n protected telemetry!: CLITelemetryStore\n /**\n * Report real command errors to the CLI command trace.\n * User aborts (SIGINT, ExitPromptError) are not reported — the trace is left\n * incomplete, which accurately represents that the command was interrupted.\n */\n protected override async catch(err: CommandError): Promise<void> {\n // ExitPromptError is thrown by `@inquirer/prompts` when the user cancels a prompt\n // The `message === 'SIGINT'` check matches oclif's own convention (see handle.js in @oclif/core)\n const isUserAbort = err.name === 'ExitPromptError' || err.message === 'SIGINT'\n if (isUserAbort) {\n if (!this.jsonEnabled()) {\n this.logToStderr(styleText('yellow', '\\u{203A}') + ' Aborted by user')\n return this.exit(exitCodes.SIGINT)\n }\n err = new CLIError('Aborted by user', {exit: exitCodes.SIGINT})\n }\n\n if (err instanceof ExitError) {\n if (err.oclif.exit !== exitCodes.SUCCESS) reportCliTraceError(err)\n if (getCliExecutionContext() || !this.jsonEnabled()) throw err\n process.exitCode = err.oclif.exit\n return\n }\n\n // 401s carry login/membership guidance in their message. Applied here\n // rather than in transport middleware since client v8 dropped custom\n // requesters.\n enrichAuthError(err)\n\n // In other cases, we _do_ want to report the error\n if (!isUserAbort) reportCliTraceError(err)\n\n // oclif's base `catch` sets `process.exitCode` as a side effect\n // we do not want to write to the host's own exit status.\n if (getCliExecutionContext()) {\n if (this.jsonEnabled()) {\n this.logJson(this.toErrorJson(err))\n }\n throw err\n }\n\n if (this.jsonEnabled()) {\n process.exitCode =\n err instanceof CLIError ? err.oclif.exit : (err.exitCode ?? exitCodes.RUNTIME_ERROR)\n }\n return super.catch(err)\n }\n\n /**\n * Get the CLI config.\n *\n * @returns The CLI config.\n */\n public async getCliConfig(): Promise<CliConfig> {\n const root = await this.getProjectRoot()\n\n debug(`Using project root`, root)\n return getCliConfig(root.directory)\n }\n\n /**\n * Get the project ID from passed flags or (if not provided) the CLI config.\n *\n * Optionally accepts a `fallback` function that is called when no project ID\n * can be determined from flags or config. This allows commands to provide\n * interactive project selection while keeping the prompt logic in the CLI package.\n *\n * If the fallback throws a `NonInteractiveError` (e.g. because the terminal is\n * not interactive), it falls through to the standard error with suggestions.\n *\n * Optionally accepts a `deprecatedFlagName` for commands that have a deprecated\n * flag (e.g. `--project`) that should be checked after `--project-id` but before\n * the CLI config.\n *\n * @returns The project ID.\n */\n public async getProjectId(options?: {\n deprecatedFlagName?: string\n fallback?: () => Promise<string>\n }): Promise<string> {\n const hasProjectFlag = this.ctor.flags != null && 'project-id' in this.ctor.flags\n\n // Check --project-id flag first\n if (hasProjectFlag) {\n const flagProjectId =\n 'project-id' in this.flags && typeof this.flags['project-id'] === 'string'\n ? this.flags['project-id']\n : undefined\n\n if (flagProjectId) return flagProjectId\n }\n\n // Check deprecated flag (e.g. --project) before CLI config\n if (options?.deprecatedFlagName) {\n const deprecatedValue =\n options.deprecatedFlagName in this.flags &&\n typeof this.flags[options.deprecatedFlagName] === 'string'\n ? (this.flags[options.deprecatedFlagName] as string)\n : undefined\n\n if (deprecatedValue) return deprecatedValue\n }\n\n // Fall back to CLI config\n try {\n const config = await this.getCliConfig()\n const configProjectId = config.api?.projectId\n if (configProjectId) return configProjectId\n } catch (err) {\n if (!(err instanceof ProjectRootNotFoundError)) throw err\n // No project root — fall through to fallback/error\n }\n\n // Offer interactive selection if a fallback was provided\n if (options?.fallback) {\n try {\n return await options.fallback()\n } catch (err) {\n if (!(err instanceof NonInteractiveError)) throw err\n // Non-interactive: throw with actionable suggestions\n throw new ProjectRootNotFoundError('Unable to determine project ID', {\n cause: err,\n suggestions: [\n ...(hasProjectFlag ? ['Providing a project ID: --project-id <project-id>'] : []),\n 'Running this command from within a Sanity project directory',\n 'Running in an interactive terminal to get a project selection prompt',\n ],\n })\n }\n }\n\n throw new ProjectRootNotFoundError('Unable to determine project ID', {\n suggestions: [\n ...(hasProjectFlag ? ['Providing a project ID: --project-id <project-id>'] : []),\n 'Running this command from within a Sanity project directory',\n ],\n })\n }\n\n /**\n * Get the project's root directory by resolving the config\n *\n * @returns The project root result.\n */\n public getProjectRoot(): Promise<ProjectRootResult> {\n if (getCliExecutionContext()) {\n throw new ProjectRootNotFoundError(\n 'Project root resolution from the filesystem is disabled for programmatic invocations',\n )\n }\n return findProjectRoot(process.cwd())\n }\n\n public async init(): Promise<void> {\n const {args, flags} = await this.parse({\n args: this.ctor.args,\n baseFlags: (super.ctor as typeof SanityCommand).baseFlags,\n enableJsonFlag: this.ctor.enableJsonFlag,\n flags: this.ctor.flags,\n strict: this.ctor.strict,\n })\n\n this.args = args as Args<T>\n this.flags = flags as Flags<T>\n this.telemetry = getCliTelemetry()\n\n await super.init()\n }\n\n /**\n * Check if the command is running in unattended mode.\n *\n * This means the command should not ask for user input, instead using defaults where\n * possible, and if that does not make sense (eg there's missing information), then we\n * should error out (remember to exit with a non-zero code).\n *\n * Most commands should take an explicit `--yes` flag to enable unattended mode, but\n * some commands may also be run in unattended mode if `process.stdin` is not a TTY\n * (eg when running in a CI environment), or when `--json` asks for machine-readable\n * output (a caller parsing JSON can't answer a prompt).\n */\n public isUnattended(): boolean {\n return resolveIsUnattended({\n isInteractive: this.resolveIsInteractive(),\n json: this.flags.json,\n yes: this.flags.yes,\n })\n }\n\n /**\n * Whether this run should emit JSON.\n *\n * oclif's own check also treats `SANITY_CONTENT_TYPE=json` as a request for\n * JSON. That reads the host process's environment, so it is consulted only\n * for a real command line: a programmatic invocation must decide from its own\n * arguments, never from whatever the embedding process happens to export.\n */\n public override jsonEnabled(): boolean {\n if (!this.ctor.enableJsonFlag) return false\n if (this.flags) return Boolean(this.flags.json)\n\n if (!getCliExecutionContext() && super.jsonEnabled()) return true\n return hasJsonFlagInArgv(this.argv, {...this.ctor.baseFlags, ...this.ctor.flags})\n }\n\n /**\n * Write to stdout — or, when running under an execution context (e.g. from\n * an MCP server), to the context's `stdout` sink. Mirrors oclif's `log`\n * semantics: suppressed when `--json` is enabled, printf-style formatting.\n */\n public override log(message = '', ...args: unknown[]): void {\n const context = getCliExecutionContext()\n if (!context?.stdout) {\n super.log(message, ...args)\n return\n }\n if (!this.jsonEnabled()) context.stdout(format(message, ...args))\n }\n\n /**\n * Write a diagnostic that stays visible in JSON mode.\n *\n * `log`, `warn` and `logToStderr` are all suppressed once `--json` is on, so\n * a command that skipped part of its work would report the remainder as a\n * complete result. stderr carries it instead, where it cannot corrupt the\n * payload: JSON mode is reachable only from a real command line, since\n * programmatic invocations drop the flag.\n */\n public logDiagnostic(message: string): void {\n const context = getCliExecutionContext()\n if (context?.stderr) {\n context.stderr(message)\n return\n }\n ux.stderr(message)\n }\n\n /**\n * Pretty-print JSON to stdout — or plain (un-colorized) JSON to the\n * execution context's `stdout` sink, so programmatic callers don't have to\n * strip ANSI codes.\n */\n public override logJson(json: unknown): void {\n const context = getCliExecutionContext()\n if (!context?.stdout) {\n super.logJson(json)\n return\n }\n context.stdout(JSON.stringify(json, null, 2))\n }\n\n /**\n * Like `log`, but for stderr / the context's `stderr` sink.\n */\n public override logToStderr(message = '', ...args: unknown[]): void {\n const context = getCliExecutionContext()\n if (!context?.stderr) {\n super.logToStderr(message, ...args)\n return\n }\n if (!this.jsonEnabled()) context.stderr(format(message, ...args))\n }\n\n protected override async parse<\n F extends ParserValues,\n B extends ParserValues,\n A extends ParserValues,\n >(options?: Input<F, B, A>, argv: string[] = this.argv): Promise<ParserOutput<F, B, A>> {\n let resolvedOptions = options\n const jsonEnabled = this.jsonEnabled()\n\n if (options?.flags) {\n const resolvedFlags = resolveUnattendedFlagRequirements(\n options.flags,\n jsonEnabled || isUnattendedInvocation({argv, isInteractive: this.resolveIsInteractive()}),\n )\n if (resolvedFlags !== options.flags) {\n resolvedOptions = {...options, flags: resolvedFlags as Interfaces.FlagInput<F>}\n }\n }\n\n const parsed = await super.parse(resolvedOptions, argv)\n const jsonFlag = Boolean(parsed.flags.json) || jsonEnabled\n\n parsed.flags = {...parsed.flags, json: jsonFlag}\n return parsed\n }\n\n /**\n * Resolver for checking if the terminal is interactive. Override in tests to provide mock values.\n *\n * @returns Whether the terminal is interactive.\n */\n public resolveIsInteractive(): boolean {\n return isInteractive()\n }\n\n /**\n * Execute an already-constructed command without oclif's static runner:\n * `Command.run()` performs a full `Config.load()` — filesystem reads, env\n * consultation, and a process-global config cache write — on every call,\n * which programmatic invocations must not repeat per request.\n */\n public runInExecutionContext<TResult>(): Promise<TResult> {\n if (!getCliExecutionContext()) {\n throw new Error('runInExecutionContext requires a CLI execution context')\n }\n return this._run<TResult>()\n }\n\n /**\n * A command-specific report wins; otherwise oclif's envelope, trimmed to a\n * bounded set of properties when a programmatic caller will relay it. See\n * {@link toRelayableErrorJson} for why the untrimmed form is unsafe there.\n */\n public override toErrorJson(err: unknown): unknown {\n if (err instanceof JsonOutputError) return err.payload\n if (getCliExecutionContext()) return toRelayableErrorJson(err)\n return super.toErrorJson(err)\n }\n\n /**\n * Get the CLI config, returning an empty config if no project root is found.\n *\n * Use this instead of `getCliConfig()` in commands that can operate without a\n * project directory (e.g. when `--project-id` and `--dataset` flags are provided).\n *\n * @returns The CLI config, or an empty config object if no project root is found.\n */\n protected async tryGetCliConfig(): Promise<CliConfig> {\n try {\n return await this.getCliConfig()\n } catch (err) {\n if (!(err instanceof ProjectRootNotFoundError)) throw err\n return {}\n }\n }\n\n /**\n * Emit a warning — routed to the execution context's `stderr` sink when one\n * is active, otherwise through oclif's standard warning printer.\n */\n public override warn(input: Error | string): Error | string {\n const context = getCliExecutionContext()\n if (!context?.stderr) return super.warn(input)\n\n if (!this.jsonEnabled()) {\n context.stderr(`Warning: ${input instanceof Error ? input.message : input}`)\n }\n return input\n }\n}\n"],"names":["format","styleText","Command","ux","CLIError","ExitError","subdebug","resolveUnattendedFlagRequirements","getGlobalCliClient","getProjectCliClient","getCliConfig","findProjectRoot","enrichAuthError","JsonOutputError","NonInteractiveError","ProjectRootNotFoundError","getCliExecutionContext","exitCodes","getCliTelemetry","reportCliTraceError","isInteractive","isUnattendedInvocation","isUnattended","resolveIsUnattended","hasJsonFlagInArgv","toRelayableErrorJson","debug","SanityCommand","args","flags","getGlobalApiClient","getProjectApiClient","output","error","bind","log","logDiagnostic","logJson","warn","telemetry","catch","err","isUserAbort","name","message","jsonEnabled","logToStderr","exit","SIGINT","oclif","SUCCESS","process","exitCode","toErrorJson","RUNTIME_ERROR","root","getProjectRoot","directory","getProjectId","options","hasProjectFlag","ctor","flagProjectId","undefined","deprecatedFlagName","deprecatedValue","config","configProjectId","api","projectId","fallback","cause","suggestions","cwd","init","parse","baseFlags","enableJsonFlag","strict","resolveIsInteractive","json","yes","Boolean","argv","context","stdout","stderr","JSON","stringify","resolvedOptions","resolvedFlags","parsed","jsonFlag","runInExecutionContext","Error","_run","payload","tryGetCliConfig","input"],"mappings":"AAAA,SAAQA,MAAM,EAAEC,SAAS,QAAO,YAAW;AAE3C,SAAQC,OAAO,EAAcC,EAAE,QAAO,cAAa;AACnD,SAAQC,QAAQ,EAAEC,SAAS,QAAO,qBAAoB;AAGtD,SAAQC,QAAQ,QAAO,sBAAqB;AAC5C,SAAQC,iCAAiC,QAAO,sBAAqB;AACrE,SACEC,kBAAkB,EAClBC,mBAAmB,QAGd,iBAAgB;AACvB,SAAQC,YAAY,QAAO,+BAA8B;AAEzD,SAAQC,eAAe,QAAO,8BAA6B;AAE3D,SAAQC,eAAe,QAAO,8BAA6B;AAC3D,SAAQC,eAAe,QAAO,8BAA6B;AAC3D,SAAQC,mBAAmB,QAAO,kCAAiC;AACnE,SAAQC,wBAAwB,QAAO,uCAAsC;AAC7E,SAAQC,sBAAsB,QAAO,wBAAuB;AAC5D,SAAQC,SAAS,QAAO,iBAAgB;AACxC,SAAQC,eAAe,EAAEC,mBAAmB,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AMY;QAAQ;QAC/C,OAAOD;IACT;IAEA;;;;GAIC,GACD,AAAOZ,uBAAgC;QACrC,OAAO3D;IACT;IAEA;;;;;GAKC,GACD,AAAOyE,wBAAmD;QACxD,IAAI,CAAC7E,0BAA0B;YAC7B,MAAM,IAAI8E,MAAM;QAClB;QACA,OAAO,IAAI,CAACC,IAAI;IAClB;IAEA;;;;GAIC,GACD,AAAgB1C,YAAYZ,GAAY,EAAW;QACjD,IAAIA,eAAe5B,iBAAiB,OAAO4B,IAAIuD,OAAO;QACtD,IAAIhF,0BAA0B,OAAOS,qBAAqBgB;QAC1D,OAAO,KAAK,CAACY,YAAYZ;IAC3B;IAEA;;;;;;;GAOC,GACD,MAAgBwD,kBAAsC;QACpD,IAAI;YACF,OAAO,MAAM,IAAI,CAACvF,YAAY;QAChC,EAAE,OAAO+B,KAAK;YACZ,IAAI,CAAEA,CAAAA,eAAe1B,wBAAuB,GAAI,MAAM0B;YACtD,OAAO,CAAC;QACV;IACF;IAEA;;;GAGC,GACD,AAAgBH,KAAK4D,KAAqB,EAAkB;QAC1D,MAAMd,UAAUpE;QAChB,IAAI,CAACoE,SAASE,QAAQ,OAAO,KAAK,CAAChD,KAAK4D;QAExC,IAAI,CAAC,IAAI,CAACrD,WAAW,IAAI;YACvBuC,QAAQE,MAAM,CAAC,CAAC,SAAS,EAAEY,iBAAiBJ,QAAQI,MAAMtD,OAAO,GAAGsD,OAAO;QAC7E;QACA,OAAOA;IACT;AACF"}
@@ -1,5 +1,6 @@
1
1
  import { t as NonInteractiveError } from "../NonInteractiveError-CSLT5y93.js";
2
2
  import { i as isNotFoundError, n as isProjectRootNotFoundError, r as NotFoundError, t as ProjectRootNotFoundError } from "../ProjectRootNotFoundError-RgthN9uy.js";
3
+ import { CLIError } from "@oclif/core/errors";
3
4
  /**
4
5
  * Coerce an unknown thrown value into an Error instance.
5
6
  *
@@ -16,5 +17,10 @@ declare function toError(value: unknown): Error;
16
17
  * @internal
17
18
  */
18
19
  declare function getErrorMessage(err: unknown): string;
19
- export { NonInteractiveError, NotFoundError, ProjectRootNotFoundError, getErrorMessage, isNotFoundError, isProjectRootNotFoundError, toError };
20
+ /** A command failure with an existing JSON response or diagnostic report. */
21
+ declare class JsonOutputError extends CLIError {
22
+ readonly payload: unknown;
23
+ constructor(message: string, payload: unknown, exit: number);
24
+ }
25
+ export { JsonOutputError, NonInteractiveError, NotFoundError, ProjectRootNotFoundError, getErrorMessage, isNotFoundError, isProjectRootNotFoundError, toError };
20
26
  //# sourceMappingURL=errors.d.ts.map
@@ -1,4 +1,5 @@
1
1
  export { getErrorMessage, toError } from '../errors/getErrorMessage.js';
2
+ export { JsonOutputError } from '../errors/JsonOutputError.js';
2
3
  export { NonInteractiveError } from '../errors/NonInteractiveError.js';
3
4
  export { isNotFoundError, NotFoundError } from '../errors/NotFoundError.js';
4
5
  export { isProjectRootNotFoundError, ProjectRootNotFoundError } from '../errors/ProjectRootNotFoundError.js';
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/_exports/errors.ts"],"sourcesContent":["export {getErrorMessage, toError} from '../errors/getErrorMessage.js'\nexport {NonInteractiveError} from '../errors/NonInteractiveError.js'\nexport {isNotFoundError, NotFoundError} from '../errors/NotFoundError.js'\nexport {\n isProjectRootNotFoundError,\n ProjectRootNotFoundError,\n} from '../errors/ProjectRootNotFoundError.js'\n"],"names":["getErrorMessage","toError","NonInteractiveError","isNotFoundError","NotFoundError","isProjectRootNotFoundError","ProjectRootNotFoundError"],"mappings":"AAAA,SAAQA,eAAe,EAAEC,OAAO,QAAO,+BAA8B;AACrE,SAAQC,mBAAmB,QAAO,mCAAkC;AACpE,SAAQC,eAAe,EAAEC,aAAa,QAAO,6BAA4B;AACzE,SACEC,0BAA0B,EAC1BC,wBAAwB,QACnB,wCAAuC"}
1
+ {"version":3,"sources":["../../src/_exports/errors.ts"],"sourcesContent":["export {getErrorMessage, toError} from '../errors/getErrorMessage.js'\nexport {JsonOutputError} from '../errors/JsonOutputError.js'\nexport {NonInteractiveError} from '../errors/NonInteractiveError.js'\nexport {isNotFoundError, NotFoundError} from '../errors/NotFoundError.js'\nexport {\n isProjectRootNotFoundError,\n ProjectRootNotFoundError,\n} from '../errors/ProjectRootNotFoundError.js'\n"],"names":["getErrorMessage","toError","JsonOutputError","NonInteractiveError","isNotFoundError","NotFoundError","isProjectRootNotFoundError","ProjectRootNotFoundError"],"mappings":"AAAA,SAAQA,eAAe,EAAEC,OAAO,QAAO,+BAA8B;AACrE,SAAQC,eAAe,QAAO,+BAA8B;AAC5D,SAAQC,mBAAmB,QAAO,mCAAkC;AACpE,SAAQC,eAAe,EAAEC,aAAa,QAAO,6BAA4B;AACzE,SACEC,0BAA0B,EAC1BC,wBAAwB,QACnB,wCAAuC"}
@@ -2,7 +2,7 @@ import { i as getProjectCliClient, n as ProjectCliClientOptions, r as getGlobalC
2
2
  import { c as UserViteConfig, i as ConfigStore, n as AppVisibility, r as CliConfig, t as APP_VISIBILITIES } from "../cliConfig-BZgn8ge1.js";
3
3
  import { t as ProjectRootResult } from "../recursivelyResolveProjectRoot-BE54uEP6.js";
4
4
  import { n as ConsentInformation, r as TelemetryUserProperties, t as CLITelemetryStore } from "../types-ZNH3prAd.js";
5
- import { n as RequireProps, r as SanityOrgUser, t as Output } from "../types-CwJLTYDj.js";
5
+ import { n as RequireProps, r as SanityOrgUser, t as Output } from "../types-ii6VUp6a.js";
6
6
  import { SanityCommand, SanityCommandInterface } from "../SanityCommand.js";
7
7
  import { t as mockBrowserEnvironment } from "../mockBrowserEnvironment-BjFQPb2W.js";
8
8
  import { _ as CliTokenInfo, a as getStudioWorkspaces, c as findProjectRoot, d as getCliConfigUncached, f as getCliToken, g as setCliUserConfig, h as getUserConfig, i as isStudioConfig, l as getCliConfigSync, m as getCliUserConfig, n as tryFindStudioConfigPath, o as getStudioConfig, p as getCliTokenInfo, r as findPathForFiles, s as findProjectRootSync, t as findStudioConfigPath, u as getCliConfig, v as clearCliTokenCache } from "../findStudioConfigPath-B35la6W9.js";
@@ -12,7 +12,7 @@ import { debug, subdebug } from "./debug.js";
12
12
  import { t as NonInteractiveError } from "../NonInteractiveError-CSLT5y93.js";
13
13
  import { i as isNotFoundError, n as isProjectRootNotFoundError, r as NotFoundError, t as ProjectRootNotFoundError } from "../ProjectRootNotFoundError-RgthN9uy.js";
14
14
  import { exitCodes } from "../exitCodes.js";
15
- import { n as createStudioWorker, r as studioWorkerTask, t as tsxWorkerTask } from "../tsxWorkerTask-cAuOb_uk.js";
15
+ import { n as createStudioWorker, r as studioWorkerTask, t as tsxWorkerTask } from "../tsxWorkerTask-DQQSOYCZ.js";
16
16
  import { a as getCliTelemetry, i as clearCliTelemetry, n as getTelemetryBaseInfo, o as reportCliTraceError, r as CLI_TELEMETRY_SYMBOL, s as setCliTelemetry, t as noopLogger } from "../noopTelemetry-BJRIvASI.js";
17
17
  import { a as isCi, i as isInteractive, n as normalizePath, o as importModule, r as isStaging, s as doImport, t as safeStructuredClone } from "../safeStructuredClone-DAFcnqtc.js";
18
18
  import { a as getLocalPackageVersion, i as getLocalPackageDir, n as resolveLocalPackageFrom, r as resolveLocalPackagePath, t as resolveLocalPackage } from "../resolveLocalPackage-Dr-TNTyk.js";
@@ -1,2 +1,2 @@
1
- import { n as createStudioWorker, r as studioWorkerTask, t as tsxWorkerTask } from "../tsxWorkerTask-cAuOb_uk.js";
1
+ import { n as createStudioWorker, r as studioWorkerTask, t as tsxWorkerTask } from "../tsxWorkerTask-DQQSOYCZ.js";
2
2
  export { createStudioWorker, studioWorkerTask, tsxWorkerTask };
@@ -1,7 +1,7 @@
1
1
  import { a as ReactCompilerConfig, c as UserViteConfig, i as ConfigStore, o as TypeGenConfig, r as CliConfig, s as TypeGenResource } from "../cliConfig-BZgn8ge1.js";
2
2
  import { t as ProjectRootResult } from "../recursivelyResolveProjectRoot-BE54uEP6.js";
3
3
  import { n as ConsentInformation, r as TelemetryUserProperties, t as CLITelemetryStore } from "../types-ZNH3prAd.js";
4
- import { n as RequireProps, r as SanityOrgUser, t as Output } from "../types-CwJLTYDj.js";
4
+ import { n as RequireProps, r as SanityOrgUser, t as Output } from "../types-ii6VUp6a.js";
5
5
  import { SanityCommandInterface } from "../SanityCommand.js";
6
6
  import { t as ApplicationType } from "../workbenchApp-DFUFhE7a.js";
7
7
  import { n as ReadPackageJsonOptions, t as PackageJson } from "../readPackageJson-Cr_lbjVR.js";
@@ -21,5 +21,26 @@ interface IsUnattendedInvocationOptions {
21
21
  }
22
22
  declare function isUnattended({ isInteractive, json, yes }: IsUnattendedOptions): boolean;
23
23
  declare function isUnattendedInvocation({ argv, isInteractive }: IsUnattendedInvocationOptions): boolean;
24
- export { doImport, getCoreAppUrl, getSanityConfigDir, getSanityDataDir, getSanityEnvVar, getSanityUrl, getWorkspace, importModule, isCi, isInteractive$1 as isInteractive, isRecord, isStaging, isTrueish, isUnattended, isUnattendedInvocation, normalizePath, safeStructuredClone };
24
+ type FlagDefinitions = Record<string, {
25
+ char?: string;
26
+ type?: string;
27
+ } | undefined>;
28
+ /**
29
+ * Walks argv the way oclif's parser would: stopping at `--`, honouring the
30
+ * `--json` long form, and recognizing a short alias inside a bundle such as
31
+ * `-yj`. A token following an option flag is skipped, so a parse that fails on
32
+ * `--name -j` is not read as a request for JSON.
33
+ *
34
+ * `--json=<value>` counts regardless of the value. oclif discards the `=` part
35
+ * for a boolean flag.
36
+ */
37
+ declare function hasJsonFlagInArgv(argv: string[], definitions: FlagDefinitions): boolean;
38
+ /**
39
+ * A subset of oclif's own error JSON, so the shape stays compatible
40
+ * with what the same command prints on the command line.
41
+ */
42
+ declare function toRelayableErrorJson(err: unknown): {
43
+ error: unknown;
44
+ };
45
+ export { doImport, getCoreAppUrl, getSanityConfigDir, getSanityDataDir, getSanityEnvVar, getSanityUrl, getWorkspace, hasJsonFlagInArgv, importModule, isCi, isInteractive$1 as isInteractive, isRecord, isStaging, isTrueish, isUnattended, isUnattendedInvocation, normalizePath, safeStructuredClone, toRelayableErrorJson };
25
46
  //# sourceMappingURL=util.d.ts.map
@@ -13,6 +13,7 @@ export { isRecord } from '../util/isRecord.js';
13
13
  export { isStaging } from '../util/isStaging.js';
14
14
  export { isTrueish } from '../util/isTrueish.js';
15
15
  export { isUnattended, isUnattendedInvocation } from '../util/isUnattended.js';
16
+ export { hasJsonFlagInArgv, toRelayableErrorJson } from '../util/jsonInvocation.js';
16
17
  export { normalizePath } from '../util/normalizePath.js';
17
18
  export { safeStructuredClone } from '../util/safeStructuredClone.js';
18
19
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/_exports/util.ts"],"sourcesContent":["// Pure in-memory and zero dep utilities\n//\nexport {doImport} from '../util/doImport.js'\nexport {getCoreAppUrl} from '../util/getCoreAppUrl.js'\nexport {getSanityConfigDir, getSanityDataDir} from '../util/getSanityConfigDir.js'\nexport {getSanityEnvVar} from '../util/getSanityEnvVar.js'\nexport {getSanityUrl} from '../util/getSanityUrl.js'\nexport {getWorkspace} from '../util/getWorkspace.js'\nexport {importModule} from '../util/importModule.js'\nexport {isCi} from '../util/isCi.js'\nexport {isInteractive} from '../util/isInteractive.js'\nexport {isRecord} from '../util/isRecord.js'\nexport {isStaging} from '../util/isStaging.js'\nexport {isTrueish} from '../util/isTrueish.js'\nexport {isUnattended, isUnattendedInvocation} from '../util/isUnattended.js'\nexport {normalizePath} from '../util/normalizePath.js'\nexport {safeStructuredClone} from '../util/safeStructuredClone.js'\n"],"names":["doImport","getCoreAppUrl","getSanityConfigDir","getSanityDataDir","getSanityEnvVar","getSanityUrl","getWorkspace","importModule","isCi","isInteractive","isRecord","isStaging","isTrueish","isUnattended","isUnattendedInvocation","normalizePath","safeStructuredClone"],"mappings":"AAAA,wCAAwC;AACxC,EAAE;AACF,SAAQA,QAAQ,QAAO,sBAAqB;AAC5C,SAAQC,aAAa,QAAO,2BAA0B;AACtD,SAAQC,kBAAkB,EAAEC,gBAAgB,QAAO,gCAA+B;AAClF,SAAQC,eAAe,QAAO,6BAA4B;AAC1D,SAAQC,YAAY,QAAO,0BAAyB;AACpD,SAAQC,YAAY,QAAO,0BAAyB;AACpD,SAAQC,YAAY,QAAO,0BAAyB;AACpD,SAAQC,IAAI,QAAO,kBAAiB;AACpC,SAAQC,aAAa,QAAO,2BAA0B;AACtD,SAAQC,QAAQ,QAAO,sBAAqB;AAC5C,SAAQC,SAAS,QAAO,uBAAsB;AAC9C,SAAQC,SAAS,QAAO,uBAAsB;AAC9C,SAAQC,YAAY,EAAEC,sBAAsB,QAAO,0BAAyB;AAC5E,SAAQC,aAAa,QAAO,2BAA0B;AACtD,SAAQC,mBAAmB,QAAO,iCAAgC"}
1
+ {"version":3,"sources":["../../src/_exports/util.ts"],"sourcesContent":["// Pure in-memory and zero dep utilities\n//\nexport {doImport} from '../util/doImport.js'\nexport {getCoreAppUrl} from '../util/getCoreAppUrl.js'\nexport {getSanityConfigDir, getSanityDataDir} from '../util/getSanityConfigDir.js'\nexport {getSanityEnvVar} from '../util/getSanityEnvVar.js'\nexport {getSanityUrl} from '../util/getSanityUrl.js'\nexport {getWorkspace} from '../util/getWorkspace.js'\nexport {importModule} from '../util/importModule.js'\nexport {isCi} from '../util/isCi.js'\nexport {isInteractive} from '../util/isInteractive.js'\nexport {isRecord} from '../util/isRecord.js'\nexport {isStaging} from '../util/isStaging.js'\nexport {isTrueish} from '../util/isTrueish.js'\nexport {isUnattended, isUnattendedInvocation} from '../util/isUnattended.js'\nexport {hasJsonFlagInArgv, toRelayableErrorJson} from '../util/jsonInvocation.js'\nexport {normalizePath} from '../util/normalizePath.js'\nexport {safeStructuredClone} from '../util/safeStructuredClone.js'\n"],"names":["doImport","getCoreAppUrl","getSanityConfigDir","getSanityDataDir","getSanityEnvVar","getSanityUrl","getWorkspace","importModule","isCi","isInteractive","isRecord","isStaging","isTrueish","isUnattended","isUnattendedInvocation","hasJsonFlagInArgv","toRelayableErrorJson","normalizePath","safeStructuredClone"],"mappings":"AAAA,wCAAwC;AACxC,EAAE;AACF,SAAQA,QAAQ,QAAO,sBAAqB;AAC5C,SAAQC,aAAa,QAAO,2BAA0B;AACtD,SAAQC,kBAAkB,EAAEC,gBAAgB,QAAO,gCAA+B;AAClF,SAAQC,eAAe,QAAO,6BAA4B;AAC1D,SAAQC,YAAY,QAAO,0BAAyB;AACpD,SAAQC,YAAY,QAAO,0BAAyB;AACpD,SAAQC,YAAY,QAAO,0BAAyB;AACpD,SAAQC,IAAI,QAAO,kBAAiB;AACpC,SAAQC,aAAa,QAAO,2BAA0B;AACtD,SAAQC,QAAQ,QAAO,sBAAqB;AAC5C,SAAQC,SAAS,QAAO,uBAAsB;AAC9C,SAAQC,SAAS,QAAO,uBAAsB;AAC9C,SAAQC,YAAY,EAAEC,sBAAsB,QAAO,0BAAyB;AAC5E,SAAQC,iBAAiB,EAAEC,oBAAoB,QAAO,4BAA2B;AACjF,SAAQC,aAAa,QAAO,2BAA0B;AACtD,SAAQC,mBAAmB,QAAO,iCAAgC"}
@@ -0,0 +1,12 @@
1
+ import { CLIError } from '@oclif/core/errors';
2
+ /** A command failure with an existing JSON response or diagnostic report. */ export class JsonOutputError extends CLIError {
3
+ payload;
4
+ constructor(message, payload, exit){
5
+ super(message, {
6
+ exit
7
+ });
8
+ this.payload = payload;
9
+ }
10
+ }
11
+
12
+ //# sourceMappingURL=JsonOutputError.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/errors/JsonOutputError.ts"],"sourcesContent":["import {CLIError} from '@oclif/core/errors'\n\n/** A command failure with an existing JSON response or diagnostic report. */\nexport class JsonOutputError extends CLIError {\n public readonly payload: unknown\n\n constructor(message: string, payload: unknown, exit: number) {\n super(message, {exit})\n this.payload = payload\n }\n}\n"],"names":["CLIError","JsonOutputError","payload","message","exit"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,qBAAoB;AAE3C,2EAA2E,GAC3E,OAAO,MAAMC,wBAAwBD;IACnBE,QAAgB;IAEhC,YAAYC,OAAe,EAAED,OAAgB,EAAEE,IAAY,CAAE;QAC3D,KAAK,CAACD,SAAS;YAACC;QAAI;QACpB,IAAI,CAACF,OAAO,GAAGA;IACjB;AACF"}
@@ -1,7 +1,5 @@
1
1
  import { readFile } from 'node:fs/promises';
2
2
  const DEPENDENCY_SCRIPT_RE = /[\\/]node_modules[\\/].+\.[cm]?js$/;
3
- // Mirrors the `//# sourceMappingURL=` form Vite itself strips (via `convert-source-map`)
4
- const SOURCEMAP_COMMENT_RE = /^[ \t]*\/\/[#@][ \t]+sourceMappingURL=[^\s'"`]+[ \t]*$/gm;
5
3
  /**
6
4
  * Loads plain JavaScript files from `node_modules` without their source maps.
7
5
  *
@@ -12,11 +10,11 @@ const SOURCEMAP_COMMENT_RE = /^[ \t]*\/\/[#@][ \t]+sourceMappingURL=[^\s'"`]+[ \
12
10
  * For a studio that imports `sanity` this means thousands of modules and tens of
13
11
  * megabytes of source maps, which roughly doubles the worker's peak memory.
14
12
  *
15
- * Returning `map: {mappings: ''}` from `load` tells Vite there is no source map
16
- * to preserve, so none of that work happens for dependencies. User code (the
17
- * studio config, schema files, plugins outside `node_modules`) keeps full source
18
- * maps. Stack frames inside dependencies still name the file, through a
19
- * `sourceURL` comment, but their line numbers refer to the transformed code.
13
+ * Returning `map: {mappings: ''}` from `load` skips Vite's source map handling.
14
+ * Keep the source intact: sourceMappingURL text can also appear inside strings.
15
+ * User code (the studio config, schema files, plugins outside `node_modules`)
16
+ * keeps full source maps. A `sourceURL` comment keeps dependency file names in
17
+ * stack traces.
20
18
  *
21
19
  * @internal
22
20
  */ export function skipDependencySourcemapsPlugin() {
@@ -35,7 +33,7 @@ const SOURCEMAP_COMMENT_RE = /^[ \t]*\/\/[#@][ \t]+sourceMappingURL=[^\s'"`]+[ \
35
33
  return null;
36
34
  }
37
35
  return {
38
- code: `${code.replaceAll(SOURCEMAP_COMMENT_RE, '')}\n//# sourceURL=${id.replaceAll(/\s/g, encodeURIComponent)}\n`,
36
+ code: `${code}\n//# sourceURL=${id.replaceAll(/\s/g, encodeURIComponent)}\n`,
39
37
  map: {
40
38
  mappings: ''
41
39
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/loaders/studio/skipDependencySourcemapsPlugin.ts"],"sourcesContent":["import {readFile} from 'node:fs/promises'\n\nimport {type Plugin} from 'vite'\n\nconst DEPENDENCY_SCRIPT_RE = /[\\\\/]node_modules[\\\\/].+\\.[cm]?js$/\n// Mirrors the `//# sourceMappingURL=` form Vite itself strips (via `convert-source-map`)\nconst SOURCEMAP_COMMENT_RE = /^[ \\t]*\\/\\/[#@][ \\t]+sourceMappingURL=[^\\s'\"`]+[ \\t]*$/gm\n\n/**\n * Loads plain JavaScript files from `node_modules` without their source maps.\n *\n * The studio worker runs every dependency through Vite's SSR transform\n * (`ssr.noExternal: true`). By default Vite reads each dependency's `.js.map`,\n * combines it with the SSR transform's own map, inlines the result as a base64\n * comment and the module runner then has Node parse it again for stack traces.\n * For a studio that imports `sanity` this means thousands of modules and tens of\n * megabytes of source maps, which roughly doubles the worker's peak memory.\n *\n * Returning `map: {mappings: ''}` from `load` tells Vite there is no source map\n * to preserve, so none of that work happens for dependencies. User code (the\n * studio config, schema files, plugins outside `node_modules`) keeps full source\n * maps. Stack frames inside dependencies still name the file, through a\n * `sourceURL` comment, but their line numbers refer to the transformed code.\n *\n * @internal\n */\nexport function skipDependencySourcemapsPlugin(): Plugin {\n return {\n // Run after other plugins' `load` hooks so user plugins can still claim these files\n enforce: 'post',\n async load(id) {\n if (id.startsWith('\\0') || id.includes('?') || !DEPENDENCY_SCRIPT_RE.test(id)) {\n return null\n }\n\n let code: string\n try {\n code = await readFile(id, 'utf8')\n } catch {\n // Let Vite's own loader produce its usual error\n return null\n }\n\n return {\n code: `${code.replaceAll(SOURCEMAP_COMMENT_RE, '')}\\n//# sourceURL=${id.replaceAll(/\\s/g, encodeURIComponent)}\\n`,\n map: {mappings: ''},\n }\n },\n name: 'sanity:studio-worker-skip-dependency-sourcemaps',\n }\n}\n"],"names":["readFile","DEPENDENCY_SCRIPT_RE","SOURCEMAP_COMMENT_RE","skipDependencySourcemapsPlugin","enforce","load","id","startsWith","includes","test","code","replaceAll","encodeURIComponent","map","mappings","name"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,mBAAkB;AAIzC,MAAMC,uBAAuB;AAC7B,yFAAyF;AACzF,MAAMC,uBAAuB;AAE7B;;;;;;;;;;;;;;;;;CAiBC,GACD,OAAO,SAASC;IACd,OAAO;QACL,oFAAoF;QACpFC,SAAS;QACT,MAAMC,MAAKC,EAAE;YACX,IAAIA,GAAGC,UAAU,CAAC,SAASD,GAAGE,QAAQ,CAAC,QAAQ,CAACP,qBAAqBQ,IAAI,CAACH,KAAK;gBAC7E,OAAO;YACT;YAEA,IAAII;YACJ,IAAI;gBACFA,OAAO,MAAMV,SAASM,IAAI;YAC5B,EAAE,OAAM;gBACN,gDAAgD;gBAChD,OAAO;YACT;YAEA,OAAO;gBACLI,MAAM,GAAGA,KAAKC,UAAU,CAACT,sBAAsB,IAAI,gBAAgB,EAAEI,GAAGK,UAAU,CAAC,OAAOC,oBAAoB,EAAE,CAAC;gBACjHC,KAAK;oBAACC,UAAU;gBAAE;YACpB;QACF;QACAC,MAAM;IACR;AACF"}
1
+ {"version":3,"sources":["../../../src/loaders/studio/skipDependencySourcemapsPlugin.ts"],"sourcesContent":["import {readFile} from 'node:fs/promises'\n\nimport {type Plugin} from 'vite'\n\nconst DEPENDENCY_SCRIPT_RE = /[\\\\/]node_modules[\\\\/].+\\.[cm]?js$/\n\n/**\n * Loads plain JavaScript files from `node_modules` without their source maps.\n *\n * The studio worker runs every dependency through Vite's SSR transform\n * (`ssr.noExternal: true`). By default Vite reads each dependency's `.js.map`,\n * combines it with the SSR transform's own map, inlines the result as a base64\n * comment and the module runner then has Node parse it again for stack traces.\n * For a studio that imports `sanity` this means thousands of modules and tens of\n * megabytes of source maps, which roughly doubles the worker's peak memory.\n *\n * Returning `map: {mappings: ''}` from `load` skips Vite's source map handling.\n * Keep the source intact: sourceMappingURL text can also appear inside strings.\n * User code (the studio config, schema files, plugins outside `node_modules`)\n * keeps full source maps. A `sourceURL` comment keeps dependency file names in\n * stack traces.\n *\n * @internal\n */\nexport function skipDependencySourcemapsPlugin(): Plugin {\n return {\n // Run after other plugins' `load` hooks so user plugins can still claim these files\n enforce: 'post',\n async load(id) {\n if (id.startsWith('\\0') || id.includes('?') || !DEPENDENCY_SCRIPT_RE.test(id)) {\n return null\n }\n\n let code: string\n try {\n code = await readFile(id, 'utf8')\n } catch {\n // Let Vite's own loader produce its usual error\n return null\n }\n\n return {\n code: `${code}\\n//# sourceURL=${id.replaceAll(/\\s/g, encodeURIComponent)}\\n`,\n map: {mappings: ''},\n }\n },\n name: 'sanity:studio-worker-skip-dependency-sourcemaps',\n }\n}\n"],"names":["readFile","DEPENDENCY_SCRIPT_RE","skipDependencySourcemapsPlugin","enforce","load","id","startsWith","includes","test","code","replaceAll","encodeURIComponent","map","mappings","name"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,mBAAkB;AAIzC,MAAMC,uBAAuB;AAE7B;;;;;;;;;;;;;;;;;CAiBC,GACD,OAAO,SAASC;IACd,OAAO;QACL,oFAAoF;QACpFC,SAAS;QACT,MAAMC,MAAKC,EAAE;YACX,IAAIA,GAAGC,UAAU,CAAC,SAASD,GAAGE,QAAQ,CAAC,QAAQ,CAACN,qBAAqBO,IAAI,CAACH,KAAK;gBAC7E,OAAO;YACT;YAEA,IAAII;YACJ,IAAI;gBACFA,OAAO,MAAMT,SAASK,IAAI;YAC5B,EAAE,OAAM;gBACN,gDAAgD;gBAChD,OAAO;YACT;YAEA,OAAO;gBACLI,MAAM,GAAGA,KAAK,gBAAgB,EAAEJ,GAAGK,UAAU,CAAC,OAAOC,oBAAoB,EAAE,CAAC;gBAC5EC,KAAK;oBAACC,UAAU;gBAAE;YACpB;QACF;QACAC,MAAM;IACR;AACF"}
@@ -1,4 +1,4 @@
1
- import { n as RequireProps } from "./types-CwJLTYDj.js";
1
+ import { n as RequireProps } from "./types-ii6VUp6a.js";
2
2
  import { Worker, WorkerOptions } from "node:worker_threads";
3
3
  import { URL as URL$1 } from "node:url";
4
4
  /**
@@ -95,4 +95,4 @@ interface TsxWorkerTaskOptions extends RequireProps<WorkerOptions, 'name'> {
95
95
  */
96
96
  declare function tsxWorkerTask<T = unknown>(filePath: URL$1, options: TsxWorkerTaskOptions): Promise<T>;
97
97
  export { createStudioWorker as n, studioWorkerTask as r, tsxWorkerTask as t };
98
- //# sourceMappingURL=tsxWorkerTask-cAuOb_uk.d.ts.map
98
+ //# sourceMappingURL=tsxWorkerTask-DQQSOYCZ.d.ts.map
@@ -2,6 +2,9 @@ import { Command } from "@oclif/core";
2
2
  interface Output {
3
3
  error: Command['error'];
4
4
  log: Command['log'];
5
+ /** Write a diagnostic to stderr that stays visible in JSON mode. */
6
+ logDiagnostic: (message: string) => void;
7
+ logJson: Command['logJson'];
5
8
  warn: Command['warn'];
6
9
  }
7
10
  type RequireProps<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;
@@ -20,4 +23,4 @@ type SanityOrgUser = {
20
23
  tosAcceptedAt?: string;
21
24
  };
22
25
  export { RequireProps as n, SanityOrgUser as r, Output as t };
23
- //# sourceMappingURL=types-CwJLTYDj.d.ts.map
26
+ //# sourceMappingURL=types-ii6VUp6a.d.ts.map
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/types.ts"],"sourcesContent":["import {type Command} from '@oclif/core'\n\nexport interface Output {\n error: Command['error']\n log: Command['log']\n warn: Command['warn']\n}\n\nexport type RequireProps<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>\n\n// @todo\n// Replace with SanityUser type from client once implemented\nexport type SanityOrgUser = {\n /**\n * Null when authenticating with an API token rather than a user account —\n * robot tokens resolve to a user whose `email` and `familyName` are null.\n * Use `getUserDisplayName()` for anything user-facing.\n */\n email: string | null\n id: string\n name: string\n profileImage?: string\n /** `sanity-token` is returned when authenticating with an API token. */\n provider: 'github' | 'google' | 'sanity' | 'sanity-token' | `saml-${string}`\n tosAcceptedAt?: string\n}\n"],"names":[],"mappings":"AAUA,QAAQ;AACR,4DAA4D;AAC5D,WAaC"}
1
+ {"version":3,"sources":["../src/types.ts"],"sourcesContent":["import {type Command} from '@oclif/core'\n\nexport interface Output {\n error: Command['error']\n log: Command['log']\n /** Write a diagnostic to stderr that stays visible in JSON mode. */\n logDiagnostic: (message: string) => void\n logJson: Command['logJson']\n warn: Command['warn']\n}\n\nexport type RequireProps<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>\n\n// @todo\n// Replace with SanityUser type from client once implemented\nexport type SanityOrgUser = {\n /**\n * Null when authenticating with an API token rather than a user account —\n * robot tokens resolve to a user whose `email` and `familyName` are null.\n * Use `getUserDisplayName()` for anything user-facing.\n */\n email: string | null\n id: string\n name: string\n profileImage?: string\n /** `sanity-token` is returned when authenticating with an API token. */\n provider: 'github' | 'google' | 'sanity' | 'sanity-token' | `saml-${string}`\n tosAcceptedAt?: string\n}\n"],"names":[],"mappings":"AAaA,QAAQ;AACR,4DAA4D;AAC5D,WAaC"}
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Walks argv the way oclif's parser would: stopping at `--`, honouring the
3
+ * `--json` long form, and recognizing a short alias inside a bundle such as
4
+ * `-yj`. A token following an option flag is skipped, so a parse that fails on
5
+ * `--name -j` is not read as a request for JSON.
6
+ *
7
+ * `--json=<value>` counts regardless of the value. oclif discards the `=` part
8
+ * for a boolean flag.
9
+ */ export function hasJsonFlagInArgv(argv, definitions) {
10
+ for(let index = 0; index < argv.length; index++){
11
+ const argument = argv[index];
12
+ if (argument === '--') break;
13
+ if (argument.startsWith('--')) {
14
+ if (argument === '--json' || argument.startsWith('--json=')) return true;
15
+ if (!argument.includes('=') && definitions[argument.slice(2)]?.type === 'option') index++;
16
+ continue;
17
+ }
18
+ if (!argument.startsWith('-')) continue;
19
+ // oclif splits alphabetic short flag bundles left to right, so scan until a
20
+ // character is either unknown or consumes the rest of the token as a value.
21
+ const characters = argument.slice(1);
22
+ for(let offset = 0; offset < characters.length; offset++){
23
+ const flag = Object.entries(definitions).find(([, value])=>value?.char === characters[offset]);
24
+ if (!flag) break;
25
+ if (flag[0] === 'json') return true;
26
+ if (flag[1]?.type === 'option') {
27
+ if (offset === characters.length - 1) index++;
28
+ break;
29
+ }
30
+ }
31
+ }
32
+ return false;
33
+ }
34
+ const RELAYED_ERROR_PROPERTIES = [
35
+ 'code',
36
+ 'oclif',
37
+ 'statusCode',
38
+ 'suggestions'
39
+ ];
40
+ /**
41
+ * A subset of oclif's own error JSON, so the shape stays compatible
42
+ * with what the same command prints on the command line.
43
+ */ export function toRelayableErrorJson(err) {
44
+ if (!(err instanceof Error)) return {
45
+ error: err
46
+ };
47
+ const source = err;
48
+ const error = {
49
+ message: err.message,
50
+ name: err.name
51
+ };
52
+ for (const key of RELAYED_ERROR_PROPERTIES){
53
+ if (source[key] !== undefined) error[key] = source[key];
54
+ }
55
+ return {
56
+ error
57
+ };
58
+ }
59
+
60
+ //# sourceMappingURL=jsonInvocation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/util/jsonInvocation.ts"],"sourcesContent":["type FlagDefinitions = Record<string, {char?: string; type?: string} | undefined>\n\n/**\n * Walks argv the way oclif's parser would: stopping at `--`, honouring the\n * `--json` long form, and recognizing a short alias inside a bundle such as\n * `-yj`. A token following an option flag is skipped, so a parse that fails on\n * `--name -j` is not read as a request for JSON.\n *\n * `--json=<value>` counts regardless of the value. oclif discards the `=` part\n * for a boolean flag.\n */\nexport function hasJsonFlagInArgv(argv: string[], definitions: FlagDefinitions): boolean {\n for (let index = 0; index < argv.length; index++) {\n const argument = argv[index]\n if (argument === '--') break\n\n if (argument.startsWith('--')) {\n if (argument === '--json' || argument.startsWith('--json=')) return true\n if (!argument.includes('=') && definitions[argument.slice(2)]?.type === 'option') index++\n continue\n }\n\n if (!argument.startsWith('-')) continue\n\n // oclif splits alphabetic short flag bundles left to right, so scan until a\n // character is either unknown or consumes the rest of the token as a value.\n const characters = argument.slice(1)\n for (let offset = 0; offset < characters.length; offset++) {\n const flag = Object.entries(definitions).find(\n ([, value]) => value?.char === characters[offset],\n )\n if (!flag) break\n if (flag[0] === 'json') return true\n if (flag[1]?.type === 'option') {\n if (offset === characters.length - 1) index++\n break\n }\n }\n }\n\n return false\n}\n\nconst RELAYED_ERROR_PROPERTIES = ['code', 'oclif', 'statusCode', 'suggestions'] as const\n\n/**\n * A subset of oclif's own error JSON, so the shape stays compatible\n * with what the same command prints on the command line.\n */\nexport function toRelayableErrorJson(err: unknown): {error: unknown} {\n if (!(err instanceof Error)) return {error: err}\n\n const source = err as Error & Record<string, unknown>\n const error: Record<string, unknown> = {message: err.message, name: err.name}\n for (const key of RELAYED_ERROR_PROPERTIES) {\n if (source[key] !== undefined) error[key] = source[key]\n }\n\n return {error}\n}\n"],"names":["hasJsonFlagInArgv","argv","definitions","index","length","argument","startsWith","includes","slice","type","characters","offset","flag","Object","entries","find","value","char","RELAYED_ERROR_PROPERTIES","toRelayableErrorJson","err","Error","error","source","message","name","key","undefined"],"mappings":"AAEA;;;;;;;;CAQC,GACD,OAAO,SAASA,kBAAkBC,IAAc,EAAEC,WAA4B;IAC5E,IAAK,IAAIC,QAAQ,GAAGA,QAAQF,KAAKG,MAAM,EAAED,QAAS;QAChD,MAAME,WAAWJ,IAAI,CAACE,MAAM;QAC5B,IAAIE,aAAa,MAAM;QAEvB,IAAIA,SAASC,UAAU,CAAC,OAAO;YAC7B,IAAID,aAAa,YAAYA,SAASC,UAAU,CAAC,YAAY,OAAO;YACpE,IAAI,CAACD,SAASE,QAAQ,CAAC,QAAQL,WAAW,CAACG,SAASG,KAAK,CAAC,GAAG,EAAEC,SAAS,UAAUN;YAClF;QACF;QAEA,IAAI,CAACE,SAASC,UAAU,CAAC,MAAM;QAE/B,4EAA4E;QAC5E,4EAA4E;QAC5E,MAAMI,aAAaL,SAASG,KAAK,CAAC;QAClC,IAAK,IAAIG,SAAS,GAAGA,SAASD,WAAWN,MAAM,EAAEO,SAAU;YACzD,MAAMC,OAAOC,OAAOC,OAAO,CAACZ,aAAaa,IAAI,CAC3C,CAAC,GAAGC,MAAM,GAAKA,OAAOC,SAASP,UAAU,CAACC,OAAO;YAEnD,IAAI,CAACC,MAAM;YACX,IAAIA,IAAI,CAAC,EAAE,KAAK,QAAQ,OAAO;YAC/B,IAAIA,IAAI,CAAC,EAAE,EAAEH,SAAS,UAAU;gBAC9B,IAAIE,WAAWD,WAAWN,MAAM,GAAG,GAAGD;gBACtC;YACF;QACF;IACF;IAEA,OAAO;AACT;AAEA,MAAMe,2BAA2B;IAAC;IAAQ;IAAS;IAAc;CAAc;AAE/E;;;CAGC,GACD,OAAO,SAASC,qBAAqBC,GAAY;IAC/C,IAAI,CAAEA,CAAAA,eAAeC,KAAI,GAAI,OAAO;QAACC,OAAOF;IAAG;IAE/C,MAAMG,SAASH;IACf,MAAME,QAAiC;QAACE,SAASJ,IAAII,OAAO;QAAEC,MAAML,IAAIK,IAAI;IAAA;IAC5E,KAAK,MAAMC,OAAOR,yBAA0B;QAC1C,IAAIK,MAAM,CAACG,IAAI,KAAKC,WAAWL,KAAK,CAACI,IAAI,GAAGH,MAAM,CAACG,IAAI;IACzD;IAEA,OAAO;QAACJ;IAAK;AACf"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sanity/cli-core",
3
- "version": "3.10.0",
3
+ "version": "3.11.1",
4
4
  "description": "Sanity CLI core package",
5
5
  "keywords": [
6
6
  "cli",