@sanity/cli 8.31.0 → 8.32.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 (49) hide show
  1. package/README.md +179 -103
  2. package/bin/run.js +1 -1
  3. package/dist/actions/context/waitForSourceSync.js +1 -1
  4. package/dist/actions/context/waitForSourceSync.js.map +1 -1
  5. package/dist/actions/cors/filterAndValidateOrigin.js +1 -1
  6. package/dist/actions/cors/filterAndValidateOrigin.js.map +1 -1
  7. package/dist/actions/deploy/deployStudioSchemasAndManifestsWorker.js +13 -1
  8. package/dist/actions/deploy/deployStudioSchemasAndManifestsWorker.js.map +1 -1
  9. package/dist/actions/documents/validateDocuments.worker.js +2 -1
  10. package/dist/actions/documents/validateDocuments.worker.js.map +1 -1
  11. package/dist/actions/graphql/extractFromSanitySchema.js +1 -1
  12. package/dist/actions/graphql/extractFromSanitySchema.js.map +1 -1
  13. package/dist/actions/init/initStudio.js +1 -1
  14. package/dist/actions/init/initStudio.js.map +1 -1
  15. package/dist/actions/init/processTemplate.js +1 -1
  16. package/dist/actions/init/processTemplate.js.map +1 -1
  17. package/dist/actions/init/remoteTemplate.js +1 -1
  18. package/dist/actions/init/remoteTemplate.js.map +1 -1
  19. package/dist/actions/media/pullAspects.js +1 -1
  20. package/dist/actions/media/pullAspects.js.map +1 -1
  21. package/dist/actions/organizations/readOrganizationLogo.js +49 -0
  22. package/dist/actions/organizations/readOrganizationLogo.js.map +1 -0
  23. package/dist/actions/preview/previewAction.js +1 -1
  24. package/dist/actions/preview/previewAction.js.map +1 -1
  25. package/dist/actions/skills/readSkillState.js +1 -1
  26. package/dist/actions/skills/readSkillState.js.map +1 -1
  27. package/dist/actions/skills/setupSkills.js +1 -1
  28. package/dist/actions/skills/setupSkills.js.map +1 -1
  29. package/dist/commands/organizations/create.js +43 -3
  30. package/dist/commands/organizations/create.js.map +1 -1
  31. package/dist/commands/organizations/update.js +67 -14
  32. package/dist/commands/organizations/update.js.map +1 -1
  33. package/dist/exports/invokeSanityCli/commandPolicies/mcpPolicy.js +7 -2
  34. package/dist/exports/invokeSanityCli/commandPolicies/mcpPolicy.js.map +1 -1
  35. package/dist/generated/contextOperations.js +2 -2
  36. package/dist/generated/contextOperations.js.map +1 -1
  37. package/dist/hooks/commandNotFound/topicAliases.js +1 -1
  38. package/dist/hooks/commandNotFound/topicAliases.js.map +1 -1
  39. package/dist/server/devServer.js +8 -10
  40. package/dist/server/devServer.js.map +1 -1
  41. package/dist/services/organizations.js +30 -0
  42. package/dist/services/organizations.js.map +1 -1
  43. package/dist/util/telemetry/cliCommandIdentity.js +3 -2
  44. package/dist/util/telemetry/cliCommandIdentity.js.map +1 -1
  45. package/dist/util/update/updateChecker.js +1 -1
  46. package/dist/util/update/updateChecker.js.map +1 -1
  47. package/oclif.config.js +1 -1
  48. package/oclif.manifest.json +2665 -2623
  49. package/package.json +25 -26
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/media/pullAspects.ts"],"sourcesContent":["import {validateMediaLibraryAssetAspect} from '@sanity/schema/_internal'\nimport {type SchemaValidationProblem} from '@sanity/types'\nimport startCase from 'lodash-es/startCase.js'\n\nimport {type StoredAspectDocument} from '../../services/mediaLibraries.js'\nimport {VALID_ASPECT_NAME} from './aspectName.js'\n\n/** Keys whose object members are schema definitions, printed wrapped in a definer call. */\nconst DEFINER_BY_PARENT_KEY: Record<string, string> = {\n fields: 'defineField',\n of: 'defineArrayMember',\n}\n\nconst IDENTIFIER_KEY = /^[A-Za-z_$][A-Za-z0-9_$]*$/\n\n/** Scalar arrays shorter than this print inline (e.g. `options.list`). */\nconst INLINE_ARRAY_MAX_WIDTH = 60\n\n/**\n * The stored `sanity.asset.aspect` document shape this migration reads.\n * Deliberately loose: documents may predate the config model (authored via\n * `sanity media deploy-aspect` or by hand) and carry fields the model has no\n * equivalent for.\n */\nexport type PullableAspectDocument = StoredAspectDocument\n\nexport interface GeneratedFieldModule {\n filename: string\n /** The `aspects.<name>` data key — module filename and config entry name. */\n name: string\n source: string\n status: 'generated'\n title: string\n warnings: string[]\n\n public?: boolean\n}\n\nexport interface SkippedAspect {\n id: string\n reasons: string[]\n status: 'skipped'\n validationErrors: SchemaValidationProblem[][]\n}\n\nexport type PullAspectOutcome = GeneratedFieldModule | SkippedAspect\n\n/**\n * Convert a page of stored aspect documents into field modules, one per field\n * name. Two stored documents can resolve to the same name (a legacy document\n * whose `_id` predates its `definition.name`), which would otherwise produce\n * the same module twice — the document whose `_id` matches the name wins, the\n * rest are reported as skipped. Shared by `sanity media pull-aspects` and the\n * init-time pull offer.\n *\n * @internal\n */\nexport function convertAspectDocuments(documents: PullableAspectDocument[]): {\n modules: GeneratedFieldModule[]\n skipped: SkippedAspect[]\n} {\n const skipped: SkippedAspect[] = []\n\n // First pass: convert every stored document.\n const candidates: Array<{module: GeneratedFieldModule; sourceId: string}> = []\n for (const doc of documents) {\n const outcome = aspectDocumentToFieldModule(doc)\n if (outcome.status === 'skipped') {\n skipped.push(outcome)\n } else {\n candidates.push({module: outcome, sourceId: String(doc._id)})\n }\n }\n\n // Second pass: pick one winner per name.\n const byName = new Map<string, Array<{module: GeneratedFieldModule; sourceId: string}>>()\n for (const candidate of candidates) {\n const group = byName.get(candidate.module.name) ?? []\n group.push(candidate)\n byName.set(candidate.module.name, group)\n }\n const modules: GeneratedFieldModule[] = []\n for (const [name, group] of byName) {\n const winner = group.find((candidate) => candidate.sourceId === name) ?? group[0]\n modules.push(winner.module)\n for (const loser of group) {\n if (loser === winner) continue\n skipped.push({\n id: loser.sourceId,\n reasons: [`Also defines \"${name}\" — generated from \"${winner.sourceId}\" instead`],\n status: 'skipped',\n validationErrors: [],\n })\n }\n }\n\n return {modules, skipped}\n}\n\n/**\n * Codegen one stored aspect document into a `src/fields/<name>.tsx` field\n * module for a Media Library config app.\n *\n * Stored aspects are migration-ready by construction: `definition` is the\n * JSON-serialized `defineField(...)` value with functions and component\n * references already stripped, so generation is mechanical pretty-printing\n * into a `defineField({...})` call (nested `fields`/`of` members wrapped in\n * `defineField`/`defineArrayMember`, matching hand-authored style).\n *\n * Edge cases handled here, not silently:\n *\n * - `_id` vs `definition.name` mismatch: the module is generated under\n * `definition.name` — the `aspects.<name>` key existing asset data lives\n * under. Normalizing onto `_id` instead would silently orphan that data.\n * The old document (keyed `_id`) is reported for manual deletion.\n * - `assetType` has no equivalent in the config model; a document carrying it\n * generates with a warning that the scoping is lost.\n * - Definitions failing current schema validation are skipped with the\n * validation errors, mirroring `sanity media deploy-aspect`.\n *\n * Pure (no I/O): the command decides where modules are written.\n *\n * @internal\n */\nexport function aspectDocumentToFieldModule(doc: PullableAspectDocument): PullAspectOutcome {\n const {_id} = doc\n\n if (!isRecord(doc.definition)) {\n return {\n id: _id,\n reasons: ['The stored document has no field definition object'],\n status: 'skipped',\n validationErrors: [],\n }\n }\n\n const definitionName = typeof doc.definition.name === 'string' ? doc.definition.name : undefined\n const name = definitionName ?? _id\n\n if (!VALID_ASPECT_NAME.test(name)) {\n return {\n id: _id,\n reasons: [\n `\"${name}\" is not a valid field name (${VALID_ASPECT_NAME}) — it becomes the module name and the aspects.<name> key on assets`,\n ],\n status: 'skipped',\n validationErrors: [],\n }\n }\n\n const warnings: string[] = []\n\n if (definitionName === undefined) {\n warnings.push(`The stored definition has no name — using the document _id \"${_id}\"`)\n } else if (definitionName !== _id) {\n warnings.push(\n `Stored _id \"${_id}\" and definition name \"${definitionName}\" differ. Generated as ` +\n `\"${definitionName}\" — the aspects.<name> key existing asset data lives under; using ` +\n `\"${_id}\" would orphan that data. Deploying the config creates \"${definitionName}\" ` +\n `and deletes the old \"${_id}\" document.`,\n )\n }\n\n if (doc.assetType !== undefined && doc.assetType !== null) {\n warnings.push(\n `The stored document scopes the aspect by assetType (${JSON.stringify(doc.assetType)}), ` +\n `which has no equivalent in the config model — the generated field applies to all ` +\n `asset types, and syncing the config drops the scoping.`,\n )\n }\n\n // Normalize the name in before validating, so a document that only carries\n // its name as `_id` isn't rejected for the missing property.\n const definition: Record<string, unknown> = definitionName\n ? doc.definition\n : {name, ...doc.definition}\n\n const [valid, validationErrors] = validateMediaLibraryAssetAspect(definition)\n if (!valid) {\n return {\n id: _id,\n reasons: ['The stored definition fails schema validation'],\n status: 'skipped',\n validationErrors,\n }\n }\n\n return {\n // .tsx although the generated content has no JSX: field modules are\n // expected to grow custom input components (the one thing the stored\n // aspect could not carry), and a later rename would also mean fixing the\n // `src:` entry in sanity.cli.ts. Matches the template's example modules.\n filename: `${name}.tsx`,\n name,\n ...(typeof doc.public === 'boolean' ? {public: doc.public} : {}),\n source: printFieldModule(definition),\n status: 'generated',\n title: typeof definition.title === 'string' ? definition.title : startCase(name),\n warnings,\n }\n}\n\n/**\n * The paste-ready `fields: [...]` entries for `sanity.cli.ts`, one line per\n * generated module. When `writtenPaths` (module name to root-relative path)\n * has an entry for a module, that path wins — the module may have replaced an\n * existing file (e.g. a `.tsx` variant) rather than landing at the default\n * `<srcDir>/<filename>` location.\n *\n * @internal\n */\nexport function formatFieldEntries(\n modules: GeneratedFieldModule[],\n srcDir: string,\n writtenPaths?: Map<string, string>,\n): string {\n const dir = srcDir.replaceAll('\\\\', '/').replace(/\\/+$/, '')\n return modules\n .map((module) => {\n const src =\n writtenPaths?.get(module.name)?.replaceAll('\\\\', '/') ?? `${dir}/${module.filename}`\n const publicPart = module.public === undefined ? '' : `, public: ${module.public}`\n return `{name: '${module.name}', src: './${src}', title: ${quote(module.title)}${publicPart}},`\n })\n .join('\\n')\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\ninterface PrinterState {\n usesDefineArrayMember: boolean\n}\n\nfunction printFieldModule(definition: Record<string, unknown>): string {\n const state: PrinterState = {usesDefineArrayMember: false}\n const literal = printObject(definition, '', state)\n const imports = state.usesDefineArrayMember ? 'defineArrayMember, defineField' : 'defineField'\n\n return `import {${imports}} from 'sanity'\\n\\nexport default defineField(${literal})\\n`\n}\n\nfunction quote(value: string): string {\n const escaped = value\n .replaceAll('\\\\', '\\\\\\\\')\n .replaceAll(\"'\", String.raw`\\'`)\n .replaceAll('\\n', String.raw`\\n`)\n .replaceAll('\\r', String.raw`\\r`)\n .replaceAll('\\t', String.raw`\\t`)\n return `'${escaped}'`\n}\n\nfunction printKey(key: string): string {\n return IDENTIFIER_KEY.test(key) ? key : quote(key)\n}\n\nfunction printValue(\n value: unknown,\n indent: string,\n parentKey: string | null,\n state: PrinterState,\n): string {\n if (value === null) return 'null'\n if (typeof value === 'string') return quote(value)\n if (typeof value === 'number' || typeof value === 'boolean') return String(value)\n if (Array.isArray(value)) return printArray(value, indent, parentKey, state)\n if (isRecord(value)) return printObject(value, indent, state)\n // Stored definitions are JSON documents; anything else cannot occur.\n throw new TypeError(`Cannot print value of type ${typeof value}`)\n}\n\nfunction printArray(\n items: unknown[],\n indent: string,\n parentKey: string | null,\n state: PrinterState,\n): string {\n if (items.length === 0) return '[]'\n\n const allScalar = items.every(\n (item) => item === null || ['boolean', 'number', 'string'].includes(typeof item),\n )\n if (allScalar) {\n const inline = `[${items.map((item) => printValue(item, indent, null, state)).join(', ')}]`\n if (inline.length <= INLINE_ARRAY_MAX_WIDTH) return inline\n }\n\n const definer = parentKey === null ? undefined : DEFINER_BY_PARENT_KEY[parentKey]\n const innerIndent = `${indent} `\n const lines = items.map((item) => {\n if (definer !== undefined && isRecord(item)) {\n if (definer === 'defineArrayMember') state.usesDefineArrayMember = true\n return `${innerIndent}${definer}(${printObject(item, innerIndent, state)}),`\n }\n return `${innerIndent}${printValue(item, innerIndent, null, state)},`\n })\n return `[\\n${lines.join('\\n')}\\n${indent}]`\n}\n\nfunction printObject(obj: Record<string, unknown>, indent: string, state: PrinterState): string {\n const entries = Object.entries(obj).filter(([, value]) => value !== undefined)\n if (entries.length === 0) return '{}'\n\n const innerIndent = `${indent} `\n const lines = entries.map(\n ([key, value]) =>\n `${innerIndent}${printKey(key)}: ${printValue(value, innerIndent, key, state)},`,\n )\n return `{\\n${lines.join('\\n')}\\n${indent}}`\n}\n"],"names":["validateMediaLibraryAssetAspect","startCase","VALID_ASPECT_NAME","DEFINER_BY_PARENT_KEY","fields","of","IDENTIFIER_KEY","INLINE_ARRAY_MAX_WIDTH","convertAspectDocuments","documents","skipped","candidates","doc","outcome","aspectDocumentToFieldModule","status","push","module","sourceId","String","_id","byName","Map","candidate","group","get","name","set","modules","winner","find","loser","id","reasons","validationErrors","isRecord","definition","definitionName","undefined","test","warnings","assetType","JSON","stringify","valid","filename","public","source","printFieldModule","title","formatFieldEntries","srcDir","writtenPaths","dir","replaceAll","replace","map","src","publicPart","quote","join","value","Array","isArray","state","usesDefineArrayMember","literal","printObject","imports","escaped","raw","printKey","key","printValue","indent","parentKey","printArray","TypeError","items","length","allScalar","every","item","includes","inline","definer","innerIndent","lines","obj","entries","Object","filter"],"mappings":"AAAA,SAAQA,+BAA+B,QAAO,2BAA0B;AAExE,OAAOC,eAAe,yBAAwB;AAG9C,SAAQC,iBAAiB,QAAO,kBAAiB;AAEjD,yFAAyF,GACzF,MAAMC,wBAAgD;IACpDC,QAAQ;IACRC,IAAI;AACN;AAEA,MAAMC,iBAAiB;AAEvB,wEAAwE,GACxE,MAAMC,yBAAyB;AA+B/B;;;;;;;;;CASC,GACD,OAAO,SAASC,uBAAuBC,SAAmC;IAIxE,MAAMC,UAA2B,EAAE;IAEnC,6CAA6C;IAC7C,MAAMC,aAAsE,EAAE;IAC9E,KAAK,MAAMC,OAAOH,UAAW;QAC3B,MAAMI,UAAUC,4BAA4BF;QAC5C,IAAIC,QAAQE,MAAM,KAAK,WAAW;YAChCL,QAAQM,IAAI,CAACH;QACf,OAAO;YACLF,WAAWK,IAAI,CAAC;gBAACC,QAAQJ;gBAASK,UAAUC,OAAOP,IAAIQ,GAAG;YAAC;QAC7D;IACF;IAEA,yCAAyC;IACzC,MAAMC,SAAS,IAAIC;IACnB,KAAK,MAAMC,aAAaZ,WAAY;QAClC,MAAMa,QAAQH,OAAOI,GAAG,CAACF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Z,OAAO,EAAE,CAAC;IACjC,MAAMa,QAAQT,MAAMtB,GAAG,CAAC,CAAC0B;QACvB,IAAIG,YAAY/C,aAAaH,SAAS+C,OAAO;YAC3C,IAAIG,YAAY,qBAAqBrB,MAAMC,qBAAqB,GAAG;YACnE,OAAO,GAAGqB,cAAcD,QAAQ,CAAC,EAAElB,YAAYe,MAAMI,aAAatB,OAAO,EAAE,CAAC;QAC9E;QACA,OAAO,GAAGsB,cAAcb,WAAWS,MAAMI,aAAa,MAAMtB,OAAO,CAAC,CAAC;IACvE;IACA,OAAO,CAAC,GAAG,EAAEuB,MAAM3B,IAAI,CAAC,MAAM,EAAE,EAAEc,OAAO,CAAC,CAAC;AAC7C;AAEA,SAASP,YAAYqB,GAA4B,EAAEd,MAAc,EAAEV,KAAmB;IACpF,MAAMyB,UAAUC,OAAOD,OAAO,CAACD,KAAKG,MAAM,CAAC,CAAC,GAAG9B,MAAM,GAAKA,UAAUvB;IACpE,IAAImD,QAAQV,MAAM,KAAK,GAAG,OAAO;IAEjC,MAAMO,cAAc,GAAGZ,OAAO,EAAE,CAAC;IACjC,MAAMa,QAAQE,QAAQjC,GAAG,CACvB,CAAC,CAACgB,KAAKX,MAAM,GACX,GAAGyB,cAAcf,SAASC,KAAK,EAAE,EAAEC,WAAWZ,OAAOyB,aAAad,KAAKR,OAAO,CAAC,CAAC;IAEpF,OAAO,CAAC,GAAG,EAAEuB,MAAM3B,IAAI,CAAC,MAAM,EAAE,EAAEc,OAAO,CAAC,CAAC;AAC7C"}
1
+ {"version":3,"sources":["../../../src/actions/media/pullAspects.ts"],"sourcesContent":["import {validateMediaLibraryAssetAspect} from '@sanity/schema/_internal'\nimport {type SchemaValidationProblem} from '@sanity/types'\nimport startCase from 'lodash-es/startCase.js'\n\nimport {type StoredAspectDocument} from '../../services/mediaLibraries.js'\nimport {VALID_ASPECT_NAME} from './aspectName.js'\n\n/** Keys whose object members are schema definitions, printed wrapped in a definer call. */\nconst DEFINER_BY_PARENT_KEY: Record<string, string> = {\n fields: 'defineField',\n of: 'defineArrayMember',\n}\n\nconst IDENTIFIER_KEY = /^[A-Za-z_$][A-Za-z0-9_$]*$/\n\n/** Scalar arrays shorter than this print inline (e.g. `options.list`). */\nconst INLINE_ARRAY_MAX_WIDTH = 60\n\n/**\n * The stored `sanity.asset.aspect` document shape this migration reads.\n * Deliberately loose: documents may predate the config model (authored via\n * `sanity media deploy-aspect` or by hand) and carry fields the model has no\n * equivalent for.\n */\nexport type PullableAspectDocument = StoredAspectDocument\n\nexport interface GeneratedFieldModule {\n filename: string\n /** The `aspects.<name>` data key — module filename and config entry name. */\n name: string\n source: string\n status: 'generated'\n title: string\n warnings: string[]\n\n public?: boolean\n}\n\nexport interface SkippedAspect {\n id: string\n reasons: string[]\n status: 'skipped'\n validationErrors: SchemaValidationProblem[][]\n}\n\nexport type PullAspectOutcome = GeneratedFieldModule | SkippedAspect\n\n/**\n * Convert a page of stored aspect documents into field modules, one per field\n * name. Two stored documents can resolve to the same name (a legacy document\n * whose `_id` predates its `definition.name`), which would otherwise produce\n * the same module twice — the document whose `_id` matches the name wins, the\n * rest are reported as skipped. Shared by `sanity media pull-aspects` and the\n * init-time pull offer.\n *\n * @internal\n */\nexport function convertAspectDocuments(documents: PullableAspectDocument[]): {\n modules: GeneratedFieldModule[]\n skipped: SkippedAspect[]\n} {\n const skipped: SkippedAspect[] = []\n\n // First pass: convert every stored document.\n const candidates: Array<{module: GeneratedFieldModule; sourceId: string}> = []\n for (const doc of documents) {\n const outcome = aspectDocumentToFieldModule(doc)\n if (outcome.status === 'skipped') {\n skipped.push(outcome)\n } else {\n candidates.push({module: outcome, sourceId: String(doc._id)})\n }\n }\n\n // Second pass: pick one winner per name.\n const byName = new Map<string, Array<{module: GeneratedFieldModule; sourceId: string}>>()\n for (const candidate of candidates) {\n const group = byName.get(candidate.module.name) ?? []\n group.push(candidate)\n byName.set(candidate.module.name, group)\n }\n const modules: GeneratedFieldModule[] = []\n for (const [name, group] of byName) {\n const winner = group.find((candidate) => candidate.sourceId === name) ?? group[0]\n modules.push(winner.module)\n for (const loser of group) {\n if (loser === winner) continue\n skipped.push({\n id: loser.sourceId,\n reasons: [`Also defines \"${name}\" — generated from \"${winner.sourceId}\" instead`],\n status: 'skipped',\n validationErrors: [],\n })\n }\n }\n\n return {modules, skipped}\n}\n\n/**\n * Codegen one stored aspect document into a `src/fields/<name>.tsx` field\n * module for a Media Library config app.\n *\n * Stored aspects are migration-ready by construction: `definition` is the\n * JSON-serialized `defineField(...)` value with functions and component\n * references already stripped, so generation is mechanical pretty-printing\n * into a `defineField({...})` call (nested `fields`/`of` members wrapped in\n * `defineField`/`defineArrayMember`, matching hand-authored style).\n *\n * Edge cases handled here, not silently:\n *\n * - `_id` vs `definition.name` mismatch: the module is generated under\n * `definition.name` — the `aspects.<name>` key existing asset data lives\n * under. Normalizing onto `_id` instead would silently orphan that data.\n * The old document (keyed `_id`) is reported for manual deletion.\n * - `assetType` has no equivalent in the config model; a document carrying it\n * generates with a warning that the scoping is lost.\n * - Definitions failing current schema validation are skipped with the\n * validation errors, mirroring `sanity media deploy-aspect`.\n *\n * Pure (no I/O): the command decides where modules are written.\n *\n * @internal\n */\nexport function aspectDocumentToFieldModule(doc: PullableAspectDocument): PullAspectOutcome {\n const {_id} = doc\n\n if (!isRecord(doc.definition)) {\n return {\n id: _id,\n reasons: ['The stored document has no field definition object'],\n status: 'skipped',\n validationErrors: [],\n }\n }\n\n const definitionName = typeof doc.definition.name === 'string' ? doc.definition.name : undefined\n const name = definitionName ?? _id\n\n if (!VALID_ASPECT_NAME.test(name)) {\n return {\n id: _id,\n reasons: [\n `\"${name}\" is not a valid field name (${VALID_ASPECT_NAME}) — it becomes the module name and the aspects.<name> key on assets`,\n ],\n status: 'skipped',\n validationErrors: [],\n }\n }\n\n const warnings: string[] = []\n\n if (definitionName === undefined) {\n warnings.push(`The stored definition has no name — using the document _id \"${_id}\"`)\n } else if (definitionName !== _id) {\n warnings.push(\n `Stored _id \"${_id}\" and definition name \"${definitionName}\" differ. Generated as ` +\n `\"${definitionName}\" — the aspects.<name> key existing asset data lives under; using ` +\n `\"${_id}\" would orphan that data. Deploying the config creates \"${definitionName}\" ` +\n `and deletes the old \"${_id}\" document.`,\n )\n }\n\n if (doc.assetType !== undefined && doc.assetType !== null) {\n warnings.push(\n `The stored document scopes the aspect by assetType (${JSON.stringify(doc.assetType)}), ` +\n `which has no equivalent in the config model — the generated field applies to all ` +\n `asset types, and syncing the config drops the scoping.`,\n )\n }\n\n // Normalize the name in before validating, so a document that only carries\n // its name as `_id` isn't rejected for the missing property.\n const definition: Record<string, unknown> = definitionName\n ? doc.definition\n : {name, ...doc.definition}\n\n const [valid, validationErrors] = validateMediaLibraryAssetAspect(definition)\n if (!valid) {\n return {\n id: _id,\n reasons: ['The stored definition fails schema validation'],\n status: 'skipped',\n validationErrors,\n }\n }\n\n return {\n // .tsx although the generated content has no JSX: field modules are\n // expected to grow custom input components (the one thing the stored\n // aspect could not carry), and a later rename would also mean fixing the\n // `src:` entry in sanity.cli.ts. Matches the template's example modules.\n filename: `${name}.tsx`,\n name,\n ...(typeof doc.public === 'boolean' ? {public: doc.public} : {}),\n source: printFieldModule(definition),\n status: 'generated',\n title: typeof definition.title === 'string' ? definition.title : startCase(name),\n warnings,\n }\n}\n\n/**\n * The paste-ready `fields: [...]` entries for `sanity.cli.ts`, one line per\n * generated module. When `writtenPaths` (module name to root-relative path)\n * has an entry for a module, that path wins — the module may have replaced an\n * existing file (e.g. a `.tsx` variant) rather than landing at the default\n * `<srcDir>/<filename>` location.\n *\n * @internal\n */\nexport function formatFieldEntries(\n modules: GeneratedFieldModule[],\n srcDir: string,\n writtenPaths?: Map<string, string>,\n): string {\n const dir = srcDir.replaceAll('\\\\', '/').replace(/\\/+$/, '')\n return modules\n .map((module) => {\n const src =\n writtenPaths?.get(module.name)?.replaceAll('\\\\', '/') ?? `${dir}/${module.filename}`\n const publicPart = module.public === undefined ? '' : `, public: ${module.public}`\n return `{name: '${module.name}', src: './${src}', title: ${quote(module.title)}${publicPart}},`\n })\n .join('\\n')\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\ninterface PrinterState {\n usesDefineArrayMember: boolean\n}\n\nfunction printFieldModule(definition: Record<string, unknown>): string {\n const state: PrinterState = {usesDefineArrayMember: false}\n const literal = printObject(definition, '', state)\n const imports = state.usesDefineArrayMember ? 'defineArrayMember, defineField' : 'defineField'\n\n return `import {${imports}} from 'sanity'\\n\\nexport default defineField(${literal})\\n`\n}\n\nfunction quote(value: string): string {\n const escaped = value\n .replaceAll('\\\\', String.raw`\\\\`)\n .replaceAll(\"'\", String.raw`\\'`)\n .replaceAll('\\n', String.raw`\\n`)\n .replaceAll('\\r', String.raw`\\r`)\n .replaceAll('\\t', String.raw`\\t`)\n return `'${escaped}'`\n}\n\nfunction printKey(key: string): string {\n return IDENTIFIER_KEY.test(key) ? key : quote(key)\n}\n\nfunction printValue(\n value: unknown,\n indent: string,\n parentKey: string | null,\n state: PrinterState,\n): string {\n if (value === null) return 'null'\n if (typeof value === 'string') return quote(value)\n if (typeof value === 'number' || typeof value === 'boolean') return String(value)\n if (Array.isArray(value)) return printArray(value, indent, parentKey, state)\n if (isRecord(value)) return printObject(value, indent, state)\n // Stored definitions are JSON documents; anything else cannot occur.\n throw new TypeError(`Cannot print value of type ${typeof value}`)\n}\n\nfunction printArray(\n items: unknown[],\n indent: string,\n parentKey: string | null,\n state: PrinterState,\n): string {\n if (items.length === 0) return '[]'\n\n const allScalar = items.every(\n (item) => item === null || ['boolean', 'number', 'string'].includes(typeof item),\n )\n if (allScalar) {\n const inline = `[${items.map((item) => printValue(item, indent, null, state)).join(', ')}]`\n if (inline.length <= INLINE_ARRAY_MAX_WIDTH) return inline\n }\n\n const definer = parentKey === null ? undefined : DEFINER_BY_PARENT_KEY[parentKey]\n const innerIndent = `${indent} `\n const lines = items.map((item) => {\n if (definer !== undefined && isRecord(item)) {\n if (definer === 'defineArrayMember') state.usesDefineArrayMember = true\n return `${innerIndent}${definer}(${printObject(item, innerIndent, state)}),`\n }\n return `${innerIndent}${printValue(item, innerIndent, null, state)},`\n })\n return `[\\n${lines.join('\\n')}\\n${indent}]`\n}\n\nfunction printObject(obj: Record<string, unknown>, indent: string, state: PrinterState): string {\n const entries = Object.entries(obj).filter(([, value]) => value !== undefined)\n if (entries.length === 0) return '{}'\n\n const innerIndent = `${indent} `\n const lines = entries.map(\n ([key, value]) =>\n `${innerIndent}${printKey(key)}: ${printValue(value, innerIndent, key, state)},`,\n )\n return `{\\n${lines.join('\\n')}\\n${indent}}`\n}\n"],"names":["validateMediaLibraryAssetAspect","startCase","VALID_ASPECT_NAME","DEFINER_BY_PARENT_KEY","fields","of","IDENTIFIER_KEY","INLINE_ARRAY_MAX_WIDTH","convertAspectDocuments","documents","skipped","candidates","doc","outcome","aspectDocumentToFieldModule","status","push","module","sourceId","String","_id","byName","Map","candidate","group","get","name","set","modules","winner","find","loser","id","reasons","validationErrors","isRecord","definition","definitionName","undefined","test","warnings","assetType","JSON","stringify","valid","filename","public","source","printFieldModule","title","formatFieldEntries","srcDir","writtenPaths","dir","replaceAll","replace","map","src","publicPart","quote","join","value","Array","isArray","state","usesDefineArrayMember","literal","printObject","imports","escaped","raw","printKey","key","printValue","indent","parentKey","printArray","TypeError","items","length","allScalar","every","item","includes","inline","definer","innerIndent","lines","obj","entries","Object","filter"],"mappings":"AAAA,SAAQA,+BAA+B,QAAO,2BAA0B;AAExE,OAAOC,eAAe,yBAAwB;AAG9C,SAAQC,iBAAiB,QAAO,kBAAiB;AAEjD,yFAAyF,GACzF,MAAMC,wBAAgD;IACpDC,QAAQ;IACRC,IAAI;AACN;AAEA,MAAMC,iBAAiB;AAEvB,wEAAwE,GACxE,MAAMC,yBAAyB;AA+B/B;;;;;;;;;CASC,GACD,OAAO,SAASC,uBAAuBC,SAAmC;IAIxE,MAAMC,UAA2B,EAAE;IAEnC,6CAA6C;IAC7C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,OAAO,CAAC,CAAC;IAEpF,OAAO,CAAC,GAAG,EAAEuB,MAAM3B,IAAI,CAAC,MAAM,EAAE,EAAEc,OAAO,CAAC,CAAC;AAC7C"}
@@ -0,0 +1,49 @@
1
+ import { readFile, stat } from 'node:fs/promises';
2
+ import { extname } from 'node:path';
3
+ // The image formats populus accepts as an organization logo. It needs an image Content-Type, and
4
+ // the CLI has no other source for one.
5
+ const LOGO_CONTENT_TYPES = {
6
+ '.avif': 'image/avif',
7
+ '.bmp': 'image/bmp',
8
+ '.gif': 'image/gif',
9
+ '.heic': 'image/heic',
10
+ '.heif': 'image/heif',
11
+ '.jpeg': 'image/jpeg',
12
+ '.jpg': 'image/jpeg',
13
+ '.png': 'image/png',
14
+ '.svg': 'image/svg+xml',
15
+ '.tif': 'image/tiff',
16
+ '.tiff': 'image/tiff',
17
+ '.webp': 'image/webp'
18
+ };
19
+ // Matches populus's limit, so a large file fails here instead of after uploading it.
20
+ const MAX_LOGO_BYTES = 5 * 1024 * 1024;
21
+ /**
22
+ * Read an image file to upload as an organization's logo. Throws an error a user can act on when
23
+ * the file is missing, isn't a supported image type, or is over 5 MB.
24
+ */ export async function readOrganizationLogo(filePath) {
25
+ const contentType = LOGO_CONTENT_TYPES[extname(filePath).toLowerCase()];
26
+ if (!contentType) {
27
+ throw new Error(`"${filePath}" isn't a supported image type. Use a PNG, JPEG, GIF, WebP, SVG, BMP, TIFF, HEIF or AVIF file.`);
28
+ }
29
+ let stats;
30
+ try {
31
+ stats = await stat(filePath);
32
+ } catch (error) {
33
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
34
+ throw new Error(`Couldn't find "${filePath}". Check the path and try again.`, {
35
+ cause: error
36
+ });
37
+ }
38
+ throw error;
39
+ }
40
+ if (stats.size > MAX_LOGO_BYTES) {
41
+ throw new Error(`"${filePath}" is larger than 5 MB, the limit for a logo. Use a smaller image.`);
42
+ }
43
+ return {
44
+ contentType,
45
+ image: await readFile(filePath)
46
+ };
47
+ }
48
+
49
+ //# sourceMappingURL=readOrganizationLogo.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/actions/organizations/readOrganizationLogo.ts"],"sourcesContent":["import {type Stats} from 'node:fs'\nimport {readFile, stat} from 'node:fs/promises'\nimport {extname} from 'node:path'\n\n// The image formats populus accepts as an organization logo. It needs an image Content-Type, and\n// the CLI has no other source for one.\nconst LOGO_CONTENT_TYPES: Record<string, string> = {\n '.avif': 'image/avif',\n '.bmp': 'image/bmp',\n '.gif': 'image/gif',\n '.heic': 'image/heic',\n '.heif': 'image/heif',\n '.jpeg': 'image/jpeg',\n '.jpg': 'image/jpeg',\n '.png': 'image/png',\n '.svg': 'image/svg+xml',\n '.tif': 'image/tiff',\n '.tiff': 'image/tiff',\n '.webp': 'image/webp',\n}\n\n// Matches populus's limit, so a large file fails here instead of after uploading it.\nconst MAX_LOGO_BYTES = 5 * 1024 * 1024\n\nexport interface OrganizationLogo {\n contentType: string\n image: Buffer\n}\n\n/**\n * Read an image file to upload as an organization's logo. Throws an error a user can act on when\n * the file is missing, isn't a supported image type, or is over 5 MB.\n */\nexport async function readOrganizationLogo(filePath: string): Promise<OrganizationLogo> {\n const contentType = LOGO_CONTENT_TYPES[extname(filePath).toLowerCase()]\n if (!contentType) {\n throw new Error(\n `\"${filePath}\" isn't a supported image type. Use a PNG, JPEG, GIF, WebP, SVG, BMP, TIFF, HEIF or AVIF file.`,\n )\n }\n\n let stats: Stats\n try {\n stats = await stat(filePath)\n } catch (error) {\n if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {\n throw new Error(`Couldn't find \"${filePath}\". Check the path and try again.`, {cause: error})\n }\n throw error\n }\n\n if (stats.size > MAX_LOGO_BYTES) {\n throw new Error(`\"${filePath}\" is larger than 5 MB, the limit for a logo. Use a smaller image.`)\n }\n\n return {contentType, image: await readFile(filePath)}\n}\n"],"names":["readFile","stat","extname","LOGO_CONTENT_TYPES","MAX_LOGO_BYTES","readOrganizationLogo","filePath","contentType","toLowerCase","Error","stats","error","code","cause","size","image"],"mappings":"AACA,SAAQA,QAAQ,EAAEC,IAAI,QAAO,mBAAkB;AAC/C,SAAQC,OAAO,QAAO,YAAW;AAEjC,iGAAiG;AACjG,uCAAuC;AACvC,MAAMC,qBAA6C;IACjD,SAAS;IACT,QAAQ;IACR,QAAQ;IACR,SAAS;IACT,SAAS;IACT,SAAS;IACT,QAAQ;IACR,QAAQ;IACR,QAAQ;IACR,QAAQ;IACR,SAAS;IACT,SAAS;AACX;AAEA,qFAAqF;AACrF,MAAMC,iBAAiB,IAAI,OAAO;AAOlC;;;CAGC,GACD,OAAO,eAAeC,qBAAqBC,QAAgB;IACzD,MAAMC,cAAcJ,kBAAkB,CAACD,QAAQI,UAAUE,WAAW,GAAG;IACvE,IAAI,CAACD,aAAa;QAChB,MAAM,IAAIE,MACR,CAAC,CAAC,EAAEH,SAAS,8FAA8F,CAAC;IAEhH;IAEA,IAAII;IACJ,IAAI;QACFA,QAAQ,MAAMT,KAAKK;IACrB,EAAE,OAAOK,OAAO;QACd,IAAIA,iBAAiBF,SAAS,UAAUE,SAASA,MAAMC,IAAI,KAAK,UAAU;YACxE,MAAM,IAAIH,MAAM,CAAC,eAAe,EAAEH,SAAS,gCAAgC,CAAC,EAAE;gBAACO,OAAOF;YAAK;QAC7F;QACA,MAAMA;IACR;IAEA,IAAID,MAAMI,IAAI,GAAGV,gBAAgB;QAC/B,MAAM,IAAIK,MAAM,CAAC,CAAC,EAAEH,SAAS,iEAAiE,CAAC;IACjG;IAEA,OAAO;QAACC;QAAaQ,OAAO,MAAMf,SAASM;IAAS;AACtD"}
@@ -20,7 +20,7 @@ export async function previewAction(options) {
20
20
  const isApp = determineIsApp(cliConfig);
21
21
  // Lazy so a non-workbench `sanity start` never loads the package. `doImport`
22
22
  // is path-based and doesn't apply to a bare specifier.
23
- // eslint-disable-next-line no-restricted-syntax
23
+ // eslint-disable-next-line eslint-js/no-restricted-syntax
24
24
  const { startWorkbenchPreview } = await import('@sanity/workbench-cli/preview');
25
25
  return startWorkbenchPreview({
26
26
  cacheDir: `${SANITY_CACHE_DIR}/vite`,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/preview/previewAction.ts"],"sourcesContent":["import {SANITY_CACHE_DIR} from '@sanity/cli-build/_internal/build'\nimport {extractCoreAppManifest} from '@sanity/cli-build/_internal/manifest'\nimport {type CliConfig, type Output} from '@sanity/cli-core'\nimport {isWorkbenchApp} from '@sanity/workbench-cli'\n\nimport {gracefulServerDeath} from '../../server/gracefulServerDeath.js'\nimport {type PreviewServer, startPreviewServer} from '../../server/previewServer.js'\nimport {checkForDeprecatedAppId} from '../../util/appId.js'\nimport {determineIsApp} from '../../util/determineIsApp.js'\nimport {resolveReactStrictMode} from '../../util/resolveReactStrictMode.js'\nimport {extractStudioManifest} from '../manifest/extractStudioManifest.js'\nimport {getPreviewServerConfig} from './getPreviewServerConfig.js'\nimport {type PreviewFlags} from './types.js'\n\ninterface PreviewActionOptions {\n cliConfig: CliConfig\n flags: PreviewFlags\n outDir: string\n output: Output\n workDir: string\n}\n\nexport async function previewAction(\n options: PreviewActionOptions,\n): Promise<PreviewServer | {close: () => Promise<void>}> {\n const {cliConfig, flags, outDir, output, workDir} = options\n\n const config = getPreviewServerConfig({cliConfig, flags, rootDir: outDir, workDir})\n\n if (isWorkbenchApp(cliConfig?.app)) {\n const isApp = determineIsApp(cliConfig)\n // Lazy so a non-workbench `sanity start` never loads the package. `doImport`\n // is path-based and doesn't apply to a bare specifier.\n // eslint-disable-next-line no-restricted-syntax\n const {startWorkbenchPreview} = await import('@sanity/workbench-cli/preview')\n return startWorkbenchPreview({\n cacheDir: `${SANITY_CACHE_DIR}/vite`,\n checkForDeprecatedAppId: () => checkForDeprecatedAppId({cliConfig, output}),\n cliConfig,\n extractManifest: isApp\n ? ({workDir: wd}) => extractCoreAppManifest({workDir: wd})\n : (params) => extractStudioManifest(params),\n httpHost: config.httpHost,\n httpPort: config.httpPort,\n isApp,\n outDir,\n output,\n reactStrictMode: resolveReactStrictMode(cliConfig) ?? false,\n workDir,\n })\n }\n\n try {\n const server = await startPreviewServer(config)\n return server\n } catch (err) {\n throw gracefulServerDeath('preview', config.httpHost, config.httpPort, err)\n }\n}\n"],"names":["SANITY_CACHE_DIR","extractCoreAppManifest","isWorkbenchApp","gracefulServerDeath","startPreviewServer","checkForDeprecatedAppId","determineIsApp","resolveReactStrictMode","extractStudioManifest","getPreviewServerConfig","previewAction","options","cliConfig","flags","outDir","output","workDir","config","rootDir","app","isApp","startWorkbenchPreview","cacheDir","extractManifest","wd","params","httpHost","httpPort","reactStrictMode","server","err"],"mappings":"AAAA,SAAQA,gBAAgB,QAAO,oCAAmC;AAClE,SAAQC,sBAAsB,QAAO,uCAAsC;AAE3E,SAAQC,cAAc,QAAO,wBAAuB;AAEpD,SAAQC,mBAAmB,QAAO,sCAAqC;AACvE,SAA4BC,kBAAkB,QAAO,gCAA+B;AACpF,SAAQC,uBAAuB,QAAO,sBAAqB;AAC3D,SAAQC,cAAc,QAAO,+BAA8B;AAC3D,SAAQC,sBAAsB,QAAO,uCAAsC;AAC3E,SAAQC,qBAAqB,QAAO,uCAAsC;AAC1E,SAAQC,sBAAsB,QAAO,8BAA6B;AAWlE,OAAO,eAAeC,cACpBC,OAA6B;IAE7B,MAAM,EAACC,SAAS,EAAEC,KAAK,EAAEC,MAAM,EAAEC,MAAM,EAAEC,OAAO,EAAC,GAAGL;IAEpD,MAAMM,SAASR,uBAAuB;QAACG;QAAWC;QAAOK,SAASJ;QAAQE;IAAO;IAEjF,IAAId,eAAeU,WAAWO,MAAM;QAClC,MAAMC,QAAQd,eAAeM;QAC7B,6EAA6E;QAC7E,uDAAuD;QACvD,gDAAgD;QAChD,MAAM,EAACS,qBAAqB,EAAC,GAAG,MAAM,MAAM,CAAC;QAC7C,OAAOA,sBAAsB;YAC3BC,UAAU,GAAGtB,iBAAiB,KAAK,CAAC;YACpCK,yBAAyB,IAAMA,wBAAwB;oBAACO;oBAAWG;gBAAM;YACzEH;YACAW,iBAAiBH,QACb,CAAC,EAACJ,SAASQ,EAAE,EAAC,GAAKvB,uBAAuB;oBAACe,SAASQ;gBAAE,KACtD,CAACC,SAAWjB,sBAAsBiB;YACtCC,UAAUT,OAAOS,QAAQ;YACzBC,UAAUV,OAAOU,QAAQ;YACzBP;YACAN;YACAC;YACAa,iBAAiBrB,uBAAuBK,cAAc;YACtDI;QACF;IACF;IAEA,IAAI;QACF,MAAMa,SAAS,MAAMzB,mBAAmBa;QACxC,OAAOY;IACT,EAAE,OAAOC,KAAK;QACZ,MAAM3B,oBAAoB,WAAWc,OAAOS,QAAQ,EAAET,OAAOU,QAAQ,EAAEG;IACzE;AACF"}
1
+ {"version":3,"sources":["../../../src/actions/preview/previewAction.ts"],"sourcesContent":["import {SANITY_CACHE_DIR} from '@sanity/cli-build/_internal/build'\nimport {extractCoreAppManifest} from '@sanity/cli-build/_internal/manifest'\nimport {type CliConfig, type Output} from '@sanity/cli-core'\nimport {isWorkbenchApp} from '@sanity/workbench-cli'\n\nimport {gracefulServerDeath} from '../../server/gracefulServerDeath.js'\nimport {type PreviewServer, startPreviewServer} from '../../server/previewServer.js'\nimport {checkForDeprecatedAppId} from '../../util/appId.js'\nimport {determineIsApp} from '../../util/determineIsApp.js'\nimport {resolveReactStrictMode} from '../../util/resolveReactStrictMode.js'\nimport {extractStudioManifest} from '../manifest/extractStudioManifest.js'\nimport {getPreviewServerConfig} from './getPreviewServerConfig.js'\nimport {type PreviewFlags} from './types.js'\n\ninterface PreviewActionOptions {\n cliConfig: CliConfig\n flags: PreviewFlags\n outDir: string\n output: Output\n workDir: string\n}\n\nexport async function previewAction(\n options: PreviewActionOptions,\n): Promise<PreviewServer | {close: () => Promise<void>}> {\n const {cliConfig, flags, outDir, output, workDir} = options\n\n const config = getPreviewServerConfig({cliConfig, flags, rootDir: outDir, workDir})\n\n if (isWorkbenchApp(cliConfig?.app)) {\n const isApp = determineIsApp(cliConfig)\n // Lazy so a non-workbench `sanity start` never loads the package. `doImport`\n // is path-based and doesn't apply to a bare specifier.\n // eslint-disable-next-line eslint-js/no-restricted-syntax\n const {startWorkbenchPreview} = await import('@sanity/workbench-cli/preview')\n return startWorkbenchPreview({\n cacheDir: `${SANITY_CACHE_DIR}/vite`,\n checkForDeprecatedAppId: () => checkForDeprecatedAppId({cliConfig, output}),\n cliConfig,\n extractManifest: isApp\n ? ({workDir: wd}) => extractCoreAppManifest({workDir: wd})\n : (params) => extractStudioManifest(params),\n httpHost: config.httpHost,\n httpPort: config.httpPort,\n isApp,\n outDir,\n output,\n reactStrictMode: resolveReactStrictMode(cliConfig) ?? false,\n workDir,\n })\n }\n\n try {\n const server = await startPreviewServer(config)\n return server\n } catch (err) {\n throw gracefulServerDeath('preview', config.httpHost, config.httpPort, err)\n }\n}\n"],"names":["SANITY_CACHE_DIR","extractCoreAppManifest","isWorkbenchApp","gracefulServerDeath","startPreviewServer","checkForDeprecatedAppId","determineIsApp","resolveReactStrictMode","extractStudioManifest","getPreviewServerConfig","previewAction","options","cliConfig","flags","outDir","output","workDir","config","rootDir","app","isApp","startWorkbenchPreview","cacheDir","extractManifest","wd","params","httpHost","httpPort","reactStrictMode","server","err"],"mappings":"AAAA,SAAQA,gBAAgB,QAAO,oCAAmC;AAClE,SAAQC,sBAAsB,QAAO,uCAAsC;AAE3E,SAAQC,cAAc,QAAO,wBAAuB;AAEpD,SAAQC,mBAAmB,QAAO,sCAAqC;AACvE,SAA4BC,kBAAkB,QAAO,gCAA+B;AACpF,SAAQC,uBAAuB,QAAO,sBAAqB;AAC3D,SAAQC,cAAc,QAAO,+BAA8B;AAC3D,SAAQC,sBAAsB,QAAO,uCAAsC;AAC3E,SAAQC,qBAAqB,QAAO,uCAAsC;AAC1E,SAAQC,sBAAsB,QAAO,8BAA6B;AAWlE,OAAO,eAAeC,cACpBC,OAA6B;IAE7B,MAAM,EAACC,SAAS,EAAEC,KAAK,EAAEC,MAAM,EAAEC,MAAM,EAAEC,OAAO,EAAC,GAAGL;IAEpD,MAAMM,SAASR,uBAAuB;QAACG;QAAWC;QAAOK,SAASJ;QAAQE;IAAO;IAEjF,IAAId,eAAeU,WAAWO,MAAM;QAClC,MAAMC,QAAQd,eAAeM;QAC7B,6EAA6E;QAC7E,uDAAuD;QACvD,0DAA0D;QAC1D,MAAM,EAACS,qBAAqB,EAAC,GAAG,MAAM,MAAM,CAAC;QAC7C,OAAOA,sBAAsB;YAC3BC,UAAU,GAAGtB,iBAAiB,KAAK,CAAC;YACpCK,yBAAyB,IAAMA,wBAAwB;oBAACO;oBAAWG;gBAAM;YACzEH;YACAW,iBAAiBH,QACb,CAAC,EAACJ,SAASQ,EAAE,EAAC,GAAKvB,uBAAuB;oBAACe,SAASQ;gBAAE,KACtD,CAACC,SAAWjB,sBAAsBiB;YACtCC,UAAUT,OAAOS,QAAQ;YACzBC,UAAUV,OAAOU,QAAQ;YACzBP;YACAN;YACAC;YACAa,iBAAiBrB,uBAAuBK,cAAc;YACtDI;QACF;IACF;IAEA,IAAI;QACF,MAAMa,SAAS,MAAMzB,mBAAmBa;QACxC,OAAOY;IACT,EAAE,OAAOC,KAAK;QACZ,MAAM3B,oBAAoB,WAAWc,OAAOS,QAAQ,EAAET,OAAOU,QAAQ,EAAEG;IACzE;AACF"}
@@ -38,7 +38,7 @@ const debug = subdebug('skills:state');
38
38
  try {
39
39
  // Loaded lazily so a problem with the `skills` package only affects this
40
40
  // best-effort probe, not every command that imports this module.
41
- // eslint-disable-next-line no-restricted-syntax -- package import, not a file path
41
+ // eslint-disable-next-line eslint-js/no-restricted-syntax -- package import, not a file path
42
42
  const { listSkills } = await import('skills');
43
43
  const result = await listSkills({
44
44
  scope: 'global',
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/skills/readSkillState.ts"],"sourcesContent":["import {subdebug} from '@sanity/cli-core'\nimport {type InstalledSkillInfo} from 'skills'\n\nimport {\n getSkillsCliAgentDisplayName,\n getSkillsCliAgentDisplayNameById,\n isUniversalSkillsCliAgentByEditorName,\n UNIVERSAL_SKILLS_DIR,\n} from '../mcp/editorConfigs.js'\nimport {type Editor} from '../mcp/types.js'\n\nconst debug = subdebug('skills:state')\n\ninterface ReadSkillStateOptions {\n /**\n * Detected editors. Used to credit \"universal\" agents (those that read from\n * the shared `.agents/skills` directory) when the skills live there — see\n * note in `readSkillState`.\n */\n editors: Editor[]\n /** Names of the skills to look up (match the `name` of `listSkills()` entries). */\n skillNames: string[]\n}\n\ninterface SkillState {\n /** Display names of agents that have all of these skills installed globally. */\n installedAgentDisplayNames: Set<string>\n}\n\n/** Upper bound for reading the global skill state (checked between steps). */\nconst LIST_TIMEOUT_MS = 10_000\n\n/** Normalizes path separators to `/` so comparisons are OS-agnostic. */\nfunction toPosixPath(value: string): string {\n return value.replaceAll('\\\\', '/')\n}\n\n/**\n * A skill lives in the shared universal skills directory when its canonical\n * path is under `.agents/skills`. The `skills` CLI installs universal-agent\n * skills there directly (rather than under an agent-specific directory).\n */\nfunction isUniversalSkillPath(skillPath: string): boolean {\n return toPosixPath(skillPath).includes(`${UNIVERSAL_SKILLS_DIR}/`)\n}\n\n/**\n * Lists global skills via the bundled `skills` package's `listSkills` and\n * returns the set of agent display names that have every skill in\n * `skillNames` installed globally.\n * Agents missing any of the skills are excluded, so they get a (idempotent)\n * re-install that fills the gap.\n *\n * \"Universal\" agents (those whose `skillsDir` is the shared `.agents/skills`\n * directory) are credited whenever every requested skill lives in that shared\n * directory. `listSkills` only attributes a skill to agents it independently\n * detects, so a universal editor we detected may be absent from the output even\n * though it reads from the shared directory and already has the skills.\n *\n * Any failure (import, read, timeout) is debug-logged and\n * resolved with an empty set. Callers should treat that as \"treat all agents\n * as not installed\" — re-installing is idempotent, so over-installing is\n * safer than skipping based on a flaky probe.\n */\nexport async function readSkillState(opts: ReadSkillStateOptions): Promise<SkillState> {\n const {editors, skillNames} = opts\n const empty: SkillState = {installedAgentDisplayNames: new Set()}\n\n let entries: readonly InstalledSkillInfo[]\n try {\n // Loaded lazily so a problem with the `skills` package only affects this\n // best-effort probe, not every command that imports this module.\n // eslint-disable-next-line no-restricted-syntax -- package import, not a file path\n const {listSkills} = await import('skills')\n const result = await listSkills({\n scope: 'global',\n signal: AbortSignal.timeout(LIST_TIMEOUT_MS),\n })\n entries = result.skills\n } catch (error) {\n debug('skills list failed: %O', error)\n return empty\n }\n\n const agentSets = skillNames.map((skillName) => {\n const match = entries.find((entry) => entry.name === skillName)\n if (!match) {\n return new Set<string>()\n }\n // `listSkills` reports agent IDs; callers match on display names.\n return new Set(\n match.agents.map((agentId) => getSkillsCliAgentDisplayNameById(agentId) ?? agentId),\n )\n })\n\n const installed = new Set(\n [...(agentSets[0] ?? [])].filter((agent) => agentSets.every((set) => set.has(agent))),\n )\n\n // Universal agents share the `.agents/skills` directory. If every requested\n // skill lives there, credit each detected universal editor — otherwise a\n // detected universal editor that the `skills` CLI didn't independently detect\n // would be treated as missing and trigger a redundant re-install.\n const allSkillsInUniversalDir =\n skillNames.length > 0 &&\n skillNames.every((skillName) => {\n const match = entries.find((entry) => entry.name === skillName)\n return match ? isUniversalSkillPath(match.path) : false\n })\n\n if (allSkillsInUniversalDir) {\n for (const editor of editors) {\n if (!isUniversalSkillsCliAgentByEditorName(editor.name)) continue\n const displayName = getSkillsCliAgentDisplayName(editor.name)\n if (displayName) installed.add(displayName)\n }\n }\n\n return {installedAgentDisplayNames: installed}\n}\n"],"names":["subdebug","getSkillsCliAgentDisplayName","getSkillsCliAgentDisplayNameById","isUniversalSkillsCliAgentByEditorName","UNIVERSAL_SKILLS_DIR","debug","LIST_TIMEOUT_MS","toPosixPath","value","replaceAll","isUniversalSkillPath","skillPath","includes","readSkillState","opts","editors","skillNames","empty","installedAgentDisplayNames","Set","entries","listSkills","result","scope","signal","AbortSignal","timeout","skills","error","agentSets","map","skillName","match","find","entry","name","agents","agentId","installed","filter","agent","every","set","has","allSkillsInUniversalDir","length","path","editor","displayName","add"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,mBAAkB;AAGzC,S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A,IAAIC,GAAG,CAACH;IAG/E,4EAA4E;IAC5E,yEAAyE;IACzE,8EAA8E;IAC9E,kEAAkE;IAClE,MAAMI,0BACJ5B,WAAW6B,MAAM,GAAG,KACpB7B,WAAWyB,KAAK,CAAC,CAACV;QAChB,MAAMC,QAAQZ,QAAQa,IAAI,CAAC,CAACC,QAAUA,MAAMC,IAAI,KAAKJ;QACrD,OAAOC,QAAQtB,qBAAqBsB,MAAMc,IAAI,IAAI;IACpD;IAEF,IAAIF,yBAAyB;QAC3B,KAAK,MAAMG,UAAUhC,QAAS;YAC5B,IAAI,CAACZ,sCAAsC4C,OAAOZ,IAAI,GAAG;YACzD,MAAMa,cAAc/C,6BAA6B8C,OAAOZ,IAAI;YAC5D,IAAIa,aAAaV,UAAUW,GAAG,CAACD;QACjC;IACF;IAEA,OAAO;QAAC9B,4BAA4BoB;IAAS;AAC/C"}
1
+ {"version":3,"sources":["../../../src/actions/skills/readSkillState.ts"],"sourcesContent":["import {subdebug} from '@sanity/cli-core'\nimport {type InstalledSkillInfo} from 'skills'\n\nimport {\n getSkillsCliAgentDisplayName,\n getSkillsCliAgentDisplayNameById,\n isUniversalSkillsCliAgentByEditorName,\n UNIVERSAL_SKILLS_DIR,\n} from '../mcp/editorConfigs.js'\nimport {type Editor} from '../mcp/types.js'\n\nconst debug = subdebug('skills:state')\n\ninterface ReadSkillStateOptions {\n /**\n * Detected editors. Used to credit \"universal\" agents (those that read from\n * the shared `.agents/skills` directory) when the skills live there — see\n * note in `readSkillState`.\n */\n editors: Editor[]\n /** Names of the skills to look up (match the `name` of `listSkills()` entries). */\n skillNames: string[]\n}\n\ninterface SkillState {\n /** Display names of agents that have all of these skills installed globally. */\n installedAgentDisplayNames: Set<string>\n}\n\n/** Upper bound for reading the global skill state (checked between steps). */\nconst LIST_TIMEOUT_MS = 10_000\n\n/** Normalizes path separators to `/` so comparisons are OS-agnostic. */\nfunction toPosixPath(value: string): string {\n return value.replaceAll('\\\\', '/')\n}\n\n/**\n * A skill lives in the shared universal skills directory when its canonical\n * path is under `.agents/skills`. The `skills` CLI installs universal-agent\n * skills there directly (rather than under an agent-specific directory).\n */\nfunction isUniversalSkillPath(skillPath: string): boolean {\n return toPosixPath(skillPath).includes(`${UNIVERSAL_SKILLS_DIR}/`)\n}\n\n/**\n * Lists global skills via the bundled `skills` package's `listSkills` and\n * returns the set of agent display names that have every skill in\n * `skillNames` installed globally.\n * Agents missing any of the skills are excluded, so they get a (idempotent)\n * re-install that fills the gap.\n *\n * \"Universal\" agents (those whose `skillsDir` is the shared `.agents/skills`\n * directory) are credited whenever every requested skill lives in that shared\n * directory. `listSkills` only attributes a skill to agents it independently\n * detects, so a universal editor we detected may be absent from the output even\n * though it reads from the shared directory and already has the skills.\n *\n * Any failure (import, read, timeout) is debug-logged and\n * resolved with an empty set. Callers should treat that as \"treat all agents\n * as not installed\" — re-installing is idempotent, so over-installing is\n * safer than skipping based on a flaky probe.\n */\nexport async function readSkillState(opts: ReadSkillStateOptions): Promise<SkillState> {\n const {editors, skillNames} = opts\n const empty: SkillState = {installedAgentDisplayNames: new Set()}\n\n let entries: readonly InstalledSkillInfo[]\n try {\n // Loaded lazily so a problem with the `skills` package only affects this\n // best-effort probe, not every command that imports this module.\n // eslint-disable-next-line eslint-js/no-restricted-syntax -- package import, not a file path\n const {listSkills} = await import('skills')\n const result = await listSkills({\n scope: 'global',\n signal: AbortSignal.timeout(LIST_TIMEOUT_MS),\n })\n entries = result.skills\n } catch (error) {\n debug('skills list failed: %O', error)\n return empty\n }\n\n const agentSets = skillNames.map((skillName) => {\n const match = entries.find((entry) => entry.name === skillName)\n if (!match) {\n return new Set<string>()\n }\n // `listSkills` reports agent IDs; callers match on display names.\n return new Set(\n match.agents.map((agentId) => getSkillsCliAgentDisplayNameById(agentId) ?? agentId),\n )\n })\n\n const installed = new Set(\n [...(agentSets[0] ?? [])].filter((agent) => agentSets.every((set) => set.has(agent))),\n )\n\n // Universal agents share the `.agents/skills` directory. If every requested\n // skill lives there, credit each detected universal editor — otherwise a\n // detected universal editor that the `skills` CLI didn't independently detect\n // would be treated as missing and trigger a redundant re-install.\n const allSkillsInUniversalDir =\n skillNames.length > 0 &&\n skillNames.every((skillName) => {\n const match = entries.find((entry) => entry.name === skillName)\n return match ? isUniversalSkillPath(match.path) : false\n })\n\n if (allSkillsInUniversalDir) {\n for (const editor of editors) {\n if (!isUniversalSkillsCliAgentByEditorName(editor.name)) continue\n const displayName = getSkillsCliAgentDisplayName(editor.name)\n if (displayName) installed.add(displayName)\n }\n }\n\n return {installedAgentDisplayNames: installed}\n}\n"],"names":["subdebug","getSkillsCliAgentDisplayName","getSkillsCliAgentDisplayNameById","isUniversalSkillsCliAgentByEditorName","UNIVERSAL_SKILLS_DIR","debug","LIST_TIMEOUT_MS","toPosixPath","value","replaceAll","isUniversalSkillPath","skillPath","includes","readSkillState","opts","editors","skillNames","empty","installedAgentDisplayNames","Set","entries","listSkills","result","scope","signal","AbortSignal","timeout","skills","error","agentSets","map","skillName","match","find","entry","name","agents","agentId","installed","filter","agent","every","set","has","allSkillsInUniversalDir","length","path","editor","displayName","add"],"mappings":"AAAA,SAAQA,QAAQ,QAAO,mBAAkB;AAGzC,SACEC,4BAA4B,EAC5BC,gCAAgC,EAChCC,qCAAqC,EACrCC,oBAAoB,QACf,0BAAyB;AAGhC,MAAMC,QAAQL,SAAS;AAkBvB,4EAA4E,GAC5E,MAAMM,kBAAkB;AAExB,sEAAsE,GACtE,SAASC,YAAYC,KAAa;IAChC,OAAOA,MAAMC,UAAU,CAAC,MAAM;AAChC;AAEA;;;;CAIC,GACD,SAASC,qBAAqBC,SAAiB;IAC7C,OAAOJ,YAAYI,WAAWC,QAAQ,CAAC,GAAGR,qBAAqB,CAAC,CAAC;AACnE;AAEA;;;;;;;;;;;;;;;;;CAiBC,GACD,OAAO,eAAeS,eAAeC,IAA2B;IAC9D,MAAM,EAACC,OAAO,EAAEC,UAAU,EAAC,GAAGF;IAC9B,MAAMG,QAAoB;QAACC,4BAA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C;IACF;IAEA,OAAO;QAAC9B,4BAA4BoB;IAAS;AAC/C"}
@@ -68,7 +68,7 @@ const skillsDebug = subdebug('skills:setup');
68
68
  try {
69
69
  // Loaded lazily so a problem with the `skills` package only affects this
70
70
  // best-effort step, not every command that imports this module.
71
- // eslint-disable-next-line no-restricted-syntax -- package import, not a file path
71
+ // eslint-disable-next-line eslint-js/no-restricted-syntax -- package import, not a file path
72
72
  const { installSkills } = await import('skills');
73
73
  const result = await installSkills(SANITY_SKILLS_REPO, {
74
74
  agents: uniqueAgents,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/actions/skills/setupSkills.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {type Output, subdebug} from '@sanity/cli-core'\nimport {getErrorMessage, toError} from '@sanity/cli-core/errors'\nimport {logSymbols, spinner} from '@sanity/cli-core/ux'\n\nimport {\n getSkillsCliAgentDisplayNameById,\n getSkillsCliAgentSkillsDir,\n UNIVERSAL_SKILLS_DIR,\n} from '../mcp/editorConfigs.js'\n\nconst skillsDebug = subdebug('skills:setup')\n\n/** Source repo for the bundled `skills` package. See https://www.sanity.io/docs/ai/skills. */\nexport const SANITY_SKILLS_REPO = 'sanity-io/agent-toolkit'\n\n/** Names of the skills we install — must match the entries in the source repo. */\nexport const SANITY_SKILL_NAMES = ['sanity-best-practices', 'sanity-migration']\n\n/** Upper bound for fetching and installing the skills (checked between steps). */\nconst INSTALL_TIMEOUT_MS = 90_000\n\ninterface SetupSkillsOptions {\n /** Skills-CLI agent IDs (e.g. 'cursor', 'claude-code') to install for. */\n agents: string[]\n\n /**\n * Output to use for user-facing messages, so they go through the calling\n * command rather than directly to stdout/stderr.\n */\n output: Output\n}\n\ninterface SetupSkillsResult {\n /** Deduplicated agent IDs the skills were installed for. */\n installedAgents: string[]\n skipped: boolean\n\n error?: Error\n}\n\n/**\n * Prints a short summary beneath the success line: the skills that were\n * installed, grouped by where they live. Universal agents share\n * `~/.agents/skills`, so they're listed together under one header; any agent\n * with its own directory (e.g. Claude Code) is listed separately with its\n * location. Global (`-g`) installs are home-anchored, so locations show `~/`.\n */\nfunction printInstallSummary(agents: string[], output: Output): void {\n const universal: string[] = []\n const additional: {dir: string; name: string}[] = []\n\n for (const agent of agents) {\n const name = getSkillsCliAgentDisplayNameById(agent) ?? agent\n const dir = getSkillsCliAgentSkillsDir(agent)\n if (dir && dir !== UNIVERSAL_SKILLS_DIR) {\n additional.push({dir, name})\n } else {\n universal.push(name)\n }\n }\n\n if (universal.length > 0) {\n output.log('')\n output.log(styleText('dim', ` Universal (~/${UNIVERSAL_SKILLS_DIR})`))\n output.log(styleText('dim', ` ${universal.join(', ')}`))\n }\n\n if (additional.length > 0) {\n output.log('')\n output.log(styleText('dim', ' Additional agents'))\n for (const {dir, name} of additional) {\n output.log(styleText('dim', ` ${name} (~/${dir})`))\n }\n }\n output.log('')\n}\n\n/**\n * Installs the Sanity skills globally for the given agents using the bundled\n * `skills` package's programmatic API (equivalent to\n * `skills add <repo> --skill <names> -g -a <agent>... -y`). Failures are\n * surfaced as warnings and never throw — skills install is best-effort and\n * must not abort `sanity init`.\n */\nexport async function setupSkills(options: SetupSkillsOptions): Promise<SetupSkillsResult> {\n const {output} = options\n const uniqueAgents = [...new Set(options.agents)]\n\n if (uniqueAgents.length === 0) {\n skillsDebug('No agents passed — skipping skills install')\n return {installedAgents: [], skipped: true}\n }\n\n skillsDebug(\n 'Installing %s from %s globally for agents: %s',\n SANITY_SKILL_NAMES.join(', '),\n SANITY_SKILLS_REPO,\n uniqueAgents.join(', '),\n )\n\n const spin = spinner('Installing Sanity agent skills').start()\n\n try {\n // Loaded lazily so a problem with the `skills` package only affects this\n // best-effort step, not every command that imports this module.\n // eslint-disable-next-line no-restricted-syntax -- package import, not a file path\n const {installSkills} = await import('skills')\n const result = await installSkills(SANITY_SKILLS_REPO, {\n agents: uniqueAgents,\n onWarning: (warning) => skillsDebug('skills warning: %s', warning.message),\n scope: 'global',\n signal: AbortSignal.timeout(INSTALL_TIMEOUT_MS),\n skills: SANITY_SKILL_NAMES,\n })\n skillsDebug('skills install result: %O', result)\n spin.stop()\n\n const failedAgents = new Set(result.failed.map((failure) => failure.agent))\n const installedAgents = uniqueAgents.filter((agent) => !failedAgents.has(agent))\n\n if (installedAgents.length > 0) {\n output.log(\n `${logSymbols.success} Sanity agent skills installed: [${SANITY_SKILL_NAMES.join(', ')}]`,\n )\n printInstallSummary(installedAgents, output)\n }\n\n if (result.failed.length === 0) {\n return {installedAgents, skipped: false}\n }\n\n const failureMessages = result.failed.map((failure) => failure.message)\n output.warn(\n installedAgents.length > 0\n ? 'Could not install Sanity agent skills for some agents:'\n : 'Could not install Sanity agent skills:',\n )\n for (const message of failureMessages) output.warn(message)\n return {error: new Error(failureMessages.join('\\n')), installedAgents, skipped: false}\n } catch (error) {\n skillsDebug('Error installing skills %O', error)\n const err = toError(error)\n spin.stop()\n output.warn(`Could not install Sanity agent skills: ${getErrorMessage(error)}`)\n const fix = (error as {fix?: unknown} | null)?.fix\n if (typeof fix === 'string' && fix) output.warn(fix)\n return {error: err, installedAgents: [], skipped: false}\n }\n}\n"],"names":["styleText","subdebug","getErrorMessage","toError","logSymbols","spinner","getSkillsCliAgentDisplayNameById","getSkillsCliAgentSkillsDir","UNIVERSAL_SKILLS_DIR","skillsDebug","SANITY_SKILLS_REPO","SANITY_SKILL_NAMES","INSTALL_TIMEOUT_MS","printInstallSummary","agents","output","universal","additional","agent","name","dir","push","length","log","join","setupSkills","options","uniqueAgents","Set","installedAgents","skipped","spin","start","installSkills","result","onWarning","warning","message","scope","signal","AbortSignal","timeout","skills","stop","failedAgents","failed","map","failure","filter","has","success","failureMessages","warn","error","Error","err","fix"],"mappings":"AAAA,SAAQA,SAAS,QAAO,YAAW;AAEnC,SAAqBC,QAAQ,QAAO,mBAAkB;AACtD,SAAQC,eAAe,EAAEC,OAAO,QAAO,0BAAyB;AAChE,SAAQC,UAAU,EAAEC,OAAO,QAAO,sBAAqB;AAEvD,SACEC,gCAAgC,E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M,GAAG,IACrB,2DACA;QAEN,KAAK,MAAMe,WAAWc,gBAAiBpC,OAAOqC,IAAI,CAACf;QACnD,OAAO;YAACgB,OAAO,IAAIC,MAAMH,gBAAgB3B,IAAI,CAAC;YAAQK;YAAiBC,SAAS;QAAK;IACvF,EAAE,OAAOuB,OAAO;QACd5C,YAAY,8BAA8B4C;QAC1C,MAAME,MAAMpD,QAAQkD;QACpBtB,KAAKY,IAAI;QACT5B,OAAOqC,IAAI,CAAC,CAAC,uCAAuC,EAAElD,gBAAgBmD,QAAQ;QAC9E,MAAMG,MAAOH,OAAkCG;QAC/C,IAAI,OAAOA,QAAQ,YAAYA,KAAKzC,OAAOqC,IAAI,CAACI;QAChD,OAAO;YAACH,OAAOE;YAAK1B,iBAAiB,EAAE;YAAEC,SAAS;QAAK;IACzD;AACF"}
1
+ {"version":3,"sources":["../../../src/actions/skills/setupSkills.ts"],"sourcesContent":["import {styleText} from 'node:util'\n\nimport {type Output, subdebug} from '@sanity/cli-core'\nimport {getErrorMessage, toError} from '@sanity/cli-core/errors'\nimport {logSymbols, spinner} from '@sanity/cli-core/ux'\n\nimport {\n getSkillsCliAgentDisplayNameById,\n getSkillsCliAgentSkillsDir,\n UNIVERSAL_SKILLS_DIR,\n} from '../mcp/editorConfigs.js'\n\nconst skillsDebug = subdebug('skills:setup')\n\n/** Source repo for the bundled `skills` package. See https://www.sanity.io/docs/ai/skills. */\nexport const SANITY_SKILLS_REPO = 'sanity-io/agent-toolkit'\n\n/** Names of the skills we install — must match the entries in the source repo. */\nexport const SANITY_SKILL_NAMES = ['sanity-best-practices', 'sanity-migration']\n\n/** Upper bound for fetching and installing the skills (checked between steps). */\nconst INSTALL_TIMEOUT_MS = 90_000\n\ninterface SetupSkillsOptions {\n /** Skills-CLI agent IDs (e.g. 'cursor', 'claude-code') to install for. */\n agents: string[]\n\n /**\n * Output to use for user-facing messages, so they go through the calling\n * command rather than directly to stdout/stderr.\n */\n output: Output\n}\n\ninterface SetupSkillsResult {\n /** Deduplicated agent IDs the skills were installed for. */\n installedAgents: string[]\n skipped: boolean\n\n error?: Error\n}\n\n/**\n * Prints a short summary beneath the success line: the skills that were\n * installed, grouped by where they live. Universal agents share\n * `~/.agents/skills`, so they're listed together under one header; any agent\n * with its own directory (e.g. Claude Code) is listed separately with its\n * location. Global (`-g`) installs are home-anchored, so locations show `~/`.\n */\nfunction printInstallSummary(agents: string[], output: Output): void {\n const universal: string[] = []\n const additional: {dir: string; name: string}[] = []\n\n for (const agent of agents) {\n const name = getSkillsCliAgentDisplayNameById(agent) ?? agent\n const dir = getSkillsCliAgentSkillsDir(agent)\n if (dir && dir !== UNIVERSAL_SKILLS_DIR) {\n additional.push({dir, name})\n } else {\n universal.push(name)\n }\n }\n\n if (universal.length > 0) {\n output.log('')\n output.log(styleText('dim', ` Universal (~/${UNIVERSAL_SKILLS_DIR})`))\n output.log(styleText('dim', ` ${universal.join(', ')}`))\n }\n\n if (additional.length > 0) {\n output.log('')\n output.log(styleText('dim', ' Additional agents'))\n for (const {dir, name} of additional) {\n output.log(styleText('dim', ` ${name} (~/${dir})`))\n }\n }\n output.log('')\n}\n\n/**\n * Installs the Sanity skills globally for the given agents using the bundled\n * `skills` package's programmatic API (equivalent to\n * `skills add <repo> --skill <names> -g -a <agent>... -y`). Failures are\n * surfaced as warnings and never throw — skills install is best-effort and\n * must not abort `sanity init`.\n */\nexport async function setupSkills(options: SetupSkillsOptions): Promise<SetupSkillsResult> {\n const {output} = options\n const uniqueAgents = [...new Set(options.agents)]\n\n if (uniqueAgents.length === 0) {\n skillsDebug('No agents passed — skipping skills install')\n return {installedAgents: [], skipped: true}\n }\n\n skillsDebug(\n 'Installing %s from %s globally for agents: %s',\n SANITY_SKILL_NAMES.join(', '),\n SANITY_SKILLS_REPO,\n uniqueAgents.join(', '),\n )\n\n const spin = spinner('Installing Sanity agent skills').start()\n\n try {\n // Loaded lazily so a problem with the `skills` package only affects this\n // best-effort step, not every command that imports this module.\n // eslint-disable-next-line eslint-js/no-restricted-syntax -- package import, not a file path\n const {installSkills} = await import('skills')\n const result = await installSkills(SANITY_SKILLS_REPO, {\n agents: uniqueAgents,\n onWarning: (warning) => skillsDebug('skills warning: %s', warning.message),\n scope: 'global',\n signal: AbortSignal.timeout(INSTALL_TIMEOUT_MS),\n skills: SANITY_SKILL_NAMES,\n })\n skillsDebug('skills install result: %O', result)\n spin.stop()\n\n const failedAgents = new Set(result.failed.map((failure) => failure.agent))\n const installedAgents = uniqueAgents.filter((agent) => !failedAgents.has(agent))\n\n if (installedAgents.length > 0) {\n output.log(\n `${logSymbols.success} Sanity agent skills installed: [${SANITY_SKILL_NAMES.join(', ')}]`,\n )\n printInstallSummary(installedAgents, output)\n }\n\n if (result.failed.length === 0) {\n return {installedAgents, skipped: false}\n }\n\n const failureMessages = result.failed.map((failure) => failure.message)\n output.warn(\n installedAgents.length > 0\n ? 'Could not install Sanity agent skills for some agents:'\n : 'Could not install Sanity agent skills:',\n )\n for (const message of failureMessages) output.warn(message)\n return {error: new Error(failureMessages.join('\\n')), installedAgents, skipped: false}\n } catch (error) {\n skillsDebug('Error installing skills %O', error)\n const err = toError(error)\n spin.stop()\n output.warn(`Could not install Sanity agent skills: ${getErrorMessage(error)}`)\n const fix = (error as {fix?: unknown} | null)?.fix\n if (typeof fix === 'string' && fix) output.warn(fix)\n return {error: err, installedAgents: [], skipped: false}\n }\n}\n"],"names":["styleText","subdebug","getErrorMessage","toError","logSymbols","spinner","getSkillsCliAgentDisplayNameById","getSkillsCliAgentSkillsDir","UNIVERSAL_SKILLS_DIR","skillsDebug","SANITY_SKILLS_REPO","SANITY_SKILL_NAMES","INSTALL_TIMEOUT_MS","printInstallSummary","agents","output","universal","additional","agent","name","dir","push","length","log","join","setupSkills","options","uniqueAgents","Set","installedAgents","skipped","spin","start","installSkills","result","onWarning","warning","message","scope","signal","AbortSignal","timeout","skills","stop","failedAgents","failed","map","failure","filter","has","success","failureMessages","warn","error","Error","err","fix"],"mappings":"AAAA,SAAQA,SAA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B,OAAO;gBAACO;gBAAiBC,SAAS;YAAK;QACzC;QAEA,MAAMqB,kBAAkBjB,OAAOW,MAAM,CAACC,GAAG,CAAC,CAACC,UAAYA,QAAQV,OAAO;QACtEtB,OAAOqC,IAAI,CACTvB,gBAAgBP,MAAM,GAAG,IACrB,2DACA;QAEN,KAAK,MAAMe,WAAWc,gBAAiBpC,OAAOqC,IAAI,CAACf;QACnD,OAAO;YAACgB,OAAO,IAAIC,MAAMH,gBAAgB3B,IAAI,CAAC;YAAQK;YAAiBC,SAAS;QAAK;IACvF,EAAE,OAAOuB,OAAO;QACd5C,YAAY,8BAA8B4C;QAC1C,MAAME,MAAMpD,QAAQkD;QACpBtB,KAAKY,IAAI;QACT5B,OAAOqC,IAAI,CAAC,CAAC,uCAAuC,EAAElD,gBAAgBmD,QAAQ;QAC9E,MAAMG,MAAOH,OAAkCG;QAC/C,IAAI,OAAOA,QAAQ,YAAYA,KAAKzC,OAAOqC,IAAI,CAACI;QAChD,OAAO;YAACH,OAAOE;YAAK1B,iBAAiB,EAAE;YAAEC,SAAS;QAAK;IACzD;AACF"}
@@ -3,9 +3,10 @@ import { exitCodes, SanityCommand, subdebug } from '@sanity/cli-core';
3
3
  import { getErrorMessage } from '@sanity/cli-core/errors';
4
4
  import { requiredWhenUnattended } from '@sanity/cli-core/flags';
5
5
  import { spinner } from '@sanity/cli-core/ux';
6
+ import { readOrganizationLogo } from '../../actions/organizations/readOrganizationLogo.js';
6
7
  import { validateOrganizationName } from '../../actions/organizations/validateOrganizationName.js';
7
8
  import { promptForOrganizationName } from '../../prompts/promptForOrganizationName.js';
8
- import { createOrganization } from '../../services/organizations.js';
9
+ import { createOrganization, setOrganizationLogo } from '../../services/organizations.js';
9
10
  import { organizationAliases } from '../../util/organizationAliases.js';
10
11
  import { defineCommandTelemetry } from '../../util/telemetry/commandTelemetry.js';
11
12
  const createOrgDebug = subdebug('organizations:create');
@@ -23,6 +24,10 @@ export class CreateOrganizationCommand extends SanityCommand {
23
24
  {
24
25
  command: '<%= config.bin %> <%= command.id %> --name "Acme Corp" --default-role member',
25
26
  description: 'Create an organization with a default member role'
27
+ },
28
+ {
29
+ command: '<%= config.bin %> <%= command.id %> --name "Acme Corp" --logo ./logo.png',
30
+ description: 'Create an organization with a logo'
26
31
  }
27
32
  ];
28
33
  static flags = {
@@ -30,6 +35,11 @@ export class CreateOrganizationCommand extends SanityCommand {
30
35
  description: 'Default role assigned to new members',
31
36
  required: false
32
37
  }),
38
+ logo: Flags.string({
39
+ description: 'Image file to use as the logo: PNG, JPEG, GIF, WebP, SVG, BMP, TIFF, HEIF or AVIF, at most 5 MB',
40
+ helpValue: '<path>',
41
+ required: false
42
+ }),
33
43
  name: requiredWhenUnattended(Flags.string({
34
44
  description: 'Organization name'
35
45
  }))
@@ -37,17 +47,33 @@ export class CreateOrganizationCommand extends SanityCommand {
37
47
  static hiddenAliases = organizationAliases('create');
38
48
  static telemetry = defineCommandTelemetry(this.flags, {
39
49
  redact: [
50
+ 'logo',
40
51
  'name'
41
52
  ]
42
53
  });
43
54
  async run() {
44
- const { 'default-role': defaultRoleFlag, name: nameFlag } = this.flags;
55
+ const { 'default-role': defaultRoleFlag, logo: logoPath, name: nameFlag } = this.flags;
45
56
  const defaultRole = defaultRoleFlag?.trim();
46
57
  if (defaultRole === '') {
47
58
  this.error('Default role cannot be empty', {
48
59
  exit: exitCodes.RUNTIME_ERROR
49
60
  });
50
61
  }
62
+ // Read the logo before creating anything, so a bad file doesn't leave an organization without it.
63
+ let logo;
64
+ if (logoPath === '') {
65
+ this.error('--logo needs the path to an image file. To create the organization without a logo, leave out --logo.', {
66
+ exit: exitCodes.RUNTIME_ERROR
67
+ });
68
+ } else if (logoPath !== undefined) {
69
+ try {
70
+ logo = await readOrganizationLogo(logoPath);
71
+ } catch (error) {
72
+ this.error(getErrorMessage(error), {
73
+ exit: exitCodes.RUNTIME_ERROR
74
+ });
75
+ }
76
+ }
51
77
  let name;
52
78
  if (nameFlag === undefined) {
53
79
  name = await promptForOrganizationName();
@@ -62,8 +88,9 @@ export class CreateOrganizationCommand extends SanityCommand {
62
88
  name = trimmedName;
63
89
  }
64
90
  const spin = spinner('Creating organization').start();
91
+ let org;
65
92
  try {
66
- const org = await createOrganization(name, defaultRole);
93
+ org = await createOrganization(name, defaultRole);
67
94
  spin.succeed('Organization created');
68
95
  this.log(`ID: ${org.id}`);
69
96
  this.log(`Name: ${org.name}`);
@@ -74,6 +101,19 @@ export class CreateOrganizationCommand extends SanityCommand {
74
101
  exit: exitCodes.RUNTIME_ERROR
75
102
  });
76
103
  }
104
+ if (!logo) return;
105
+ const logoSpin = spinner('Setting logo').start();
106
+ try {
107
+ const { logoUrl } = await setOrganizationLogo(org.id, logo);
108
+ logoSpin.succeed();
109
+ this.log(`Logo: ${logoUrl}`);
110
+ } catch (error) {
111
+ logoSpin.fail();
112
+ createOrgDebug('Error setting organization logo', error);
113
+ this.error(`The organization was created, but its logo wasn't set: ${getErrorMessage(error)}\nTo try again, run: ${this.config.bin} organizations update ${org.id} --logo "${logoPath}"`, {
114
+ exit: exitCodes.RUNTIME_ERROR
115
+ });
116
+ }
77
117
  }
78
118
  }
79
119
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/commands/organizations/create.ts"],"sourcesContent":["import {Flags} from '@oclif/core'\nimport {type FlagInput} from '@oclif/core/interfaces'\nimport {exitCodes, SanityCommand, subdebug} from '@sanity/cli-core'\nimport {getErrorMessage} from '@sanity/cli-core/errors'\nimport {requiredWhenUnattended} from '@sanity/cli-core/flags'\nimport {spinner} from '@sanity/cli-core/ux'\n\nimport {validateOrganizationName} from '../../actions/organizations/validateOrganizationName.js'\nimport {promptForOrganizationName} from '../../prompts/promptForOrganizationName.js'\nimport {createOrganization} from '../../services/organizations.js'\nimport {organizationAliases} from '../../util/organizationAliases.js'\nimport {defineCommandTelemetry} from '../../util/telemetry/commandTelemetry.js'\n\nconst createOrgDebug = subdebug('organizations:create')\n\nexport class CreateOrganizationCommand extends SanityCommand<typeof CreateOrganizationCommand> {\n static override description = 'Create a new organization'\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %>',\n description: 'Interactively create an organization',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --name \"Acme Corp\"',\n description: 'Create an organization named \"Acme Corp\"',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --name \"Acme Corp\" --default-role member',\n description: 'Create an organization with a default member role',\n },\n ]\n\n static override flags = {\n 'default-role': Flags.string({\n description: 'Default role assigned to new members',\n required: false,\n }),\n name: requiredWhenUnattended(\n Flags.string({\n description: 'Organization name',\n }),\n ),\n } satisfies FlagInput\n\n static override hiddenAliases = organizationAliases('create')\n\n static telemetry = defineCommandTelemetry(this.flags, {redact: ['name']})\n\n public async run(): Promise<void> {\n const {'default-role': defaultRoleFlag, name: nameFlag} = this.flags\n\n const defaultRole = defaultRoleFlag?.trim()\n if (defaultRole === '') {\n this.error('Default role cannot be empty', {exit: exitCodes.RUNTIME_ERROR})\n }\n\n let name: string\n if (nameFlag === undefined) {\n name = await promptForOrganizationName()\n } else {\n const trimmedName = nameFlag.trim()\n const validation = validateOrganizationName(trimmedName)\n if (validation !== true) {\n this.error(validation, {exit: exitCodes.RUNTIME_ERROR})\n }\n name = trimmedName\n }\n\n const spin = spinner('Creating organization').start()\n try {\n const org = await createOrganization(name, defaultRole)\n spin.succeed('Organization created')\n this.log(`ID: ${org.id}`)\n this.log(`Name: ${org.name}`)\n } catch (error) {\n spin.fail()\n createOrgDebug('Error creating organization', error)\n this.error(`Failed to create organization: ${getErrorMessage(error)}`, {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n }\n}\n"],"names":["Flags","exitCodes","SanityCommand","subdebug","getErrorMessage","requiredWhenUnattended","spinner","validateOrganizationName","promptForOrganizationName","createOrganization","organizationAliases","defineCommandTelemetry","createOrgDebug","CreateOrganizationCommand","description","examples","command","flags","string","required","name","hiddenAliases","telemetry","redact","run","defaultRoleFlag","nameFlag","defaultRole","trim","error","exit","RUNTIME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,WAAW;YAC1BZ,OAAO,MAAMZ;QACf,OAAO;YACL,MAAMyB,cAAcP,SAASE,IAAI;YACjC,MAAMM,aAAa3B,yBAAyB0B;YAC5C,IAAIC,eAAe,MAAM;gBACvB,IAAI,CAACL,KAAK,CAACK,YAAY;oBAACJ,MAAM7B,UAAU8B,aAAa;gBAAA;YACvD;YACAX,OAAOa;QACT;QAEA,MAAME,OAAO7B,QAAQ,yBAAyB8B,KAAK;QACnD,IAAI;YACF,MAAMC,MAAM,MAAM5B,mBAAmBW,MAAMO;YAC3CQ,KAAKG,OAAO,CAAC;YACb,IAAI,CAACC,GAAG,CAAC,CAAC,MAAM,EAAEF,IAAIG,EAAE,EAAE;YAC1B,IAAI,CAACD,GAAG,CAAC,CAAC,MAAM,EAAEF,IAAIjB,IAAI,EAAE;QAC9B,EAAE,OAAOS,OAAO;YACdM,KAAKM,IAAI;YACT7B,eAAe,+BAA+BiB;YAC9C,IAAI,CAACA,KAAK,CAAC,CAAC,+BAA+B,EAAEzB,gBAAgByB,QAAQ,EAAE;gBACrEC,MAAM7B,UAAU8B,aAAa;YAC/B;QACF;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/commands/organizations/create.ts"],"sourcesContent":["import {Flags} from '@oclif/core'\nimport {type FlagInput} from '@oclif/core/interfaces'\nimport {exitCodes, SanityCommand, subdebug} from '@sanity/cli-core'\nimport {getErrorMessage} from '@sanity/cli-core/errors'\nimport {requiredWhenUnattended} from '@sanity/cli-core/flags'\nimport {spinner} from '@sanity/cli-core/ux'\n\nimport {\n type OrganizationLogo,\n readOrganizationLogo,\n} from '../../actions/organizations/readOrganizationLogo.js'\nimport {validateOrganizationName} from '../../actions/organizations/validateOrganizationName.js'\nimport {promptForOrganizationName} from '../../prompts/promptForOrganizationName.js'\nimport {\n createOrganization,\n type OrganizationCreateResponse,\n setOrganizationLogo,\n} from '../../services/organizations.js'\nimport {organizationAliases} from '../../util/organizationAliases.js'\nimport {defineCommandTelemetry} from '../../util/telemetry/commandTelemetry.js'\n\nconst createOrgDebug = subdebug('organizations:create')\n\nexport class CreateOrganizationCommand extends SanityCommand<typeof CreateOrganizationCommand> {\n static override description = 'Create a new organization'\n\n static override examples = [\n {\n command: '<%= config.bin %> <%= command.id %>',\n description: 'Interactively create an organization',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --name \"Acme Corp\"',\n description: 'Create an organization named \"Acme Corp\"',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --name \"Acme Corp\" --default-role member',\n description: 'Create an organization with a default member role',\n },\n {\n command: '<%= config.bin %> <%= command.id %> --name \"Acme Corp\" --logo ./logo.png',\n description: 'Create an organization with a logo',\n },\n ]\n\n static override flags = {\n 'default-role': Flags.string({\n description: 'Default role assigned to new members',\n required: false,\n }),\n logo: Flags.string({\n description:\n 'Image file to use as the logo: PNG, JPEG, GIF, WebP, SVG, BMP, TIFF, HEIF or AVIF, at most 5 MB',\n helpValue: '<path>',\n required: false,\n }),\n name: requiredWhenUnattended(\n Flags.string({\n description: 'Organization name',\n }),\n ),\n } satisfies FlagInput\n\n static override hiddenAliases = organizationAliases('create')\n\n static telemetry = defineCommandTelemetry(this.flags, {redact: ['logo', 'name']})\n\n public async run(): Promise<void> {\n const {'default-role': defaultRoleFlag, logo: logoPath, name: nameFlag} = this.flags\n\n const defaultRole = defaultRoleFlag?.trim()\n if (defaultRole === '') {\n this.error('Default role cannot be empty', {exit: exitCodes.RUNTIME_ERROR})\n }\n\n // Read the logo before creating anything, so a bad file doesn't leave an organization without it.\n let logo: OrganizationLogo | undefined\n if (logoPath === '') {\n this.error(\n '--logo needs the path to an image file. To create the organization without a logo, leave out --logo.',\n {exit: exitCodes.RUNTIME_ERROR},\n )\n } else if (logoPath !== undefined) {\n try {\n logo = await readOrganizationLogo(logoPath)\n } catch (error) {\n this.error(getErrorMessage(error), {exit: exitCodes.RUNTIME_ERROR})\n }\n }\n\n let name: string\n if (nameFlag === undefined) {\n name = await promptForOrganizationName()\n } else {\n const trimmedName = nameFlag.trim()\n const validation = validateOrganizationName(trimmedName)\n if (validation !== true) {\n this.error(validation, {exit: exitCodes.RUNTIME_ERROR})\n }\n name = trimmedName\n }\n\n const spin = spinner('Creating organization').start()\n let org: OrganizationCreateResponse\n try {\n org = await createOrganization(name, defaultRole)\n spin.succeed('Organization created')\n this.log(`ID: ${org.id}`)\n this.log(`Name: ${org.name}`)\n } catch (error) {\n spin.fail()\n createOrgDebug('Error creating organization', error)\n this.error(`Failed to create organization: ${getErrorMessage(error)}`, {\n exit: exitCodes.RUNTIME_ERROR,\n })\n }\n\n if (!logo) return\n\n const logoSpin = spinner('Setting logo').start()\n try {\n const {logoUrl} = await setOrganizationLogo(org.id, logo)\n logoSpin.succeed()\n this.log(`Logo: ${logoUrl}`)\n } catch (error) {\n logoSpin.fail()\n createOrgDebug('Error setting organization logo', error)\n this.error(\n `The organization was created, but its logo wasn't set: ${getErrorMessage(error)}\\nTo try again, run: ${this.config.bin} organizations update ${org.id} --logo \"${logoPath}\"`,\n {exit: exitCodes.RUNTIME_ERROR},\n )\n }\n }\n}\n"],"names":["Flags","exitCodes","SanityCommand","subdebug","getErrorMessage","requiredWhenUnattended","spinner","readOrganizationLogo","validateOrganizationName","promptForOrganizationName","createOrganization","setOrganizationLogo","organizationAliases","defineCommandTelemetry","createOrgDebug","CreateOrganizationCommand","description","examples","command","flags","string","required","logo","helpValue","name","hiddenAliases","telemetry","redact","run","defaultRoleFlag","logoPath","nameFlag","defaultRole","trim","error","exit","RUNTIME_ERROR","undefined","trimmedName","validation","spin","start","org","succeed","log","id","fail","logoSpin","logoUrl","config","bin"],"mappings":"AAAA,SAAQA,KAAK,QAAO,cAAa;AAEjC,SAAQC,SAAS,EAAEC,aAAa,EAAEC,QAAQ,QAAO,mBAAkB;AACnE,SAAQC,eAAe,QAAO,0BAAyB;AACvD,SAAQC,sBAAsB,QAAO,yBAAwB;AAC7D,SAAQC,OAAO,QAAO,sBAAqB;AAE3C,SAEEC,oBAAoB,QACf,sDAAqD;AAC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AClD,IAAI,CAACA,KAAK,CACR,CAAC,uDAAuD,EAAE9B,gBAAgB8B,OAAO,qBAAqB,EAAE,IAAI,CAACe,MAAM,CAACC,GAAG,CAAC,sBAAsB,EAAER,IAAIG,EAAE,CAAC,SAAS,EAAEf,SAAS,CAAC,CAAC,EAC7K;gBAACK,MAAMlC,UAAUmC,aAAa;YAAA;QAElC;IACF;AACF"}
@@ -3,16 +3,18 @@ import { exitCodes, SanityCommand, subdebug } from '@sanity/cli-core';
3
3
  import { getErrorMessage } from '@sanity/cli-core/errors';
4
4
  import { spinner } from '@sanity/cli-core/ux';
5
5
  import { isHttpError } from '@sanity/client';
6
+ import { readOrganizationLogo } from '../../actions/organizations/readOrganizationLogo.js';
6
7
  import { validateOrganizationName } from '../../actions/organizations/validateOrganizationName.js';
7
8
  import { validateOrganizationSlug } from '../../actions/organizations/validateOrganizationSlug.js';
8
- import { updateOrganization } from '../../services/organizations.js';
9
+ import { removeOrganizationLogo, setOrganizationLogo, updateOrganization } from '../../services/organizations.js';
9
10
  import { organizationAliases } from '../../util/organizationAliases.js';
10
11
  import { defineCommandTelemetry } from '../../util/telemetry/commandTelemetry.js';
11
12
  const updateOrgDebug = subdebug('organizations:update');
12
13
  const UPDATE_FLAGS = [
13
14
  'name',
14
15
  'slug',
15
- 'default-role'
16
+ 'default-role',
17
+ 'logo'
16
18
  ];
17
19
  export class UpdateOrganizationCommand extends SanityCommand {
18
20
  static args = {
@@ -34,6 +36,14 @@ export class UpdateOrganizationCommand extends SanityCommand {
34
36
  {
35
37
  command: '<%= config.bin %> <%= command.id %> org-abc123 --default-role viewer',
36
38
  description: 'Change the default member role'
39
+ },
40
+ {
41
+ command: '<%= config.bin %> <%= command.id %> org-abc123 --logo ./logo.png',
42
+ description: 'Set or replace the organization logo'
43
+ },
44
+ {
45
+ command: '<%= config.bin %> <%= command.id %> org-abc123 --logo ""',
46
+ description: 'Remove the organization logo'
37
47
  }
38
48
  ];
39
49
  static flags = {
@@ -44,6 +54,14 @@ export class UpdateOrganizationCommand extends SanityCommand {
44
54
  description: 'New default role for new members',
45
55
  required: false
46
56
  }),
57
+ logo: Flags.string({
58
+ atLeastOne: [
59
+ ...UPDATE_FLAGS
60
+ ],
61
+ description: 'Image file to use as the logo: PNG, JPEG, GIF, WebP, SVG, BMP, TIFF, HEIF or AVIF, at most 5 MB ("" removes it)',
62
+ helpValue: '<path>',
63
+ required: false
64
+ }),
47
65
  name: Flags.string({
48
66
  atLeastOne: [
49
67
  ...UPDATE_FLAGS
@@ -62,12 +80,13 @@ export class UpdateOrganizationCommand extends SanityCommand {
62
80
  static hiddenAliases = organizationAliases('update');
63
81
  static telemetry = defineCommandTelemetry(this.flags, {
64
82
  redact: [
83
+ 'logo',
65
84
  'name'
66
85
  ]
67
86
  });
68
87
  async run() {
69
88
  const { organizationId } = this.args;
70
- const { 'default-role': defaultRole, name, slug } = this.flags;
89
+ const { 'default-role': defaultRole, logo: logoPath, name, slug } = this.flags;
71
90
  const params = {};
72
91
  if (name !== undefined) {
73
92
  const trimmedName = name.trim();
@@ -98,23 +117,57 @@ export class UpdateOrganizationCommand extends SanityCommand {
98
117
  }
99
118
  params.defaultRoleName = trimmedRole;
100
119
  }
101
- const spin = spinner('Updating organization').start();
102
- try {
103
- await updateOrganization(organizationId, params);
104
- spin.succeed();
105
- this.log('Organization updated');
106
- } catch (error) {
107
- spin.fail();
108
- updateOrgDebug('Error updating organization', error);
109
- if (isHttpError(error) && error.statusCode === 404) {
110
- this.error(`Organization "${organizationId}" not found`, {
120
+ // undefined leaves the logo as it is, null removes it.
121
+ let logo;
122
+ if (logoPath === '') {
123
+ logo = null;
124
+ } else if (logoPath !== undefined) {
125
+ try {
126
+ logo = await readOrganizationLogo(logoPath);
127
+ } catch (error) {
128
+ this.error(getErrorMessage(error), {
111
129
  exit: exitCodes.RUNTIME_ERROR
112
130
  });
113
131
  }
114
- this.error(`Failed to update organization: ${getErrorMessage(error)}`, {
132
+ }
133
+ const spin = spinner('Updating organization').start();
134
+ const updatesFields = Object.keys(params).length > 0;
135
+ if (updatesFields) {
136
+ try {
137
+ await updateOrganization(organizationId, params);
138
+ } catch (error) {
139
+ spin.fail();
140
+ this.failRequest(error, 'Failed to update organization');
141
+ }
142
+ }
143
+ let logoUrl = null;
144
+ if (logo !== undefined) {
145
+ try {
146
+ const response = logo ? await setOrganizationLogo(organizationId, logo) : await removeOrganizationLogo(organizationId);
147
+ logoUrl = response.logoUrl;
148
+ } catch (error) {
149
+ spin.fail();
150
+ this.failRequest(error, updatesFields ? `The organization was updated, but its logo wasn't ${logo ? 'set' : 'removed'}` : `Failed to ${logo ? 'set' : 'remove'} the organization's logo`);
151
+ }
152
+ }
153
+ spin.succeed();
154
+ this.log('Organization updated');
155
+ if (logo) {
156
+ this.log(`Logo: ${logoUrl}`);
157
+ } else if (logo === null) {
158
+ this.log('Logo removed');
159
+ }
160
+ }
161
+ failRequest(error, message) {
162
+ updateOrgDebug(message, error);
163
+ if (isHttpError(error) && error.statusCode === 404) {
164
+ this.error(`Organization "${this.args.organizationId}" not found`, {
115
165
  exit: exitCodes.RUNTIME_ERROR
116
166
  });
117
167
  }
168
+ this.error(`${message}: ${getErrorMessage(error)}`, {
169
+ exit: exitCodes.RUNTIME_ERROR
170
+ });
118
171
  }
119
172
  }
120
173