@sanity/cli 8.38.1 → 8.39.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 (31) hide show
  1. package/dist/actions/deploy/deployApp.js +12 -1
  2. package/dist/actions/deploy/deployApp.js.map +1 -1
  3. package/dist/actions/deploy/deployRunner.js +9 -1
  4. package/dist/actions/deploy/deployRunner.js.map +1 -1
  5. package/dist/actions/deploy/deployStudio.js +12 -1
  6. package/dist/actions/deploy/deployStudio.js.map +1 -1
  7. package/dist/actions/graphql/getSourceDeprecationWarning.js +20 -0
  8. package/dist/actions/graphql/getSourceDeprecationWarning.js.map +1 -0
  9. package/dist/actions/graphql/resolveGraphQLApisFromWorkspaces.js +12 -6
  10. package/dist/actions/graphql/resolveGraphQLApisFromWorkspaces.js.map +1 -1
  11. package/dist/actions/graphql/types.js.map +1 -1
  12. package/dist/actions/init/offerAspectPull.js +6 -8
  13. package/dist/actions/init/offerAspectPull.js.map +1 -1
  14. package/dist/commands/graphql/deploy.js +5 -0
  15. package/dist/commands/graphql/deploy.js.map +1 -1
  16. package/dist/commands/graphql/undeploy.js +5 -0
  17. package/dist/commands/graphql/undeploy.js.map +1 -1
  18. package/dist/commands/login.js +2 -3
  19. package/dist/commands/login.js.map +1 -1
  20. package/dist/commands/new.js +28 -29
  21. package/dist/commands/new.js.map +1 -1
  22. package/dist/commands/projects/unclaimed.js +6 -5
  23. package/dist/commands/projects/unclaimed.js.map +1 -1
  24. package/dist/exports/index.d.ts +3 -0
  25. package/dist/generated/apiRoutes.js +6 -0
  26. package/dist/generated/apiRoutes.js.map +1 -1
  27. package/dist/services/mintProject.js +4 -0
  28. package/dist/services/mintProject.js.map +1 -1
  29. package/oclif.manifest.json +762 -762
  30. package/package.json +5 -5
  31. package/templates/shared/AGENTS.md +8 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/graphql/resolveGraphQLApisFromWorkspaces.ts"],"sourcesContent":["import {type Schema} from '@sanity/types'\nimport {oneline} from 'oneline'\n\nimport {\n type ExtractedGraphQLAPI,\n type GraphQLAPIConfig,\n type SchemaDefinitionish,\n type TypeResolvedGraphQLAPI,\n} from './types.js'\n\ninterface Source {\n dataset: string\n name: string\n projectId: string\n schema: Schema\n}\n\nexport interface Workspace extends Source {\n unstable_sources: Source[]\n}\n\n/**\n * Minimal source metadata — dataset/projectId pair for a source within a workspace.\n */\nexport interface SourceMetadata {\n dataset: string\n name: string\n projectId: string\n}\n\n/**\n * Minimal workspace metadata — enough for resolving API identifiers without compiling schemas.\n * This matches the raw workspace shape from `defineConfig()` before `resolveConfig()` processes it.\n *\n * The `sources` array mirrors `Workspace.unstable_sources` from the full resolved config.\n * When the raw config includes `unstable_sources`, they are extracted here. Otherwise, the\n * workspace itself is used as a single default source (matching what `resolveConfig()` would do).\n */\nexport interface WorkspaceMetadata {\n dataset: string\n name: string\n projectId: string\n sources: SourceMetadata[]\n}\n\ninterface ResolveGraphQLApisOptions {\n workspaces: Workspace[]\n\n cliConfig?: {graphql?: GraphQLAPIConfig[]}\n}\n\nexport function resolveGraphQLApis({\n cliConfig,\n workspaces,\n}: ResolveGraphQLApisOptions): TypeResolvedGraphQLAPI[] {\n const numSources = workspaces.reduce(\n (count, workspace) => count + workspace.unstable_sources.length,\n 0,\n )\n const multiSource = numSources > 1\n const multiWorkspace = workspaces.length > 1\n const hasGraphQLConfig = Boolean(cliConfig?.graphql)\n\n if (workspaces.length === 0) {\n throw new Error('No studio configuration found')\n }\n\n if (numSources === 0) {\n throw new Error('No sources (project ID / dataset) configured')\n }\n\n // We can only automatically configure if there is a single workspace + source in play\n if ((multiWorkspace || multiSource) && !hasGraphQLConfig) {\n throw new Error(oneline`\n Multiple workspaces/sources configured.\n You must define an array of GraphQL APIs in \\`sanity.cli.ts\\` or \\`sanity.cli.js\\`\n and specify which workspace/source to use.\n `)\n }\n\n // No config is defined, but we have a single workspace + source, so use that\n if (!hasGraphQLConfig) {\n const {dataset, projectId, schema} = workspaces[0].unstable_sources[0]\n return [{dataset, projectId, schemaTypes: getStrippedSchemaTypes(schema)}]\n }\n\n // Explicitly defined config\n const apiDefs = validateCliConfig(cliConfig?.graphql || [])\n return resolveGraphQLAPIsFromConfig(apiDefs, workspaces)\n}\n\n/**\n * Resolve GraphQL API metadata (projectId, dataset, tag, etc.) from raw workspace configs\n * without compiling schemas. This is used when we only need API identifiers, not schema types —\n * e.g. for `graphql undeploy --api` or `graphql list`.\n */\nexport function resolveGraphQLApiMetadata({\n cliConfig,\n workspaces,\n}: {\n cliConfig?: {graphql?: GraphQLAPIConfig[]}\n workspaces: WorkspaceMetadata[]\n}): ExtractedGraphQLAPI[] {\n const numSources = workspaces.reduce((count, ws) => count + ws.sources.length, 0)\n const multiSource = numSources > 1\n const multiWorkspace = workspaces.length > 1\n const hasGraphQLConfig = Boolean(cliConfig?.graphql)\n\n if (workspaces.length === 0) {\n throw new Error('No studio configuration found')\n }\n\n if (numSources === 0) {\n throw new Error('No sources (project ID / dataset) configured')\n }\n\n // We can only automatically configure if there is a single workspace + source in play\n if ((multiWorkspace || multiSource) && !hasGraphQLConfig) {\n throw new Error(oneline`\n Multiple workspaces/sources configured.\n You must define an array of GraphQL APIs in \\`sanity.cli.ts\\` or \\`sanity.cli.js\\`\n and specify which workspace/source to use.\n `)\n }\n\n // Validate that workspaces and their sources have non-empty projectId/dataset.\n // The worker's toWorkspaceMetadata validates this before constructing metadata,\n // but assert here to make the invariant explicit.\n for (const ws of workspaces) {\n if (!ws.projectId || !ws.dataset) {\n throw new Error(\n `Workspace \"${ws.name}\" is missing a projectId or dataset. ` +\n 'Check your studio configuration.',\n )\n }\n for (const source of ws.sources) {\n if (!source.projectId || !source.dataset) {\n throw new Error(\n `Source \"${source.name}\" in workspace \"${ws.name}\" is missing a projectId or dataset. ` +\n 'Check your studio configuration.',\n )\n }\n }\n }\n\n // No config is defined, but we have a single workspace + source, so use that\n if (!hasGraphQLConfig) {\n const {dataset, projectId} = workspaces[0].sources[0]\n return [{dataset, projectId}]\n }\n\n // Explicitly defined config\n const apiDefs = validateCliConfig(cliConfig?.graphql || [])\n return resolveGraphQLApiMetadataFromConfig(apiDefs, workspaces)\n}\n\n/**\n * Shared workspace/source resolution logic for both the metadata and full-compile paths.\n *\n * Both `resolveGraphQLAPIsFromConfig` and `resolveGraphQLApiMetadataFromConfig` need to\n * resolve the workspace and source for each GraphQL API config entry. This helper\n * extracts that shared logic so bug fixes and edge-case handling apply to both paths.\n */\nfunction resolveWorkspaceAndSource<\n TWorkspace extends {name: string},\n TSource extends {name: string},\n>(\n apiDef: GraphQLAPIConfig,\n workspaces: TWorkspace[],\n getSources: (workspace: TWorkspace) => TSource[],\n): {source: TSource; workspace: TWorkspace} {\n const {source: sourceName, workspace: workspaceName} = apiDef\n\n if (!workspaceName && workspaces.length > 1) {\n throw new Error(\n 'Must define `workspace` name in GraphQL API config when multiple workspaces are defined',\n )\n }\n\n // If we only have a single workspace defined, we can assume that is the intended one,\n // even if no `workspace` is defined for the GraphQL API\n const workspace =\n !workspaceName && workspaces.length === 1\n ? workspaces[0]\n : workspaces.find((space) => space.name === (workspaceName || 'default'))\n\n if (!workspace) {\n throw new Error(`Workspace \"${workspaceName || 'default'}\" not found`)\n }\n\n const sources = getSources(workspace)\n\n // If we only have a single source defined, we can assume that is the intended one,\n // even if no `source` is defined for the GraphQL API\n const source =\n !sourceName && sources.length === 1\n ? sources[0]\n : sources.find((src) => src.name === (sourceName || 'default'))\n\n if (!source) {\n throw new Error(\n `Source \"${sourceName || 'default'}\" not found in workspace \"${workspaceName || 'default'}\"`,\n )\n }\n\n return {source, workspace}\n}\n\nfunction resolveGraphQLApiMetadataFromConfig(\n apiDefs: GraphQLAPIConfig[],\n workspaces: WorkspaceMetadata[],\n): ExtractedGraphQLAPI[] {\n return apiDefs.map((apiDef) => {\n const {source} = resolveWorkspaceAndSource(apiDef, workspaces, (ws) => ws.sources)\n\n return {\n dataset: source.dataset,\n filterSuffix: apiDef.filterSuffix,\n generation: apiDef.generation,\n id: apiDef.id,\n nonNullDocumentFields: apiDef.nonNullDocumentFields,\n playground: apiDef.playground,\n projectId: source.projectId,\n tag: apiDef.tag,\n }\n })\n}\n\nfunction resolveGraphQLAPIsFromConfig(\n apiDefs: GraphQLAPIConfig[],\n workspaces: Workspace[],\n): TypeResolvedGraphQLAPI[] {\n return apiDefs.map((apiDef) => {\n const {source} = resolveWorkspaceAndSource(apiDef, workspaces, (ws) => ws.unstable_sources)\n\n return {\n ...apiDef,\n dataset: source.dataset,\n projectId: source.projectId,\n schemaTypes: getStrippedSchemaTypes(source.schema),\n }\n })\n}\n\nfunction validateCliConfig(\n config: GraphQLAPIConfig[],\n configPath = 'sanity.cli.js',\n): GraphQLAPIConfig[] {\n if (!Array.isArray(config)) {\n throw new TypeError(`\"graphql\" key in \"${configPath}\" must be an array if defined`)\n }\n\n if (config.length === 0) {\n throw new Error(`No GraphQL APIs defined in \"${configPath}\"`)\n }\n\n return config\n}\n\nfunction getStrippedSchemaTypes(schema: Schema): SchemaDefinitionish[] {\n const schemaDef = schema._original || {types: []}\n return schemaDef.types.map((type) => stripType(type))\n}\n\nfunction stripType(input: unknown): SchemaDefinitionish {\n return strip(input) as SchemaDefinitionish\n}\n\nfunction strip(input: unknown): unknown {\n if (Array.isArray(input)) {\n return input.map((item) => strip(item)).filter((item) => item !== undefined)\n }\n\n if (isPlainishObject(input)) {\n const stripped: Record<string, unknown> = {}\n for (const key of Object.keys(input)) {\n stripped[key] = strip(input[key])\n }\n return stripped\n }\n\n return isBasicType(input) ? input : undefined\n}\n\nfunction isPlainishObject(input: unknown): input is Record<string, unknown> {\n if (typeof input !== 'object' || input === null) {\n return false\n }\n\n const prototype = Object.getPrototypeOf(input)\n return prototype === null || prototype === Object.prototype\n}\n\nfunction isBasicType(input: unknown): boolean {\n const type = typeof input\n if (type === 'boolean' || type === 'number' || type === 'string') {\n return true\n }\n\n if (type !== 'object') {\n return false\n }\n\n return Array.isArray(input) || input === null || isPlainishObject(input)\n}\n"],"names":["oneline","resolveGraphQLApis","cliConfig","workspaces","numSources","reduce","count","workspace","unstable_sources","length","multiSource","multiWorkspace","hasGraphQLConfig","Boolean","graphql","Error","dataset","projectId","schema","schemaTypes","getStrippedSchemaTypes","apiDefs","validateCliConfig","resolveGraphQLAPIsFromConfig","resolveGraphQLApiMetadata","ws","sources","name","source","resolveGraphQLApiMetadataFromConfig","resolveWorkspaceAndSource","apiDef","getSources","sourceName","workspaceName","find","space","src","map","filterSuffix","generation","id","nonNullDocumentFields","playground","tag","config","configPath","Array","isArray","TypeError","schemaDef","_original","types","type","stripType","input","strip","item","filter","undefined","isPlainishObject","stripped","key","Object","keys","isBasicType","prototype","getPrototypeOf"],"mappings":"AACA,SAAQA,OAAO,QAAO,UAAS;AAkD/B,OAAO,SAASC,mBAAmB,EACjCC,SAAS,EACTC,UAAU,EACgB;IAC1B,MAAMC,aAAaD,WAAWE,MAAM,CAClC,CAACC,OAAOC,YAAcD,QAAQC,UAAUC,gBAAgB,CAACC,MAAM,EAC/D;IAEF,MAAMC,cAAcN,aAAa;IACjC,MAAMO,iBAAiBR,WAAWM,MAAM,GAAG;IAC3C,MAAMG,mBAAmBC,QAAQX,WAAWY;IAE5C,IAAIX,WAAWM,MAAM,KAAK,GAAG;QAC3B,MAAM,IAAIM,MAAM;IAClB;IAEA,IAAIX,eAAe,GAAG;QACpB,MAAM,IAAIW,MAAM;IAClB;IAEA,sFAAsF;IACtF,IAAI,AAACJ,CAAAA,kBAAkBD,WAAU,KAAM,CAACE,kBAAkB;QACxD,MAAM,IAAIG,MAAMf,OAAO,CAAC;;;;IAIxB,CAAC;IACH;IAEA,6EAA6E;IAC7E,IAAI,CAACY,kBAAkB;QACrB,MAAM,EAACI,OAAO,EAAEC,SAAS,EAAEC,MAAM,EAAC,GAAGf,UAAU,CAAC,EAAE,CAACK,gBAAgB,CAAC,EAAE;QACtE,OAAO;YAAC;gBAACQ;gBAASC;gBAAWE,aAAaC,uBAAuBF;YAAO;SAAE;IA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AAQ;QACxB,OAAOA,MAAMjB,GAAG,CAAC,CAACmB,OAASD,MAAMC,OAAOC,MAAM,CAAC,CAACD,OAASA,SAASE;IACpE;IAEA,IAAIC,iBAAiBL,QAAQ;QAC3B,MAAMM,WAAoC,CAAC;QAC3C,KAAK,MAAMC,OAAOC,OAAOC,IAAI,CAACT,OAAQ;YACpCM,QAAQ,CAACC,IAAI,GAAGN,MAAMD,KAAK,CAACO,IAAI;QAClC;QACA,OAAOD;IACT;IAEA,OAAOI,YAAYV,SAASA,QAAQI;AACtC;AAEA,SAASC,iBAAiBL,KAAc;IACtC,IAAI,OAAOA,UAAU,YAAYA,UAAU,MAAM;QAC/C,OAAO;IACT;IAEA,MAAMW,YAAYH,OAAOI,cAAc,CAACZ;IACxC,OAAOW,cAAc,QAAQA,cAAcH,OAAOG,SAAS;AAC7D;AAEA,SAASD,YAAYV,KAAc;IACjC,MAAMF,OAAO,OAAOE;IACpB,IAAIF,SAAS,aAAaA,SAAS,YAAYA,SAAS,UAAU;QAChE,OAAO;IACT;IAEA,IAAIA,SAAS,UAAU;QACrB,OAAO;IACT;IAEA,OAAON,MAAMC,OAAO,CAACO,UAAUA,UAAU,QAAQK,iBAAiBL;AACpE"}
1
+ {"version":3,"sources":["../../../src/actions/graphql/resolveGraphQLApisFromWorkspaces.ts"],"sourcesContent":["import {type Schema} from '@sanity/types'\nimport {oneline} from 'oneline'\n\nimport {\n type ExtractedGraphQLAPI,\n type GraphQLAPIConfig,\n type SchemaDefinitionish,\n type TypeResolvedGraphQLAPI,\n} from './types.js'\n\ninterface Source {\n dataset: string\n name: string\n projectId: string\n schema: Schema\n}\n\nexport interface Workspace extends Source {\n /**\n * Only Studio v6 resolves sources, the first being the workspace itself. Studio v7 workspaces\n * have none, or list just the workspace for older CLIs.\n */\n unstable_sources?: Source[]\n}\n\n/**\n * Minimal source metadata — dataset/projectId pair for a source within a workspace.\n */\nexport interface SourceMetadata {\n dataset: string\n name: string\n projectId: string\n}\n\n/**\n * Minimal workspace metadata — enough for resolving API identifiers without compiling schemas.\n * This matches the raw workspace shape from `defineConfig()` before `resolveConfig()` processes it.\n *\n * The `sources` array mirrors `Workspace.unstable_sources` from the full resolved config.\n * When the raw config includes `unstable_sources`, they are extracted here. Otherwise, the\n * workspace itself is used as a single default source (matching what `resolveConfig()` would do).\n */\nexport interface WorkspaceMetadata {\n dataset: string\n name: string\n projectId: string\n sources: SourceMetadata[]\n}\n\ninterface ResolveGraphQLApisOptions {\n workspaces: Workspace[]\n\n cliConfig?: {graphql?: GraphQLAPIConfig[]}\n}\n\nexport function resolveGraphQLApis({\n cliConfig,\n workspaces,\n}: ResolveGraphQLApisOptions): TypeResolvedGraphQLAPI[] {\n const numSources = workspaces.reduce(\n (count, workspace) => count + getWorkspaceSources(workspace).length,\n 0,\n )\n const multiSource = numSources > 1\n const multiWorkspace = workspaces.length > 1\n const hasGraphQLConfig = Boolean(cliConfig?.graphql)\n\n if (workspaces.length === 0) {\n throw new Error('No studio configuration found')\n }\n\n // We can only automatically configure if there is a single workspace + source in play\n if ((multiWorkspace || multiSource) && !hasGraphQLConfig) {\n throw new Error(oneline`\n Multiple workspaces/sources configured.\n You must define an array of GraphQL APIs in \\`sanity.cli.ts\\` or \\`sanity.cli.js\\`\n and specify which workspace/source to use.\n `)\n }\n\n // No config is defined, but we have a single workspace + source, so use that\n if (!hasGraphQLConfig) {\n const {dataset, projectId, schema} = workspaces[0]\n return [{dataset, projectId, schemaTypes: getStrippedSchemaTypes(schema)}]\n }\n\n // Explicitly defined config\n const apiDefs = validateCliConfig(cliConfig?.graphql || [])\n return resolveGraphQLAPIsFromConfig(apiDefs, workspaces)\n}\n\n/**\n * Resolve GraphQL API metadata (projectId, dataset, tag, etc.) from raw workspace configs\n * without compiling schemas. This is used when we only need API identifiers, not schema types —\n * e.g. for `graphql undeploy --api` or `graphql list`.\n */\nexport function resolveGraphQLApiMetadata({\n cliConfig,\n workspaces,\n}: {\n cliConfig?: {graphql?: GraphQLAPIConfig[]}\n workspaces: WorkspaceMetadata[]\n}): ExtractedGraphQLAPI[] {\n const numSources = workspaces.reduce((count, ws) => count + ws.sources.length, 0)\n const multiSource = numSources > 1\n const multiWorkspace = workspaces.length > 1\n const hasGraphQLConfig = Boolean(cliConfig?.graphql)\n\n if (workspaces.length === 0) {\n throw new Error('No studio configuration found')\n }\n\n if (numSources === 0) {\n throw new Error('No sources (project ID / dataset) configured')\n }\n\n // We can only automatically configure if there is a single workspace + source in play\n if ((multiWorkspace || multiSource) && !hasGraphQLConfig) {\n throw new Error(oneline`\n Multiple workspaces/sources configured.\n You must define an array of GraphQL APIs in \\`sanity.cli.ts\\` or \\`sanity.cli.js\\`\n and specify which workspace/source to use.\n `)\n }\n\n // Validate that workspaces and their sources have non-empty projectId/dataset.\n // The worker's toWorkspaceMetadata validates this before constructing metadata,\n // but assert here to make the invariant explicit.\n for (const ws of workspaces) {\n if (!ws.projectId || !ws.dataset) {\n throw new Error(\n `Workspace \"${ws.name}\" is missing a projectId or dataset. ` +\n 'Check your studio configuration.',\n )\n }\n for (const source of ws.sources) {\n if (!source.projectId || !source.dataset) {\n throw new Error(\n `Source \"${source.name}\" in workspace \"${ws.name}\" is missing a projectId or dataset. ` +\n 'Check your studio configuration.',\n )\n }\n }\n }\n\n // No config is defined, but we have a single workspace + source, so use that\n if (!hasGraphQLConfig) {\n const {dataset, projectId} = workspaces[0].sources[0]\n return [{dataset, projectId}]\n }\n\n // Explicitly defined config\n const apiDefs = validateCliConfig(cliConfig?.graphql || [])\n return resolveGraphQLApiMetadataFromConfig(apiDefs, workspaces)\n}\n\n/**\n * Shared workspace/source resolution logic for both the metadata and full-compile paths.\n *\n * Both `resolveGraphQLAPIsFromConfig` and `resolveGraphQLApiMetadataFromConfig` need to\n * resolve the workspace and source for each GraphQL API config entry. This helper\n * extracts that shared logic so bug fixes and edge-case handling apply to both paths.\n */\nfunction resolveWorkspaceAndSource<\n TWorkspace extends {name: string},\n TSource extends {name: string},\n>(\n apiDef: GraphQLAPIConfig,\n workspaces: TWorkspace[],\n getSources: (workspace: TWorkspace) => TSource[],\n): {source: TSource; workspace: TWorkspace} {\n const {source: sourceName, workspace: workspaceName} = apiDef\n\n if (!workspaceName && workspaces.length > 1) {\n throw new Error(\n 'Must define `workspace` name in GraphQL API config when multiple workspaces are defined',\n )\n }\n\n // If we only have a single workspace defined, we can assume that is the intended one,\n // even if no `workspace` is defined for the GraphQL API\n const workspace =\n !workspaceName && workspaces.length === 1\n ? workspaces[0]\n : workspaces.find((space) => space.name === (workspaceName || 'default'))\n\n if (!workspace) {\n throw new Error(`Workspace \"${workspaceName || 'default'}\" not found`)\n }\n\n const sources = getSources(workspace)\n\n // If we only have a single source defined, we can assume that is the intended one,\n // even if no `source` is defined for the GraphQL API\n const source =\n !sourceName && sources.length === 1\n ? sources[0]\n : sources.find((src) => src.name === (sourceName || 'default'))\n\n if (!source) {\n throw new Error(\n `Source \"${sourceName || 'default'}\" not found in workspace \"${workspaceName || 'default'}\"`,\n )\n }\n\n return {source, workspace}\n}\n\nfunction resolveGraphQLApiMetadataFromConfig(\n apiDefs: GraphQLAPIConfig[],\n workspaces: WorkspaceMetadata[],\n): ExtractedGraphQLAPI[] {\n return apiDefs.map((apiDef) => {\n const {source} = resolveWorkspaceAndSource(apiDef, workspaces, (ws) => ws.sources)\n\n return {\n dataset: source.dataset,\n filterSuffix: apiDef.filterSuffix,\n generation: apiDef.generation,\n id: apiDef.id,\n nonNullDocumentFields: apiDef.nonNullDocumentFields,\n playground: apiDef.playground,\n projectId: source.projectId,\n tag: apiDef.tag,\n }\n })\n}\n\nfunction resolveGraphQLAPIsFromConfig(\n apiDefs: GraphQLAPIConfig[],\n workspaces: Workspace[],\n): TypeResolvedGraphQLAPI[] {\n return apiDefs.map((apiDef) => {\n const {source} = resolveWorkspaceAndSource(apiDef, workspaces, getWorkspaceSources)\n\n return {\n ...apiDef,\n dataset: source.dataset,\n projectId: source.projectId,\n schemaTypes: getStrippedSchemaTypes(source.schema),\n }\n })\n}\n\n/**\n * A workspace is its own single source, unless it comes from a Studio v6 config with more than\n * one source in `unstable_sources`.\n */\nfunction getWorkspaceSources(workspace: Workspace): Source[] {\n const sources = workspace.unstable_sources ?? []\n return sources.length > 1 ? sources : [workspace]\n}\n\nfunction validateCliConfig(\n config: GraphQLAPIConfig[],\n configPath = 'sanity.cli.js',\n): GraphQLAPIConfig[] {\n if (!Array.isArray(config)) {\n throw new TypeError(`\"graphql\" key in \"${configPath}\" must be an array if defined`)\n }\n\n if (config.length === 0) {\n throw new Error(`No GraphQL APIs defined in \"${configPath}\"`)\n }\n\n return config\n}\n\nfunction getStrippedSchemaTypes(schema: Schema): SchemaDefinitionish[] {\n const schemaDef = schema._original || {types: []}\n return schemaDef.types.map((type) => stripType(type))\n}\n\nfunction stripType(input: unknown): SchemaDefinitionish {\n return strip(input) as SchemaDefinitionish\n}\n\nfunction strip(input: unknown): unknown {\n if (Array.isArray(input)) {\n return input.map((item) => strip(item)).filter((item) => item !== undefined)\n }\n\n if (isPlainishObject(input)) {\n const stripped: Record<string, unknown> = {}\n for (const key of Object.keys(input)) {\n stripped[key] = strip(input[key])\n }\n return stripped\n }\n\n return isBasicType(input) ? input : undefined\n}\n\nfunction isPlainishObject(input: unknown): input is Record<string, unknown> {\n if (typeof input !== 'object' || input === null) {\n return false\n }\n\n const prototype = Object.getPrototypeOf(input)\n return prototype === null || prototype === Object.prototype\n}\n\nfunction isBasicType(input: unknown): boolean {\n const type = typeof input\n if (type === 'boolean' || type === 'number' || type === 'string') {\n return true\n }\n\n if (type !== 'object') {\n return false\n }\n\n return Array.isArray(input) || input === null || isPlainishObject(input)\n}\n"],"names":["oneline","resolveGraphQLApis","cliConfig","workspaces","numSources","reduce","count","workspace","getWorkspaceSources","length","multiSource","multiWorkspace","hasGraphQLConfig","Boolean","graphql","Error","dataset","projectId","schema","schemaTypes","getStrippedSchemaTypes","apiDefs","validateCliConfig","resolveGraphQLAPIsFromConfig","resolveGraphQLApiMetadata","ws","sources","name","source","resolveGraphQLApiMetadataFromConfig","resolveWorkspaceAndSource","apiDef","getSources","sourceName","workspaceName","find","space","src","map","filterSuffix","generation","id","nonNullDocumentFields","playground","tag","unstable_sources","config","configPath","Array","isArray","TypeError","schemaDef","_original","types","type","stripType","input","strip","item","filter","undefined","isPlainishObject","stripped","key","Object","keys","isBasicType","prototype","getPrototypeOf"],"mappings":"AACA,SAAQA,OAAO,QAAO,UAAS;AAsD/B,OAAO,SAASC,mBAAmB,EACjCC,SAAS,EACTC,UAAU,EACgB;IAC1B,MAAMC,aAAaD,WAAWE,MAAM,CAClC,CAACC,OAAOC,YAAcD,QAAQE,oBAAoBD,WAAWE,MAAM,EACnE;IAEF,MAAMC,cAAcN,aAAa;IACjC,MAAMO,iBAAiBR,WAAWM,MAAM,GAAG;IAC3C,MAAMG,mBAAmBC,QAAQX,WAAWY;IAE5C,IAAIX,WAAWM,MAAM,KAAK,GAAG;QAC3B,MAAM,IAAIM,MAAM;IAClB;IAEA,sFAAsF;IACtF,IAAI,AAACJ,CAAAA,kBAAkBD,WAAU,KAAM,CAACE,kBAAkB;QACxD,MAAM,IAAIG,MAAMf,OAAO,CAAC;;;;IAIxB,CAAC;IACH;IAEA,6EAA6E;IAC7E,IAAI,CAACY,kBAAkB;QACrB,MAAM,EAACI,OAAO,EAAEC,SAAS,EAAEC,MAAM,EAAC,GAAGf,UAAU,CAAC,EAAE;QAClD,OAAO;YAAC;gBAACa;gBAASC;gBAAWE,aAAaC,uBAAuBF;YAAO;SAAE;IAC5E;IAEA,4BAA4B;IAC5B,MAAMG,UAAUC,kBAAkBpB,WAAWY,WAAW,EAAE;IAC1D,OAAOS,6BAA6BF,SAASlB;AAC/C;AAEA;;;;CAIC,GACD,OAAO,SAASqB,0BAA0B,EACxCtB,SAAS,EACTC,UAAU,EAIX;IACC,MAAMC,aAAaD,WAAWE,MAAM,CAAC,CAACC,OAAOmB,KAAOnB,QAAQmB,GAAGC,OAAO,CAACjB,MAAM,EAAE;IAC/E,MAAMC,c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C,KAAK,MAAMC,OAAOC,OAAOC,IAAI,CAACT,OAAQ;YACpCM,QAAQ,CAACC,IAAI,GAAGN,MAAMD,KAAK,CAACO,IAAI;QAClC;QACA,OAAOD;IACT;IAEA,OAAOI,YAAYV,SAASA,QAAQI;AACtC;AAEA,SAASC,iBAAiBL,KAAc;IACtC,IAAI,OAAOA,UAAU,YAAYA,UAAU,MAAM;QAC/C,OAAO;IACT;IAEA,MAAMW,YAAYH,OAAOI,cAAc,CAACZ;IACxC,OAAOW,cAAc,QAAQA,cAAcH,OAAOG,SAAS;AAC7D;AAEA,SAASD,YAAYV,KAAc;IACjC,MAAMF,OAAO,OAAOE;IACpB,IAAIF,SAAS,aAAaA,SAAS,YAAYA,SAAS,UAAU;QAChE,OAAO;IACT;IAEA,IAAIA,SAAS,UAAU;QACrB,OAAO;IACT;IAEA,OAAON,MAAMC,OAAO,CAACO,UAAUA,UAAU,QAAQK,iBAAiBL;AACpE"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/graphql/types.ts"],"sourcesContent":["import {type SchemaValidationProblemGroup} from '@sanity/types'\n\nexport interface Deprecation {\n deprecationReason: string\n}\n\nexport interface ApiSpecification {\n interfaces: ConvertedInterface[]\n types: (ConvertedType | ConvertedUnion)[]\n}\n\n/**\n * @public\n */\nexport interface GraphQLAPIConfig {\n /**\n * Suffix to use for generated filter types.\n *\n * Optional, Defaults to `Filter`.\n *\n */\n filterSuffix?: string\n\n /**\n * Generation of API to deploy\n *\n * Optional, defaults to `gen3` (which is the only option, currently)\n */\n generation?: 'gen1' | 'gen2' | 'gen3'\n\n /**\n * ID of GraphQL API. Only (currently) required when using the `--api` flag\n * for `sanity graphql deploy`, in order to only deploy a specific API.\n */\n id?: string\n\n /**\n * Whether or not to enable the GraphQL v2021-10-21 query semantics\n */\n nonNullDocumentFields?: boolean\n\n /**\n * Whether or not to enable the GraphQL Playground for this API\n *\n * Optional, defaults to `true` in development mode, `false` otherwise\n */\n playground?: boolean\n\n /**\n * Name of source containing the schema to deploy, within the configured workspace\n *\n * Optional, defaults to `default` (eg the one used if no `name` is defined)\n */\n source?: string\n\n /**\n * API tag for this API - allows deploying multiple different APIs to a single dataset\n *\n * Optional, defaults to `default`\n */\n tag?: string\n\n /**\n * Name of workspace containing the schema to deploy\n *\n * Optional, defaults to `default` (eg the one used if no `name` is defined)\n */\n workspace?: string\n}\n\nexport interface DeployResponse {\n location: string\n}\n\ninterface ApiChange {\n description: string\n type: string\n}\n\nexport interface ValidationResponse {\n breakingChanges: ApiChange[]\n dangerousChanges: ApiChange[]\n validationError: string\n}\n\nexport interface SchemaDefinitionish {\n name: string\n type: string\n\n fields?: SchemaDefinitionish[]\n}\n\ninterface ResolvedSerializableProperties {\n dataset: string\n projectId: string\n schemaTypes: SchemaDefinitionish[]\n}\n\nexport type TypeResolvedGraphQLAPI = Omit<GraphQLAPIConfig, 'source' | 'workspace'> &\n ResolvedSerializableProperties\n\nexport interface ExtractedGraphQLAPI {\n dataset: string\n projectId: string\n\n extracted?: ApiSpecification\n extractionError?: string\n filterSuffix?: string\n generation?: string\n id?: string\n nonNullDocumentFields?: boolean\n playground?: boolean\n schemaErrors?: SchemaValidationProblemGroup[]\n tag?: string\n}\n\nexport interface GraphQLWorkerResult {\n apis: ExtractedGraphQLAPI[]\n\n configErrors?: SchemaValidationProblemGroup[]\n}\n\ninterface ConvertedNode {\n description: string\n fields: ConvertedFieldDefinition[]\n kind: 'Interface' | 'List' | 'Type' | 'Union'\n name: string\n type: string\n}\n\ntype FieldArg =\n | {isFieldFilter?: boolean; name: string; type: string}\n | {name: string; type: ConvertedNode}\n\nexport interface ConvertedField extends Partial<Deprecation> {\n fieldName: string\n type: string\n\n args?: FieldArg[]\n description?: string\n filter?: string\n isNullable?: boolean\n isRawAlias?: boolean\n isReference?: boolean\n kind?: 'List'\n originalName?: string\n}\n\ninterface ConvertedListField extends ConvertedField {\n children: {\n inlineObjects?: string[]\n type: string\n }\n kind: 'List'\n}\n\nexport interface ApiCustomizationOptions {\n filterSuffix?: string\n}\n\nexport type InputFilterField =\n | ListDefinition\n | {\n constraint: {\n comparator: string\n field?: string\n }\n description?: string\n fieldName: string\n type: string\n }\n\nexport type ConvertedFieldDefinition = ConvertedField | ConvertedListField\n\ninterface ListDefinition {\n children: {isNullable?: boolean; type: string}\n kind: 'List'\n\n isNullable?: boolean\n}\n\nexport interface ConvertedEnum {\n kind: 'Enum'\n name: string\n values: {\n description?: string\n name: string\n value: unknown\n }[]\n}\n\nexport interface ConvertedInterface {\n fields: ConvertedFieldDefinition[]\n kind: 'Interface'\n name: string\n\n description?: string\n}\n\nexport interface ConvertedUnion {\n kind: 'Union'\n name: string\n types: string[]\n\n interfaces?: string[]\n}\n\nexport interface ConvertedDocumentType extends ConvertedType {\n interfaces: ['Document', ...string[]]\n}\n\nexport interface ConvertedType extends Partial<Deprecation> {\n fields: ConvertedFieldDefinition[]\n kind: 'Interface' | 'Type'\n name: string\n type: string\n\n _internal?: Partial<Deprecation>\n crossDatasetReferenceMetadata?: {\n dataset: string\n typeNames: string[]\n }\n description?: string\n interfaces?: string[]\n isReference?: boolean\n originalName?: string\n}\n\nexport interface InputObjectType {\n fields: unknown[] // @todo\n kind: 'InputObject'\n name: string\n\n isConstraintFilter?: boolean\n}\n\nexport interface QueryDefinition extends Partial<Deprecation> {\n args: {\n description?: string\n isFieldFilter?: boolean\n isNullable?: boolean\n name: string\n type: ListDefinition | string\n }[]\n fieldName: string\n\n type: ListDefinition | string\n\n constraints?: {\n comparator: string\n field?: string\n value?: {argName: string; kind: 'argumentValue'}\n }[]\n\n filter?: string\n}\n\nexport interface GeneratedApiSpecification {\n generation: string\n interfaces: ConvertedInterface[]\n queries: QueryDefinition[]\n types: (ConvertedEnum | ConvertedType | ConvertedUnion | InputObjectType)[]\n}\n"],"names":[],"mappings":"AAiQA,WAKC"}
1
+ {"version":3,"sources":["../../../src/actions/graphql/types.ts"],"sourcesContent":["import {type SchemaValidationProblemGroup} from '@sanity/types'\n\nexport interface Deprecation {\n deprecationReason: string\n}\n\nexport interface ApiSpecification {\n interfaces: ConvertedInterface[]\n types: (ConvertedType | ConvertedUnion)[]\n}\n\n/**\n * @public\n */\nexport interface GraphQLAPIConfig {\n /**\n * Suffix to use for generated filter types.\n *\n * Optional, Defaults to `Filter`.\n *\n */\n filterSuffix?: string\n\n /**\n * Generation of API to deploy\n *\n * Optional, defaults to `gen3` (which is the only option, currently)\n */\n generation?: 'gen1' | 'gen2' | 'gen3'\n\n /**\n * ID of GraphQL API. Only (currently) required when using the `--api` flag\n * for `sanity graphql deploy`, in order to only deploy a specific API.\n */\n id?: string\n\n /**\n * Whether or not to enable the GraphQL v2021-10-21 query semantics\n */\n nonNullDocumentFields?: boolean\n\n /**\n * Whether or not to enable the GraphQL Playground for this API\n *\n * Optional, defaults to `true` in development mode, `false` otherwise\n */\n playground?: boolean\n\n /**\n * Name of source containing the schema to deploy, within the configured workspace\n *\n * Optional, defaults to `default` (eg the one used if no `name` is defined)\n *\n * @deprecated Studio v7 removes workspace sources. Configure the source as its own workspace\n * and select it with `workspace` instead.\n */\n source?: string\n\n /**\n * API tag for this API - allows deploying multiple different APIs to a single dataset\n *\n * Optional, defaults to `default`\n */\n tag?: string\n\n /**\n * Name of workspace containing the schema to deploy\n *\n * Optional, defaults to `default` (eg the one used if no `name` is defined)\n */\n workspace?: string\n}\n\nexport interface DeployResponse {\n location: string\n}\n\ninterface ApiChange {\n description: string\n type: string\n}\n\nexport interface ValidationResponse {\n breakingChanges: ApiChange[]\n dangerousChanges: ApiChange[]\n validationError: string\n}\n\nexport interface SchemaDefinitionish {\n name: string\n type: string\n\n fields?: SchemaDefinitionish[]\n}\n\ninterface ResolvedSerializableProperties {\n dataset: string\n projectId: string\n schemaTypes: SchemaDefinitionish[]\n}\n\nexport type TypeResolvedGraphQLAPI = Omit<GraphQLAPIConfig, 'source' | 'workspace'> &\n ResolvedSerializableProperties\n\nexport interface ExtractedGraphQLAPI {\n dataset: string\n projectId: string\n\n extracted?: ApiSpecification\n extractionError?: string\n filterSuffix?: string\n generation?: string\n id?: string\n nonNullDocumentFields?: boolean\n playground?: boolean\n schemaErrors?: SchemaValidationProblemGroup[]\n tag?: string\n}\n\nexport interface GraphQLWorkerResult {\n apis: ExtractedGraphQLAPI[]\n\n configErrors?: SchemaValidationProblemGroup[]\n}\n\ninterface ConvertedNode {\n description: string\n fields: ConvertedFieldDefinition[]\n kind: 'Interface' | 'List' | 'Type' | 'Union'\n name: string\n type: string\n}\n\ntype FieldArg =\n | {isFieldFilter?: boolean; name: string; type: string}\n | {name: string; type: ConvertedNode}\n\nexport interface ConvertedField extends Partial<Deprecation> {\n fieldName: string\n type: string\n\n args?: FieldArg[]\n description?: string\n filter?: string\n isNullable?: boolean\n isRawAlias?: boolean\n isReference?: boolean\n kind?: 'List'\n originalName?: string\n}\n\ninterface ConvertedListField extends ConvertedField {\n children: {\n inlineObjects?: string[]\n type: string\n }\n kind: 'List'\n}\n\nexport interface ApiCustomizationOptions {\n filterSuffix?: string\n}\n\nexport type InputFilterField =\n | ListDefinition\n | {\n constraint: {\n comparator: string\n field?: string\n }\n description?: string\n fieldName: string\n type: string\n }\n\nexport type ConvertedFieldDefinition = ConvertedField | ConvertedListField\n\ninterface ListDefinition {\n children: {isNullable?: boolean; type: string}\n kind: 'List'\n\n isNullable?: boolean\n}\n\nexport interface ConvertedEnum {\n kind: 'Enum'\n name: string\n values: {\n description?: string\n name: string\n value: unknown\n }[]\n}\n\nexport interface ConvertedInterface {\n fields: ConvertedFieldDefinition[]\n kind: 'Interface'\n name: string\n\n description?: string\n}\n\nexport interface ConvertedUnion {\n kind: 'Union'\n name: string\n types: string[]\n\n interfaces?: string[]\n}\n\nexport interface ConvertedDocumentType extends ConvertedType {\n interfaces: ['Document', ...string[]]\n}\n\nexport interface ConvertedType extends Partial<Deprecation> {\n fields: ConvertedFieldDefinition[]\n kind: 'Interface' | 'Type'\n name: string\n type: string\n\n _internal?: Partial<Deprecation>\n crossDatasetReferenceMetadata?: {\n dataset: string\n typeNames: string[]\n }\n description?: string\n interfaces?: string[]\n isReference?: boolean\n originalName?: string\n}\n\nexport interface InputObjectType {\n fields: unknown[] // @todo\n kind: 'InputObject'\n name: string\n\n isConstraintFilter?: boolean\n}\n\nexport interface QueryDefinition extends Partial<Deprecation> {\n args: {\n description?: string\n isFieldFilter?: boolean\n isNullable?: boolean\n name: string\n type: ListDefinition | string\n }[]\n fieldName: string\n\n type: ListDefinition | string\n\n constraints?: {\n comparator: string\n field?: string\n value?: {argName: string; kind: 'argumentValue'}\n }[]\n\n filter?: string\n}\n\nexport interface GeneratedApiSpecification {\n generation: string\n interfaces: ConvertedInterface[]\n queries: QueryDefinition[]\n types: (ConvertedEnum | ConvertedType | ConvertedUnion | InputObjectType)[]\n}\n"],"names":[],"mappings":"AAoQA,WAKC"}
@@ -38,14 +38,12 @@ import { convertAspectDocuments, formatFieldEntries } from '../media/pullAspects
38
38
  message: `Media library ${library.id} already defines ${modules.length} ${pluralize('aspect', modules.length)}. ` + 'Generate field modules from them (replaces the example fields)?'
39
39
  });
40
40
  if (!shouldPull) return false;
41
- if (skipped.length > 0) {
42
- for (const aspect of skipped){
43
- const errors = aspect.validationErrors.flatMap((group)=>group.map(({ message })=>message));
44
- output.warn(`Skipped aspect ${aspect.id}: ${[
45
- ...aspect.reasons,
46
- ...errors
47
- ].join('; ')}`);
48
- }
41
+ for (const aspect of skipped){
42
+ const errors = aspect.validationErrors.flatMap((group)=>group.map(({ message })=>message));
43
+ output.warn(`Skipped aspect ${aspect.id}: ${[
44
+ ...aspect.reasons,
45
+ ...errors
46
+ ].join('; ')}`);
49
47
  }
50
48
  // The config edit is resolved before anything touches the disk: bailing
51
49
  // after deleting the example modules would leave the scaffold declaring
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/init/offerAspectPull.ts"],"sourcesContent":["import {mkdir, readFile, rm, writeFile} from 'node:fs/promises'\nimport path from 'node:path'\n\nimport {type Output} from '@sanity/cli-core'\nimport {confirm, logSymbols, spinner} from '@sanity/cli-core/ux'\n\nimport {getAspects, type MediaLibrary} from '../../services/mediaLibraries.js'\nimport {pluralize} from '../../util/pluralize.js'\nimport {replaceFieldEntries} from '../media/cliConfigFields.js'\nimport {\n convertAspectDocuments,\n formatFieldEntries,\n type PullableAspectDocument,\n} from '../media/pullAspects.js'\n\n/** Where the scaffold keeps field modules — the template's `fields[*].src` dir. */\nconst FIELDS_DIR = path.join('src', 'fields')\n\n/**\n * Offer to seed the freshly scaffolded config app from the organization's\n * existing aspects. Deploying the config mirrors it into the library —\n * stored aspects the config does not declare get deleted — so a scaffold\n * that starts from the example fields instead of the real ones is a loaded\n * footgun. Pulling at init time defuses it while we are still interactive\n * and authenticated.\n *\n * Only offered when the organization has exactly one active library (no\n * prompt-stacking during init); lookups and conversion errors degrade to a\n * silent skip — the scaffold is complete without this, and\n * `sanity media pull-aspects` covers it later.\n *\n * @returns `true` when the example fields were replaced by pulled modules.\n */\nexport async function offerAspectPull({\n library,\n output,\n outputPath,\n}: {\n library: MediaLibrary\n output: Output\n outputPath: string\n}): Promise<boolean> {\n const spin = spinner('Checking the media library for existing aspects').start()\n let documents: PullableAspectDocument[]\n try {\n documents = await getAspects(library.id)\n } catch {\n return false\n } finally {\n spin.stop()\n }\n if (documents.length === 0) return false\n\n const {modules, skipped} = convertAspectDocuments(documents)\n if (modules.length === 0) return false\n\n const shouldPull = await confirm({\n default: true,\n message:\n `Media library ${library.id} already defines ${modules.length} ${pluralize('aspect', modules.length)}. ` +\n 'Generate field modules from them (replaces the example fields)?',\n })\n if (!shouldPull) return false\n\n if (skipped.length > 0) {\n for (const aspect of skipped) {\n const errors = aspect.validationErrors.flatMap((group) => group.map(({message}) => message))\n output.warn(`Skipped aspect ${aspect.id}: ${[...aspect.reasons, ...errors].join('; ')}`)\n }\n }\n\n // The config edit is resolved before anything touches the disk: bailing\n // after deleting the example modules would leave the scaffold declaring\n // files that no longer exist. On bail the scaffold stays a consistent,\n // working pair (example fields + their declarations), and the caller's\n // `!pulledAspects` branch already points at `sanity media pull-aspects`.\n // The template is `typescriptOnly`, so the scaffold always writes this file.\n const configPath = path.join(outputPath, 'sanity.cli.ts')\n const entryLines = formatFieldEntries(modules, FIELDS_DIR.replaceAll(path.sep, '/')).split('\\n')\n\n const result = replaceFieldEntries(await readFile(configPath, 'utf8'), entryLines)\n if (!result.ok) {\n output.warn(\n `Could not seed the config from the existing aspects (${result.reason}) — the example fields are kept.`,\n )\n return false\n }\n\n // The example modules make way for the real ones: entries are replaced\n // wholesale in the config, so files left behind would just be orphans.\n const fieldsDir = path.join(outputPath, FIELDS_DIR)\n await rm(fieldsDir, {force: true, recursive: true})\n await mkdir(fieldsDir, {recursive: true})\n for (const module of modules) {\n await writeFile(path.join(fieldsDir, module.filename), module.source)\n }\n\n await writeFile(configPath, result.updated)\n output.log(\n `${logSymbols.success} Generated ${modules.length} field ${pluralize('module', modules.length)} from your media library and declared them in sanity.cli.ts`,\n )\n return true\n}\n"],"names":["mkdir","readFile","rm","writeFile","path","confirm","logSymbols","spinner","getAspects","pluralize","replaceFieldEntries","convertAspectDocuments","formatFieldEntries","FIELDS_DIR","join","offerAspectPull","library","output","outputPath","spin","start","documents","id","stop","length","modules","skipped","shouldPull","default","message","aspect","errors","validationErrors","flatMap","group","map","warn","reasons","configPath","entryLines","replaceAll","sep","split","result","ok","reason","fieldsDir","force","recursive","module","filename","source","updated","log","success"],"mappings":"AAAA,SAAQA,KAAK,EAAEC,QAAQ,EAAEC,EAAE,EAAEC,SAAS,QAAO,mBAAkB;AAC/D,OAAOC,UAAU,YAAW;AAG5B,SAAQC,OAAO,EAAEC,UAAU,EAAEC,OAAO,QAAO,sBAAqB;AAEhE,SAAQC,UAAU,QAA0B,mCAAkC;AAC9E,SAAQC,SAAS,QAAO,0BAAyB;AACjD,SAAQC,mBAAmB,QAAO,8BAA6B;AAC/D,SACEC,sBAAsB,EACtBC,kBAAkB,QAEb,0BAAyB;AAEhC,iFAAiF,GACjF,MAAMC,aAAaT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AG,EAAE,MAAMC,KAAK,CAAC;IAE3F,MAAMC,SAASjC,oBAAoB,MAAMT,SAASqC,YAAY,SAASC;IACvE,IAAI,CAACI,OAAOC,EAAE,EAAE;QACd3B,OAAOmB,IAAI,CACT,CAAC,qDAAqD,EAAEO,OAAOE,MAAM,CAAC,gCAAgC,CAAC;QAEzG,OAAO;IACT;IAEA,uEAAuE;IACvE,uEAAuE;IACvE,MAAMC,YAAY1C,KAAKU,IAAI,CAACI,YAAYL;IACxC,MAAMX,GAAG4C,WAAW;QAACC,OAAO;QAAMC,WAAW;IAAI;IACjD,MAAMhD,MAAM8C,WAAW;QAACE,WAAW;IAAI;IACvC,KAAK,MAAMC,UAAUxB,QAAS;QAC5B,MAAMtB,UAAUC,KAAKU,IAAI,CAACgC,WAAWG,OAAOC,QAAQ,GAAGD,OAAOE,MAAM;IACtE;IAEA,MAAMhD,UAAUmC,YAAYK,OAAOS,OAAO;IAC1CnC,OAAOoC,GAAG,CACR,GAAG/C,WAAWgD,OAAO,CAAC,WAAW,EAAE7B,QAAQD,MAAM,CAAC,OAAO,EAAEf,UAAU,UAAUgB,QAAQD,MAAM,EAAE,2DAA2D,CAAC;IAE7J,OAAO;AACT"}
1
+ {"version":3,"sources":["../../../src/actions/init/offerAspectPull.ts"],"sourcesContent":["import {mkdir, readFile, rm, writeFile} from 'node:fs/promises'\nimport path from 'node:path'\n\nimport {type Output} from '@sanity/cli-core'\nimport {confirm, logSymbols, spinner} from '@sanity/cli-core/ux'\n\nimport {getAspects, type MediaLibrary} from '../../services/mediaLibraries.js'\nimport {pluralize} from '../../util/pluralize.js'\nimport {replaceFieldEntries} from '../media/cliConfigFields.js'\nimport {\n convertAspectDocuments,\n formatFieldEntries,\n type PullableAspectDocument,\n} from '../media/pullAspects.js'\n\n/** Where the scaffold keeps field modules — the template's `fields[*].src` dir. */\nconst FIELDS_DIR = path.join('src', 'fields')\n\n/**\n * Offer to seed the freshly scaffolded config app from the organization's\n * existing aspects. Deploying the config mirrors it into the library —\n * stored aspects the config does not declare get deleted — so a scaffold\n * that starts from the example fields instead of the real ones is a loaded\n * footgun. Pulling at init time defuses it while we are still interactive\n * and authenticated.\n *\n * Only offered when the organization has exactly one active library (no\n * prompt-stacking during init); lookups and conversion errors degrade to a\n * silent skip — the scaffold is complete without this, and\n * `sanity media pull-aspects` covers it later.\n *\n * @returns `true` when the example fields were replaced by pulled modules.\n */\nexport async function offerAspectPull({\n library,\n output,\n outputPath,\n}: {\n library: MediaLibrary\n output: Output\n outputPath: string\n}): Promise<boolean> {\n const spin = spinner('Checking the media library for existing aspects').start()\n let documents: PullableAspectDocument[]\n try {\n documents = await getAspects(library.id)\n } catch {\n return false\n } finally {\n spin.stop()\n }\n if (documents.length === 0) return false\n\n const {modules, skipped} = convertAspectDocuments(documents)\n if (modules.length === 0) return false\n\n const shouldPull = await confirm({\n default: true,\n message:\n `Media library ${library.id} already defines ${modules.length} ${pluralize('aspect', modules.length)}. ` +\n 'Generate field modules from them (replaces the example fields)?',\n })\n if (!shouldPull) return false\n\n for (const aspect of skipped) {\n const errors = aspect.validationErrors.flatMap((group) => group.map(({message}) => message))\n output.warn(`Skipped aspect ${aspect.id}: ${[...aspect.reasons, ...errors].join('; ')}`)\n }\n\n // The config edit is resolved before anything touches the disk: bailing\n // after deleting the example modules would leave the scaffold declaring\n // files that no longer exist. On bail the scaffold stays a consistent,\n // working pair (example fields + their declarations), and the caller's\n // `!pulledAspects` branch already points at `sanity media pull-aspects`.\n // The template is `typescriptOnly`, so the scaffold always writes this file.\n const configPath = path.join(outputPath, 'sanity.cli.ts')\n const entryLines = formatFieldEntries(modules, FIELDS_DIR.replaceAll(path.sep, '/')).split('\\n')\n\n const result = replaceFieldEntries(await readFile(configPath, 'utf8'), entryLines)\n if (!result.ok) {\n output.warn(\n `Could not seed the config from the existing aspects (${result.reason}) — the example fields are kept.`,\n )\n return false\n }\n\n // The example modules make way for the real ones: entries are replaced\n // wholesale in the config, so files left behind would just be orphans.\n const fieldsDir = path.join(outputPath, FIELDS_DIR)\n await rm(fieldsDir, {force: true, recursive: true})\n await mkdir(fieldsDir, {recursive: true})\n for (const module of modules) {\n await writeFile(path.join(fieldsDir, module.filename), module.source)\n }\n\n await writeFile(configPath, result.updated)\n output.log(\n `${logSymbols.success} Generated ${modules.length} field ${pluralize('module', modules.length)} from your media library and declared them in sanity.cli.ts`,\n )\n return true\n}\n"],"names":["mkdir","readFile","rm","writeFile","path","confirm","logSymbols","spinner","getAspects","pluralize","replaceFieldEntries","convertAspectDocuments","formatFieldEntries","FIELDS_DIR","join","offerAspectPull","library","output","outputPath","spin","start","documents","id","stop","length","modules","skipped","shouldPull","default","message","aspect","errors","validationErrors","flatMap","group","map","warn","reasons","configPath","entryLines","replaceAll","sep","split","result","ok","reason","fieldsDir","force","recursive","module","filename","source","updated","log","success"],"mappings":"AAAA,SAAQA,KAAK,EAAEC,QAAQ,EAAEC,EAAE,EAAEC,SAAS,QAAO,mBAAkB;AAC/D,OAAOC,UAAU,YAAW;AAG5B,SAAQC,OAAO,EAAEC,UAAU,EAAEC,OAAO,QAAO,sBAAqB;AAEhE,SAAQC,UAAU,QAA0B,mCAAkC;AAC9E,SAAQC,SAAS,QAAO,0BAAyB;AACjD,SAAQC,mBAAmB,QAAO,8BAA6B;AAC/D,SACEC,sBAAsB,EACtBC,kBAAkB,QAEb,0BAAyB;AAEhC,iFAAiF,GACjF,MAAMC,aAAaT,KAAKU,IAAI,CAAC,OAAO;AAEpC;;;;;;;;;;;;;;CAcC,GACD,OAAO,eAAeC,gBAAgB,EACpCC,OAAO,EACPC,MAAM,EACNC,UAAU,EAKX;IACC,MAAMC,OAAOZ,QAAQ,mDAAmDa,KAAK;IAC7E,IAAIC;IACJ,IAAI;QACFA,YAAY,MAAMb,WAAWQ,QAAQM,EAAE;IACzC,EAAE,OAAM;QACN,OAAO;IACT,SAAU;QACRH,KAAKI,IAAI;IACX;IACA,IAAIF,UAAUG,MAAM,KAAK,GAAG,OAAO;IAEnC,MAAM,EA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I;IACvC,KAAK,MAAMC,UAAUxB,QAAS;QAC5B,MAAMtB,UAAUC,KAAKU,IAAI,CAACgC,WAAWG,OAAOC,QAAQ,GAAGD,OAAOE,MAAM;IACtE;IAEA,MAAMhD,UAAUmC,YAAYK,OAAOS,OAAO;IAC1CnC,OAAOoC,GAAG,CACR,GAAG/C,WAAWgD,OAAO,CAAC,WAAW,EAAE7B,QAAQD,MAAM,CAAC,OAAO,EAAEf,UAAU,UAAUgB,QAAQD,MAAM,EAAE,2DAA2D,CAAC;IAE7J,OAAO;AACT"}
@@ -6,6 +6,7 @@ import { extractGraphQLAPIs } from '../../actions/graphql/extractGraphQLAPIs.js'
6
6
  import gen1 from '../../actions/graphql/gen1/index.js';
7
7
  import gen2 from '../../actions/graphql/gen2/index.js';
8
8
  import gen3 from '../../actions/graphql/gen3/index.js';
9
+ import { getSourceDeprecationWarning } from '../../actions/graphql/getSourceDeprecationWarning.js';
9
10
  import { graphqlDebug } from '../../actions/graphql/graphqlDebug.js';
10
11
  import { resolveApiGeneration } from '../../actions/graphql/resolveApiGeneration.js';
11
12
  import { SchemaError } from '../../actions/graphql/SchemaError.js';
@@ -88,6 +89,10 @@ export class GraphQLDeployCommand extends SanityCommand {
88
89
  let apiDefs = [];
89
90
  let spin;
90
91
  try {
92
+ const sourceDeprecation = getSourceDeprecationWarning((await this.getCliConfig()).graphql);
93
+ if (sourceDeprecation) {
94
+ this.warn(sourceDeprecation);
95
+ }
91
96
  apiDefs = await extractGraphQLAPIs(workDir, {
92
97
  nonNullDocumentFieldsFlag,
93
98
  withUnionCache
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/commands/graphql/deploy.ts"],"sourcesContent":["import {Flags} from '@oclif/core'\nimport {exitCodes, SanityCommand} from '@sanity/cli-core'\nimport {confirm, spinner} from '@sanity/cli-core/ux'\nimport get from 'lodash-es/get.js'\n\nimport {extractGraphQLAPIs} from '../../actions/graphql/extractGraphQLAPIs.js'\nimport gen1 from '../../actions/graphql/gen1/index.js'\nimport gen2 from '../../actions/graphql/gen2/index.js'\nimport gen3 from '../../actions/graphql/gen3/index.js'\nimport {graphqlDebug} from '../../actions/graphql/graphqlDebug.js'\nimport {resolveApiGeneration} from '../../actions/graphql/resolveApiGeneration.js'\nimport {SchemaError} from '../../actions/graphql/SchemaError.js'\nimport {\n type ExtractedGraphQLAPI,\n type GeneratedApiSpecification,\n type ValidationResponse,\n} from '../../actions/graphql/types.js'\nimport {\n deployGraphQLAPI,\n getClientUrl,\n getCurrentSchemaProps,\n validateGraphQLAPI,\n} from '../../services/graphql.js'\nimport {getDatasetFlag} from '../../util/sharedFlags.js'\n\ninterface DeployTask {\n dataset: string\n enablePlayground: boolean\n projectId: string\n schema: GeneratedApiSpecification\n tag: string\n}\n\nconst apiIdRegex = /^[a-z0-9_-]+$/\nconst generations = {\n gen1,\n gen2,\n gen3,\n}\n\nconst ignoredBreaking = new Set<string>(['OPTIONAL_INPUT_FIELD_ADDED'])\n// Reserved for future use to filter out specific dangerous change types\nconst ignoredWarnings = new Set<string>()\n\nconst debug = graphqlDebug.extend('deploy')\n\nexport class GraphQLDeployCommand extends SanityCommand<typeof GraphQLDeployCommand> {\n static override description = 'Deploy a GraphQL API from the current Sanity schema'\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %>',\n description: 'Deploy all defined GraphQL APIs',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --dry-run',\n description: 'Validate defined GraphQL APIs, check for breaking changes, skip deploy',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --api staging --api ios',\n description: 'Deploy only the GraphQL APIs with the IDs \"staging\" and \"ios\"',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --playground',\n description: 'Deploy all defined GraphQL APIs, overriding any playground setting',\n },\n ]\n\n static override flags = {\n api: Flags.string({\n description: 'Only deploy API with this ID (can be specified multiple times)',\n multiple: true,\n }),\n ...getDatasetFlag({description: 'Deploy API for the given dataset', semantics: 'specify'}),\n 'dry-run': Flags.boolean({\n default: false,\n description: 'Validate defined GraphQL APIs, check for breaking changes, skip deploy',\n }),\n force: Flags.boolean({\n description: 'Deploy API without confirming breaking changes',\n }),\n generation: Flags.string({\n description: 'API generation to deploy (defaults to \"gen3\")',\n options: ['gen1', 'gen2', 'gen3'],\n }),\n 'non-null-document-fields': Flags.boolean({\n description: 'Use non-null document fields (_id, _type etc)',\n }),\n playground: Flags.boolean({\n allowNo: true,\n description: 'Enable GraphQL playground for easier debugging',\n }),\n tag: Flags.string({\n description: 'Deploy API(s) to given tag (defaults to \"default\")',\n }),\n 'with-union-cache': Flags.boolean({\n description: 'Cache union types (faster for schemas with many self-references)',\n }),\n }\n\n public async run(): Promise<void> {\n const {flags} = await this.parse(GraphQLDeployCommand)\n const {\n api: onlyApis,\n dataset: datasetFlag,\n 'dry-run': dryRun,\n generation: generationFlag,\n 'non-null-document-fields': nonNullDocumentFieldsFlag,\n playground: playgroundFlag,\n tag: tagFlag,\n 'with-union-cache': withUnionCache,\n } = flags\n\n const workDir = (await this.getProjectRoot()).directory\n\n let apiDefs: ExtractedGraphQLAPI[] = []\n let spin: ReturnType<typeof spinner>\n\n try {\n apiDefs = await extractGraphQLAPIs(workDir, {\n nonNullDocumentFieldsFlag,\n withUnionCache,\n })\n } catch (error) {\n if (error instanceof SchemaError) {\n debug('Schema validation errors: %O', error.problemGroups)\n error.print(this.output)\n this.error('Fix the schema errors above and try again', {exit: exitCodes.RUNTIME_ERROR})\n }\n debug('Failed to resolve GraphQL APIs: %O', error)\n const message = error instanceof Error ? error.message : String(error)\n this.error(`Failed to resolve GraphQL APIs: ${message}`, {exit: exitCodes.RUNTIME_ERROR})\n }\n\n const hasMultipleApis = flags.api ? flags.api.length > 1 : apiDefs.length > 1\n\n const usedFlags = [\n datasetFlag && '--dataset',\n tagFlag && '--tag',\n playgroundFlag !== undefined && '--playground',\n generationFlag !== undefined && '--generation',\n nonNullDocumentFieldsFlag !== undefined && '--non-null-document-fields',\n ].filter(Boolean)\n\n if (hasMultipleApis && usedFlags.length > 0) {\n this.warn(`More than one API defined, and ${usedFlags.join('/')} is specified`)\n this.warn(`This will use the specified flag(s) for ALL APIs, overriding config!`)\n\n if (flags.force) {\n this.warn(`--force specified, continuing...`)\n } else if (this.isUnattended()) {\n this.error(\n 'Flag overrides for multiple APIs require confirmation. Pass `--force` to continue.',\n {\n exit: exitCodes.USAGE_ERROR,\n },\n )\n } else {\n const confirmed = await confirm({\n default: false,\n message: 'Continue with flag overrides for all APIs?',\n })\n if (!confirmed) {\n this.log('GraphQL deployment cancelled')\n this.exit(exitCodes.USER_ABORT)\n }\n }\n }\n\n const deployTasks: DeployTask[] = []\n let hasErrors = false\n\n for (const apiId of onlyApis || []) {\n if (!apiDefs.some((apiDef) => apiDef.id === apiId)) {\n this.error(`GraphQL API with id \"${apiId}\" not found`, {exit: exitCodes.RUNTIME_ERROR})\n }\n }\n\n const apiNames = new Set<string>()\n const apiIds = new Set<string>()\n\n for (const apiDef of apiDefs) {\n if (onlyApis && (!apiDef.id || !onlyApis.includes(apiDef.id))) {\n continue\n }\n\n const {apiName} = this.getApiIdentifiers(apiDef, datasetFlag, tagFlag)\n if (apiNames.has(apiName)) {\n this.error(`Multiple GraphQL APIs with the same dataset and tag found (${apiName})`, {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n\n if (apiDef.id) {\n if (!apiIdRegex.test(apiDef.id)) {\n this.error(\n `Invalid GraphQL API id \"${apiDef.id}\" - only a-z, 0-9, underscore and dashes are allowed`,\n {exit: exitCodes.RUNTIME_ERROR},\n )\n }\n\n if (apiIds.has(apiDef.id)) {\n this.error(`Multiple GraphQL APIs with the same ID found (${apiDef.id})`, {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n\n apiIds.add(apiDef.id)\n }\n\n apiNames.add(apiName)\n }\n\n if (onlyApis) {\n this.warn(`Deploying only specified APIs: ${onlyApis.join(', ')}`)\n }\n\n let index = -1\n for (const apiDef of apiDefs) {\n if (onlyApis && (!apiDef.id || !onlyApis.includes(apiDef.id))) {\n continue\n }\n\n index++\n\n const {apiName, dataset, tag} = this.getApiIdentifiers(apiDef, datasetFlag, tagFlag)\n const {playground, projectId} = apiDef\n spin = spinner(`Generating GraphQL API: ${apiName}`).start()\n\n if (!dataset) {\n spin.fail()\n this.error(\n `Dataset is required for API at index ${index}. Pass it with \\`--dataset <name>\\` or configure a dataset for the API.`,\n {exit: exitCodes.USAGE_ERROR},\n )\n }\n\n // Handle extraction errors early (computed in worker), before network calls and prompts.\n // Continue the loop so all API errors are reported — don't exit on the first failure.\n if (apiDef.schemaErrors?.length) {\n spin.fail()\n new SchemaError(apiDef.schemaErrors).print(this.output, `Schema errors in ${apiName}`)\n hasErrors = true\n continue\n }\n\n if (apiDef.extractionError) {\n debug('Failed to extract schema', apiDef.extractionError)\n spin.fail()\n this.log(`Failed to extract schema for ${apiName}: ${apiDef.extractionError}`)\n hasErrors = true\n continue\n }\n\n if (!apiDef.extracted) {\n spin.fail()\n this.log(`Failed to extract schema for ${apiName}: No extraction result`)\n hasErrors = true\n continue\n }\n\n let currentGeneration: string | undefined\n let playgroundEnabled: boolean | undefined\n try {\n const schemaProps = await getCurrentSchemaProps(projectId, dataset, tag)\n currentGeneration = schemaProps.currentGeneration\n playgroundEnabled = schemaProps.playgroundEnabled\n } catch (err) {\n debug('Failed to get current GraphQL schema properties', err)\n spin.fail()\n this.error('Failed to get current GraphQL schema properties', {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n\n // CLI flag takes precedence over configuration\n const specifiedGeneration = generationFlag === undefined ? apiDef.generation : generationFlag\n\n const generation = await resolveApiGeneration({\n currentGeneration,\n force: flags.force,\n index,\n output: this.output,\n specifiedGeneration,\n unattended: this.isUnattended(),\n })\n\n if (!generation) {\n spin.stop()\n this.log('GraphQL deployment cancelled')\n this.exit(exitCodes.USER_ABORT)\n }\n\n if (!this.isRecognizedApiGeneration(generation)) {\n spin.fail()\n this.error(`Unknown API generation \"${generation}\" for API at index ${index}`, {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n\n const enablePlayground = await this.shouldEnablePlayground({\n dryRun,\n playgroundCliFlag: playgroundFlag,\n playgroundConfiguration: playground,\n playgroundCurrentlyEnabled: playgroundEnabled,\n spin,\n })\n\n let apiSpec: GeneratedApiSpecification\n try {\n const generateSchema = generations[generation]\n apiSpec = generateSchema(apiDef.extracted, {filterSuffix: apiDef.filterSuffix})\n } catch (err) {\n debug('Failed to generate schema', err)\n spin.fail()\n const message = err instanceof Error ? err.message : 'Unknown error'\n this.error(`Failed to generate schema: ${message}`, {exit: exitCodes.RUNTIME_ERROR})\n }\n\n let valid: ValidationResponse | undefined\n try {\n valid = await validateGraphQLAPI({\n dataset,\n enablePlayground,\n projectId,\n schema: apiSpec,\n tag,\n })\n } catch (err) {\n debug('validateGraphQLAPI error', err)\n const validationError = get(err, 'response.body.validationError')\n spin.fail()\n this.error(validationError ?? 'Failed to validate GraphQL API', {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n\n // when the result is not valid and there are breaking changes afoot!\n if (!this.isResultValid(valid, {force: flags.force, spin})) {\n // not valid and a dry run? then it can exit with a error\n if (dryRun) {\n spin.fail()\n this.renderBreakingChanges(valid)\n hasErrors = true\n continue\n }\n\n if (this.isUnattended()) {\n spin.fail()\n this.renderBreakingChanges(valid)\n this.error(\n 'GraphQL deployment requires confirmation because the schema contains dangerous changes. Pass `--force` to continue.',\n {exit: exitCodes.USAGE_ERROR},\n )\n }\n\n spin.stop()\n this.renderBreakingChanges(valid)\n const shouldDeploy = await confirm({\n default: false,\n message: 'Do you want to deploy a new API despite the dangerous changes?',\n })\n\n if (!shouldDeploy) {\n this.log('GraphQL deployment cancelled')\n this.exit(exitCodes.USER_ABORT)\n }\n\n spin.succeed()\n } else if (dryRun) {\n // isResultValid() already set the spinner state (succeed or warn).\n // Check whether changes were forced so we print the correct message.\n const {breakingChanges, dangerousChanges} = this.filterChanges(valid)\n if (breakingChanges.length > 0 || dangerousChanges.length > 0) {\n this.renderBreakingChanges(valid)\n this.log('Forced with `--force`, skipping deploy (dry run)')\n } else {\n this.log('GraphQL API is valid and has no breaking changes')\n }\n continue\n }\n\n deployTasks.push({\n dataset,\n enablePlayground,\n projectId,\n schema: apiSpec,\n tag,\n })\n }\n\n // Give some space for deployment tasks\n this.log('')\n\n for (const task of deployTasks) {\n const {dataset, enablePlayground, projectId, schema, tag} = task\n\n this.log(`Project: ${projectId}`)\n this.log(`Dataset: ${dataset}`)\n this.log(`Tag: ${tag}`)\n\n spin = spinner('Deploying GraphQL API').start()\n\n try {\n const response = await deployGraphQLAPI({\n dataset,\n enablePlayground,\n projectId,\n schema,\n tag,\n })\n\n spin.stop()\n const apiUrl = await getClientUrl(\n projectId,\n response.location.replace(/^\\/(v1|v\\d{4}-\\d{2}-\\d{2})\\//, '/'),\n )\n this.log(`URL: ${apiUrl}`)\n spin.start('Deployed!').succeed()\n this.log('')\n } catch (error) {\n spin.fail()\n debug('Failed to deploy GraphQL API', error)\n this.error('Failed to deploy GraphQL API', {exit: exitCodes.RUNTIME_ERROR})\n }\n }\n\n if (hasErrors) {\n this.exit(exitCodes.RUNTIME_ERROR)\n }\n }\n\n private filterChanges(valid: ValidationResponse) {\n const {breakingChanges: breaking, dangerousChanges: dangerous} = valid\n return {\n breakingChanges: breaking.filter((change) => !ignoredBreaking.has(change.type)),\n dangerousChanges: dangerous.filter((change) => !ignoredWarnings.has(change.type)),\n }\n }\n\n private getApiIdentifiers(apiDef: ExtractedGraphQLAPI, datasetFlag?: string, tagFlag?: string) {\n const dataset = datasetFlag || apiDef.dataset\n const tag = tagFlag || apiDef.tag || 'default'\n const apiName = [dataset, tag].join('/')\n return {apiName, dataset, tag}\n }\n\n private isRecognizedApiGeneration(generation: string): generation is 'gen1' | 'gen2' | 'gen3' {\n return ['gen1', 'gen2', 'gen3'].includes(generation)\n }\n\n private isResultValid(\n valid: ValidationResponse,\n {force, spin}: {force?: boolean; spin: ReturnType<typeof spinner>},\n ) {\n const {validationError} = valid\n if (validationError) {\n spin.fail()\n this.error(`GraphQL schema is not valid:\\n\\n${validationError}`, {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n\n const {breakingChanges, dangerousChanges} = this.filterChanges(valid)\n\n const hasProblematicChanges = breakingChanges.length > 0 || dangerousChanges.length > 0\n\n if (!hasProblematicChanges) {\n spin.succeed()\n return true\n }\n\n if (force) {\n spin.text = 'Validating GraphQL API: Dangerous changes. Forced with `--force`.'\n spin.warn()\n return true\n }\n\n spin.warn()\n return false\n }\n\n private renderBreakingChanges(valid: ValidationResponse) {\n const {breakingChanges, dangerousChanges} = this.filterChanges(valid)\n\n if (dangerousChanges.length > 0) {\n this.log('\\nFound potentially dangerous changes from previous schema:')\n for (const change of dangerousChanges) this.log(` - ${change.description}`)\n }\n\n if (breakingChanges.length > 0) {\n this.log('\\nFound BREAKING changes from previous schema:')\n for (const change of breakingChanges) this.log(` - ${change.description}`)\n }\n\n this.output.log('')\n }\n\n private async shouldEnablePlayground({\n dryRun,\n playgroundCliFlag,\n playgroundConfiguration,\n playgroundCurrentlyEnabled,\n spin,\n }: {\n dryRun: boolean\n playgroundCliFlag?: boolean\n playgroundConfiguration?: boolean\n playgroundCurrentlyEnabled?: boolean\n spin: ReturnType<typeof spinner>\n }): Promise<boolean> {\n // On a dry run, it doesn't matter, return true 🤷‍♂️\n if (dryRun) {\n return true\n }\n\n // Prioritize CLI flag if set\n if (playgroundCliFlag !== undefined) {\n return playgroundCliFlag\n }\n\n // If explicitly set true/false in configuration, use that\n if (playgroundConfiguration !== undefined) {\n return playgroundConfiguration\n }\n\n // If API is already deployed, use the current state\n if (playgroundCurrentlyEnabled !== undefined) {\n return playgroundCurrentlyEnabled\n }\n\n // If no API is deployed, default to true if non-interactive\n if (this.isUnattended()) {\n return true\n }\n\n // Interactive environment, so prompt the user\n const prevText = spin.text\n spin.warn()\n const shouldDeploy = await confirm({\n default: true,\n message: 'Do you want to enable a GraphQL playground?',\n })\n spin.clear().start(prevText)\n\n return shouldDeploy\n }\n}\n"],"names":["Flags","exitCodes","SanityCommand","confirm","spinner","get","extractGraphQLAPIs","gen1","gen2","gen3","graphqlDebug","resolveApiGeneration","SchemaError","deployGraphQLAPI","getClientUrl","getCurrentSchemaProps","validateGraphQLAPI","getDatasetFlag","apiIdRegex","generations","ignoredBreaking","Set","ignoredWarnings","debug","extend","GraphQLDeployCommand","description","examples","command","flags","api","string","multiple","semantics","boolean","default","force","generation","options","playground","allowNo","tag","run","parse","onlyApis","dataset","datasetFlag","dryRun","generationFlag","nonNullDocumentFieldsFlag","playgroundFlag","tagFlag","withUnionCache","workDir","getProjectRoot","directory","apiDefs","spin","error","problemGroups","print","output","exit","RUNTIME_ERROR","message","Error","String","hasMultipleApis","length","usedFlags","undefined","filter","Boolean","warn","join","isUnattended","USAGE_ERROR","confirmed","log","USER_ABORT","deployTasks","hasErrors","apiId","some","apiDef","id","apiNames","apiIds","includes","apiName","getApiIdentifiers","has","test","add","index","projectId","start","fail","schemaErrors","extractionError","extracted","currentGeneration","playgroundEnabled","schemaProps","err","specifiedGeneration","unattended","stop","isRecognizedApiGeneration","enablePlayground","shouldEnablePlayground","playgroundCliFlag","playgroundConfiguration","playgroundCurrentlyEnabled","apiSpec","generateSchema","filterSuffix","valid","schema","validationError","isResultValid","renderBreakingChanges","shouldDeploy","succeed","breakingChanges","dangerousChanges","filterChanges","push","task","response","apiUrl","location","replace","breaking","dangerous","change","type","hasProblematicChanges","text","prevText","clear"],"mappings":"AAAA,SAAQA,KAAK,QAAO,cAAa;AACjC,SAAQC,SAAS,EAAEC,aAAa,QAAO,mBAAkB;AACzD,SAAQC,OAAO,EAAEC,OAAO,QAAO,sBAAqB;AACpD,OAAOC,SAAS,mBAAkB;AAElC,SAAQC,kBAAkB,QAAO,8CAA6C;AAC9E,OAAOC,UAAU,sCAAqC;AACtD,OAAOC,UAAU,sCAAqC;AACtD,OAAOC,UAAU,sCAAqC;AACtD,SAAQC,YAAY,QAAO,wCAAuC;AAClE,SAAQC,oBAAoB,QAAO,gDA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iB,IAAI,CAAC9C,GAAG,CAAC,CAAC,GAAG,EAAEyD,OAAO7G,WAAW,EAAE;QAC3E;QAEA,IAAI,CAACmC,MAAM,CAACiB,GAAG,CAAC;IAClB;IAEA,MAAcgC,uBAAuB,EACnC/D,MAAM,EACNgE,iBAAiB,EACjBC,uBAAuB,EACvBC,0BAA0B,EAC1BxD,IAAI,EAOL,EAAoB;QACnB,qDAAqD;QACrD,IAAIV,QAAQ;YACV,OAAO;QACT;QAEA,6BAA6B;QAC7B,IAAIgE,sBAAsBzC,WAAW;YACnC,OAAOyC;QACT;QAEA,0DAA0D;QAC1D,IAAIC,4BAA4B1C,WAAW;YACzC,OAAO0C;QACT;QAEA,oDAAoD;QACpD,IAAIC,+BAA+B3C,WAAW;YAC5C,OAAO2C;QACT;QAEA,4DAA4D;QAC5D,IAAI,IAAI,CAACtC,YAAY,IAAI;YACvB,OAAO;QACT;QAEA,8CAA8C;QAC9C,MAAMgE,WAAWlF,KAAKiF,IAAI;QAC1BjF,KAAKgB,IAAI;QACT,MAAMiD,eAAe,MAAMvH,QAAQ;YACjCgC,SAAS;YACT6B,SAAS;QACX;QACAP,KAAKmF,KAAK,GAAG5C,KAAK,CAAC2C;QAEnB,OAAOjB;IACT;AACF"}
1
+ {"version":3,"sources":["../../../src/commands/graphql/deploy.ts"],"sourcesContent":["import {Flags} from '@oclif/core'\nimport {exitCodes, SanityCommand} from '@sanity/cli-core'\nimport {confirm, spinner} from '@sanity/cli-core/ux'\nimport get from 'lodash-es/get.js'\n\nimport {extractGraphQLAPIs} from '../../actions/graphql/extractGraphQLAPIs.js'\nimport gen1 from '../../actions/graphql/gen1/index.js'\nimport gen2 from '../../actions/graphql/gen2/index.js'\nimport gen3 from '../../actions/graphql/gen3/index.js'\nimport {getSourceDeprecationWarning} from '../../actions/graphql/getSourceDeprecationWarning.js'\nimport {graphqlDebug} from '../../actions/graphql/graphqlDebug.js'\nimport {resolveApiGeneration} from '../../actions/graphql/resolveApiGeneration.js'\nimport {SchemaError} from '../../actions/graphql/SchemaError.js'\nimport {\n type ExtractedGraphQLAPI,\n type GeneratedApiSpecification,\n type ValidationResponse,\n} from '../../actions/graphql/types.js'\nimport {\n deployGraphQLAPI,\n getClientUrl,\n getCurrentSchemaProps,\n validateGraphQLAPI,\n} from '../../services/graphql.js'\nimport {getDatasetFlag} from '../../util/sharedFlags.js'\n\ninterface DeployTask {\n dataset: string\n enablePlayground: boolean\n projectId: string\n schema: GeneratedApiSpecification\n tag: string\n}\n\nconst apiIdRegex = /^[a-z0-9_-]+$/\nconst generations = {\n gen1,\n gen2,\n gen3,\n}\n\nconst ignoredBreaking = new Set<string>(['OPTIONAL_INPUT_FIELD_ADDED'])\n// Reserved for future use to filter out specific dangerous change types\nconst ignoredWarnings = new Set<string>()\n\nconst debug = graphqlDebug.extend('deploy')\n\nexport class GraphQLDeployCommand extends SanityCommand<typeof GraphQLDeployCommand> {\n static override description = 'Deploy a GraphQL API from the current Sanity schema'\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %>',\n description: 'Deploy all defined GraphQL APIs',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --dry-run',\n description: 'Validate defined GraphQL APIs, check for breaking changes, skip deploy',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --api staging --api ios',\n description: 'Deploy only the GraphQL APIs with the IDs \"staging\" and \"ios\"',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --playground',\n description: 'Deploy all defined GraphQL APIs, overriding any playground setting',\n },\n ]\n\n static override flags = {\n api: Flags.string({\n description: 'Only deploy API with this ID (can be specified multiple times)',\n multiple: true,\n }),\n ...getDatasetFlag({description: 'Deploy API for the given dataset', semantics: 'specify'}),\n 'dry-run': Flags.boolean({\n default: false,\n description: 'Validate defined GraphQL APIs, check for breaking changes, skip deploy',\n }),\n force: Flags.boolean({\n description: 'Deploy API without confirming breaking changes',\n }),\n generation: Flags.string({\n description: 'API generation to deploy (defaults to \"gen3\")',\n options: ['gen1', 'gen2', 'gen3'],\n }),\n 'non-null-document-fields': Flags.boolean({\n description: 'Use non-null document fields (_id, _type etc)',\n }),\n playground: Flags.boolean({\n allowNo: true,\n description: 'Enable GraphQL playground for easier debugging',\n }),\n tag: Flags.string({\n description: 'Deploy API(s) to given tag (defaults to \"default\")',\n }),\n 'with-union-cache': Flags.boolean({\n description: 'Cache union types (faster for schemas with many self-references)',\n }),\n }\n\n public async run(): Promise<void> {\n const {flags} = await this.parse(GraphQLDeployCommand)\n const {\n api: onlyApis,\n dataset: datasetFlag,\n 'dry-run': dryRun,\n generation: generationFlag,\n 'non-null-document-fields': nonNullDocumentFieldsFlag,\n playground: playgroundFlag,\n tag: tagFlag,\n 'with-union-cache': withUnionCache,\n } = flags\n\n const workDir = (await this.getProjectRoot()).directory\n\n let apiDefs: ExtractedGraphQLAPI[] = []\n let spin: ReturnType<typeof spinner>\n\n try {\n const sourceDeprecation = getSourceDeprecationWarning((await this.getCliConfig()).graphql)\n if (sourceDeprecation) {\n this.warn(sourceDeprecation)\n }\n\n apiDefs = await extractGraphQLAPIs(workDir, {\n nonNullDocumentFieldsFlag,\n withUnionCache,\n })\n } catch (error) {\n if (error instanceof SchemaError) {\n debug('Schema validation errors: %O', error.problemGroups)\n error.print(this.output)\n this.error('Fix the schema errors above and try again', {exit: exitCodes.RUNTIME_ERROR})\n }\n debug('Failed to resolve GraphQL APIs: %O', error)\n const message = error instanceof Error ? error.message : String(error)\n this.error(`Failed to resolve GraphQL APIs: ${message}`, {exit: exitCodes.RUNTIME_ERROR})\n }\n\n const hasMultipleApis = flags.api ? flags.api.length > 1 : apiDefs.length > 1\n\n const usedFlags = [\n datasetFlag && '--dataset',\n tagFlag && '--tag',\n playgroundFlag !== undefined && '--playground',\n generationFlag !== undefined && '--generation',\n nonNullDocumentFieldsFlag !== undefined && '--non-null-document-fields',\n ].filter(Boolean)\n\n if (hasMultipleApis && usedFlags.length > 0) {\n this.warn(`More than one API defined, and ${usedFlags.join('/')} is specified`)\n this.warn(`This will use the specified flag(s) for ALL APIs, overriding config!`)\n\n if (flags.force) {\n this.warn(`--force specified, continuing...`)\n } else if (this.isUnattended()) {\n this.error(\n 'Flag overrides for multiple APIs require confirmation. Pass `--force` to continue.',\n {\n exit: exitCodes.USAGE_ERROR,\n },\n )\n } else {\n const confirmed = await confirm({\n default: false,\n message: 'Continue with flag overrides for all APIs?',\n })\n if (!confirmed) {\n this.log('GraphQL deployment cancelled')\n this.exit(exitCodes.USER_ABORT)\n }\n }\n }\n\n const deployTasks: DeployTask[] = []\n let hasErrors = false\n\n for (const apiId of onlyApis || []) {\n if (!apiDefs.some((apiDef) => apiDef.id === apiId)) {\n this.error(`GraphQL API with id \"${apiId}\" not found`, {exit: exitCodes.RUNTIME_ERROR})\n }\n }\n\n const apiNames = new Set<string>()\n const apiIds = new Set<string>()\n\n for (const apiDef of apiDefs) {\n if (onlyApis && (!apiDef.id || !onlyApis.includes(apiDef.id))) {\n continue\n }\n\n const {apiName} = this.getApiIdentifiers(apiDef, datasetFlag, tagFlag)\n if (apiNames.has(apiName)) {\n this.error(`Multiple GraphQL APIs with the same dataset and tag found (${apiName})`, {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n\n if (apiDef.id) {\n if (!apiIdRegex.test(apiDef.id)) {\n this.error(\n `Invalid GraphQL API id \"${apiDef.id}\" - only a-z, 0-9, underscore and dashes are allowed`,\n {exit: exitCodes.RUNTIME_ERROR},\n )\n }\n\n if (apiIds.has(apiDef.id)) {\n this.error(`Multiple GraphQL APIs with the same ID found (${apiDef.id})`, {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n\n apiIds.add(apiDef.id)\n }\n\n apiNames.add(apiName)\n }\n\n if (onlyApis) {\n this.warn(`Deploying only specified APIs: ${onlyApis.join(', ')}`)\n }\n\n let index = -1\n for (const apiDef of apiDefs) {\n if (onlyApis && (!apiDef.id || !onlyApis.includes(apiDef.id))) {\n continue\n }\n\n index++\n\n const {apiName, dataset, tag} = this.getApiIdentifiers(apiDef, datasetFlag, tagFlag)\n const {playground, projectId} = apiDef\n spin = spinner(`Generating GraphQL API: ${apiName}`).start()\n\n if (!dataset) {\n spin.fail()\n this.error(\n `Dataset is required for API at index ${index}. Pass it with \\`--dataset <name>\\` or configure a dataset for the API.`,\n {exit: exitCodes.USAGE_ERROR},\n )\n }\n\n // Handle extraction errors early (computed in worker), before network calls and prompts.\n // Continue the loop so all API errors are reported — don't exit on the first failure.\n if (apiDef.schemaErrors?.length) {\n spin.fail()\n new SchemaError(apiDef.schemaErrors).print(this.output, `Schema errors in ${apiName}`)\n hasErrors = true\n continue\n }\n\n if (apiDef.extractionError) {\n debug('Failed to extract schema', apiDef.extractionError)\n spin.fail()\n this.log(`Failed to extract schema for ${apiName}: ${apiDef.extractionError}`)\n hasErrors = true\n continue\n }\n\n if (!apiDef.extracted) {\n spin.fail()\n this.log(`Failed to extract schema for ${apiName}: No extraction result`)\n hasErrors = true\n continue\n }\n\n let currentGeneration: string | undefined\n let playgroundEnabled: boolean | undefined\n try {\n const schemaProps = await getCurrentSchemaProps(projectId, dataset, tag)\n currentGeneration = schemaProps.currentGeneration\n playgroundEnabled = schemaProps.playgroundEnabled\n } catch (err) {\n debug('Failed to get current GraphQL schema properties', err)\n spin.fail()\n this.error('Failed to get current GraphQL schema properties', {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n\n // CLI flag takes precedence over configuration\n const specifiedGeneration = generationFlag === undefined ? apiDef.generation : generationFlag\n\n const generation = await resolveApiGeneration({\n currentGeneration,\n force: flags.force,\n index,\n output: this.output,\n specifiedGeneration,\n unattended: this.isUnattended(),\n })\n\n if (!generation) {\n spin.stop()\n this.log('GraphQL deployment cancelled')\n this.exit(exitCodes.USER_ABORT)\n }\n\n if (!this.isRecognizedApiGeneration(generation)) {\n spin.fail()\n this.error(`Unknown API generation \"${generation}\" for API at index ${index}`, {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n\n const enablePlayground = await this.shouldEnablePlayground({\n dryRun,\n playgroundCliFlag: playgroundFlag,\n playgroundConfiguration: playground,\n playgroundCurrentlyEnabled: playgroundEnabled,\n spin,\n })\n\n let apiSpec: GeneratedApiSpecification\n try {\n const generateSchema = generations[generation]\n apiSpec = generateSchema(apiDef.extracted, {filterSuffix: apiDef.filterSuffix})\n } catch (err) {\n debug('Failed to generate schema', err)\n spin.fail()\n const message = err instanceof Error ? err.message : 'Unknown error'\n this.error(`Failed to generate schema: ${message}`, {exit: exitCodes.RUNTIME_ERROR})\n }\n\n let valid: ValidationResponse | undefined\n try {\n valid = await validateGraphQLAPI({\n dataset,\n enablePlayground,\n projectId,\n schema: apiSpec,\n tag,\n })\n } catch (err) {\n debug('validateGraphQLAPI error', err)\n const validationError = get(err, 'response.body.validationError')\n spin.fail()\n this.error(validationError ?? 'Failed to validate GraphQL API', {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n\n // when the result is not valid and there are breaking changes afoot!\n if (!this.isResultValid(valid, {force: flags.force, spin})) {\n // not valid and a dry run? then it can exit with a error\n if (dryRun) {\n spin.fail()\n this.renderBreakingChanges(valid)\n hasErrors = true\n continue\n }\n\n if (this.isUnattended()) {\n spin.fail()\n this.renderBreakingChanges(valid)\n this.error(\n 'GraphQL deployment requires confirmation because the schema contains dangerous changes. Pass `--force` to continue.',\n {exit: exitCodes.USAGE_ERROR},\n )\n }\n\n spin.stop()\n this.renderBreakingChanges(valid)\n const shouldDeploy = await confirm({\n default: false,\n message: 'Do you want to deploy a new API despite the dangerous changes?',\n })\n\n if (!shouldDeploy) {\n this.log('GraphQL deployment cancelled')\n this.exit(exitCodes.USER_ABORT)\n }\n\n spin.succeed()\n } else if (dryRun) {\n // isResultValid() already set the spinner state (succeed or warn).\n // Check whether changes were forced so we print the correct message.\n const {breakingChanges, dangerousChanges} = this.filterChanges(valid)\n if (breakingChanges.length > 0 || dangerousChanges.length > 0) {\n this.renderBreakingChanges(valid)\n this.log('Forced with `--force`, skipping deploy (dry run)')\n } else {\n this.log('GraphQL API is valid and has no breaking changes')\n }\n continue\n }\n\n deployTasks.push({\n dataset,\n enablePlayground,\n projectId,\n schema: apiSpec,\n tag,\n })\n }\n\n // Give some space for deployment tasks\n this.log('')\n\n for (const task of deployTasks) {\n const {dataset, enablePlayground, projectId, schema, tag} = task\n\n this.log(`Project: ${projectId}`)\n this.log(`Dataset: ${dataset}`)\n this.log(`Tag: ${tag}`)\n\n spin = spinner('Deploying GraphQL API').start()\n\n try {\n const response = await deployGraphQLAPI({\n dataset,\n enablePlayground,\n projectId,\n schema,\n tag,\n })\n\n spin.stop()\n const apiUrl = await getClientUrl(\n projectId,\n response.location.replace(/^\\/(v1|v\\d{4}-\\d{2}-\\d{2})\\//, '/'),\n )\n this.log(`URL: ${apiUrl}`)\n spin.start('Deployed!').succeed()\n this.log('')\n } catch (error) {\n spin.fail()\n debug('Failed to deploy GraphQL API', error)\n this.error('Failed to deploy GraphQL API', {exit: exitCodes.RUNTIME_ERROR})\n }\n }\n\n if (hasErrors) {\n this.exit(exitCodes.RUNTIME_ERROR)\n }\n }\n\n private filterChanges(valid: ValidationResponse) {\n const {breakingChanges: breaking, dangerousChanges: dangerous} = valid\n return {\n breakingChanges: breaking.filter((change) => !ignoredBreaking.has(change.type)),\n dangerousChanges: dangerous.filter((change) => !ignoredWarnings.has(change.type)),\n }\n }\n\n private getApiIdentifiers(apiDef: ExtractedGraphQLAPI, datasetFlag?: string, tagFlag?: string) {\n const dataset = datasetFlag || apiDef.dataset\n const tag = tagFlag || apiDef.tag || 'default'\n const apiName = [dataset, tag].join('/')\n return {apiName, dataset, tag}\n }\n\n private isRecognizedApiGeneration(generation: string): generation is 'gen1' | 'gen2' | 'gen3' {\n return ['gen1', 'gen2', 'gen3'].includes(generation)\n }\n\n private isResultValid(\n valid: ValidationResponse,\n {force, spin}: {force?: boolean; spin: ReturnType<typeof spinner>},\n ) {\n const {validationError} = valid\n if (validationError) {\n spin.fail()\n this.error(`GraphQL schema is not valid:\\n\\n${validationError}`, {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n\n const {breakingChanges, dangerousChanges} = this.filterChanges(valid)\n\n const hasProblematicChanges = breakingChanges.length > 0 || dangerousChanges.length > 0\n\n if (!hasProblematicChanges) {\n spin.succeed()\n return true\n }\n\n if (force) {\n spin.text = 'Validating GraphQL API: Dangerous changes. Forced with `--force`.'\n spin.warn()\n return true\n }\n\n spin.warn()\n return false\n }\n\n private renderBreakingChanges(valid: ValidationResponse) {\n const {breakingChanges, dangerousChanges} = this.filterChanges(valid)\n\n if (dangerousChanges.length > 0) {\n this.log('\\nFound potentially dangerous changes from previous schema:')\n for (const change of dangerousChanges) this.log(` - ${change.description}`)\n }\n\n if (breakingChanges.length > 0) {\n this.log('\\nFound BREAKING changes from previous schema:')\n for (const change of breakingChanges) this.log(` - ${change.description}`)\n }\n\n this.output.log('')\n }\n\n private async shouldEnablePlayground({\n dryRun,\n playgroundCliFlag,\n playgroundConfiguration,\n playgroundCurrentlyEnabled,\n spin,\n }: {\n dryRun: boolean\n playgroundCliFlag?: boolean\n playgroundConfiguration?: boolean\n playgroundCurrentlyEnabled?: boolean\n spin: ReturnType<typeof spinner>\n }): Promise<boolean> {\n // On a dry run, it doesn't matter, return true 🤷‍♂️\n if (dryRun) {\n return true\n }\n\n // Prioritize CLI flag if set\n if (playgroundCliFlag !== undefined) {\n return playgroundCliFlag\n }\n\n // If explicitly set true/false in configuration, use that\n if (playgroundConfiguration !== undefined) {\n return playgroundConfiguration\n }\n\n // If API is already deployed, use the current state\n if (playgroundCurrentlyEnabled !== undefined) {\n return playgroundCurrentlyEnabled\n }\n\n // If no API is deployed, default to true if non-interactive\n if (this.isUnattended()) {\n return true\n }\n\n // Interactive environment, so prompt the user\n const prevText = spin.text\n spin.warn()\n const shouldDeploy = await confirm({\n default: true,\n message: 'Do you want to enable a GraphQL playground?',\n })\n spin.clear().start(prevText)\n\n return shouldDeploy\n }\n}\n"],"names":["Flags","exitCodes","SanityCommand","confirm","spinner","get","extractGraphQLAPIs","gen1","gen2","gen3","getSourceDeprecationWarning","graphqlDebug","resolveApiGeneration","SchemaError","deployGraphQLAPI","getClientUrl","getCurrentSchemaProps","validateGraphQLAPI","getDatasetFlag","apiIdRegex","generations","ignoredBreaking","Set","ignoredWarnings","debug","extend","GraphQLDeployCommand","description","examples","command","flags","api","string","multiple","semantics","boolean","default","force","generation","options","playground","allowNo","tag","run","parse","onlyApis","dataset","datasetFlag","dryRun","generationFlag","nonNullDocumentFieldsFlag","playgroundFlag","tagFlag","withUnionCache","workDir","getProjectRoot","directory","apiDefs","spin","sourceDeprecation","getCliConfig","graphql","warn","error","problemGroups","print","output","exit","RUNTIME_ERROR","message","Error","String","hasMultipleApis","length","usedFlags","undefined","filter","Boolean","join","isUnattended","USAGE_ERROR","confirmed","log","USER_ABORT","deployTasks","hasErrors","apiId","some","apiDef","id","apiNames","apiIds","includes","apiName","getApiIdentifiers","has","test","add","index","projectId","start","fail","schemaErrors","extractionError","extracted","currentGeneration","playgroundEnabled","schemaProps","err","specifiedGeneration","unattended","stop","isRecognizedApiGeneration","enablePlayground","shouldEnablePlayground","playgroundCliFlag","playgroundConfiguration","playgroundCurrentlyEnabled","apiSpec","generateSchema","filterSuffix","valid","schema","validationError","isResultValid","renderBreakingChanges","shouldDeploy","succeed","breakingChanges","dangerousChanges","filterChanges","push","task","response","apiUrl","location","replace","breaking","dangerous","change","type","hasProblematicChanges","text","prevText","clear"],"mappings":"AAAA,SAAQA,KAAK,QAAO,cAAa;AACjC,SAAQC,SAAS,EAAEC,aAAa,QAAO,mBAAkB;AACzD,SAAQC,OAAO,EAAEC,OAAO,QAAO,sBAAqB;AACpD,OAAOC,SAAS,mBAAkB;AAElC,SAAQC,kBAAkB,QAAO,8CAA6C;AAC9E,OAAOC,UAAU,sCAAqC;AACtD,OAAOC,UAAU,sCAAqC;AACtD,OAAOC,UAAU,sCAAqC;AACtD,SAAQC,2BAA2B,QAAO,uDAAsD;AAChG,SAAQC,YAAY,QAAO,wCAAuC;AAClE,SAAQC,oBAAoB,QAAO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C,GAAG,EAAEyD,OAAOhH,WAAW,EAAE;QAC5E;QAEA,IAAIqG,gBAAgBvD,MAAM,GAAG,GAAG;YAC9B,IAAI,CAACS,GAAG,CAAC;YACT,KAAK,MAAMyD,UAAUX,gBAAiB,IAAI,CAAC9C,GAAG,CAAC,CAAC,GAAG,EAAEyD,OAAOhH,WAAW,EAAE;QAC3E;QAEA,IAAI,CAACuC,MAAM,CAACgB,GAAG,CAAC;IAClB;IAEA,MAAcgC,uBAAuB,EACnClE,MAAM,EACNmE,iBAAiB,EACjBC,uBAAuB,EACvBC,0BAA0B,EAC1B3D,IAAI,EAOL,EAAoB;QACnB,qDAAqD;QACrD,IAAIV,QAAQ;YACV,OAAO;QACT;QAEA,6BAA6B;QAC7B,IAAImE,sBAAsBxC,WAAW;YACnC,OAAOwC;QACT;QAEA,0DAA0D;QAC1D,IAAIC,4BAA4BzC,WAAW;YACzC,OAAOyC;QACT;QAEA,oDAAoD;QACpD,IAAIC,+BAA+B1C,WAAW;YAC5C,OAAO0C;QACT;QAEA,4DAA4D;QAC5D,IAAI,IAAI,CAACtC,YAAY,IAAI;YACvB,OAAO;QACT;QAEA,8CAA8C;QAC9C,MAAMgE,WAAWrF,KAAKoF,IAAI;QAC1BpF,KAAKI,IAAI;QACT,MAAMgE,eAAe,MAAM3H,QAAQ;YACjCiC,SAAS;YACTiC,SAAS;QACX;QACAX,KAAKsF,KAAK,GAAG5C,KAAK,CAAC2C;QAEnB,OAAOjB;IACT;AACF"}
@@ -3,6 +3,7 @@ import { exitCodes, SanityCommand, subdebug } from '@sanity/cli-core';
3
3
  import { requiredWhenUnattended } from '@sanity/cli-core/flags';
4
4
  import { confirm } from '@sanity/cli-core/ux';
5
5
  import { getGraphQLAPIs } from '../../actions/graphql/getGraphQLAPIs.js';
6
+ import { getSourceDeprecationWarning } from '../../actions/graphql/getSourceDeprecationWarning.js';
6
7
  import { promptForProject } from '../../prompts/promptForProject.js';
7
8
  import { deleteGraphQLAPI } from '../../services/graphql.js';
8
9
  import { getDatasetFlag, getProjectIdFlag } from '../../util/sharedFlags.js';
@@ -69,6 +70,10 @@ export class Undeploy extends SanityCommand {
69
70
  // If specifying --api, use it for the flags not provided
70
71
  if (apiFlag) {
71
72
  const workDir = (await this.getProjectRoot()).directory;
73
+ const sourceDeprecation = getSourceDeprecationWarning((await this.getCliConfig()).graphql);
74
+ if (sourceDeprecation) {
75
+ this.warn(sourceDeprecation);
76
+ }
72
77
  const apiDefs = await getGraphQLAPIs(workDir);
73
78
  const apiDef = apiDefs.find((def)=>def.id === apiFlag);
74
79
  if (!apiDef) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/commands/graphql/undeploy.ts"],"sourcesContent":["import {Flags} from '@oclif/core'\nimport {exitCodes, SanityCommand, subdebug} from '@sanity/cli-core'\nimport {requiredWhenUnattended} from '@sanity/cli-core/flags'\nimport {confirm} from '@sanity/cli-core/ux'\n\nimport {getGraphQLAPIs} from '../../actions/graphql/getGraphQLAPIs.js'\nimport {promptForProject} from '../../prompts/promptForProject.js'\nimport {deleteGraphQLAPI} from '../../services/graphql.js'\nimport {getDatasetFlag, getProjectIdFlag} from '../../util/sharedFlags.js'\n\nconst undeployGraphqlDebug = subdebug('graphql:undeploy')\n\nexport class Undeploy extends SanityCommand<typeof Undeploy> {\n static override description = 'Remove a deployed GraphQL API'\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %>',\n description: 'Undeploy GraphQL API for current project and dataset',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --api ios',\n description: 'Undeploy API with ID \"ios\"',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --dataset staging',\n description: 'Undeploy GraphQL API for staging dataset',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --dataset staging --tag next',\n description: 'Undeploy GraphQL API for staging dataset with \"next\" tag',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --force',\n description: 'Undeploy GraphQL API without confirmation prompt',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --project abc123 --dataset production',\n description: 'Undeploy GraphQL API for a specific project and dataset',\n },\n ]\n\n static override flags = {\n ...getProjectIdFlag({\n description: 'Project ID to undeploy GraphQL API from',\n semantics: 'override',\n }),\n api: Flags.string({\n description: 'Undeploy API with this ID',\n exclusive: ['project'],\n required: false,\n }),\n ...getDatasetFlag({description: 'Dataset to undeploy GraphQL API from', semantics: 'override'}),\n force: requiredWhenUnattended(\n Flags.boolean({\n description: 'Skip confirmation prompt',\n }),\n ),\n tag: Flags.string({\n default: 'default',\n description: 'Tag to undeploy GraphQL API from',\n required: false,\n }),\n }\n\n public async run(): Promise<void> {\n const {flags} = await this.parse(Undeploy)\n const {api: apiFlag, dataset: datasetFlag, force, tag: tagFlag} = flags\n\n let projectId: string | undefined\n let dataset = datasetFlag\n let tag = tagFlag\n\n // If specifying --api, use it for the flags not provided\n if (apiFlag) {\n const workDir = (await this.getProjectRoot()).directory\n const apiDefs = await getGraphQLAPIs(workDir)\n const apiDef = apiDefs.find((def) => def.id === apiFlag)\n\n if (!apiDef) {\n this.error(`GraphQL API \"${apiFlag}\" not found`, {exit: exitCodes.RUNTIME_ERROR})\n }\n\n projectId = apiDef.projectId\n\n if (dataset && dataset !== apiDef.dataset) {\n this.warn(`Both --api and --dataset specified, using --dataset ${dataset}`)\n } else {\n dataset = apiDef.dataset\n }\n\n if (tag && tag !== 'default' && apiDef.tag && tag !== apiDef.tag) {\n this.warn(`Both --api and --tag specified, using --tag ${tag}`)\n } else {\n tag = apiDef.tag || 'default'\n }\n }\n\n // Get projectId from config if not specified\n if (!projectId) {\n projectId = await this.getProjectId({\n fallback: () =>\n promptForProject({\n requiredPermissions: [{grant: 'manage', permission: 'sanity.project.graphql'}],\n }),\n })\n }\n\n // Get dataset from CLI config if not specified\n if (!dataset) {\n const cliConfig = await this.tryGetCliConfig()\n dataset = cliConfig.api?.dataset\n }\n\n if (!dataset) {\n this.error(\n 'Dataset is required. Pass it with `--dataset <name>` or configure it in your project.',\n {\n exit: exitCodes.USAGE_ERROR,\n },\n )\n }\n\n // Confirm deletion unless --force is used\n if (!force) {\n const confirmMessage =\n tag === 'default'\n ? `Delete the GraphQL API for dataset \"${dataset}\" in project ${projectId}?`\n : `Delete the GraphQL API for dataset \"${dataset}\" in project ${projectId} with tag \"${tag}\"?`\n\n const confirmed = await confirm({\n default: false,\n message: confirmMessage,\n })\n\n if (!confirmed) {\n this.log('GraphQL API undeploy cancelled')\n this.exit(exitCodes.USER_ABORT)\n }\n }\n\n try {\n await deleteGraphQLAPI({\n dataset,\n projectId,\n tag,\n })\n\n this.log('GraphQL API deleted')\n } catch (error) {\n const err = error instanceof Error ? error : new Error(`${error}`)\n undeployGraphqlDebug(`Error deleting GraphQL API for ${dataset}/${tag}`, err)\n this.error(`GraphQL API deletion failed:\\n${err.message}`, {exit: exitCodes.RUNTIME_ERROR})\n }\n }\n}\n"],"names":["Flags","exitCodes","SanityCommand","subdebug","requiredWhenUnattended","confirm","getGraphQLAPIs","promptForProject","deleteGraphQLAPI","getDatasetFlag","getProjectIdFlag","undeployGraphqlDebug","Undeploy","description","examples","command","flags","semantics","api","string","exclusive","required","force","boolean","tag","default","run","parse","apiFlag","dataset","datasetFlag","tagFlag","projectId","workDir","getProjectRoot","directory","apiDefs","apiDef","find","def","id","error","exit","RUNTIME_ERROR","warn","getProjectId","fallback","requiredPermissions","grant","permission","cliConfig","tryGetCliConfig","USAGE_ERROR","confirmMessage","confirmed","message","log","USER_ABORT","err","Error"],"mappings":"AAAA,SAAQA,KAAK,QAAO,cAAa;AACjC,SAAQC,SAAS,EAAEC,aAAa,EAAEC,QAAQ,QAAO,mBAAkB;AACnE,SAAQC,sBAAsB,QAAO,yBAAwB;AAC7D,SAAQC,OAAO,QAAO,sBAAqB;AAE3C,SAAQC,cAAc,QAAO,0CAAyC;AACtE,SAAQC,gBAAgB,QAAO,oCAAmC;AAClE,SAAQC,gBAAgB,QAAO,4BAA2B;AAC1D,SAAQC,cAAc,EAAEC,gBAAgB,QAAO,4BAA2B;AA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AG,CAAC;gBACT,IAAI,CAACd,IAAI,CAACzC,UAAUwD,UAAU;YAChC;QACF;QAEA,IAAI;YACF,MAAMjD,iBAAiB;gBACrBqB;gBACAG;gBACAR;YACF;YAEA,IAAI,CAACgC,GAAG,CAAC;QACX,EAAE,OAAOf,OAAO;YACd,MAAMiB,MAAMjB,iBAAiBkB,QAAQlB,QAAQ,IAAIkB,MAAM,GAAGlB,OAAO;YACjE9B,qBAAqB,CAAC,+BAA+B,EAAEkB,QAAQ,CAAC,EAAEL,KAAK,EAAEkC;YACzE,IAAI,CAACjB,KAAK,CAAC,CAAC,8BAA8B,EAAEiB,IAAIH,OAAO,EAAE,EAAE;gBAACb,MAAMzC,UAAU0C,aAAa;YAAA;QAC3F;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/commands/graphql/undeploy.ts"],"sourcesContent":["import {Flags} from '@oclif/core'\nimport {exitCodes, SanityCommand, subdebug} from '@sanity/cli-core'\nimport {requiredWhenUnattended} from '@sanity/cli-core/flags'\nimport {confirm} from '@sanity/cli-core/ux'\n\nimport {getGraphQLAPIs} from '../../actions/graphql/getGraphQLAPIs.js'\nimport {getSourceDeprecationWarning} from '../../actions/graphql/getSourceDeprecationWarning.js'\nimport {promptForProject} from '../../prompts/promptForProject.js'\nimport {deleteGraphQLAPI} from '../../services/graphql.js'\nimport {getDatasetFlag, getProjectIdFlag} from '../../util/sharedFlags.js'\n\nconst undeployGraphqlDebug = subdebug('graphql:undeploy')\n\nexport class Undeploy extends SanityCommand<typeof Undeploy> {\n static override description = 'Remove a deployed GraphQL API'\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %>',\n description: 'Undeploy GraphQL API for current project and dataset',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --api ios',\n description: 'Undeploy API with ID \"ios\"',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --dataset staging',\n description: 'Undeploy GraphQL API for staging dataset',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --dataset staging --tag next',\n description: 'Undeploy GraphQL API for staging dataset with \"next\" tag',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --force',\n description: 'Undeploy GraphQL API without confirmation prompt',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --project abc123 --dataset production',\n description: 'Undeploy GraphQL API for a specific project and dataset',\n },\n ]\n\n static override flags = {\n ...getProjectIdFlag({\n description: 'Project ID to undeploy GraphQL API from',\n semantics: 'override',\n }),\n api: Flags.string({\n description: 'Undeploy API with this ID',\n exclusive: ['project'],\n required: false,\n }),\n ...getDatasetFlag({description: 'Dataset to undeploy GraphQL API from', semantics: 'override'}),\n force: requiredWhenUnattended(\n Flags.boolean({\n description: 'Skip confirmation prompt',\n }),\n ),\n tag: Flags.string({\n default: 'default',\n description: 'Tag to undeploy GraphQL API from',\n required: false,\n }),\n }\n\n public async run(): Promise<void> {\n const {flags} = await this.parse(Undeploy)\n const {api: apiFlag, dataset: datasetFlag, force, tag: tagFlag} = flags\n\n let projectId: string | undefined\n let dataset = datasetFlag\n let tag = tagFlag\n\n // If specifying --api, use it for the flags not provided\n if (apiFlag) {\n const workDir = (await this.getProjectRoot()).directory\n const sourceDeprecation = getSourceDeprecationWarning((await this.getCliConfig()).graphql)\n if (sourceDeprecation) {\n this.warn(sourceDeprecation)\n }\n\n const apiDefs = await getGraphQLAPIs(workDir)\n const apiDef = apiDefs.find((def) => def.id === apiFlag)\n\n if (!apiDef) {\n this.error(`GraphQL API \"${apiFlag}\" not found`, {exit: exitCodes.RUNTIME_ERROR})\n }\n\n projectId = apiDef.projectId\n\n if (dataset && dataset !== apiDef.dataset) {\n this.warn(`Both --api and --dataset specified, using --dataset ${dataset}`)\n } else {\n dataset = apiDef.dataset\n }\n\n if (tag && tag !== 'default' && apiDef.tag && tag !== apiDef.tag) {\n this.warn(`Both --api and --tag specified, using --tag ${tag}`)\n } else {\n tag = apiDef.tag || 'default'\n }\n }\n\n // Get projectId from config if not specified\n if (!projectId) {\n projectId = await this.getProjectId({\n fallback: () =>\n promptForProject({\n requiredPermissions: [{grant: 'manage', permission: 'sanity.project.graphql'}],\n }),\n })\n }\n\n // Get dataset from CLI config if not specified\n if (!dataset) {\n const cliConfig = await this.tryGetCliConfig()\n dataset = cliConfig.api?.dataset\n }\n\n if (!dataset) {\n this.error(\n 'Dataset is required. Pass it with `--dataset <name>` or configure it in your project.',\n {\n exit: exitCodes.USAGE_ERROR,\n },\n )\n }\n\n // Confirm deletion unless --force is used\n if (!force) {\n const confirmMessage =\n tag === 'default'\n ? `Delete the GraphQL API for dataset \"${dataset}\" in project ${projectId}?`\n : `Delete the GraphQL API for dataset \"${dataset}\" in project ${projectId} with tag \"${tag}\"?`\n\n const confirmed = await confirm({\n default: false,\n message: confirmMessage,\n })\n\n if (!confirmed) {\n this.log('GraphQL API undeploy cancelled')\n this.exit(exitCodes.USER_ABORT)\n }\n }\n\n try {\n await deleteGraphQLAPI({\n dataset,\n projectId,\n tag,\n })\n\n this.log('GraphQL API deleted')\n } catch (error) {\n const err = error instanceof Error ? error : new Error(`${error}`)\n undeployGraphqlDebug(`Error deleting GraphQL API for ${dataset}/${tag}`, err)\n this.error(`GraphQL API deletion failed:\\n${err.message}`, {exit: exitCodes.RUNTIME_ERROR})\n }\n }\n}\n"],"names":["Flags","exitCodes","SanityCommand","subdebug","requiredWhenUnattended","confirm","getGraphQLAPIs","getSourceDeprecationWarning","promptForProject","deleteGraphQLAPI","getDatasetFlag","getProjectIdFlag","undeployGraphqlDebug","Undeploy","description","examples","command","flags","semantics","api","string","exclusive","required","force","boolean","tag","default","run","parse","apiFlag","dataset","datasetFlag","tagFlag","projectId","workDir","getProjectRoot","directory","sourceDeprecation","getCliConfig","graphql","warn","apiDefs","apiDef","find","def","id","error","exit","RUNTIME_ERROR","getProjectId","fallback","requiredPermissions","grant","permission","cliConfig","tryGetCliConfig","USAGE_ERROR","confirmMessage","confirmed","message","log","USER_ABORT","err","Error"],"mappings":"AAAA,SAAQA,KAAK,QAAO,cAAa;AACjC,SAAQC,SAAS,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nC,GAAG,EAAEW;QAC3B;QAEA,IAAI,CAACA,SAAS;YACZ,IAAI,CAACgB,KAAK,CACR,yFACA;gBACEC,MAAM9C,UAAUuD,WAAW;YAC7B;QAEJ;QAEA,0CAA0C;QAC1C,IAAI,CAACjC,OAAO;YACV,MAAMkC,iBACJhC,QAAQ,YACJ,CAAC,oCAAoC,EAAEK,QAAQ,aAAa,EAAEG,UAAU,CAAC,CAAC,GAC1E,CAAC,oCAAoC,EAAEH,QAAQ,aAAa,EAAEG,UAAU,WAAW,EAAER,IAAI,EAAE,CAAC;YAElG,MAAMiC,YAAY,MAAMrD,QAAQ;gBAC9BqB,SAAS;gBACTiC,SAASF;YACX;YAEA,IAAI,CAACC,WAAW;gBACd,IAAI,CAACE,GAAG,CAAC;gBACT,IAAI,CAACb,IAAI,CAAC9C,UAAU4D,UAAU;YAChC;QACF;QAEA,IAAI;YACF,MAAMpD,iBAAiB;gBACrBqB;gBACAG;gBACAR;YACF;YAEA,IAAI,CAACmC,GAAG,CAAC;QACX,EAAE,OAAOd,OAAO;YACd,MAAMgB,MAAMhB,iBAAiBiB,QAAQjB,QAAQ,IAAIiB,MAAM,GAAGjB,OAAO;YACjElC,qBAAqB,CAAC,+BAA+B,EAAEkB,QAAQ,CAAC,EAAEL,KAAK,EAAEqC;YACzE,IAAI,CAAChB,KAAK,CAAC,CAAC,8BAA8B,EAAEgB,IAAIH,OAAO,EAAE,EAAE;gBAACZ,MAAM9C,UAAU+C,aAAa;YAAA;QAC3F;IACF;AACF"}
@@ -27,7 +27,7 @@ export class LoginCommand extends SanityCommand {
27
27
  description: 'Log in using a specific SSO provider within an organization'
28
28
  }
29
29
  ];
30
- static flags = {
30
+ /* eslint-disable perfectionist/sort-objects -- Keep token login first in generated usage. */ static flags = {
31
31
  'with-token': Flags.boolean({
32
32
  description: 'Read token from standard input',
33
33
  exclusive: [
@@ -35,7 +35,6 @@ export class LoginCommand extends SanityCommand {
35
35
  'sso'
36
36
  ]
37
37
  }),
38
- // eslint-disable-next-line perfectionist/sort-objects -- Keep token login first in generated usage.
39
38
  experimental: Flags.boolean({
40
39
  default: false,
41
40
  hidden: true
@@ -69,7 +68,7 @@ export class LoginCommand extends SanityCommand {
69
68
  helpValue: '<name>'
70
69
  })
71
70
  };
72
- async run() {
71
+ /* eslint-enable perfectionist/sort-objects */ async run() {
73
72
  const { flags } = await this.parse(LoginCommand);
74
73
  const { 'sso-provider': ssoProvider, 'with-token': withToken, ...loginFlags } = flags;
75
74
  try {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/commands/login.ts"],"sourcesContent":["import {Command, Flags} from '@oclif/core'\nimport {type FlagInput} from '@oclif/core/interfaces'\nimport {exitCodes, SanityCommand} from '@sanity/cli-core'\n\nimport {login} from '../actions/auth/login/login.js'\nimport {LOGIN_PROVIDER_IDS} from '../actions/auth/login/loginInstructions.js'\nimport {readTokenFromStdin} from '../util/readTokenFromStdin.js'\n\nexport class LoginCommand extends SanityCommand<typeof LoginCommand> {\n static override description = 'Log in to your Sanity account'\n static override examples: Array<Command.Example> = [\n {\n command: '<%= config.bin %> <%= command.id %>',\n description: 'Log in using default settings',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --with-token < token.txt',\n description: 'Log in using a token from standard input',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --provider github --no-open',\n description: 'Login with GitHub provider, but do not open a browser window automatically',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --sso my-organization',\n description: 'Log in using Single Sign-On with the \"my-organization\" slug',\n },\n {\n command:\n '<%= config.bin %> <%= command.id %> --sso my-organization --sso-provider \"Okta SSO\"',\n description: 'Log in using a specific SSO provider within an organization',\n },\n ]\n static override flags = {\n 'with-token': Flags.boolean({\n description: 'Read token from standard input',\n exclusive: ['provider', 'sso'],\n }),\n // eslint-disable-next-line perfectionist/sort-objects -- Keep token login first in generated usage.\n experimental: Flags.boolean({\n default: false,\n hidden: true,\n }),\n open: Flags.boolean({\n allowNo: true,\n default: true,\n description: 'Open a browser window to log in (`--no-open` only prints URL)',\n }),\n provider: Flags.string({\n description: `Log in using a provider ID (${LOGIN_PROVIDER_IDS.join(', ')})`,\n exclusive: ['sso', 'with-token'],\n helpValue: '<providerId>',\n }),\n sso: Flags.string({\n description: 'Log in using Single Sign-On, using the given organization slug',\n exclusive: ['provider', 'with-token'],\n helpValue: '<slug>',\n }),\n 'sso-provider': Flags.string({\n dependsOn: ['sso'],\n description: 'Select a specific SSO provider by name (use with --sso)',\n helpValue: '<name>',\n }),\n } satisfies FlagInput\n\n public async run(): Promise<void> {\n const {flags} = await this.parse(LoginCommand)\n const {'sso-provider': ssoProvider, 'with-token': withToken, ...loginFlags} = flags\n\n try {\n const token = withToken\n ? await readTokenFromStdin(\n 'Token is required on standard input. Run `sanity login --with-token < token.txt`.',\n )\n : undefined\n\n await login({\n ...loginFlags,\n output: this.output,\n ssoProvider,\n telemetry: this.telemetry,\n token,\n })\n this.log('Login successful')\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n this.error(`Login failed: ${message}`, {exit: exitCodes.RUNTIME_ERROR})\n }\n }\n}\n"],"names":["Flags","exitCodes","SanityCommand","login","LOGIN_PROVIDER_IDS","readTokenFromStdin","LoginCommand","description","examples","command","flags","boolean","exclusive","experimental","default","hidden","open","allowNo","provider","string","join","helpValue","sso","dependsOn","run","parse","ssoProvider","withToken","loginFlags","token","undefined","output","telemetry","log","error","message","Error","String","exit","RUNTIME_ERROR"],"mappings":"AAAA,SAAiBA,KAAK,QAAO,cAAa;AAE1C,SAAQC,SAAS,EAAEC,aAAa,QAAO,mBAAkB;AAEzD,SAAQC,KAAK,QAAO,iCAAgC;AACpD,SAAQC,kBAAkB,QAAO,6CAA4C;AAC7E,SAAQC,kBAAkB,QAAO,gCAA+B;AAEhE,OAAO,MAAMC,qBAAqBJ;IAChC,OAAgBK,cAAc,gCAA+B;IAC7D,OAAgBC,WAAmC;QACjD;YACEC,SAAS;YACTF,aAAa;QACf;QACA;YACEE,SAAS;YACTF,aAAa;Q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IAAI,CAACA,KAAK,CAAC,CAAC,cAAc,EAAEC,SAAS,EAAE;gBAACG,MAAMrC,UAAUsC,aAAa;YAAA;QACvE;IACF;AACF"}
1
+ {"version":3,"sources":["../../src/commands/login.ts"],"sourcesContent":["import {Command, Flags} from '@oclif/core'\nimport {type FlagInput} from '@oclif/core/interfaces'\nimport {exitCodes, SanityCommand} from '@sanity/cli-core'\n\nimport {login} from '../actions/auth/login/login.js'\nimport {LOGIN_PROVIDER_IDS} from '../actions/auth/login/loginInstructions.js'\nimport {readTokenFromStdin} from '../util/readTokenFromStdin.js'\n\nexport class LoginCommand extends SanityCommand<typeof LoginCommand> {\n static override description = 'Log in to your Sanity account'\n static override examples: Array<Command.Example> = [\n {\n command: '<%= config.bin %> <%= command.id %>',\n description: 'Log in using default settings',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --with-token < token.txt',\n description: 'Log in using a token from standard input',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --provider github --no-open',\n description: 'Login with GitHub provider, but do not open a browser window automatically',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --sso my-organization',\n description: 'Log in using Single Sign-On with the \"my-organization\" slug',\n },\n {\n command:\n '<%= config.bin %> <%= command.id %> --sso my-organization --sso-provider \"Okta SSO\"',\n description: 'Log in using a specific SSO provider within an organization',\n },\n ]\n /* eslint-disable perfectionist/sort-objects -- Keep token login first in generated usage. */\n static override flags = {\n 'with-token': Flags.boolean({\n description: 'Read token from standard input',\n exclusive: ['provider', 'sso'],\n }),\n experimental: Flags.boolean({\n default: false,\n hidden: true,\n }),\n open: Flags.boolean({\n allowNo: true,\n default: true,\n description: 'Open a browser window to log in (`--no-open` only prints URL)',\n }),\n provider: Flags.string({\n description: `Log in using a provider ID (${LOGIN_PROVIDER_IDS.join(', ')})`,\n exclusive: ['sso', 'with-token'],\n helpValue: '<providerId>',\n }),\n sso: Flags.string({\n description: 'Log in using Single Sign-On, using the given organization slug',\n exclusive: ['provider', 'with-token'],\n helpValue: '<slug>',\n }),\n 'sso-provider': Flags.string({\n dependsOn: ['sso'],\n description: 'Select a specific SSO provider by name (use with --sso)',\n helpValue: '<name>',\n }),\n } satisfies FlagInput\n /* eslint-enable perfectionist/sort-objects */\n\n public async run(): Promise<void> {\n const {flags} = await this.parse(LoginCommand)\n const {'sso-provider': ssoProvider, 'with-token': withToken, ...loginFlags} = flags\n\n try {\n const token = withToken\n ? await readTokenFromStdin(\n 'Token is required on standard input. Run `sanity login --with-token < token.txt`.',\n )\n : undefined\n\n await login({\n ...loginFlags,\n output: this.output,\n ssoProvider,\n telemetry: this.telemetry,\n token,\n })\n this.log('Login successful')\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n this.error(`Login failed: ${message}`, {exit: exitCodes.RUNTIME_ERROR})\n }\n }\n}\n"],"names":["Flags","exitCodes","SanityCommand","login","LOGIN_PROVIDER_IDS","readTokenFromStdin","LoginCommand","description","examples","command","flags","boolean","exclusive","experimental","default","hidden","open","allowNo","provider","string","join","helpValue","sso","dependsOn","run","parse","ssoProvider","withToken","loginFlags","token","undefined","output","telemetry","log","error","message","Error","String","exit","RUNTIME_ERROR"],"mappings":"AAAA,SAAiBA,KAAK,QAAO,cAAa;AAE1C,SAAQC,SAAS,EAAEC,aAAa,QAAO,mBAAkB;AAEzD,SAAQC,KAAK,QAAO,iCAAgC;AACpD,SAAQC,kBAAkB,QAAO,6CAA4C;AAC7E,SAAQC,kBAAkB,QAAO,gCAA+B;AAEhE,OAAO,MAAMC,qBAAqBJ;IAChC,OAAgBK,cAAc,gCAA+B;IAC7D,OAAgBC,WAAmC;QACjD;YACEC,SAAS;YACTF,aAAa;QACf;QACA;YACEE,SAAS;YACTF,aAAa;QACf;QACA;YACEE,SAAS;YACTF,aAAa;QACf;QACA;YACEE,SAAS;YACTF,aAAa;QACf;QACA;YACEE,SACE;YACFF,aAAa;QACf;KACD,CAAA;IACD,2FAA2F,GAC3F,OAAgBG,QAAQ;QACtB,cAAcV,MAAMW,OAAO,CAAC;YA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if/core';
3
3
  import { CLIError } from '@oclif/core/errors';
4
4
  import { exitCodes } from '@sanity/cli-core';
5
+ import { getCliUserConfigPath } from '@sanity/cli-core/config';
5
6
  import { SanityCommand } from '@sanity/cli-core/SanityCommand';
6
7
  import { createFlow, input } from '@sanity/cli-core/ux';
7
8
  import { FRONTEND_DIR, FRONTEND_ENV_FILE, getUnavailableScaffoldTarget, scaffoldProject, STUDIO_DIR, STUDIO_ENV_FILE } from '../actions/scaffold/scaffoldProject.js';
@@ -75,8 +76,7 @@ function toResult(project) {
75
76
  terms: {
76
77
  notice: project.termsNotice,
77
78
  url: project.termsUrl
78
- },
79
- token: project.token
79
+ }
80
80
  };
81
81
  }
82
82
  export class NewCommand extends SanityCommand {
@@ -195,35 +195,40 @@ export class NewCommand extends SanityCommand {
195
195
  spin?.fail('Creating your project failed.');
196
196
  throw err;
197
197
  }
198
- const recorded = recordUnclaimedProject(project);
198
+ if (!recordUnclaimedProject(project)) {
199
+ const recoveryFile = getCliUserConfigPath();
200
+ spin?.fail('The project was created, but its credentials could not be saved.');
201
+ throw new CLIError(`Could not save credentials for project ${project.resourceId}. Make sure the CLI can write to ${recoveryFile}.`, {
202
+ code: 'UNCLAIMED_PROJECT_SAVE_FAILED',
203
+ exit: exitCodes.RUNTIME_ERROR
204
+ });
205
+ }
199
206
  spin?.succeed(`Created "${displayName}"`);
200
207
  if (!json) {
201
208
  flow.result(`Project ID: ${styleText('cyan', project.resourceId)}`);
202
209
  flow.result(`Dataset: ${styleText('cyan', project.datasetName)} (where your content lives)`);
203
- flow.result(`Token: ${styleText('cyan', project.token)}`);
204
210
  flow.link(project.claimUrl, {
205
211
  label: 'Claim link:'
206
212
  });
207
213
  flow.gap();
208
214
  flow.highlight(`Claim your project by ${styleText('yellow', formatClaimDeadline(project.expiresAt))} to avoid losing it.`);
209
215
  flow.gap();
210
- flow.line('To use the Sanity CLI before claiming use your token by setting');
211
- flow.command(`SANITY_AUTH_TOKEN="${project.token}" sanity "command"`);
212
- flow.gap();
213
- flow.note(styleText('dim', 'If you are an agent: give this claim URL to the person you are working for. They have ' + 'to open it themselves before the deadline.'));
216
+ flow.note('If you are setting this up for someone else, give them the claim link before the deadline.');
214
217
  flow.gap();
215
218
  }
216
- const studioUrl = `http://localhost:3333/#token=${encodeURIComponent(project.token)}` + `&claim=${encodeURIComponent(project.claimUrl)}`;
219
+ const printStudioSignIn = (tokenSource)=>{
220
+ flow.line('To sign in before claiming, use this URL template:');
221
+ flow.line(`http://localhost:3333/#token=$token&claim=${encodeURIComponent(project.claimUrl)}`);
222
+ flow.line(`Get the token from ${tokenSource}.`);
223
+ flow.line('URL-encode the token and replace $token in the template.');
224
+ };
217
225
  const printStudioInstructions = ()=>{
218
226
  flow.highlight('Start your Studio:');
219
227
  flow.gap();
220
228
  flow.command(`cd ${STUDIO_DIR} && npx sanity@latest dev`);
221
229
  flow.gap();
222
- flow.link(studioUrl, {
223
- label: 'Then open this link:'
224
- });
225
- flow.gap();
226
- flow.line('The token signs you in: there is no account yet.');
230
+ printStudioSignIn(`SANITY_AUTH_TOKEN in ./${STUDIO_ENV_FILE}`);
231
+ flow.line(`Run CLI commands from ./${STUDIO_DIR} to use the saved token.`);
227
232
  };
228
233
  const printWebsiteInstructions = (packageManager)=>{
229
234
  flow.highlight('In a separate terminal, start your website:');
@@ -257,8 +262,8 @@ export class NewCommand extends SanityCommand {
257
262
  }
258
263
  // Scaffolding is best-effort and may leave files or directories behind when it fails.
259
264
  // Partial filesystem state does not prove the scaffold is runnable, so report the failure,
260
- // continue only with the project/token/claim handoff below, and do not attempt cleanup.
261
- flow.note(`Automatic setup did not finish: ${err instanceof Error ? err.message : err}`);
265
+ // continue with the project and claim details below, and do not attempt cleanup.
266
+ flow.note(`Automatic setup did not finish: ${String(err instanceof Error ? err.message : err).replaceAll(project.claimUrl, '[redacted]').replaceAll(project.claimToken, '[redacted]').replaceAll(project.token, '[redacted]')}`);
262
267
  flow.line('The project was created. You do not need to create another one.');
263
268
  flow.gap();
264
269
  } finally{
@@ -299,27 +304,21 @@ export class NewCommand extends SanityCommand {
299
304
  }
300
305
  flow.gap();
301
306
  }
302
- if (recorded === false && !json) {
303
- flow.note('The local recovery record was not saved.');
304
- flow.line('Keep the claim URL and access token from this output.');
305
- flow.gap();
306
- }
307
307
  if (!json) {
308
308
  if (!scaffold && !this.flags.scaffold) {
309
309
  flow.result('Project created without scaffolding');
310
310
  flow.line('No folders or env files were created. Use the project ID and dataset above in your own setup.');
311
311
  flow.gap();
312
- flow.link(studioUrl, {
313
- label: 'Once a Studio is running on http://localhost:3333, sign in with:'
314
- });
312
+ }
313
+ if (!scaffold) {
314
+ flow.line('Find your saved token:');
315
+ flow.command(`npx sanity@latest projects unclaimed --project ${project.resourceId}`);
316
+ flow.gap();
317
+ printStudioSignIn('the recovery file shown by the command above');
315
318
  flow.gap();
316
- flow.line('The token signs you in: there is no account yet.');
319
+ flow.line('For CLI commands, set SANITY_AUTH_TOKEN to the saved token.');
317
320
  flow.gap();
318
321
  }
319
- flow.line("Treat your token as a password and don't expose it publicly in your app.");
320
- flow.gap();
321
- flow.line('The claim link and token are printed above but you can recover them ' + `with ${styleText('cyan', 'sanity projects unclaimed')} before the timer runs out on ${formatClaimDeadline(project.expiresAt)}.`);
322
- flow.gap();
323
322
  flow.line(project.termsNotice);
324
323
  flow.link(project.termsUrl, {
325
324
  label: 'Terms of Service:'