sanity 3.77.3-server-side-schemas.15 → 3.77.3-server-side-schemas.20

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 (33) hide show
  1. package/lib/_chunks-cjs/_internal.js +427 -142
  2. package/lib/_chunks-cjs/_internal.js.map +1 -1
  3. package/lib/_chunks-cjs/buildAction.js +2 -2
  4. package/lib/_chunks-cjs/buildAction.js.map +1 -1
  5. package/lib/_chunks-cjs/deleteSchemaAction.js +13 -7
  6. package/lib/_chunks-cjs/deleteSchemaAction.js.map +1 -1
  7. package/lib/_chunks-cjs/deployAction.js +3 -3
  8. package/lib/_chunks-cjs/deployAction.js.map +1 -1
  9. package/lib/_chunks-cjs/devAction.js +2 -2
  10. package/lib/_chunks-cjs/devAction.js.map +1 -1
  11. package/lib/_chunks-cjs/version.js +1 -1
  12. package/lib/_chunks-es/version.mjs +1 -1
  13. package/lib/_legacy/version.esm.js +1 -1
  14. package/lib/index.d.mts +3 -3
  15. package/lib/index.d.ts +3 -3
  16. package/lib/structure.d.mts +1 -1
  17. package/lib/structure.d.ts +1 -1
  18. package/package.json +10 -10
  19. package/src/_internal/cli/actions/manifest/extractManifestAction.ts +3 -3
  20. package/src/_internal/cli/actions/schema/deleteSchemaAction.ts +24 -9
  21. package/src/_internal/cli/actions/schema/schemaListAction.ts +28 -10
  22. package/src/_internal/cli/actions/schema/storeSchemasAction.ts +63 -22
  23. package/src/_internal/cli/commands/app/deployCommand.ts +2 -0
  24. package/src/_internal/cli/commands/index.ts +12 -4
  25. package/src/_internal/cli/commands/schema/deleteSchemaCommand.ts +1 -1
  26. package/src/_internal/cli/commands/schema/schemaListCommand.ts +1 -1
  27. package/src/_internal/cli/commands/schema/storeSchemaCommand.ts +6 -5
  28. package/lib/_chunks-cjs/extractManifestAction.js +0 -99
  29. package/lib/_chunks-cjs/extractManifestAction.js.map +0 -1
  30. package/lib/_chunks-cjs/storeSchemasAction.js +0 -147
  31. package/lib/_chunks-cjs/storeSchemasAction.js.map +0 -1
  32. package/lib/_chunks-cjs/timing.js +0 -22
  33. package/lib/_chunks-cjs/timing.js.map +0 -1
@@ -18,11 +18,291 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
18
18
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: !0 }) : target,
19
19
  mod
20
20
  ));
21
- var debug$3 = require("debug"), fs = require("node:fs"), fs$1 = require("node:fs/promises"), os = require("node:os"), path = require("node:path"), promises = require("node:stream/promises"), fs$2 = require("@sanity/util/fs"), asyncMutex = require("async-mutex"), isString = require("lodash/isString.js"), prettyMs = require("pretty-ms"), helpers = require("yargs/helpers"), yargs = require("yargs/yargs"), zlib = require("node:zlib"), rimraf = require("rimraf"), getIt = require("get-it"), middleware = require("get-it/middleware"), node_stream = require("node:stream"), consoleTablePrinter = require("console-table-printer"), dateFns = require("date-fns"), url = require("node:url"), logSymbols = require("log-symbols"), oneline = require("oneline"), EventSource = require("@sanity/eventsource"), rxjs = require("rxjs"), exportDataset = require("@sanity/export"), sanityImport = require("@sanity/import"), padStart = require("lodash/padStart.js"), uuid = require("@sanity/uuid"), chokidar = require("chokidar"), execa = require("execa"), json5 = require("json5"), isEqual = require("lodash/isEqual.js"), isPlainObject = require("lodash/isPlainObject.js"), noop$1 = require("lodash/noop.js"), pluralize = require("pluralize-esm"), tokenize = require("json-lexer"), open = require("open"), node_util = require("node:util"), groupBy = require("lodash/groupBy.js"), deburr = require("lodash/deburr.js"), node = require("esbuild-register/dist/node"), migrate = require("@sanity/migrate"), node_tty = require("node:tty"), types = require("@sanity/types"), size = require("lodash/size.js"), sortBy = require("lodash/sortBy.js");
21
+ var fs$1 = require("node:fs"), path = require("node:path"), chalk = require("chalk"), node_crypto = require("node:crypto"), fs = require("node:fs/promises"), node_worker_threads = require("node:worker_threads"), dateFns = require("date-fns"), readPkgUp = require("read-pkg-up"), node_perf_hooks = require("node:perf_hooks"), size = require("lodash/size.js"), sortBy = require("lodash/sortBy.js"), uniqBy = require("lodash/uniqBy.js"), debug$3 = require("debug"), os = require("node:os"), promises = require("node:stream/promises"), fs$2 = require("@sanity/util/fs"), asyncMutex = require("async-mutex"), isString = require("lodash/isString.js"), prettyMs = require("pretty-ms"), helpers = require("yargs/helpers"), yargs = require("yargs/yargs"), zlib = require("node:zlib"), rimraf = require("rimraf"), getIt = require("get-it"), middleware = require("get-it/middleware"), node_stream = require("node:stream"), consoleTablePrinter = require("console-table-printer"), url = require("node:url"), logSymbols = require("log-symbols"), oneline = require("oneline"), EventSource = require("@sanity/eventsource"), rxjs = require("rxjs"), exportDataset = require("@sanity/export"), sanityImport = require("@sanity/import"), padStart = require("lodash/padStart.js"), uuid = require("@sanity/uuid"), chokidar = require("chokidar"), execa = require("execa"), json5 = require("json5"), isEqual = require("lodash/isEqual.js"), isPlainObject = require("lodash/isPlainObject.js"), noop$1 = require("lodash/noop.js"), pluralize = require("pluralize-esm"), tokenize = require("json-lexer"), open = require("open"), node_util = require("node:util"), groupBy = require("lodash/groupBy.js"), deburr = require("lodash/deburr.js"), node = require("esbuild-register/dist/node"), migrate = require("@sanity/migrate"), node_tty = require("node:tty"), types = require("@sanity/types");
22
22
  function _interopDefaultCompat(e) {
23
23
  return e && typeof e == "object" && "default" in e ? e : { default: e };
24
24
  }
25
- var debug__default = /* @__PURE__ */ _interopDefaultCompat(debug$3), fs__default = /* @__PURE__ */ _interopDefaultCompat(fs), fs__default$1 = /* @__PURE__ */ _interopDefaultCompat(fs$1), os__default = /* @__PURE__ */ _interopDefaultCompat(os), path__default = /* @__PURE__ */ _interopDefaultCompat(path), isString__default = /* @__PURE__ */ _interopDefaultCompat(isString), prettyMs__default = /* @__PURE__ */ _interopDefaultCompat(prettyMs), yargs__default = /* @__PURE__ */ _interopDefaultCompat(yargs), zlib__default = /* @__PURE__ */ _interopDefaultCompat(zlib), url__default = /* @__PURE__ */ _interopDefaultCompat(url), logSymbols__default = /* @__PURE__ */ _interopDefaultCompat(logSymbols), oneline__default = /* @__PURE__ */ _interopDefaultCompat(oneline), EventSource__default = /* @__PURE__ */ _interopDefaultCompat(EventSource), exportDataset__default = /* @__PURE__ */ _interopDefaultCompat(exportDataset), sanityImport__default = /* @__PURE__ */ _interopDefaultCompat(sanityImport), padStart__default = /* @__PURE__ */ _interopDefaultCompat(padStart), chokidar__default = /* @__PURE__ */ _interopDefaultCompat(chokidar), execa__default = /* @__PURE__ */ _interopDefaultCompat(execa), json5__default = /* @__PURE__ */ _interopDefaultCompat(json5), isEqual__default = /* @__PURE__ */ _interopDefaultCompat(isEqual), isPlainObject__default = /* @__PURE__ */ _interopDefaultCompat(isPlainObject), noop__default = /* @__PURE__ */ _interopDefaultCompat(noop$1), pluralize__default = /* @__PURE__ */ _interopDefaultCompat(pluralize), tokenize__default = /* @__PURE__ */ _interopDefaultCompat(tokenize), open__default = /* @__PURE__ */ _interopDefaultCompat(open), groupBy__default = /* @__PURE__ */ _interopDefaultCompat(groupBy), deburr__default = /* @__PURE__ */ _interopDefaultCompat(deburr), size__default = /* @__PURE__ */ _interopDefaultCompat(size), sortBy__default = /* @__PURE__ */ _interopDefaultCompat(sortBy);
25
+ var fs__default = /* @__PURE__ */ _interopDefaultCompat(fs$1), path__default = /* @__PURE__ */ _interopDefaultCompat(path), chalk__default = /* @__PURE__ */ _interopDefaultCompat(chalk), fs__default$1 = /* @__PURE__ */ _interopDefaultCompat(fs), readPkgUp__default = /* @__PURE__ */ _interopDefaultCompat(readPkgUp), size__default = /* @__PURE__ */ _interopDefaultCompat(size), sortBy__default = /* @__PURE__ */ _interopDefaultCompat(sortBy), uniqBy__default = /* @__PURE__ */ _interopDefaultCompat(uniqBy), debug__default = /* @__PURE__ */ _interopDefaultCompat(debug$3), os__default = /* @__PURE__ */ _interopDefaultCompat(os), isString__default = /* @__PURE__ */ _interopDefaultCompat(isString), prettyMs__default = /* @__PURE__ */ _interopDefaultCompat(prettyMs), yargs__default = /* @__PURE__ */ _interopDefaultCompat(yargs), zlib__default = /* @__PURE__ */ _interopDefaultCompat(zlib), url__default = /* @__PURE__ */ _interopDefaultCompat(url), logSymbols__default = /* @__PURE__ */ _interopDefaultCompat(logSymbols), oneline__default = /* @__PURE__ */ _interopDefaultCompat(oneline), EventSource__default = /* @__PURE__ */ _interopDefaultCompat(EventSource), exportDataset__default = /* @__PURE__ */ _interopDefaultCompat(exportDataset), sanityImport__default = /* @__PURE__ */ _interopDefaultCompat(sanityImport), padStart__default = /* @__PURE__ */ _interopDefaultCompat(padStart), chokidar__default = /* @__PURE__ */ _interopDefaultCompat(chokidar), execa__default = /* @__PURE__ */ _interopDefaultCompat(execa), json5__default = /* @__PURE__ */ _interopDefaultCompat(json5), isEqual__default = /* @__PURE__ */ _interopDefaultCompat(isEqual), isPlainObject__default = /* @__PURE__ */ _interopDefaultCompat(isPlainObject), noop__default = /* @__PURE__ */ _interopDefaultCompat(noop$1), pluralize__default = /* @__PURE__ */ _interopDefaultCompat(pluralize), tokenize__default = /* @__PURE__ */ _interopDefaultCompat(tokenize), open__default = /* @__PURE__ */ _interopDefaultCompat(open), groupBy__default = /* @__PURE__ */ _interopDefaultCompat(groupBy), deburr__default = /* @__PURE__ */ _interopDefaultCompat(deburr);
26
+ function getTimer() {
27
+ const timings = {}, startTimes = {};
28
+ function start(name) {
29
+ if (typeof startTimes[name] < "u")
30
+ throw new Error(`Timer "${name}" already started, cannot overwrite`);
31
+ startTimes[name] = node_perf_hooks.performance.now();
32
+ }
33
+ function end(name) {
34
+ if (typeof startTimes[name] > "u")
35
+ throw new Error(`Timer "${name}" never started, cannot end`);
36
+ return timings[name] = node_perf_hooks.performance.now() - startTimes[name], timings[name];
37
+ }
38
+ return {
39
+ start,
40
+ end,
41
+ getTimings: () => timings
42
+ };
43
+ }
44
+ const MANIFEST_FILENAME = "create-manifest.json", SCHEMA_FILENAME_SUFFIX = ".create-schema.json", TOOLS_FILENAME_SUFFIX = ".create-tools.json", FEATURE_ENABLED_ENV_NAME$1 = "SANITY_CLI_EXTRACT_MANIFEST_ENABLED", EXTRACT_MANIFEST_ENABLED = process.env[FEATURE_ENABLED_ENV_NAME$1] !== "false", EXTRACT_MANIFEST_LOG_ERRORS = process.env.SANITY_CLI_EXTRACT_MANIFEST_LOG_ERRORS === "true", CREATE_TIMER = "create-manifest", EXTRACT_TASK_TIMEOUT_MS = dateFns.minutesToMilliseconds(2), EXTRACT_FAILURE_MESSAGE = `\u21B3 Couldn't extract manifest file. Sanity Create will not be available for the studio.
45
+ Disable this message with ${FEATURE_ENABLED_ENV_NAME$1}=false`;
46
+ async function extractManifestSafe(args, context) {
47
+ if (EXTRACT_MANIFEST_ENABLED)
48
+ try {
49
+ await extractManifest(args, context);
50
+ return;
51
+ } catch (err) {
52
+ return EXTRACT_MANIFEST_LOG_ERRORS && context.output.error(err), err;
53
+ }
54
+ }
55
+ async function extractManifest(args, context) {
56
+ const {
57
+ output,
58
+ workDir
59
+ } = context, flags = args.extOptions, defaultOutputDir = path.resolve(path.join(workDir, "dist")), outputDir = path.resolve(defaultOutputDir), defaultStaticPath = path.join(outputDir, "static"), staticPath = flags.path ?? defaultStaticPath, path$1 = path.join(staticPath, MANIFEST_FILENAME), rootPkgPath = readPkgUp__default.default.sync({
60
+ cwd: __dirname
61
+ })?.path;
62
+ if (!rootPkgPath)
63
+ throw new Error("Could not find root directory for `sanity` package");
64
+ const timer = getTimer();
65
+ timer.start(CREATE_TIMER);
66
+ const spinner = output.spinner({}).start("Extracting manifest");
67
+ try {
68
+ const workspaceManifests = await getWorkspaceManifests({
69
+ rootPkgPath,
70
+ workDir
71
+ });
72
+ await fs.mkdir(staticPath, {
73
+ recursive: !0
74
+ });
75
+ const workspaceFiles = await writeWorkspaceFiles(workspaceManifests, staticPath), manifest = {
76
+ /**
77
+ * Version history:
78
+ * 1: Initial release.
79
+ * 2: Added tools file.
80
+ */
81
+ version: 2,
82
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
83
+ workspaces: workspaceFiles
84
+ };
85
+ await fs.writeFile(path$1, JSON.stringify(manifest, null, 2));
86
+ const manifestDuration = timer.end(CREATE_TIMER);
87
+ spinner.succeed(`Extracted manifest (${manifestDuration.toFixed()}ms)`);
88
+ } catch (err) {
89
+ throw spinner.fail(err.message), output.print(chalk__default.default.gray(EXTRACT_FAILURE_MESSAGE)), err;
90
+ }
91
+ }
92
+ async function getWorkspaceManifests({
93
+ rootPkgPath,
94
+ workDir
95
+ }) {
96
+ const workerPath = path.join(path.dirname(rootPkgPath), "lib", "_internal", "cli", "threads", "extractManifest.js"), worker = new node_worker_threads.Worker(workerPath, {
97
+ workerData: {
98
+ workDir
99
+ },
100
+ // eslint-disable-next-line no-process-env
101
+ env: process.env
102
+ });
103
+ let timeout = !1;
104
+ const timeoutId = setTimeout(() => {
105
+ timeout = !0, worker.terminate();
106
+ }, EXTRACT_TASK_TIMEOUT_MS);
107
+ try {
108
+ return await new Promise((resolveWorkspaces, reject) => {
109
+ const buffer = [];
110
+ worker.addListener("message", (message) => buffer.push(message)), worker.addListener("exit", (exitCode) => {
111
+ exitCode === 0 ? resolveWorkspaces(buffer) : timeout && reject(new Error(`Extract manifest was aborted after ${EXTRACT_TASK_TIMEOUT_MS}ms`));
112
+ }), worker.addListener("error", reject);
113
+ });
114
+ } finally {
115
+ clearTimeout(timeoutId);
116
+ }
117
+ }
118
+ function writeWorkspaceFiles(manifestWorkspaces, staticPath) {
119
+ const output = manifestWorkspaces.reduce((workspaces, workspace) => [...workspaces, writeWorkspaceFile(workspace, staticPath)], []);
120
+ return Promise.all(output);
121
+ }
122
+ async function writeWorkspaceFile(workspace, staticPath) {
123
+ const [schemaFilename, toolsFilename] = await Promise.all([createFile(staticPath, workspace.schema, SCHEMA_FILENAME_SUFFIX), createFile(staticPath, workspace.tools, TOOLS_FILENAME_SUFFIX)]);
124
+ return {
125
+ ...workspace,
126
+ schema: schemaFilename,
127
+ tools: toolsFilename
128
+ };
129
+ }
130
+ const createFile = async (path$1, content, filenameSuffix) => {
131
+ const stringifiedContent = JSON.stringify(content, null, 2), filename = `${node_crypto.createHash("sha1").update(stringifiedContent).digest("hex").slice(0, 8)}${filenameSuffix}`;
132
+ return await fs.writeFile(path.join(path$1, filename), stringifiedContent), filename;
133
+ };
134
+ var extractManifestAction = /* @__PURE__ */ Object.freeze({
135
+ __proto__: null,
136
+ MANIFEST_FILENAME,
137
+ extractManifestSafe
138
+ });
139
+ const SANITY_WORKSPACE_SCHEMA_TYPE = "sanity.workspace.schema", printSchemaList = ({
140
+ schemas,
141
+ output
142
+ }) => {
143
+ const ordered = sortBy__default.default(schemas.map(({
144
+ _createdAt: createdAt,
145
+ _id: id,
146
+ workspace
147
+ }) => [id, workspace.name, workspace.dataset, workspace.projectId, createdAt].map(String)), ["createdAt"]), headings = ["Id", "Workspace", "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(" ");
148
+ output.print(chalk__default.default.cyan(printRow(headings))), rows.forEach((row) => output.print(printRow(row)));
149
+ };
150
+ async function schemaListAction(args, context) {
151
+ if (!SCHEMA_STORE_ENABLED)
152
+ return;
153
+ const flags = args.extOptions;
154
+ if (typeof flags.id == "boolean") throw new Error("Schema ID is empty");
155
+ if (typeof flags["manifest-dir"] == "boolean") throw new Error("Manifest directory is empty");
156
+ const {
157
+ apiClient,
158
+ output
159
+ } = context, client = apiClient({
160
+ requireUser: !0,
161
+ requireProject: !0
162
+ }).withConfig({
163
+ apiVersion: "v2024-08-01"
164
+ }), projectId = client.config().projectId, dataset = client.config().dataset;
165
+ if (!projectId || !dataset) {
166
+ output.error("Project ID and dataset must be defined.");
167
+ return;
168
+ }
169
+ const manifestDir = flags["manifest-dir"], manifestPath = getManifestPath(context, manifestDir), manifest = await readManifest(manifestPath, context), schemas = (await Promise.allSettled(uniqBy__default.default(manifest.workspaces, "dataset").map(async (workspace) => {
170
+ if (throwIfProjectIdMismatch(workspace, projectId), flags.id) {
171
+ const schemaRes = await client.withConfig({
172
+ dataset: workspace.dataset,
173
+ projectId: workspace.projectId
174
+ }).getDocument(flags.id);
175
+ if (!schemaRes)
176
+ throw new Error(`Schema "${flags.id}" not found in dataset "${workspace.dataset}"`);
177
+ return schemaRes;
178
+ }
179
+ return await client.withConfig({
180
+ dataset: workspace.dataset,
181
+ projectId: workspace.projectId,
182
+ useCdn: !1
183
+ }).fetch("*[_type == $type]", {
184
+ type: SANITY_WORKSPACE_SCHEMA_TYPE
185
+ });
186
+ }))).map((result, index) => {
187
+ if (result.status === "rejected") {
188
+ const workspace = manifest.workspaces[index];
189
+ return output.error(chalk__default.default.red(`Failed to fetch schemas for workspace '${workspace.name}': ${result.reason.message}`)), [];
190
+ }
191
+ return result.value;
192
+ }).flat();
193
+ if (schemas.length === 0) {
194
+ output.error("No schemas found");
195
+ return;
196
+ }
197
+ flags.json ? output.print(`${JSON.stringify(flags.id ? schemas[0] : schemas, null, 2)}`) : printSchemaList({
198
+ schemas,
199
+ output
200
+ });
201
+ }
202
+ var schemaListAction$1 = /* @__PURE__ */ Object.freeze({
203
+ __proto__: null,
204
+ SANITY_WORKSPACE_SCHEMA_TYPE,
205
+ default: schemaListAction
206
+ });
207
+ const FEATURE_ENABLED_ENV_NAME = "SANITY_CLI_SCHEMA_STORE_ENABLED", SCHEMA_STORE_ENABLED = process.env[FEATURE_ENABLED_ENV_NAME] === "true", getManifestPath = (context, customPath) => {
208
+ const defaultOutputDir = path.resolve(path.join(context.workDir, "dist")), outputDir = path.resolve(defaultOutputDir), defaultStaticPath = path.join(outputDir, "static"), staticPath = customPath ?? defaultStaticPath;
209
+ return path__default.default.resolve(process.cwd(), staticPath);
210
+ }, readAndParseManifest = (manifestPath, context) => {
211
+ const content = fs$1.readFileSync(manifestPath, "utf-8"), lastModified = fs$1.statSync(manifestPath).mtime.toISOString();
212
+ return context.output.print(chalk__default.default.gray(`\u21B3 Read manifest from ${manifestPath} (last modified: ${lastModified})`)), JSON.parse(content);
213
+ }, readManifest = async (readPath, context) => {
214
+ const manifestPath = `${readPath}/${MANIFEST_FILENAME}`;
215
+ try {
216
+ return readAndParseManifest(manifestPath, context);
217
+ } catch {
218
+ context.output.error(`Manifest not found, attempting to extract it...${manifestPath}`), await extractManifestSafe({
219
+ extOptions: {
220
+ path: readPath
221
+ },
222
+ groupOrCommand: "extract",
223
+ argv: [],
224
+ argsWithoutOptions: [],
225
+ extraArguments: []
226
+ }, context);
227
+ try {
228
+ return readAndParseManifest(manifestPath, context);
229
+ } catch (retryError) {
230
+ const errorMessage = `Failed to read manifest at ${manifestPath}`;
231
+ throw context.output.error(errorMessage), retryError;
232
+ }
233
+ }
234
+ }, throwIfProjectIdMismatch = (workspace, projectId) => {
235
+ if (workspace.projectId !== projectId)
236
+ throw new Error(`\u21B3 No permissions to store schema for workspace ${workspace.name} with projectId: ${workspace.projectId}`);
237
+ };
238
+ async function storeSchemasAction(args, context) {
239
+ if (!SCHEMA_STORE_ENABLED)
240
+ return;
241
+ const flags = args.extOptions, schemaRequired = flags["schema-required"], workspaceName = flags.workspace, idPrefix = flags["id-prefix"], verbose = flags.verbose, manifestDir = flags["manifest-dir"];
242
+ if (typeof manifestDir == "boolean") throw new Error("Manifest directory is empty");
243
+ if (typeof idPrefix == "boolean") throw new Error("Id prefix is empty");
244
+ if (typeof workspaceName == "boolean") throw new Error("Workspace is empty");
245
+ const {
246
+ output,
247
+ apiClient
248
+ } = context, manifestPath = getManifestPath(context, manifestDir);
249
+ try {
250
+ const client = apiClient({
251
+ requireUser: !0,
252
+ requireProject: !0
253
+ }).withConfig({
254
+ apiVersion: "v2024-08-01"
255
+ }), projectId = client.config().projectId;
256
+ if (!projectId) throw new Error("Project ID is not defined");
257
+ const manifest = await readManifest(manifestPath, context);
258
+ let storedCount = 0, error;
259
+ const saveSchema = async (workspace) => {
260
+ const id = `${idPrefix ? `${idPrefix}.` : ""}${SANITY_WORKSPACE_SCHEMA_TYPE}.${workspace.name}`;
261
+ try {
262
+ throwIfProjectIdMismatch(workspace, projectId);
263
+ const schema = JSON.parse(fs$1.readFileSync(`${manifestPath}/${workspace.schema}`, "utf-8"));
264
+ await client.withConfig({
265
+ dataset: workspace.dataset,
266
+ projectId: workspace.projectId
267
+ }).transaction().createOrReplace({
268
+ _type: SANITY_WORKSPACE_SCHEMA_TYPE,
269
+ _id: id,
270
+ workspace,
271
+ schema
272
+ }).commit(), storedCount++;
273
+ } catch (err) {
274
+ if (error = err, output.error(`Error storing schema for workspace '${workspace.name}':
275
+ ${chalk__default.default.red(`${err.message}`)}`), schemaRequired) throw err;
276
+ } finally {
277
+ verbose && output.print(chalk__default.default.gray(`\u21B3 schemaId: ${id}, projectId: ${projectId}, dataset: ${workspace.dataset}`));
278
+ }
279
+ };
280
+ if (workspaceName) {
281
+ const workspaceToSave = manifest.workspaces.find((workspace) => workspace.name === workspaceName);
282
+ if (!workspaceToSave)
283
+ throw output.error(`Workspace ${workspaceName} not found in manifest`), new Error(`Workspace ${workspaceName} not found in manifest: projectID: ${projectId}`);
284
+ await saveSchema(workspaceToSave), output.success("Stored 1 schemas");
285
+ } else
286
+ await Promise.all(manifest.workspaces.map(async (workspace) => {
287
+ await saveSchema(workspace);
288
+ })), output.success(`Stored ${storedCount}/${manifest.workspaces.length} schemas`);
289
+ if (error) throw error;
290
+ return;
291
+ } catch (err) {
292
+ if (schemaRequired) throw err;
293
+ return err;
294
+ } finally {
295
+ output.print(`${chalk__default.default.gray("\u21B3 List stored schemas with:")} ${chalk__default.default.cyan("sanity schema list")}`);
296
+ }
297
+ }
298
+ var storeSchemasAction$1 = /* @__PURE__ */ Object.freeze({
299
+ __proto__: null,
300
+ SCHEMA_STORE_ENABLED,
301
+ default: storeSchemasAction,
302
+ getManifestPath,
303
+ readManifest,
304
+ throwIfProjectIdMismatch
305
+ });
26
306
  const appGroup = {
27
307
  name: "app",
28
308
  signature: "[COMMAND]",
@@ -57,6 +337,7 @@ Options
57
337
  --source-maps Enable source maps for built bundles (increases size of bundle)
58
338
  --no-minify Skip minifying built JavaScript (speeds up build, increases size of bundle)
59
339
  --no-build Don't build the application prior to deploy, instead deploying the version currently in \`dist/\`
340
+ ${SCHEMA_STORE_ENABLED ? "--verbose Enable verbose logging for the schema store" : ""}
60
341
  -y, --yes Unattended mode, answers "yes" to any "yes/no" prompt and otherwise uses defaults
61
342
 
62
343
  Examples
@@ -138,9 +419,9 @@ Examples
138
419
  action: async (args, context) => {
139
420
  const {
140
421
  output,
141
- chalk,
422
+ chalk: chalk2,
142
423
  prompt
143
- } = context, previewAction = await getPreviewAction$2(), error = (msg) => output.warn(chalk.red.bgBlack(msg));
424
+ } = context, previewAction = await getPreviewAction$2(), error = (msg) => output.warn(chalk2.red.bgBlack(msg));
144
425
  try {
145
426
  await previewAction(args, context);
146
427
  } catch (err) {
@@ -248,7 +529,7 @@ Examples
248
529
  action: async (args, context) => {
249
530
  const {
250
531
  output,
251
- chalk
532
+ chalk: chalk2
252
533
  } = context, [dataset] = args.argsWithoutOptions, {
253
534
  projectId,
254
535
  datasetName,
@@ -265,13 +546,13 @@ Examples
265
546
  body: {
266
547
  enabled: !1
267
548
  }
268
- }), output.print(`${chalk.green(`Disabled daily backups for dataset ${datasetName}
549
+ }), output.print(`${chalk2.green(`Disabled daily backups for dataset ${datasetName}
269
550
  `)}`);
270
551
  } catch (error) {
271
552
  const {
272
553
  message
273
554
  } = parseApiErr(error);
274
- output.print(`${chalk.red(`Disabling dataset backup failed: ${message}`)}
555
+ output.print(`${chalk2.red(`Disabling dataset backup failed: ${message}`)}
275
556
  `);
276
557
  }
277
558
  }
@@ -280,7 +561,7 @@ var debug$1 = require("debug")("sanity:backup");
280
561
  const archiver = require("archiver");
281
562
  function archiveDir(tmpOutDir, outFilePath, progressCb) {
282
563
  return new Promise((resolve, reject) => {
283
- const archiveDestination = fs.createWriteStream(outFilePath);
564
+ const archiveDestination = fs$1.createWriteStream(outFilePath);
284
565
  archiveDestination.on("error", (err) => {
285
566
  reject(err);
286
567
  }), archiveDestination.on("close", () => {
@@ -369,7 +650,7 @@ async function downloadAsset(url2, fileName, fileType, outDir) {
369
650
  },
370
651
  stream: !0
371
652
  });
372
- debug$1("Received asset %s with status code %d", normalizedFileName, response?.statusCode), await promises.pipeline(response.body, fs.createWriteStream(assetFilePath));
653
+ debug$1("Received asset %s with status code %d", normalizedFileName, response?.statusCode), await promises.pipeline(response.body, fs$1.createWriteStream(assetFilePath));
373
654
  });
374
655
  }
375
656
  function getAssetFilePath(fileName, fileType, outDir) {
@@ -488,7 +769,7 @@ const downloadBackupCommand = {
488
769
  action: async (args, context) => {
489
770
  const {
490
771
  output,
491
- chalk
772
+ chalk: chalk2
492
773
  } = context, [client, opts] = await prepareBackupOptions(context, args), {
493
774
  projectId,
494
775
  datasetName,
@@ -501,14 +782,14 @@ const downloadBackupCommand = {
501
782
  return;
502
783
  }
503
784
  const outFilePath = path__default.default.join(outDir, outFileName);
504
- output.print("\u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E"), output.print("\u2502 \u2502"), output.print("\u2502 Downloading backup for: \u2502"), output.print(`\u2502 ${chalk.bold("projectId")}: ${chalk.cyan(projectId).padEnd(56)} \u2502`), output.print(`\u2502 ${chalk.bold("dataset")}: ${chalk.cyan(datasetName).padEnd(58)} \u2502`), output.print(`\u2502 ${chalk.bold("backupId")}: ${chalk.cyan(backupId).padEnd(56)} \u2502`), output.print("\u2502 \u2502"), output.print("\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F"), output.print(""), output.print(`Downloading backup to "${chalk.cyan(outFilePath)}"`);
505
- const start = Date.now(), progressSpinner = newProgress(output, "Setting up backup environment..."), tmpOutDir = await fs$1.mkdtemp(path__default.default.join(os.tmpdir(), "sanity-backup-"));
785
+ output.print("\u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E"), output.print("\u2502 \u2502"), output.print("\u2502 Downloading backup for: \u2502"), output.print(`\u2502 ${chalk2.bold("projectId")}: ${chalk2.cyan(projectId).padEnd(56)} \u2502`), output.print(`\u2502 ${chalk2.bold("dataset")}: ${chalk2.cyan(datasetName).padEnd(58)} \u2502`), output.print(`\u2502 ${chalk2.bold("backupId")}: ${chalk2.cyan(backupId).padEnd(56)} \u2502`), output.print("\u2502 \u2502"), output.print("\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F"), output.print(""), output.print(`Downloading backup to "${chalk2.cyan(outFilePath)}"`);
786
+ const start = Date.now(), progressSpinner = newProgress(output, "Setting up backup environment..."), tmpOutDir = await fs.mkdtemp(path__default.default.join(os.tmpdir(), "sanity-backup-"));
506
787
  for (const dir of [outDir, path__default.default.join(tmpOutDir, "images"), path__default.default.join(tmpOutDir, "files")])
507
- fs.mkdirSync(dir, {
788
+ fs$1.mkdirSync(dir, {
508
789
  recursive: !0
509
790
  });
510
791
  debug("Writing to temporary directory %s", tmpOutDir);
511
- const tmpOutDocumentsFile = path__default.default.join(tmpOutDir, "data.ndjson"), docOutStream = fs.createWriteStream(tmpOutDocumentsFile), docWriteMutex = new asyncMutex.Mutex();
792
+ const tmpOutDocumentsFile = path__default.default.join(tmpOutDir, "data.ndjson"), docOutStream = fs$1.createWriteStream(tmpOutDocumentsFile), docWriteMutex = new asyncMutex.Mutex();
512
793
  try {
513
794
  const backupFileStream = new PaginatedGetBackupStream(client, opts.projectId, opts.datasetName, opts.backupId, opts.token), files = [];
514
795
  let i = 0;
@@ -563,7 +844,7 @@ const downloadBackupCommand = {
563
844
  throw progressSpinner.fail(), new Error(`Archiving backup failed: ${err.message}`);
564
845
  }
565
846
  progressSpinner.set({
566
- step: `Cleaning up temporary files at ${chalk.cyan(`${tmpOutDir}`)}`
847
+ step: `Cleaning up temporary files at ${chalk2.cyan(`${tmpOutDir}`)}`
567
848
  }), await cleanupTmpDir(tmpOutDir), progressSpinner.set({
568
849
  step: `Backup download complete [${prettyMs__default.default(Date.now() - start)}]`
569
850
  }), progressSpinner.succeed();
@@ -596,7 +877,7 @@ async function prepareBackupOptions(context, args) {
596
877
  default: path__default.default.join(workDir, defaultOutFileName),
597
878
  filter: fs$2.absolutify
598
879
  }))();
599
- return isPathDirName(out) && (out = path__default.default.join(out, defaultOutFileName)), !flags.overwrite && fs.existsSync(out) && (await prompt.single({
880
+ return isPathDirName(out) && (out = path__default.default.join(out, defaultOutFileName)), !flags.overwrite && fs$1.existsSync(out) && (await prompt.single({
600
881
  type: "confirm",
601
882
  message: `File "${out}" already exists, would you like to overwrite it?`,
602
883
  default: !1
@@ -623,7 +904,7 @@ Examples
623
904
  action: async (args, context) => {
624
905
  const {
625
906
  output,
626
- chalk
907
+ chalk: chalk2
627
908
  } = context, [dataset] = args.argsWithoutOptions, {
628
909
  projectId,
629
910
  datasetName,
@@ -640,15 +921,15 @@ Examples
640
921
  body: {
641
922
  enabled: !0
642
923
  }
643
- }), output.print(`${chalk.green(`Enabled backups for dataset ${datasetName}.
924
+ }), output.print(`${chalk2.green(`Enabled backups for dataset ${datasetName}.
644
925
  Please note that it may take up to 24 hours before the first backup is created.
645
- `)}`), output.print(`${chalk.bold(`Retention policies may apply depending on your plan and agreement.
926
+ `)}`), output.print(`${chalk2.bold(`Retention policies may apply depending on your plan and agreement.
646
927
  `)}`);
647
928
  } catch (error) {
648
929
  const {
649
930
  message
650
931
  } = parseApiErr(error);
651
- output.print(`${chalk.red(`Enabling dataset backup failed: ${message}`)}
932
+ output.print(`${chalk2.red(`Enabling dataset backup failed: ${message}`)}
652
933
  `);
653
934
  }
654
935
  }
@@ -684,7 +965,7 @@ const listDatasetBackupCommand = {
684
965
  action: async (args, context) => {
685
966
  const {
686
967
  output,
687
- chalk
968
+ chalk: chalk2
688
969
  } = context, flags = await parseCliFlags$6(args), [dataset] = args.argsWithoutOptions, {
689
970
  projectId,
690
971
  datasetName,
@@ -722,7 +1003,7 @@ const listDatasetBackupCommand = {
722
1003
  const {
723
1004
  message
724
1005
  } = parseApiErr(error);
725
- output.error(`${chalk.red(`List dataset backup failed: ${message}`)}
1006
+ output.error(`${chalk2.red(`List dataset backup failed: ${message}`)}
726
1007
  `);
727
1008
  }
728
1009
  if (response && response.backups) {
@@ -818,19 +1099,19 @@ function promptForCredentials(hasWildcard, context) {
818
1099
  const {
819
1100
  prompt,
820
1101
  output,
821
- chalk
1102
+ chalk: chalk2
822
1103
  } = context;
823
1104
  return output.print(""), hasWildcard ? output.print(oneline__default.default`
824
- ${chalk.yellow(`${logSymbols__default.default.warning} Warning:`)}
825
- We ${chalk.red(chalk.underline("HIGHLY"))} recommend NOT allowing credentials
1105
+ ${chalk2.yellow(`${logSymbols__default.default.warning} Warning:`)}
1106
+ We ${chalk2.red(chalk2.underline("HIGHLY"))} recommend NOT allowing credentials
826
1107
  on origins containing wildcards. If you are logged in to a studio, people will
827
- be able to send requests ${chalk.underline("on your behalf")} to read and modify
1108
+ be able to send requests ${chalk2.underline("on your behalf")} to read and modify
828
1109
  data, from any matching origin. Please tread carefully!
829
1110
  `) : output.print(oneline__default.default`
830
- ${chalk.yellow(`${logSymbols__default.default.warning} Warning:`)}
1111
+ ${chalk2.yellow(`${logSymbols__default.default.warning} Warning:`)}
831
1112
  Should this origin be allowed to send requests using authentication tokens or
832
1113
  session cookies? Be aware that any script on this origin will be able to send
833
- requests ${chalk.underline("on your behalf")} to read and modify data if you
1114
+ requests ${chalk2.underline("on your behalf")} to read and modify data if you
834
1115
  are logged in to a Sanity studio. If this origin hosts a studio, you will need
835
1116
  this, otherwise you should probably answer "No" (n).
836
1117
  `), output.print(""), prompt.single({
@@ -845,13 +1126,13 @@ function promptForWildcardConfirmation(origin, context) {
845
1126
  const {
846
1127
  prompt,
847
1128
  output,
848
- chalk
1129
+ chalk: chalk2
849
1130
  } = context;
850
- return output.print(""), output.print(chalk.yellow(`${logSymbols__default.default.warning} Warning: Examples of allowed origins:`)), origin === "*" ? (output.print("- http://www.some-malicious.site"), output.print("- https://not.what-you-were-expecting.com"), output.print("- https://high-traffic-site.com"), output.print("- http://192.168.1.1:8080")) : (output.print(`- ${origin.replace(/:\*/, ":1234").replace(/\*/g, "foo")}`), output.print(`- ${origin.replace(/:\*/, ":3030").replace(/\*/g, "foo.bar")}`)), output.print(""), prompt.single({
1131
+ return output.print(""), output.print(chalk2.yellow(`${logSymbols__default.default.warning} Warning: Examples of allowed origins:`)), origin === "*" ? (output.print("- http://www.some-malicious.site"), output.print("- https://not.what-you-were-expecting.com"), output.print("- https://high-traffic-site.com"), output.print("- http://192.168.1.1:8080")) : (output.print(`- ${origin.replace(/:\*/, ":1234").replace(/\*/g, "foo")}`), output.print(`- ${origin.replace(/:\*/, ":3030").replace(/\*/g, "foo.bar")}`)), output.print(""), prompt.single({
851
1132
  type: "confirm",
852
1133
  message: oneline__default.default`
853
- Using wildcards can be ${chalk.red("risky")}.
854
- Are you ${chalk.underline("absolutely sure")} you want to allow this origin?`,
1134
+ Using wildcards can be ${chalk2.red("risky")}.
1135
+ Are you ${chalk2.underline("absolutely sure")} you want to allow this origin?`,
855
1136
  default: !1
856
1137
  });
857
1138
  }
@@ -1244,7 +1525,7 @@ async function listDatasetCopyJobs(flags, context) {
1244
1525
  const {
1245
1526
  apiClient,
1246
1527
  output,
1247
- chalk
1528
+ chalk: chalk2
1248
1529
  } = context, client = apiClient(), projectId = client.config().projectId, query = {};
1249
1530
  let response;
1250
1531
  flags.offset && flags.offset >= 0 && (query.offset = `${flags.offset}`), flags.limit && flags.limit > 0 && (query.limit = `${flags.limit}`);
@@ -1255,9 +1536,9 @@ async function listDatasetCopyJobs(flags, context) {
1255
1536
  query
1256
1537
  });
1257
1538
  } catch (error) {
1258
- error.statusCode ? output.error(`${chalk.red(`Dataset copy list failed:
1539
+ error.statusCode ? output.error(`${chalk2.red(`Dataset copy list failed:
1259
1540
  ${error.response.body.message}`)}
1260
- `) : output.error(`${chalk.red(`Dataset copy list failed:
1541
+ `) : output.error(`${chalk2.red(`Dataset copy list failed:
1261
1542
  ${error.message}`)}
1262
1543
  `);
1263
1544
  }
@@ -1420,7 +1701,7 @@ const progress = (url2) => new rxjs.Observable((observer) => {
1420
1701
  apiClient,
1421
1702
  output,
1422
1703
  prompt,
1423
- chalk
1704
+ chalk: chalk2
1424
1705
  } = context, flags = await parseCliFlags$3(args), client = apiClient();
1425
1706
  if (flags.list) {
1426
1707
  await listDatasetCopyJobs(flags, context);
@@ -1458,13 +1739,13 @@ const progress = (url2) => new rxjs.Observable((observer) => {
1458
1739
  skipHistory: shouldSkipHistory
1459
1740
  }
1460
1741
  });
1461
- if (output.print(`Copying dataset ${chalk.green(sourceDatasetName)} to ${chalk.green(targetDatasetName)}...`), shouldSkipHistory || output.print("Note: You can run this command with flag '--skip-history'. The flag will reduce copy time in larger datasets."), output.print(`Job ${chalk.green(response.jobId)} started`), flags.detach)
1742
+ if (output.print(`Copying dataset ${chalk2.green(sourceDatasetName)} to ${chalk2.green(targetDatasetName)}...`), shouldSkipHistory || output.print("Note: You can run this command with flag '--skip-history'. The flag will reduce copy time in larger datasets."), output.print(`Job ${chalk2.green(response.jobId)} started`), flags.detach)
1462
1743
  return;
1463
- await followProgress(response.jobId, client, output), output.print(`Job ${chalk.green(response.jobId)} completed`);
1744
+ await followProgress(response.jobId, client, output), output.print(`Job ${chalk2.green(response.jobId)} completed`);
1464
1745
  } catch (error) {
1465
- error.statusCode ? output.print(`${chalk.red(`Dataset copying failed:
1746
+ error.statusCode ? output.print(`${chalk2.red(`Dataset copying failed:
1466
1747
  ${error.response.body.message}`)}
1467
- `) : output.print(`${chalk.red(`Dataset copying failed:
1748
+ `) : output.print(`${chalk2.red(`Dataset copying failed:
1468
1749
  ${error.message}`)}
1469
1750
  `);
1470
1751
  }
@@ -1646,7 +1927,7 @@ const exportDatasetCommand = {
1646
1927
  const {
1647
1928
  apiClient,
1648
1929
  output,
1649
- chalk,
1930
+ chalk: chalk2,
1650
1931
  workDir,
1651
1932
  prompt
1652
1933
  } = context, client = apiClient(), [targetDataset, targetDestination] = args.argsWithoutOptions, flags = parseFlags$1(args.extOptions);
@@ -1662,7 +1943,7 @@ const exportDatasetCommand = {
1662
1943
  const {
1663
1944
  projectId
1664
1945
  } = client.config();
1665
- output.print("\u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E"), output.print("\u2502 \u2502"), output.print("\u2502 Exporting from: \u2502"), output.print(`\u2502 ${chalk.bold("projectId")}: ${chalk.cyan(projectId).padEnd(44)} \u2502`), output.print(`\u2502 ${chalk.bold("dataset")}: ${chalk.cyan(dataset).padEnd(46)} \u2502`), output.print("\u2502 \u2502"), output.print("\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F"), output.print("");
1946
+ output.print("\u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E"), output.print("\u2502 \u2502"), output.print("\u2502 Exporting from: \u2502"), output.print(`\u2502 ${chalk2.bold("projectId")}: ${chalk2.cyan(projectId).padEnd(44)} \u2502`), output.print(`\u2502 ${chalk2.bold("dataset")}: ${chalk2.cyan(dataset).padEnd(46)} \u2502`), output.print("\u2502 \u2502"), output.print("\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F"), output.print("");
1666
1947
  let destinationPath = targetDestination;
1667
1948
  destinationPath || (destinationPath = await prompt.single({
1668
1949
  type: "input",
@@ -1675,7 +1956,7 @@ const exportDatasetCommand = {
1675
1956
  output.print("Cancelled");
1676
1957
  return;
1677
1958
  }
1678
- outputPath !== "-" && output.print(`Exporting dataset "${chalk.cyan(dataset)}" to "${chalk.cyan(outputPath)}"`);
1959
+ outputPath !== "-" && output.print(`Exporting dataset "${chalk2.cyan(dataset)}" to "${chalk2.cyan(outputPath)}"`);
1679
1960
  let currentStep = "Exporting documents...", spinner = output.spinner(currentStep).start();
1680
1961
  const onProgress = (progress2) => {
1681
1962
  progress2.step !== currentStep ? (spinner.succeed(), spinner = output.spinner(progress2.step).start()) : progress2.step === currentStep && progress2.update && (spinner.text = `${progress2.step} (${progress2.current}/${progress2.total})`), currentStep = progress2.step;
@@ -1768,7 +2049,7 @@ const importDatasetCommand = {
1768
2049
  const {
1769
2050
  apiClient,
1770
2051
  output,
1771
- chalk,
2052
+ chalk: chalk2,
1772
2053
  fromInitCommand
1773
2054
  } = context, flags = parseFlags(args.extOptions), {
1774
2055
  allowAssetsInDifferentDataset,
@@ -1779,7 +2060,7 @@ const importDatasetCommand = {
1779
2060
  replaceAssets
1780
2061
  } = flags, operation = getMutationOperation(args.extOptions), client = apiClient(), [file, target] = args.argsWithoutOptions;
1781
2062
  if (!file)
1782
- throw new Error(`Source file name and target dataset must be specified ("sanity dataset import ${chalk.bold("[file]")} [dataset]")`);
2063
+ throw new Error(`Source file name and target dataset must be specified ("sanity dataset import ${chalk2.bold("[file]")} [dataset]")`);
1783
2064
  const targetDataset = await determineTargetDataset(target, context);
1784
2065
  debug$2(`Target dataset has been set to "${targetDataset}"`);
1785
2066
  const isUrl = /^https?:\/\//i.test(file);
@@ -1790,7 +2071,7 @@ const importDatasetCommand = {
1790
2071
  const sourceFile = path__default.default.resolve(process.cwd(), file), fileStats = await fs__default$1.default.stat(sourceFile).catch(() => null);
1791
2072
  if (!fileStats)
1792
2073
  throw new Error(`${sourceFile} does not exist or is not readable`);
1793
- sourceIsFolder = fileStats.isDirectory(), sourceIsFolder ? inputStream = sourceFile : (assetsBase = path__default.default.dirname(sourceFile), inputStream = await fs.createReadStream(sourceFile));
2074
+ sourceIsFolder = fileStats.isDirectory(), sourceIsFolder ? inputStream = sourceFile : (assetsBase = path__default.default.dirname(sourceFile), inputStream = await fs$1.createReadStream(sourceFile));
1794
2075
  }
1795
2076
  const importClient = client.clone().config({
1796
2077
  dataset: targetDataset
@@ -1798,7 +2079,7 @@ const importDatasetCommand = {
1798
2079
  projectId,
1799
2080
  dataset
1800
2081
  } = importClient.config();
1801
- output.print("\u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E"), output.print("\u2502 \u2502"), output.print("\u2502 Importing to: \u2502"), output.print(`\u2502 ${chalk.bold("projectId")}: ${chalk.cyan(projectId).padEnd(44)} \u2502`), output.print(`\u2502 ${chalk.bold("dataset")}: ${chalk.cyan(dataset).padEnd(46)} \u2502`), output.print("\u2502 \u2502"), output.print("\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F"), output.print("");
2082
+ output.print("\u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E"), output.print("\u2502 \u2502"), output.print("\u2502 Importing to: \u2502"), output.print(`\u2502 ${chalk2.bold("projectId")}: ${chalk2.cyan(projectId).padEnd(44)} \u2502`), output.print(`\u2502 ${chalk2.bold("dataset")}: ${chalk2.cyan(dataset).padEnd(46)} \u2502`), output.print("\u2502 \u2502"), output.print("\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F"), output.print("");
1802
2083
  let currentStep, currentProgress, stepStart, spinInterval = null, percent;
1803
2084
  function onProgress(opts) {
1804
2085
  const lengthComputable = opts.total, sameStep = opts.step == currentStep;
@@ -2165,7 +2446,7 @@ Example
2165
2446
  const {
2166
2447
  apiClient,
2167
2448
  output,
2168
- chalk
2449
+ chalk: chalk2
2169
2450
  } = context, {
2170
2451
  dataset
2171
2452
  } = args.extOptions, ids = args.argsWithoutOptions.map((str) => `${str}`);
@@ -2178,7 +2459,7 @@ Example
2178
2459
  const {
2179
2460
  results
2180
2461
  } = await transaction.commit(), deleted = results.filter((res) => res.operation === "delete").map((res) => res.id), notFound = ids.filter((id) => !deleted.includes(id));
2181
- deleted.length > 0 && output.print(`Deleted ${deleted.length} ${pluralize__default.default("document", deleted.length)}`), notFound.length > 0 && output.error(chalk.red(`${pluralize__default.default("Document", notFound.length)} not found: ${notFound.join(", ")}`));
2462
+ deleted.length > 0 && output.print(`Deleted ${deleted.length} ${pluralize__default.default("document", deleted.length)}`), notFound.length > 0 && output.error(chalk2.red(`${pluralize__default.default("Document", notFound.length)} not found: ${notFound.join(", ")}`));
2182
2463
  } catch (err) {
2183
2464
  throw new Error(`Failed to delete ${pluralize__default.default("document", ids.length)}:
2184
2465
  ${err.message}`);
@@ -2190,13 +2471,13 @@ ${err.message}`);
2190
2471
  isGroupRoot: !0,
2191
2472
  description: "Manages documents in your Sanity Content Lake datasets"
2192
2473
  }, identity = (inp) => inp;
2193
- function colorizeJson(input, chalk) {
2474
+ function colorizeJson(input, chalk2) {
2194
2475
  const formatters = {
2195
- punctuator: chalk.white,
2196
- key: chalk.white,
2197
- string: chalk.green,
2198
- number: chalk.yellow,
2199
- literal: chalk.bold,
2476
+ punctuator: chalk2.white,
2477
+ key: chalk2.white,
2478
+ string: chalk2.green,
2479
+ number: chalk2.yellow,
2480
+ literal: chalk2.bold,
2200
2481
  whitespace: identity
2201
2482
  }, json = JSON.stringify(input, null, 2);
2202
2483
  return tokenize__default.default(json).map((token, i, arr) => {
@@ -2230,7 +2511,7 @@ Examples
2230
2511
  const {
2231
2512
  apiClient,
2232
2513
  output,
2233
- chalk
2514
+ chalk: chalk2
2234
2515
  } = context, {
2235
2516
  pretty,
2236
2517
  dataset
@@ -2244,7 +2525,7 @@ Examples
2244
2525
  const doc = await client.getDocument(docId);
2245
2526
  if (!doc)
2246
2527
  throw new Error(`Document ${docId} not found`);
2247
- output.print(pretty ? colorizeJson(doc, chalk) : JSON.stringify(doc, null, 2));
2528
+ output.print(pretty ? colorizeJson(doc, chalk2) : JSON.stringify(doc, null, 2));
2248
2529
  } catch (err) {
2249
2530
  throw new Error(`Failed to fetch document:
2250
2531
  ${err.message}`);
@@ -2290,12 +2571,12 @@ var queryDocumentsCommand = {
2290
2571
  } = await parseCliFlags$1(args), {
2291
2572
  apiClient,
2292
2573
  output,
2293
- chalk,
2574
+ chalk: chalk2,
2294
2575
  cliConfig
2295
2576
  } = context, [query] = args.argsWithoutOptions;
2296
2577
  if (!query)
2297
2578
  throw new Error("Query must be specified");
2298
- apiVersion || output.warn(chalk.yellow(`--api-version not specified, using \`${defaultApiVersion}\``));
2579
+ apiVersion || output.warn(chalk2.yellow(`--api-version not specified, using \`${defaultApiVersion}\``));
2299
2580
  const requireDataset = !dataset, requireProject = !project, requireUser = !anonymous;
2300
2581
  if (requireProject && !cliConfig?.api?.projectId)
2301
2582
  throw new Error("No project configured in CLI config - either configure one, or use `--project` flag");
@@ -2316,7 +2597,7 @@ var queryDocumentsCommand = {
2316
2597
  const docs = await client.fetch(query);
2317
2598
  if (!docs)
2318
2599
  throw new Error("Query returned no results");
2319
- output.print(pretty ? colorizeJson(docs, chalk) : JSON.stringify(docs, null, 2));
2600
+ output.print(pretty ? colorizeJson(docs, chalk2) : JSON.stringify(docs, null, 2));
2320
2601
  } catch (err) {
2321
2602
  throw new Error(`Failed to run query:
2322
2603
  ${err.message}`);
@@ -2680,19 +2961,19 @@ function printMessage(message, context, options) {
2680
2961
  detailed
2681
2962
  } = options, {
2682
2963
  output,
2683
- chalk
2964
+ chalk: chalk2
2684
2965
  } = context;
2685
2966
  output.print(`Date: ${message.createdAt}`), output.print(`Status: ${message.status}`), output.print(`Result code: ${message.resultCode}`), message.failureCount > 0 && output.print(`Failures: ${message.failureCount}`), detailed && (output.print("Payload:"), output.print(node_util.inspect(JSON.parse(message.payload), {
2686
2967
  colors: !0
2687
2968
  }))), detailed && message.attempts && (output.print("Attempts:"), message.attempts.forEach((attempt) => {
2688
2969
  const prefix = ` [${attempt.createdAt.replace(/\.\d+Z$/, "Z")}]`;
2689
2970
  if (attempt.inProgress)
2690
- output.print(`${prefix} ${chalk.yellow("Pending")}`);
2971
+ output.print(`${prefix} ${chalk2.yellow("Pending")}`);
2691
2972
  else if (attempt.isFailure) {
2692
2973
  const failure = formatFailure(attempt, {
2693
2974
  includeHelp: !0
2694
2975
  });
2695
- output.print(`${prefix} ${chalk.yellow(`Failure: ${failure}`)}`);
2976
+ output.print(`${prefix} ${chalk2.yellow(`Failure: ${failure}`)}`);
2696
2977
  } else
2697
2978
  output.print(`${prefix} Success: HTTP ${attempt.resultCode} (${attempt.duration}ms)`);
2698
2979
  })), output.print("");
@@ -2743,10 +3024,10 @@ Examples
2743
3024
  helpText: helpText$c,
2744
3025
  action: async (args, context) => {
2745
3026
  const {
2746
- extractManifestSafe
3027
+ extractManifestSafe: extractManifestSafe2
2747
3028
  } = await Promise.resolve().then(function() {
2748
- return require("./extractManifestAction.js");
2749
- }), extractError = await extractManifestSafe(args, context);
3029
+ return extractManifestAction;
3030
+ }), extractError = await extractManifestSafe2(args, context);
2750
3031
  if (extractError)
2751
3032
  throw extractError;
2752
3033
  return extractError;
@@ -2949,7 +3230,7 @@ Examples:
2949
3230
  output,
2950
3231
  prompt,
2951
3232
  workDir,
2952
- chalk
3233
+ chalk: chalk2
2953
3234
  } = context;
2954
3235
  let [title] = args.argsWithoutOptions;
2955
3236
  for (; !title?.trim(); )
@@ -2957,7 +3238,7 @@ Examples:
2957
3238
  type: "input",
2958
3239
  suffix: ' (e.g. "Rename field from location to address")',
2959
3240
  message: "Title of migration"
2960
- }), title.trim() || output.error(chalk.red("Name cannot be empty"));
3241
+ }), title.trim() || output.error(chalk2.red("Name cannot be empty"));
2961
3242
  const types2 = await prompt.single({
2962
3243
  type: "input",
2963
3244
  suffix: " (optional)",
@@ -2970,22 +3251,22 @@ Examples:
2970
3251
  value: definedTemplate.name
2971
3252
  }))
2972
3253
  }), sluggedName = deburr__default.default(title.toLowerCase()).replace(/\s+/g, "-").replace(/[^a-z0-9-]/g, ""), destDir = path__default.default.join(workDir, MIGRATIONS_DIRECTORY, sluggedName);
2973
- if (fs.existsSync(destDir) && !await prompt.single({
3254
+ if (fs$1.existsSync(destDir) && !await prompt.single({
2974
3255
  type: "confirm",
2975
- message: `Migration directory ${chalk.cyan(destDir)} already exists. Overwrite?`,
3256
+ message: `Migration directory ${chalk2.cyan(destDir)} already exists. Overwrite?`,
2976
3257
  default: !1
2977
3258
  }))
2978
3259
  return;
2979
- fs.mkdirSync(destDir, {
3260
+ fs$1.mkdirSync(destDir, {
2980
3261
  recursive: !0
2981
3262
  });
2982
3263
  const renderedTemplate = (templatesByName[template].template || minimalSimple)({
2983
3264
  migrationName: title,
2984
3265
  documentTypes: types2.split(",").map((t) => t.trim()).filter(Boolean)
2985
3266
  }), definitionFile = path__default.default.join(destDir, "index.ts");
2986
- await fs$1.writeFile(definitionFile, renderedTemplate), output.print(), output.print(`${chalk.green("\u2713")} Migration created!`), output.print(), output.print("Next steps:"), output.print(`Open ${chalk.bold(definitionFile)} in your code editor and write the code for your migration.`), output.print(`Dry run the migration with:
2987
- \`${chalk.bold(`sanity migration run ${sluggedName} --project=<projectId> --dataset <dataset> `)}\``), output.print(`Run the migration against a dataset with:
2988
- \`${chalk.bold(`sanity migration run ${sluggedName} --project=<projectId> --dataset <dataset> --no-dry-run`)}\``), output.print(), output.print(`\u{1F449} Learn more about schema and content migrations at ${chalk.bold("https://www.sanity.io/docs/schema-and-content-migrations")}`);
3267
+ await fs.writeFile(definitionFile, renderedTemplate), output.print(), output.print(`${chalk2.green("\u2713")} Migration created!`), output.print(), output.print("Next steps:"), output.print(`Open ${chalk2.bold(definitionFile)} in your code editor and write the code for your migration.`), output.print(`Dry run the migration with:
3268
+ \`${chalk2.bold(`sanity migration run ${sluggedName} --project=<projectId> --dataset <dataset> `)}\``), output.print(`Run the migration against a dataset with:
3269
+ \`${chalk2.bold(`sanity migration run ${sluggedName} --project=<projectId> --dataset <dataset> --no-dry-run`)}\``), output.print(), output.print(`\u{1F449} Learn more about schema and content migrations at ${chalk2.bold("https://www.sanity.io/docs/schema-and-content-migrations")}`);
2989
3270
  }
2990
3271
  };
2991
3272
  function resolveMigrationScript(workDir, migrationName) {
@@ -3021,13 +3302,13 @@ const helpText$a = "", listMigrationCommand = {
3021
3302
  const {
3022
3303
  workDir,
3023
3304
  output,
3024
- chalk
3305
+ chalk: chalk2
3025
3306
  } = context;
3026
3307
  try {
3027
3308
  const migrations = await resolveMigrations(workDir);
3028
3309
  if (migrations.length === 0) {
3029
3310
  output.print("No migrations found in migrations folder of the project"), output.print(`
3030
- Run ${chalk.green("`sanity migration create <NAME>`")} to create a new migration`);
3311
+ Run ${chalk2.green("`sanity migration create <NAME>`")} to create a new migration`);
3031
3312
  return;
3032
3313
  }
3033
3314
  const table = new consoleTablePrinter.Table({
@@ -3051,7 +3332,7 @@ Run ${chalk.green("`sanity migration create <NAME>`")} to create a new migration
3051
3332
  } catch (error) {
3052
3333
  if (error.code === "ENOENT") {
3053
3334
  output.print("No migrations folder found in the project"), output.print(`
3054
- Run ${chalk.green("`sanity migration create <NAME>`")} to create a new migration`);
3335
+ Run ${chalk2.green("`sanity migration create <NAME>`")} to create a new migration`);
3055
3336
  return;
3056
3337
  }
3057
3338
  throw new Error(`An error occurred while listing migrations: ${error.message}`);
@@ -3066,7 +3347,7 @@ async function resolveMigrations(workDir) {
3066
3347
  "dynamic-import": !0
3067
3348
  }
3068
3349
  }).unregister;
3069
- const migrationsDir = path__default.default.join(workDir, MIGRATIONS_DIRECTORY), migrationEntries = await fs$1.readdir(migrationsDir, {
3350
+ const migrationsDir = path__default.default.join(workDir, MIGRATIONS_DIRECTORY), migrationEntries = await fs.readdir(migrationsDir, {
3070
3351
  withFileTypes: !0
3071
3352
  }), migrations = [];
3072
3353
  for (const entry of migrationEntries) {
@@ -3152,20 +3433,20 @@ function convertToTree(nodes) {
3152
3433
  }
3153
3434
  const isTty = node_tty.isatty(1);
3154
3435
  function prettyFormat({
3155
- chalk,
3436
+ chalk: chalk2,
3156
3437
  subject,
3157
3438
  migration,
3158
3439
  indentSize = 0
3159
3440
  }) {
3160
- return (Array.isArray(subject) ? subject : [subject]).map((subjectEntry) => subjectEntry.type === "transaction" ? [[badge("transaction", "info", chalk), typeof subjectEntry.id > "u" ? null : chalk.underline(subjectEntry.id)].filter(Boolean).join(" "), indent(prettyFormat({
3161
- chalk,
3441
+ return (Array.isArray(subject) ? subject : [subject]).map((subjectEntry) => subjectEntry.type === "transaction" ? [[badge("transaction", "info", chalk2), typeof subjectEntry.id > "u" ? null : chalk2.underline(subjectEntry.id)].filter(Boolean).join(" "), indent(prettyFormat({
3442
+ chalk: chalk2,
3162
3443
  subject: subjectEntry.mutations,
3163
3444
  migration,
3164
3445
  indentSize
3165
3446
  }))].join(`
3166
3447
 
3167
3448
  `) : prettyFormatMutation({
3168
- chalk,
3449
+ chalk: chalk2,
3169
3450
  subject: subjectEntry,
3170
3451
  migration,
3171
3452
  indentSize
@@ -3176,16 +3457,16 @@ function prettyFormat({
3176
3457
  function encodeItemRef(ref) {
3177
3458
  return typeof ref == "number" ? ref : ref._key;
3178
3459
  }
3179
- function badgeStyle(chalk, variant) {
3460
+ function badgeStyle(chalk2, variant) {
3180
3461
  return {
3181
- info: chalk.bgWhite.black,
3182
- incremental: chalk.bgGreen.black.bold,
3183
- maybeDestructive: chalk.bgYellow.black.bold,
3184
- destructive: chalk.bgRed.black.bold
3462
+ info: chalk2.bgWhite.black,
3463
+ incremental: chalk2.bgGreen.black.bold,
3464
+ maybeDestructive: chalk2.bgYellow.black.bold,
3465
+ destructive: chalk2.bgRed.black.bold
3185
3466
  }[variant];
3186
3467
  }
3187
- function badge(label, variant, chalk) {
3188
- return isTty ? badgeStyle(chalk, variant)(` ${label} `) : `[${label}]`;
3468
+ function badge(label, variant, chalk2) {
3469
+ return isTty ? badgeStyle(chalk2, variant)(` ${label} `) : `[${label}]`;
3189
3470
  }
3190
3471
  const mutationImpact = {
3191
3472
  create: "incremental",
@@ -3203,17 +3484,17 @@ function documentId(mutation) {
3203
3484
  const listFormatter = new Intl.ListFormat("en-US", {
3204
3485
  type: "disjunction"
3205
3486
  });
3206
- function mutationHeader(chalk, mutation, migration) {
3207
- const mutationType = badge(mutation.type, mutationImpact[mutation.type], chalk), documentType = "document" in mutation || migration.documentTypes ? badge("document" in mutation ? mutation.document._type : listFormatter.format(migration.documentTypes ?? []), "info", chalk) : null;
3208
- return [mutationType, documentType, chalk.underline(documentId(mutation))].filter(Boolean).join(" ");
3487
+ function mutationHeader(chalk2, mutation, migration) {
3488
+ const mutationType = badge(mutation.type, mutationImpact[mutation.type], chalk2), documentType = "document" in mutation || migration.documentTypes ? badge("document" in mutation ? mutation.document._type : listFormatter.format(migration.documentTypes ?? []), "info", chalk2) : null;
3489
+ return [mutationType, documentType, chalk2.underline(documentId(mutation))].filter(Boolean).join(" ");
3209
3490
  }
3210
3491
  function prettyFormatMutation({
3211
- chalk,
3492
+ chalk: chalk2,
3212
3493
  subject,
3213
3494
  migration,
3214
3495
  indentSize = 0
3215
3496
  }) {
3216
- const lock = "options" in subject ? chalk.cyan(`(if revision==${subject.options?.ifRevision})`) : "", header = [mutationHeader(chalk, subject, migration), lock].join(" "), padding = " ".repeat(indentSize);
3497
+ const lock = "options" in subject ? chalk2.cyan(`(if revision==${subject.options?.ifRevision})`) : "", header = [mutationHeader(chalk2, subject, migration), lock].join(" "), padding = " ".repeat(indentSize);
3217
3498
  if (subject.type === "create" || subject.type === "createIfNotExists" || subject.type === "createOrReplace")
3218
3499
  return [header, `
3219
3500
  `, indent(JSON.stringify(subject.document, null, 2), indentSize)].join("");
@@ -3224,31 +3505,31 @@ function prettyFormatMutation({
3224
3505
  node: tree.children,
3225
3506
  paddingLength,
3226
3507
  indent: padding,
3227
- getMessage: (patch) => formatPatchMutation(chalk, patch)
3508
+ getMessage: (patch) => formatPatchMutation(chalk2, patch)
3228
3509
  })].join("");
3229
3510
  }
3230
3511
  return header;
3231
3512
  }
3232
- function formatPatchMutation(chalk, patch) {
3513
+ function formatPatchMutation(chalk2, patch) {
3233
3514
  const {
3234
3515
  op
3235
- } = patch, formattedType = chalk.bold(op.type);
3516
+ } = patch, formattedType = chalk2.bold(op.type);
3236
3517
  if (op.type === "unset")
3237
- return `${chalk.red(formattedType)}()`;
3518
+ return `${chalk2.red(formattedType)}()`;
3238
3519
  if (op.type === "diffMatchPatch")
3239
- return `${chalk.yellow(formattedType)}(${op.value})`;
3520
+ return `${chalk2.yellow(formattedType)}(${op.value})`;
3240
3521
  if (op.type === "inc" || op.type === "dec")
3241
- return `${chalk.yellow(formattedType)}(${op.amount})`;
3522
+ return `${chalk2.yellow(formattedType)}(${op.amount})`;
3242
3523
  if (op.type === "set")
3243
- return `${chalk.yellow(formattedType)}(${JSON.stringify(op.value)})`;
3524
+ return `${chalk2.yellow(formattedType)}(${JSON.stringify(op.value)})`;
3244
3525
  if (op.type === "setIfMissing")
3245
- return `${chalk.green(formattedType)}(${JSON.stringify(op.value)})`;
3526
+ return `${chalk2.green(formattedType)}(${JSON.stringify(op.value)})`;
3246
3527
  if (op.type === "insert")
3247
- return `${chalk.green(formattedType)}(${op.position}, ${encodeItemRef(op.referenceItem)}, ${JSON.stringify(op.items)})`;
3528
+ return `${chalk2.green(formattedType)}(${op.position}, ${encodeItemRef(op.referenceItem)}, ${JSON.stringify(op.items)})`;
3248
3529
  if (op.type === "replace")
3249
- return `${chalk.yellow(formattedType)}(${encodeItemRef(op.referenceItem)}, ${JSON.stringify(op.items)})`;
3530
+ return `${chalk2.yellow(formattedType)}(${encodeItemRef(op.referenceItem)}, ${JSON.stringify(op.items)})`;
3250
3531
  if (op.type === "truncate")
3251
- return `${chalk.red(formattedType)}(${op.startIndex}, ${op.endIndex})`;
3532
+ return `${chalk2.red(formattedType)}(${op.startIndex}, ${op.endIndex})`;
3252
3533
  throw new Error(`Invalid operation type: ${op.type}`);
3253
3534
  }
3254
3535
  function indent(subject, size2 = 2) {
@@ -3311,13 +3592,13 @@ const runMigrationCommand = {
3311
3592
  apiClient,
3312
3593
  output,
3313
3594
  prompt,
3314
- chalk,
3595
+ chalk: chalk2,
3315
3596
  workDir
3316
3597
  } = context, [id] = args.argsWithoutOptions, migrationsDirectoryPath = path__default.default.join(workDir, MIGRATIONS_DIRECTORY), flags = await parseCliFlags(args), fromExport = flags.fromExport, dry = flags.dryRun, dataset = flags.dataset, project = flags.project;
3317
3598
  if (dataset && !project || project && !dataset)
3318
3599
  throw new Error("If either --dataset or --project is provided, both must be provided");
3319
3600
  if (!id) {
3320
- output.error(chalk.red("Error: Migration ID must be provided"));
3601
+ output.error(chalk2.red("Error: Migration ID must be provided"));
3321
3602
  const migrations = await resolveMigrations(workDir), table = new consoleTablePrinter.Table({
3322
3603
  title: "Migrations found in project",
3323
3604
  columns: [{
@@ -3346,12 +3627,12 @@ const runMigrationCommand = {
3346
3627
  });
3347
3628
  const candidates = resolveMigrationScript(workDir, id), resolvedScripts = candidates.filter(isLoadableMigrationScript);
3348
3629
  if (resolvedScripts.length > 1)
3349
- throw new Error(`Found multiple migrations for "${id}" in ${chalk.cyan(migrationsDirectoryPath)}:
3630
+ throw new Error(`Found multiple migrations for "${id}" in ${chalk2.cyan(migrationsDirectoryPath)}:
3350
3631
  - ${candidates.map((candidate) => path__default.default.relative(migrationsDirectoryPath, candidate.absolutePath)).join(`
3351
3632
  - `)}`);
3352
3633
  const script = resolvedScripts[0];
3353
3634
  if (!script)
3354
- throw new Error(`No migration found for "${id}" in ${chalk.cyan(chalk.cyan(migrationsDirectoryPath))}. Make sure that the migration file exists and exports a valid migration as its default export.
3635
+ throw new Error(`No migration found for "${id}" in ${chalk2.cyan(chalk2.cyan(migrationsDirectoryPath))}. Make sure that the migration file exists and exports a valid migration as its default export.
3355
3636
 
3356
3637
  Tried the following files:
3357
3638
  - ${candidates.map((candidate) => path__default.default.relative(migrationsDirectoryPath, candidate.absolutePath)).join(`
@@ -3387,9 +3668,9 @@ const runMigrationCommand = {
3387
3668
  return;
3388
3669
  }
3389
3670
  if (output.print(`
3390
- ${chalk.yellow(chalk.bold("Note: During migrations, your webhooks stay active."))}`), output.print(`To adjust them, launch the management interface with ${chalk.cyan("sanity manage")}, navigate to the API settings, and toggle the webhooks before and after the migration as needed.
3671
+ ${chalk2.yellow(chalk2.bold("Note: During migrations, your webhooks stay active."))}`), output.print(`To adjust them, launch the management interface with ${chalk2.cyan("sanity manage")}, navigate to the API settings, and toggle the webhooks before and after the migration as needed.
3391
3672
  `), flags.confirm && !await prompt.single({
3392
- message: `This migration will run on the ${chalk.yellow(chalk.bold(apiConfig.dataset))} dataset in ${chalk.yellow(chalk.bold(apiConfig.projectId))} project. Are you sure?`,
3673
+ message: `This migration will run on the ${chalk2.yellow(chalk2.bold(apiConfig.dataset))} dataset in ${chalk2.yellow(chalk2.bold(apiConfig.projectId))} project. Are you sure?`,
3393
3674
  type: "confirm"
3394
3675
  })) {
3395
3676
  debug$2("User aborted migration");
@@ -3410,30 +3691,30 @@ ${chalk.yellow(chalk.bold("Note: During migrations, your webhooks stay active.")
3410
3691
  if (progress2.done) {
3411
3692
  progressSpinner.text = `Migration "${id}" completed.
3412
3693
 
3413
- Project id: ${chalk.bold(apiConfig.projectId)}
3414
- Dataset: ${chalk.bold(apiConfig.dataset)}
3694
+ Project id: ${chalk2.bold(apiConfig.projectId)}
3695
+ Dataset: ${chalk2.bold(apiConfig.dataset)}
3415
3696
 
3416
3697
  ${progress2.documents} documents processed.
3417
3698
  ${progress2.mutations} mutations generated.
3418
- ${chalk.green(progress2.completedTransactions.length)} transactions committed.`, progressSpinner.stopAndPersist({
3419
- symbol: chalk.green("\u2714")
3699
+ ${chalk2.green(progress2.completedTransactions.length)} transactions committed.`, progressSpinner.stopAndPersist({
3700
+ symbol: chalk2.green("\u2714")
3420
3701
  });
3421
3702
  return;
3422
3703
  }
3423
3704
  [null, ...progress2.currentTransactions].forEach((transaction) => {
3424
3705
  progressSpinner.text = `Running migration "${id}" ${dry ? "in dry mode..." : "..."}
3425
3706
 
3426
- Project id: ${chalk.bold(apiConfig.projectId)}
3427
- Dataset: ${chalk.bold(apiConfig.dataset)}
3428
- Document type: ${chalk.bold(migration.documentTypes?.join(","))}
3707
+ Project id: ${chalk2.bold(apiConfig.projectId)}
3708
+ Dataset: ${chalk2.bold(apiConfig.dataset)}
3709
+ Document type: ${chalk2.bold(migration.documentTypes?.join(","))}
3429
3710
 
3430
3711
  ${progress2.documents} documents processed\u2026
3431
3712
  ${progress2.mutations} mutations generated\u2026
3432
- ${chalk.blue(progress2.pending)} requests pending\u2026
3433
- ${chalk.green(progress2.completedTransactions.length)} transactions committed.
3713
+ ${chalk2.blue(progress2.pending)} requests pending\u2026
3714
+ ${chalk2.green(progress2.completedTransactions.length)} transactions committed.
3434
3715
 
3435
3716
  ${transaction && !progress2.done ? `\xBB ${prettyFormat({
3436
- chalk,
3717
+ chalk: chalk2,
3437
3718
  subject: transaction,
3438
3719
  migration,
3439
3720
  indentSize: 2
@@ -3442,13 +3723,13 @@ ${chalk.yellow(chalk.bold("Note: During migrations, your webhooks stay active.")
3442
3723
  };
3443
3724
  }
3444
3725
  async function dryRunHandler() {
3445
- output.print(`Running migration "${id}" in dry mode`), fromExport && output.print(`Using export ${chalk.cyan(fromExport)}`), output.print(), output.print(`Project id: ${chalk.bold(apiConfig.projectId)}`), output.print(`Dataset: ${chalk.bold(apiConfig.dataset)}`);
3726
+ output.print(`Running migration "${id}" in dry mode`), fromExport && output.print(`Using export ${chalk2.cyan(fromExport)}`), output.print(), output.print(`Project id: ${chalk2.bold(apiConfig.projectId)}`), output.print(`Dataset: ${chalk2.bold(apiConfig.dataset)}`);
3446
3727
  for await (const mutation of migrate.dryRun({
3447
3728
  api: apiConfig,
3448
3729
  exportPath: fromExport
3449
3730
  }, migration))
3450
3731
  mutation && (output.print(), output.print(prettyFormat({
3451
- chalk,
3732
+ chalk: chalk2,
3452
3733
  subject: mutation,
3453
3734
  migration
3454
3735
  })));
@@ -3484,7 +3765,7 @@ const description$4 = "Delete schemas by their IDs.", helpText$7 = `
3484
3765
  Options
3485
3766
  --ids <schema_id_1,schema_id_2,...> comma-separated list of schema IDs to delete
3486
3767
  --dataset <dataset_name> delete schemas from a specific dataset
3487
- --path <path> path to the manifest file if it is not in the default location
3768
+ --manifest-dir <directory> directory containing your manifest file if it's not in the default location
3488
3769
 
3489
3770
  Examples
3490
3771
  # Delete single schema
@@ -3535,7 +3816,7 @@ const description$2 = "Lists all schemas in the current dataset.", helpText$5 =
3535
3816
  Options
3536
3817
  --json get schemas as json
3537
3818
  --id <schema_id> fetch a specific schema by its ID
3538
- --path <path> path to your manifest file if it's not in the default location
3819
+ --manifest-dir <directory> directory containing your manifest file if it's not in the default location
3539
3820
 
3540
3821
  Examples
3541
3822
  # Get full json schemas
@@ -3550,18 +3831,17 @@ Examples
3550
3831
  description: description$2,
3551
3832
  helpText: helpText$5,
3552
3833
  action: async (args, context) => (await Promise.resolve().then(function() {
3553
- return require("./storeSchemasAction.js");
3554
- }).then(function(n) {
3555
- return n.schemaListAction;
3834
+ return schemaListAction$1;
3556
3835
  })).default(args, context)
3557
- }, description$1 = "Store schemas into the current dataset.", helpText$4 = `
3836
+ }, description$1 = "Store schemas into workspace datasets.", helpText$4 = `
3558
3837
  **Note**: This command is experimental and subject to change.
3559
3838
 
3560
3839
  Options:
3561
- --workspace The name of the workspace to fetch the stored schema for
3562
- --path If you are not using the default static file path, you can specify it here.
3563
- --id-prefix you can specify a custom id prefix for the stored schemas. Useful if you want to store the schema in a different path than the default one.
3564
- --verbose Enable verbose logging
3840
+ --workspace <workspace_name> store schema for a specific workspace
3841
+ --manifest-dir <directory> directory containing your manifest file if it's not in the default location
3842
+ --id-prefix <prefix> add a prefix to the schema ID
3843
+ --schema-required fail if schema file is not found
3844
+ --verbose print detailed information during store
3565
3845
 
3566
3846
  Examples
3567
3847
  # if no options are provided all workspace schemas will be stored
@@ -3576,9 +3856,7 @@ Examples
3576
3856
  helpText: helpText$4,
3577
3857
  action: async (args, context) => {
3578
3858
  const mod = await Promise.resolve().then(function() {
3579
- return require("./storeSchemasAction.js");
3580
- }).then(function(n) {
3581
- return n.storeSchemasAction$1;
3859
+ return storeSchemasAction$1;
3582
3860
  }), extendedArgs = {
3583
3861
  ...args,
3584
3862
  extOptions: {
@@ -3631,9 +3909,9 @@ Examples
3631
3909
  action: async (args, context) => {
3632
3910
  const {
3633
3911
  output,
3634
- chalk,
3912
+ chalk: chalk2,
3635
3913
  prompt
3636
- } = context, previewAction = await getPreviewAction(), warn = (msg) => output.warn(chalk.yellow.bgBlack(msg)), error = (msg) => output.warn(chalk.red.bgBlack(msg));
3914
+ } = context, previewAction = await getPreviewAction(), warn = (msg) => output.warn(chalk2.yellow.bgBlack(msg)), error = (msg) => output.warn(chalk2.red.bgBlack(msg));
3637
3915
  warn("\u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E"), warn("\u2502 \u2502"), warn("\u2502 You're running Sanity Studio v3. In this version the \u2502"), warn("\u2502 [start] command is used to preview static builds. |"), warn("\u2502 \u2502"), warn("\u2502 To run a development server, use the [npm run dev] or |"), warn("\u2502 [npx sanity dev] command instead. For more information, \u2502"), warn("\u2502 see https://www.sanity.io/help/studio-v2-vs-v3 \u2502"), warn("\u2502 \u2502"), warn("\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F"), warn("");
3638
3916
  try {
3639
3917
  await previewAction(args, context);
@@ -3751,7 +4029,7 @@ Examples
3751
4029
  const {
3752
4030
  apiClient,
3753
4031
  output,
3754
- chalk
4032
+ chalk: chalk2
3755
4033
  } = context, {
3756
4034
  sort,
3757
4035
  order,
@@ -3791,9 +4069,9 @@ Examples
3791
4069
  date
3792
4070
  }) => [id, name, role, date]), [sortFields.indexOf(sort)]), rows = order === "asc" ? ordered : ordered.reverse(), maxWidths = rows.reduce((max, row) => row.map((current, index) => Math.max(size__default.default(current), max[index])), sortFields.map((str) => size__default.default(str))), printRow = (row) => {
3793
4071
  const isInvite = row[0] === "<pending>", textRow = row.map((col, i) => `${col}`.padEnd(maxWidths[i])).join(" ");
3794
- return isInvite ? chalk.dim(textRow) : textRow;
4072
+ return isInvite ? chalk2.dim(textRow) : textRow;
3795
4073
  };
3796
- output.print(chalk.cyan(printRow(sortFields))), rows.forEach((row) => output.print(printRow(row)));
4074
+ output.print(chalk2.cyan(printRow(sortFields))), rows.forEach((row) => output.print(printRow(row)));
3797
4075
  }
3798
4076
  };
3799
4077
  function getUserProps(user) {
@@ -3819,14 +4097,21 @@ const usersGroup = {
3819
4097
  signature: "[COMMAND]",
3820
4098
  isGroupRoot: !0,
3821
4099
  description: "Manages users of your Sanity project"
3822
- }, commands = [appGroup, appDeployCommand, appDevCommand, appBuildCommand, appStartCommand, buildCommand, datasetGroup, deployCommand, undeployCommand, listDatasetsCommand, createDatasetCommand, datasetVisibilityCommand, exportDatasetCommand, importDatasetCommand, deleteDatasetCommand, copyDatasetCommand, aliasCommand, datasetBackupGroup, listDatasetBackupCommand, downloadBackupCommand, disableDatasetBackupCommand, enableDatasetBackupCommand, corsGroup, listCorsOriginsCommand, addCorsOriginCommand, deleteCorsOriginCommand, usersGroup, inviteUserCommand, listUsersCommand, hookGroup, listHooksCommand, createHookCommand, migrationGroup, createMigrationCommand, runMigrationCommand, listMigrationCommand, deleteHookCommand, listHookLogsCommand, printHookAttemptCommand, documentsGroup, getDocumentsCommand, queryDocumentsCommand, deleteDocumentsCommand, createDocumentsCommand, validateDocumentsCommand$1, graphqlGroup, listGraphQLAPIsCommand, deployGraphQLAPICommand, deleteGraphQLAPICommand, devCommand, startCommand, schemaGroup, validateDocumentsCommand, extractSchemaCommand, previewCommand, fetchSchemaCommand, storeSchemaCommand, execCommand, manifestGroup, extractManifestCommand, deleteSchemaCommand], cliProjectCommands = {
4100
+ }, baseCommands = [appGroup, appDeployCommand, appDevCommand, appBuildCommand, appStartCommand, buildCommand, datasetGroup, deployCommand, undeployCommand, listDatasetsCommand, createDatasetCommand, datasetVisibilityCommand, exportDatasetCommand, importDatasetCommand, deleteDatasetCommand, copyDatasetCommand, aliasCommand, datasetBackupGroup, listDatasetBackupCommand, downloadBackupCommand, disableDatasetBackupCommand, enableDatasetBackupCommand, corsGroup, listCorsOriginsCommand, addCorsOriginCommand, deleteCorsOriginCommand, usersGroup, inviteUserCommand, listUsersCommand, hookGroup, listHooksCommand, createHookCommand, migrationGroup, createMigrationCommand, runMigrationCommand, listMigrationCommand, deleteHookCommand, listHookLogsCommand, printHookAttemptCommand, documentsGroup, getDocumentsCommand, queryDocumentsCommand, deleteDocumentsCommand, createDocumentsCommand, validateDocumentsCommand$1, graphqlGroup, listGraphQLAPIsCommand, deployGraphQLAPICommand, deleteGraphQLAPICommand, devCommand, startCommand, schemaGroup, validateDocumentsCommand, extractSchemaCommand, previewCommand, execCommand, manifestGroup, extractManifestCommand], internalSchemaCommands = [fetchSchemaCommand, storeSchemaCommand, deleteSchemaCommand], commands = [...baseCommands, ...SCHEMA_STORE_ENABLED ? internalSchemaCommands : []], cliProjectCommands = {
3823
4101
  requiredCliVersionRange: "^3.0.0",
3824
4102
  commands
3825
4103
  };
4104
+ exports.SCHEMA_STORE_ENABLED = SCHEMA_STORE_ENABLED;
3826
4105
  exports.cliProjectCommands = cliProjectCommands;
3827
4106
  exports.convertToTree = convertToTree;
3828
4107
  exports.debug = debug$2;
4108
+ exports.extractManifestSafe = extractManifestSafe;
3829
4109
  exports.formatTree = formatTree;
3830
4110
  exports.getClientUrl = getClientUrl;
4111
+ exports.getManifestPath = getManifestPath;
4112
+ exports.getTimer = getTimer;
3831
4113
  exports.maxKeyLength = maxKeyLength;
4114
+ exports.readManifest = readManifest;
4115
+ exports.storeSchemasAction = storeSchemasAction;
4116
+ exports.throwIfProjectIdMismatch = throwIfProjectIdMismatch;
3832
4117
  //# sourceMappingURL=_internal.js.map