sanity 3.77.2-server-side-schemas.21 → 3.77.2-server-side-schemas.24

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.
@@ -1,11 +1,15 @@
1
1
  import {type CliCommandArguments, type CliCommandContext, type CliOutputter} from '@sanity/cli'
2
2
  import {type SanityDocument} from '@sanity/client'
3
3
  import chalk from 'chalk'
4
- import {size, sortBy} from 'lodash'
4
+ import {size, sortBy, uniqBy} from 'lodash'
5
+
6
+ import {type ManifestWorkspaceFile} from '../../../manifest/manifestTypes'
7
+ import {getManifestPath, readManifest, throwIfProjectIdMismatch} from './storeSchemasAction'
5
8
 
6
9
  export interface SchemaListFlags {
7
10
  json: boolean
8
11
  id: string
12
+ path: string
9
13
  }
10
14
 
11
15
  type PrintSchemaListArgs = {
@@ -13,14 +17,18 @@ type PrintSchemaListArgs = {
13
17
  output: CliOutputter
14
18
  dataset: string
15
19
  projectId: string
20
+ path: string
16
21
  }
17
22
 
18
23
  export const SANITY_WORKSPACE_SCHEMA_ID = 'sanity.workspace.schema'
19
24
 
20
- const printSchemaList = ({schemas, output, dataset, projectId}: PrintSchemaListArgs) => {
25
+ const printSchemaList = ({
26
+ schemas,
27
+ output,
28
+ }: Omit<PrintSchemaListArgs, 'path' | 'dataset' | 'projectId'>) => {
21
29
  const ordered = sortBy(
22
30
  schemas.map(({_createdAt: createdAt, _id: id, workspace}) => {
23
- return [id, workspace.title, dataset, projectId, createdAt].map(String)
31
+ return [id, workspace.title, workspace.dataset, workspace.projectId, createdAt].map(String)
24
32
  }),
25
33
  ['createdAt'],
26
34
  )
@@ -38,12 +46,11 @@ const printSchemaList = ({schemas, output, dataset, projectId}: PrintSchemaListA
38
46
  rows.forEach((row) => output.print(printRow(row)))
39
47
  }
40
48
 
41
- export default async function storeSchemaAction(
49
+ export default async function fetchSchemaAction(
42
50
  args: CliCommandArguments<SchemaListFlags>,
43
51
  context: CliCommandContext,
44
52
  ): Promise<void> {
45
53
  const flags = args.extOptions
46
- if (typeof flags.id === 'boolean') throw new Error('Id is empty')
47
54
  const {apiClient, output} = context
48
55
  const client = apiClient({
49
56
  requireUser: true,
@@ -51,50 +58,67 @@ export default async function storeSchemaAction(
51
58
  }).withConfig({apiVersion: 'v2024-08-01'})
52
59
 
53
60
  const projectId = client.config().projectId
54
- const dataset = client.config().dataset
55
61
 
56
- if (!projectId || !dataset) {
57
- output.error('Project ID and Dataset must be defined.')
62
+ if (!projectId) {
63
+ output.error('Project ID must be defined.')
58
64
  return
59
65
  }
60
66
 
61
- let schemas: SanityDocument[]
62
-
63
- if (flags.id) {
64
- // Fetch a specific schema by id
65
- schemas = await client
66
- .withConfig({
67
- dataset: dataset,
68
- projectId: projectId,
69
- })
70
- .fetch<SanityDocument[]>(`*[_type == $type && _id == $id]`, {
71
- id: flags.id,
72
- type: SANITY_WORKSPACE_SCHEMA_ID,
73
- })
74
- } else {
75
- // Fetch all schemas
76
- schemas = await client
77
- .withConfig({
78
- dataset: dataset,
79
- projectId: projectId,
80
- })
81
- .fetch<SanityDocument[]>(`*[_type == $type]`, {
82
- type: SANITY_WORKSPACE_SCHEMA_ID,
83
- })
84
- }
67
+ const manifestPath = getManifestPath(context, flags.path)
68
+ const manifest = readManifest(manifestPath, output)
69
+
70
+ // Gather all schemas
71
+ const results = await Promise.allSettled(
72
+ uniqBy<ManifestWorkspaceFile>(manifest.workspaces, 'dataset').map(async (workspace) => {
73
+ throwIfProjectIdMismatch(workspace, projectId)
74
+ if (flags.id) {
75
+ // Fetch a specific schema by id
76
+ return await client
77
+ .withConfig({
78
+ dataset: workspace.dataset,
79
+ projectId: workspace.projectId,
80
+ })
81
+ .fetch<SanityDocument[]>(`*[_type == $type && _id == $id]`, {
82
+ id: flags.id,
83
+ type: SANITY_WORKSPACE_SCHEMA_ID,
84
+ })
85
+ }
86
+ // Fetch all schemas
87
+ return await client
88
+ .withConfig({
89
+ dataset: workspace.dataset,
90
+ projectId: workspace.projectId,
91
+ })
92
+ .fetch<SanityDocument[]>(`*[_type == $type]`, {
93
+ type: SANITY_WORKSPACE_SCHEMA_ID,
94
+ })
95
+ }),
96
+ )
97
+
98
+ // Log errors and collect successful results
99
+ const schemas = results
100
+ .map((result, index) => {
101
+ if (result.status === 'rejected') {
102
+ const workspace = manifest.workspaces[index]
103
+ output.error(
104
+ chalk.red(
105
+ `Failed to fetch schemas for workspace '${workspace.name}': ${result.reason.message}`,
106
+ ),
107
+ )
108
+ return []
109
+ }
110
+ return result.value
111
+ })
112
+ .flat()
85
113
 
86
114
  if (schemas.length === 0) {
87
- if (flags.id) {
88
- output.error(`No schema found with id: ${flags.id}`)
89
- } else {
90
- output.error(`No schemas found`)
91
- }
115
+ output.error(`No schemas found`)
92
116
  return
93
117
  }
94
118
 
95
119
  if (flags.json) {
96
- output.print(`${JSON.stringify(flags.id ? schemas[0] : schemas, null, 2)}`)
120
+ output.print(`${JSON.stringify(schemas, null, 2)}`)
97
121
  } else {
98
- printSchemaList({schemas, output, dataset, projectId})
122
+ printSchemaList({schemas, output})
99
123
  }
100
124
  }
@@ -1,14 +1,11 @@
1
1
  import {readFileSync} from 'node:fs'
2
2
  import path, {join, resolve} from 'node:path'
3
3
 
4
- import {type CliCommandArguments, type CliCommandContext} from '@sanity/cli'
4
+ import {type CliCommandArguments, type CliCommandContext, type CliOutputter} from '@sanity/cli'
5
5
  import chalk from 'chalk'
6
+ import {type Ora} from 'ora'
6
7
 
7
- import {
8
- type CreateManifest,
9
- type ManifestSchemaType,
10
- type ManifestWorkspaceFile,
11
- } from '../../../manifest/manifestTypes'
8
+ import {type ManifestSchemaType, type ManifestWorkspaceFile} from '../../../manifest/manifestTypes'
12
9
  import {MANIFEST_FILENAME} from '../manifest/extractManifestAction'
13
10
  import {SANITY_WORKSPACE_SCHEMA_ID} from './schemaListAction'
14
11
 
@@ -20,6 +17,36 @@ export interface StoreManifestSchemasFlags {
20
17
  'verbose'?: boolean
21
18
  }
22
19
 
20
+ export const getManifestPath = (context: CliCommandContext, customPath?: string) => {
21
+ const defaultOutputDir = resolve(join(context.workDir, 'dist'))
22
+
23
+ const outputDir = resolve(defaultOutputDir)
24
+ const defaultStaticPath = join(outputDir, 'static')
25
+
26
+ const staticPath = customPath ?? defaultStaticPath
27
+ const manifestPath = path.resolve(process.cwd(), staticPath)
28
+ return manifestPath
29
+ }
30
+
31
+ export const readManifest = (readPath: string, output?: CliOutputter, spinner?: Ora) => {
32
+ try {
33
+ return JSON.parse(readFileSync(`${readPath}/${MANIFEST_FILENAME}`, 'utf-8'))
34
+ } catch (error) {
35
+ const errorMessage = `Manifest not found at ${readPath}/${MANIFEST_FILENAME}`
36
+ if (spinner) spinner.fail(errorMessage)
37
+ if (output) output.error(errorMessage)
38
+ throw error
39
+ }
40
+ }
41
+
42
+ export const throwIfProjectIdMismatch = (workspace: ManifestWorkspaceFile, projectId: string) => {
43
+ if (workspace.projectId !== projectId) {
44
+ throw new Error(
45
+ `↳ No permissions to store schema for workspace ${workspace.name} with projectId: ${workspace.projectId}`,
46
+ )
47
+ }
48
+ }
49
+
23
50
  export default async function storeSchemasAction(
24
51
  args: CliCommandArguments<StoreManifestSchemasFlags>,
25
52
  context: CliCommandContext,
@@ -33,35 +60,22 @@ export default async function storeSchemasAction(
33
60
  const workspaceName = flags.workspace
34
61
  const idPrefix = flags['id-prefix']
35
62
  const verbose = flags.verbose
36
- const {output, workDir, apiClient} = context
37
-
38
- const defaultOutputDir = resolve(join(workDir, 'dist'))
39
-
40
- const outputDir = resolve(defaultOutputDir)
41
- const defaultStaticPath = join(outputDir, 'static')
42
-
43
- const staticPath = flags.path ?? defaultStaticPath
63
+ const {output, apiClient} = context
44
64
 
45
65
  const spinner = output.spinner({}).start('Storing schemas')
46
66
 
67
+ const manifestPath = getManifestPath(context, flags.path)
68
+
47
69
  try {
48
- const manifestPath = path.resolve(process.cwd(), staticPath)
49
70
  const client = apiClient({
50
71
  requireUser: true,
51
72
  requireProject: true,
52
73
  }).withConfig({apiVersion: 'v2024-08-01'})
53
74
 
54
75
  const projectId = client.config().projectId
76
+ if (!projectId) throw new Error('Project ID is not defined')
55
77
 
56
- let manifest: CreateManifest
57
-
58
- try {
59
- manifest = JSON.parse(readFileSync(`${manifestPath}/${MANIFEST_FILENAME}`, 'utf-8'))
60
- } catch (error) {
61
- spinner.fail(`Manifest not found at ${manifestPath}/${MANIFEST_FILENAME}`)
62
- output.error(error)
63
- throw error
64
- }
78
+ const manifest = readManifest(manifestPath, output, spinner)
65
79
 
66
80
  let storedCount = 0
67
81
 
@@ -70,11 +84,7 @@ export default async function storeSchemasAction(
70
84
  const saveSchema = async (workspace: ManifestWorkspaceFile) => {
71
85
  const id = `${idPrefix ? `${idPrefix}.` : ''}${SANITY_WORKSPACE_SCHEMA_ID}.${workspace.name}`
72
86
  try {
73
- if (workspace.projectId !== projectId) {
74
- throw new Error(
75
- `↳ No permissions to store schema for workspace ${workspace.name} with projectId: ${workspace.projectId}`,
76
- )
77
- }
87
+ throwIfProjectIdMismatch(workspace, projectId)
78
88
  const schema = JSON.parse(
79
89
  readFileSync(`${manifestPath}/${workspace.schema}`, 'utf-8'),
80
90
  ) as ManifestSchemaType
@@ -107,7 +117,7 @@ export default async function storeSchemasAction(
107
117
  // If a workspace name is provided, only save the schema for that workspace
108
118
  if (workspaceName) {
109
119
  const workspaceToSave = manifest.workspaces.find(
110
- (workspace) => workspace.name === workspaceName,
120
+ (workspace: ManifestWorkspaceFile) => workspace.name === workspaceName,
111
121
  )
112
122
  if (!workspaceToSave) {
113
123
  spinner.fail(`Workspace ${workspaceName} not found in manifest`)
@@ -117,7 +127,7 @@ export default async function storeSchemasAction(
117
127
  spinner.succeed(`Stored 1 schemas`)
118
128
  } else {
119
129
  await Promise.all(
120
- manifest.workspaces.map(async (workspace): Promise<void> => {
130
+ manifest.workspaces.map(async (workspace: ManifestWorkspaceFile): Promise<void> => {
121
131
  await saveSchema(workspace)
122
132
  }),
123
133
  )
@@ -9,6 +9,8 @@ const helpText = `
9
9
 
10
10
  Options
11
11
  --ids <schema_id_1,schema_id_2,...> comma-separated list of schema IDs to delete
12
+ --dataset <dataset_name> delete schemas from a specific dataset
13
+ --path <path> path to the manifest file if it is not in the default location
12
14
 
13
15
  Examples
14
16
  # Delete single schema
@@ -29,7 +29,18 @@ const storeSchemaCommand = {
29
29
  action: async (args, context) => {
30
30
  const mod = await import('../../actions/schema/storeSchemasAction')
31
31
 
32
- return mod.default(args as unknown as CliCommandArguments<StoreManifestSchemasFlags>, context)
32
+ const extendedArgs = {
33
+ ...args,
34
+ extOptions: {
35
+ ...args.extOptions,
36
+ 'schema-required': true,
37
+ },
38
+ }
39
+
40
+ return mod.default(
41
+ extendedArgs as unknown as CliCommandArguments<StoreManifestSchemasFlags>,
42
+ context,
43
+ )
33
44
  },
34
45
  } satisfies CliCommandDefinition
35
46
 
@@ -1,61 +0,0 @@
1
- "use strict";
2
- var chalk = require("chalk"), size = require("lodash/size.js"), sortBy = require("lodash/sortBy.js");
3
- function _interopDefaultCompat(e) {
4
- return e && typeof e == "object" && "default" in e ? e : { default: e };
5
- }
6
- var chalk__default = /* @__PURE__ */ _interopDefaultCompat(chalk), size__default = /* @__PURE__ */ _interopDefaultCompat(size), sortBy__default = /* @__PURE__ */ _interopDefaultCompat(sortBy);
7
- const SANITY_WORKSPACE_SCHEMA_ID = "sanity.workspace.schema", printSchemaList = ({
8
- schemas,
9
- output,
10
- dataset,
11
- projectId
12
- }) => {
13
- const ordered = sortBy__default.default(schemas.map(({
14
- _createdAt: createdAt,
15
- _id: id,
16
- workspace
17
- }) => [id, workspace.title, dataset, projectId, createdAt].map(String)), ["createdAt"]), headings = ["Id", "Title", "Dataset", "ProjectId", "CreatedAt"], rows = ordered.reverse(), maxWidths = rows.reduce((max, row) => row.map((current, index) => Math.max(size__default.default(current), max[index])), headings.map((str) => size__default.default(str))), printRow = (row) => row.map((col, i) => `${col}`.padEnd(maxWidths[i])).join(" ");
18
- output.print(chalk__default.default.cyan(printRow(headings))), rows.forEach((row) => output.print(printRow(row)));
19
- };
20
- async function storeSchemaAction(args, context) {
21
- const flags = args.extOptions;
22
- if (typeof flags.id == "boolean") throw new Error("Id is empty");
23
- const {
24
- apiClient,
25
- output
26
- } = context, client = apiClient({
27
- requireUser: !0,
28
- requireProject: !0
29
- }).withConfig({
30
- apiVersion: "v2024-08-01"
31
- }), projectId = client.config().projectId, dataset = client.config().dataset;
32
- if (!projectId || !dataset) {
33
- output.error("Project ID and Dataset must be defined.");
34
- return;
35
- }
36
- let schemas;
37
- if (flags.id ? schemas = await client.withConfig({
38
- dataset,
39
- projectId
40
- }).fetch("*[_type == $type && _id == $id]", {
41
- id: flags.id,
42
- type: SANITY_WORKSPACE_SCHEMA_ID
43
- }) : schemas = await client.withConfig({
44
- dataset,
45
- projectId
46
- }).fetch("*[_type == $type]", {
47
- type: SANITY_WORKSPACE_SCHEMA_ID
48
- }), schemas.length === 0) {
49
- flags.id ? output.error(`No schema found with id: ${flags.id}`) : output.error("No schemas found");
50
- return;
51
- }
52
- flags.json ? output.print(`${JSON.stringify(flags.id ? schemas[0] : schemas, null, 2)}`) : printSchemaList({
53
- schemas,
54
- output,
55
- dataset,
56
- projectId
57
- });
58
- }
59
- exports.SANITY_WORKSPACE_SCHEMA_ID = SANITY_WORKSPACE_SCHEMA_ID;
60
- exports.default = storeSchemaAction;
61
- //# sourceMappingURL=schemaListAction.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"schemaListAction.js","sources":["../../src/_internal/cli/actions/schema/schemaListAction.ts"],"sourcesContent":["import {type CliCommandArguments, type CliCommandContext, type CliOutputter} from '@sanity/cli'\nimport {type SanityDocument} from '@sanity/client'\nimport chalk from 'chalk'\nimport {size, sortBy} from 'lodash'\n\nexport interface SchemaListFlags {\n json: boolean\n id: string\n}\n\ntype PrintSchemaListArgs = {\n schemas: SanityDocument[]\n output: CliOutputter\n dataset: string\n projectId: string\n}\n\nexport const SANITY_WORKSPACE_SCHEMA_ID = 'sanity.workspace.schema'\n\nconst printSchemaList = ({schemas, output, dataset, projectId}: PrintSchemaListArgs) => {\n const ordered = sortBy(\n schemas.map(({_createdAt: createdAt, _id: id, workspace}) => {\n return [id, workspace.title, dataset, projectId, createdAt].map(String)\n }),\n ['createdAt'],\n )\n const headings = ['Id', 'Title', 'Dataset', 'ProjectId', 'CreatedAt']\n const rows = ordered.reverse()\n\n const maxWidths = rows.reduce(\n (max, row) => row.map((current, index) => Math.max(size(current), max[index])),\n headings.map((str) => size(str)),\n )\n\n const printRow = (row: string[]) => row.map((col, i) => `${col}`.padEnd(maxWidths[i])).join(' ')\n\n output.print(chalk.cyan(printRow(headings)))\n rows.forEach((row) => output.print(printRow(row)))\n}\n\nexport default async function storeSchemaAction(\n args: CliCommandArguments<SchemaListFlags>,\n context: CliCommandContext,\n): Promise<void> {\n const flags = args.extOptions\n if (typeof flags.id === 'boolean') throw new Error('Id is empty')\n const {apiClient, output} = context\n const client = apiClient({\n requireUser: true,\n requireProject: true,\n }).withConfig({apiVersion: 'v2024-08-01'})\n\n const projectId = client.config().projectId\n const dataset = client.config().dataset\n\n if (!projectId || !dataset) {\n output.error('Project ID and Dataset must be defined.')\n return\n }\n\n let schemas: SanityDocument[]\n\n if (flags.id) {\n // Fetch a specific schema by id\n schemas = await client\n .withConfig({\n dataset: dataset,\n projectId: projectId,\n })\n .fetch<SanityDocument[]>(`*[_type == $type && _id == $id]`, {\n id: flags.id,\n type: SANITY_WORKSPACE_SCHEMA_ID,\n })\n } else {\n // Fetch all schemas\n schemas = await client\n .withConfig({\n dataset: dataset,\n projectId: projectId,\n })\n .fetch<SanityDocument[]>(`*[_type == $type]`, {\n type: SANITY_WORKSPACE_SCHEMA_ID,\n })\n }\n\n if (schemas.length === 0) {\n if (flags.id) {\n output.error(`No schema found with id: ${flags.id}`)\n } else {\n output.error(`No schemas found`)\n }\n return\n }\n\n if (flags.json) {\n output.print(`${JSON.stringify(flags.id ? schemas[0] : schemas, null, 2)}`)\n } else {\n printSchemaList({schemas, output, dataset, projectId})\n }\n}\n"],"names":["SANITY_WORKSPACE_SCHEMA_ID","printSchemaList","schemas","output","dataset","projectId","ordered","sortBy","map","_createdAt","createdAt","_id","id","workspace","title","String","headings","rows","reverse","maxWidths","reduce","max","row","current","index","Math","size","str","printRow","col","i","padEnd","join","print","chalk","cyan","forEach","storeSchemaAction","args","context","flags","extOptions","Error","apiClient","client","requireUser","requireProject","withConfig","apiVersion","config","error","fetch","type","length","json","JSON","stringify"],"mappings":";;;;;;AAiBO,MAAMA,6BAA6B,2BAEpCC,kBAAkBA,CAAC;AAAA,EAACC;AAAAA,EAASC;AAAAA,EAAQC;AAAAA,EAASC;AAA8B,MAAM;AACtF,QAAMC,UAAUC,gBAAAA,QACdL,QAAQM,IAAI,CAAC;AAAA,IAACC,YAAYC;AAAAA,IAAWC,KAAKC;AAAAA,IAAIC;AAAAA,EAAAA,MACrC,CAACD,IAAIC,UAAUC,OAAOV,SAASC,WAAWK,SAAS,EAAEF,IAAIO,MAAM,CACvE,GACD,CAAC,WAAW,CACd,GACMC,WAAW,CAAC,MAAM,SAAS,WAAW,aAAa,WAAW,GAC9DC,OAAOX,QAAQY,QAAQ,GAEvBC,YAAYF,KAAKG,OACrB,CAACC,KAAKC,QAAQA,IAAId,IAAI,CAACe,SAASC,UAAUC,KAAKJ,IAAIK,cAAAA,QAAKH,OAAO,GAAGF,IAAIG,KAAK,CAAC,CAAC,GAC7ER,SAASR,IAAKmB,CAAQD,QAAAA,cAAAA,QAAKC,GAAG,CAAC,CACjC,GAEMC,WAAYN,SAAkBA,IAAId,IAAI,CAACqB,KAAKC,MAAM,GAAGD,GAAG,GAAGE,OAAOZ,UAAUW,CAAC,CAAC,CAAC,EAAEE,KAAK,KAAK;AAEjG7B,SAAO8B,MAAMC,eAAMC,QAAAA,KAAKP,SAASZ,QAAQ,CAAC,CAAC,GAC3CC,KAAKmB,QAASd,SAAQnB,OAAO8B,MAAML,SAASN,GAAG,CAAC,CAAC;AACnD;AAE8Be,eAAAA,kBAC5BC,MACAC,SACe;AACf,QAAMC,QAAQF,KAAKG;AACnB,MAAI,OAAOD,MAAM5B,MAAO,UAAiB,OAAA,IAAI8B,MAAM,aAAa;AAC1D,QAAA;AAAA,IAACC;AAAAA,IAAWxC;AAAAA,EAAAA,IAAUoC,SACtBK,SAASD,UAAU;AAAA,IACvBE,aAAa;AAAA,IACbC,gBAAgB;AAAA,EACjB,CAAA,EAAEC,WAAW;AAAA,IAACC,YAAY;AAAA,EAAA,CAAc,GAEnC3C,YAAYuC,OAAOK,SAAS5C,WAC5BD,UAAUwC,OAAOK,OAAAA,EAAS7C;AAE5B,MAAA,CAACC,aAAa,CAACD,SAAS;AAC1BD,WAAO+C,MAAM,yCAAyC;AACtD;AAAA,EAAA;AAGEhD,MAAAA;AAyBJ,MAvBIsC,MAAM5B,KAERV,UAAU,MAAM0C,OACbG,WAAW;AAAA,IACV3C;AAAAA,IACAC;AAAAA,EAAAA,CACD,EACA8C,MAAwB,mCAAmC;AAAA,IAC1DvC,IAAI4B,MAAM5B;AAAAA,IACVwC,MAAMpD;AAAAA,EACP,CAAA,IAGHE,UAAU,MAAM0C,OACbG,WAAW;AAAA,IACV3C;AAAAA,IACAC;AAAAA,EAAAA,CACD,EACA8C,MAAwB,qBAAqB;AAAA,IAC5CC,MAAMpD;AAAAA,EAAAA,CACP,GAGDE,QAAQmD,WAAW,GAAG;AACpBb,UAAM5B,KACRT,OAAO+C,MAAM,4BAA4BV,MAAM5B,EAAE,EAAE,IAEnDT,OAAO+C,MAAM,kBAAkB;AAEjC;AAAA,EAAA;AAGEV,QAAMc,OACRnD,OAAO8B,MAAM,GAAGsB,KAAKC,UAAUhB,MAAM5B,KAAKV,QAAQ,CAAC,IAAIA,SAAS,MAAM,CAAC,CAAC,EAAE,IAE1ED,gBAAgB;AAAA,IAACC;AAAAA,IAASC;AAAAA,IAAQC;AAAAA,IAASC;AAAAA,EAAAA,CAAU;AAEzD;;;"}