@sanity/cli 3.78.0 → 3.78.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,23 @@
1
1
  "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf, __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __copyProps = (to, from2, except, desc) => {
8
+ if (from2 && typeof from2 == "object" || typeof from2 == "function")
9
+ for (let key2 of __getOwnPropNames(from2))
10
+ !__hasOwnProp.call(to, key2) && key2 !== except && __defProp(to, key2, { get: () => from2[key2], enumerable: !(desc = __getOwnPropDesc(from2, key2)) || desc.enumerable });
11
+ return to;
12
+ };
13
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
14
+ // If the importer is in node compatibility mode or this is not an ESM
15
+ // file that has been converted to a CommonJS file using a Babel-
16
+ // compatible transform (i.e. "__esModule" has not been set), then set
17
+ // "default" to the CommonJS "module.exports" for node compatibility.
18
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: !0 }) : target,
19
+ mod
20
+ ));
2
21
  var fs$1 = require("node:fs"), os = require("node:os"), path$3 = require("node:path"), chalk = require("chalk"), loadEnv = require("./loadEnv.js"), require$$0$5 = require("path"), require$$1$2 = require("module"), require$$0$4 = require("fs"), telemetry = require("@sanity/telemetry"), childProcess = require("node:child_process"), fs = require("node:fs/promises"), util$4 = require("node:util"), require$$0$6 = require("os"), require$$5$1 = require("url"), require$$1$3 = require("get-it"), require$$2$1 = require("get-it/middleware"), require$$0$7 = require("constants"), require$$0$8 = require("stream"), require$$0$9 = require("util"), require$$0$a = require("assert"), require$$0$b = require("events"), require$$6$1 = require("http"), semver = require("semver"), pkgDir = require("pkg-dir"), client$1 = require("@sanity/client"), require$$3$1 = require("crypto"), require$$1$4 = require("child_process"), require$$0$c = require("fs/promises"), require$$0$d = require("buffer"), getCliConfig = require("./getCliConfig.js"), journeyConfig = require("./journeyConfig.js"), Stream = require("node:stream"), promises$1 = require("node:stream/promises"), templateValidator = require("@sanity/template-validator"), require$$2$2 = require("string_decoder"), require$$0$e = require("zlib"), require$$7$1 = require("process"), http = require("node:http"), traverse = require("@babel/traverse"), node_url = require("node:url"), node_events = require("node:events"), node_string_decoder = require("node:string_decoder"), process$2 = require("node:process"), require$$2$3 = require("readline"), require$$0$f = require("tty");
3
22
  function _interopDefaultCompat(e) {
4
23
  return e && typeof e == "object" && "default" in e ? e : { default: e };
@@ -3892,7 +3911,7 @@ function ensureNpx() {
3892
3911
  );
3893
3912
  }
3894
3913
  }
3895
- const helpText$9 = `
3914
+ const helpText$c = `
3896
3915
  Runs a given code modification script on the current studio folder.
3897
3916
  Running the command without a specified codemod name will list available transformations.
3898
3917
 
@@ -3914,7 +3933,7 @@ Examples
3914
3933
  name: "codemod",
3915
3934
  signature: "[CODEMOD_NAME]",
3916
3935
  description: "Updates Sanity Studio codebase with a code modification script",
3917
- helpText: helpText$9,
3936
+ helpText: helpText$c,
3918
3937
  action: codemodAction
3919
3938
  };
3920
3939
  var lodash_isplainobject, hasRequiredLodash_isplainobject;
@@ -7452,6 +7471,107 @@ const docsCommand = {
7452
7471
  const { output } = context, { print } = output, url = "https://www.sanity.io/docs";
7453
7472
  print(`Opening ${url}`), await open(url);
7454
7473
  }
7474
+ }, helpText$b = `
7475
+ Options
7476
+ --port <port> Port to start emulator on
7477
+
7478
+ Examples
7479
+ # Start dev server on default port
7480
+ sanity functions dev
7481
+
7482
+ # Start dev server on specific port
7483
+ sanity functions dev --port 3333
7484
+ `, defaultFlags$3 = {
7485
+ port: 8080
7486
+ }, devFunctionsCommand = {
7487
+ name: "dev",
7488
+ group: "functions",
7489
+ helpText: helpText$b,
7490
+ signature: "",
7491
+ description: "Start the Sanity Function emulator",
7492
+ hideFromHelp: !0,
7493
+ async action(args, context) {
7494
+ const { output } = context, { print } = output, flags = { ...defaultFlags$3, ...args.extOptions }, { devAction } = await import("@sanity/runtime-cli");
7495
+ devAction(flags.port), print(`Server is running on port ${flags.port}
7496
+ `), open(`http://localhost:${flags.port}`);
7497
+ }
7498
+ }, functionsGroup = {
7499
+ name: "functions",
7500
+ signature: "[COMMAND]",
7501
+ isGroupRoot: !0,
7502
+ description: "Test Sanity Functions locally and retrieve logs",
7503
+ hideFromHelp: !0
7504
+ }, helpText$a = `
7505
+ Options
7506
+ --id <id> The ID of the function to retrieve logs for
7507
+
7508
+ Examples
7509
+ # Retrieve logs for Sanity Function abcd1234
7510
+ sanity functions logs --id abcd1234
7511
+ `, defaultFlags$2 = {
7512
+ id: void 0
7513
+ }, logsFunctionsCommand = {
7514
+ name: "logs",
7515
+ group: "functions",
7516
+ helpText: helpText$a,
7517
+ signature: "",
7518
+ description: "Retrieve logs for a Sanity Function",
7519
+ hideFromHelp: !0,
7520
+ async action(args, context) {
7521
+ const { apiClient, output } = context, { print } = output, flags = { ...defaultFlags$2, ...args.extOptions }, client2 = apiClient({
7522
+ requireUser: !0,
7523
+ requireProject: !1
7524
+ });
7525
+ if (flags.id) {
7526
+ const token2 = client2.config().token;
7527
+ if (token2) {
7528
+ const { logsAction } = await import("@sanity/runtime-cli"), result = await logsAction(flags.id, token2);
7529
+ print(JSON.stringify(result, null, 2));
7530
+ }
7531
+ } else
7532
+ print("You must provide a function ID");
7533
+ }
7534
+ }, helpText$9 = `
7535
+ Options
7536
+ --data <data> Data to send to the function
7537
+ --file <file> Read data from file and send to the function
7538
+ --path <path> Path to your Sanity Function code
7539
+ --timeout <timeout> Execution timeout value in seconds
7540
+
7541
+ Examples
7542
+ # Test function passing event data on command line
7543
+ sanity functions test --path ./test.ts --data '{ "id": 1 }'
7544
+
7545
+ # Test function passing event data via a file
7546
+ sanity functions test -path ./test.js --file 'payload.json'
7547
+
7548
+ # Test function passing event data on command line and cap execution time to 60 seconds
7549
+ sanity functions test -path ./test.ts --data '{ "id": 1 }' --timeout 60
7550
+ `, defaultFlags$1 = {
7551
+ data: void 0,
7552
+ file: void 0,
7553
+ path: void 0,
7554
+ timeout: 5
7555
+ // seconds
7556
+ }, testFunctionsCommand = {
7557
+ name: "test",
7558
+ group: "functions",
7559
+ helpText: helpText$9,
7560
+ signature: "",
7561
+ description: "Invoke a local Sanity Function",
7562
+ hideFromHelp: !0,
7563
+ async action(args, context) {
7564
+ const { output } = context, { print } = output, flags = { ...defaultFlags$1, ...args.extOptions };
7565
+ if (flags.path) {
7566
+ const { testAction } = await import("@sanity/runtime-cli"), { json: json2, logs, error: error2 } = await testAction(flags.path, {
7567
+ data: flags.data,
7568
+ file: flags.file,
7569
+ timeout: flags.timeout
7570
+ });
7571
+ error2 ? print(error2.toString()) : (print("Logs:"), print(logs), print("Response:"), print(JSON.stringify(json2, null, 2)));
7572
+ } else
7573
+ print("You must provide a path to the Sanity Function code");
7574
+ }
7455
7575
  };
7456
7576
  var leven$1 = { exports: {} }, hasRequiredLeven;
7457
7577
  function requireLeven() {
@@ -8832,7 +8952,7 @@ function requireDumper$2() {
8832
8952
  function State(options2) {
8833
8953
  this.schema = options2.schema || DEFAULT_FULL_SCHEMA, this.indent = Math.max(1, options2.indent || 2), this.noArrayIndent = options2.noArrayIndent || !1, this.skipInvalid = options2.skipInvalid || !1, this.flowLevel = common2.isNothing(options2.flowLevel) ? -1 : options2.flowLevel, this.styleMap = compileStyleMap(this.schema, options2.styles || null), this.sortKeys = options2.sortKeys || !1, this.lineWidth = options2.lineWidth || 80, this.noRefs = options2.noRefs || !1, this.noCompatMode = options2.noCompatMode || !1, this.condenseFlow = options2.condenseFlow || !1, this.implicitTypes = this.schema.compiledImplicit, this.explicitTypes = this.schema.compiledExplicit, this.tag = null, this.result = "", this.duplicates = [], this.usedDuplicates = null;
8834
8954
  }
8835
- function indentString(string, spaces) {
8955
+ function indentString2(string, spaces) {
8836
8956
  for (var ind = common2.repeat(" ", spaces), position = 0, next = -1, result = "", line3, length = string.length; position < length; )
8837
8957
  next = string.indexOf(`
8838
8958
  `, position), next === -1 ? (line3 = string.slice(position), position = length) : (line3 = string.slice(position, next + 1), position = next + 1), line3.length && line3 !== `
@@ -8904,9 +9024,9 @@ function requireDumper$2() {
8904
9024
  case STYLE_SINGLE:
8905
9025
  return "'" + string.replace(/'/g, "''") + "'";
8906
9026
  case STYLE_LITERAL:
8907
- return "|" + blockHeader(string, state.indent) + dropEndingNewline(indentString(string, indent));
9027
+ return "|" + blockHeader(string, state.indent) + dropEndingNewline(indentString2(string, indent));
8908
9028
  case STYLE_FOLDED:
8909
- return ">" + blockHeader(string, state.indent) + dropEndingNewline(indentString(foldString(string, lineWidth), indent));
9029
+ return ">" + blockHeader(string, state.indent) + dropEndingNewline(indentString2(foldString(string, lineWidth), indent));
8910
9030
  case STYLE_DOUBLE:
8911
9031
  return '"' + escapeString(string) + '"';
8912
9032
  default:
@@ -15075,7 +15195,7 @@ function requireDumper$1() {
15075
15195
  function State(options2) {
15076
15196
  this.schema = options2.schema || DEFAULT_SCHEMA, this.indent = Math.max(1, options2.indent || 2), this.noArrayIndent = options2.noArrayIndent || !1, this.skipInvalid = options2.skipInvalid || !1, this.flowLevel = common2.isNothing(options2.flowLevel) ? -1 : options2.flowLevel, this.styleMap = compileStyleMap(this.schema, options2.styles || null), this.sortKeys = options2.sortKeys || !1, this.lineWidth = options2.lineWidth || 80, this.noRefs = options2.noRefs || !1, this.noCompatMode = options2.noCompatMode || !1, this.condenseFlow = options2.condenseFlow || !1, this.quotingType = options2.quotingType === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE, this.forceQuotes = options2.forceQuotes || !1, this.replacer = typeof options2.replacer == "function" ? options2.replacer : null, this.implicitTypes = this.schema.compiledImplicit, this.explicitTypes = this.schema.compiledExplicit, this.tag = null, this.result = "", this.duplicates = [], this.usedDuplicates = null;
15077
15197
  }
15078
- function indentString(string, spaces) {
15198
+ function indentString2(string, spaces) {
15079
15199
  for (var ind = common2.repeat(" ", spaces), position = 0, next = -1, result = "", line3, length = string.length; position < length; )
15080
15200
  next = string.indexOf(`
15081
15201
  `, position), next === -1 ? (line3 = string.slice(position), position = length) : (line3 = string.slice(position, next + 1), position = next + 1), line3.length && line3 !== `
@@ -15173,9 +15293,9 @@ function requireDumper$1() {
15173
15293
  case STYLE_SINGLE:
15174
15294
  return "'" + string.replace(/'/g, "''") + "'";
15175
15295
  case STYLE_LITERAL:
15176
- return "|" + blockHeader(string, state.indent) + dropEndingNewline(indentString(string, indent));
15296
+ return "|" + blockHeader(string, state.indent) + dropEndingNewline(indentString2(string, indent));
15177
15297
  case STYLE_FOLDED:
15178
- return ">" + blockHeader(string, state.indent) + dropEndingNewline(indentString(foldString(string, lineWidth), indent));
15298
+ return ">" + blockHeader(string, state.indent) + dropEndingNewline(indentString2(foldString(string, lineWidth), indent));
15179
15299
  case STYLE_DOUBLE:
15180
15300
  return '"' + escapeString(string) + '"';
15181
15301
  default:
@@ -18906,54 +19026,105 @@ function requireExeca() {
18906
19026
  );
18907
19027
  }, execa$1.exports;
18908
19028
  }
18909
- var execaExports = requireExeca(), execa = /* @__PURE__ */ loadEnv.getDefaultExportFromCjs(execaExports), pFilter$1 = { exports: {} }, pMap = { exports: {} }, hasRequiredPMap;
19029
+ var execaExports = requireExeca(), execa = /* @__PURE__ */ loadEnv.getDefaultExportFromCjs(execaExports), indentString, hasRequiredIndentString;
19030
+ function requireIndentString() {
19031
+ return hasRequiredIndentString || (hasRequiredIndentString = 1, indentString = (string, count2 = 1, options2) => {
19032
+ if (options2 = {
19033
+ indent: " ",
19034
+ includeEmptyLines: !1,
19035
+ ...options2
19036
+ }, typeof string != "string")
19037
+ throw new TypeError(
19038
+ `Expected \`input\` to be a \`string\`, got \`${typeof string}\``
19039
+ );
19040
+ if (typeof count2 != "number")
19041
+ throw new TypeError(
19042
+ `Expected \`count\` to be a \`number\`, got \`${typeof count2}\``
19043
+ );
19044
+ if (typeof options2.indent != "string")
19045
+ throw new TypeError(
19046
+ `Expected \`options.indent\` to be a \`string\`, got \`${typeof options2.indent}\``
19047
+ );
19048
+ if (count2 === 0)
19049
+ return string;
19050
+ const regex2 = options2.includeEmptyLines ? /^/gm : /^(?!\s*$)/gm;
19051
+ return string.replace(regex2, options2.indent.repeat(count2));
19052
+ }), indentString;
19053
+ }
19054
+ var cleanStack$2, hasRequiredCleanStack$1;
19055
+ function requireCleanStack$1() {
19056
+ if (hasRequiredCleanStack$1) return cleanStack$2;
19057
+ hasRequiredCleanStack$1 = 1;
19058
+ const os2 = require$$0__default$2.default, extractPathRegex = /\s+at.*(?:\(|\s)(.*)\)?/, pathRegex = /^(?:(?:(?:node|(?:internal\/[\w/]*|.*node_modules\/(?:babel-polyfill|pirates)\/.*)?\w+)\.js:\d+:\d+)|native)/, homeDir = typeof os2.homedir > "u" ? "" : os2.homedir();
19059
+ return cleanStack$2 = (stack2, options2) => (options2 = Object.assign({ pretty: !1 }, options2), stack2.replace(/\\/g, "/").split(`
19060
+ `).filter((line3) => {
19061
+ const pathMatches = line3.match(extractPathRegex);
19062
+ if (pathMatches === null || !pathMatches[1])
19063
+ return !0;
19064
+ const match2 = pathMatches[1];
19065
+ return match2.includes(".app/Contents/Resources/electron.asar") || match2.includes(".app/Contents/Resources/default_app.asar") ? !1 : !pathRegex.test(match2);
19066
+ }).filter((line3) => line3.trim() !== "").map((line3) => options2.pretty ? line3.replace(extractPathRegex, (m, p1) => m.replace(p1, p1.replace(homeDir, "~"))) : line3).join(`
19067
+ `)), cleanStack$2;
19068
+ }
19069
+ var aggregateError, hasRequiredAggregateError;
19070
+ function requireAggregateError() {
19071
+ if (hasRequiredAggregateError) return aggregateError;
19072
+ hasRequiredAggregateError = 1;
19073
+ const indentString2 = requireIndentString(), cleanStack2 = requireCleanStack$1(), cleanInternalStack = (stack2) => stack2.replace(/\s+at .*aggregate-error\/index.js:\d+:\d+\)?/g, "");
19074
+ class AggregateError extends Error {
19075
+ constructor(errors) {
19076
+ if (!Array.isArray(errors))
19077
+ throw new TypeError(`Expected input to be an Array, got ${typeof errors}`);
19078
+ errors = [...errors].map((error2) => error2 instanceof Error ? error2 : error2 !== null && typeof error2 == "object" ? Object.assign(new Error(error2.message), error2) : new Error(error2));
19079
+ let message = errors.map((error2) => typeof error2.stack == "string" ? cleanInternalStack(cleanStack2(error2.stack)) : String(error2)).join(`
19080
+ `);
19081
+ message = `
19082
+ ` + indentString2(message, 4), super(message), this.name = "AggregateError", Object.defineProperty(this, "_errors", { value: errors });
19083
+ }
19084
+ *[Symbol.iterator]() {
19085
+ for (const error2 of this._errors)
19086
+ yield error2;
19087
+ }
19088
+ }
19089
+ return aggregateError = AggregateError, aggregateError;
19090
+ }
19091
+ var pMap$1, hasRequiredPMap;
18910
19092
  function requirePMap() {
18911
- if (hasRequiredPMap) return pMap.exports;
19093
+ if (hasRequiredPMap) return pMap$1;
18912
19094
  hasRequiredPMap = 1;
18913
- const pMap$1 = (iterable, mapper, options2) => new Promise((resolve, reject) => {
18914
- if (options2 = Object.assign({
18915
- concurrency: 1 / 0
18916
- }, options2), typeof mapper != "function")
19095
+ const AggregateError = requireAggregateError();
19096
+ return pMap$1 = async (iterable, mapper, {
19097
+ concurrency = 1 / 0,
19098
+ stopOnError = !0
19099
+ } = {}) => new Promise((resolve, reject) => {
19100
+ if (typeof mapper != "function")
18917
19101
  throw new TypeError("Mapper function is required");
18918
- const { concurrency } = options2;
18919
- if (!(typeof concurrency == "number" && concurrency >= 1))
18920
- throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${concurrency}\` (${typeof concurrency})`);
18921
- const ret = [], iterator2 = iterable[Symbol.iterator]();
19102
+ if (!((Number.isSafeInteger(concurrency) || concurrency === 1 / 0) && concurrency >= 1))
19103
+ throw new TypeError(`Expected \`concurrency\` to be an integer from 1 and up or \`Infinity\`, got \`${concurrency}\` (${typeof concurrency})`);
19104
+ const result = [], errors = [], iterator2 = iterable[Symbol.iterator]();
18922
19105
  let isRejected = !1, isIterableDone = !1, resolvingCount = 0, currentIndex = 0;
18923
19106
  const next = () => {
18924
19107
  if (isRejected)
18925
19108
  return;
18926
- const nextItem = iterator2.next(), i = currentIndex;
19109
+ const nextItem = iterator2.next(), index = currentIndex;
18927
19110
  if (currentIndex++, nextItem.done) {
18928
- isIterableDone = !0, resolvingCount === 0 && resolve(ret);
19111
+ isIterableDone = !0, resolvingCount === 0 && (!stopOnError && errors.length !== 0 ? reject(new AggregateError(errors)) : resolve(result));
18929
19112
  return;
18930
19113
  }
18931
- resolvingCount++, Promise.resolve(nextItem.value).then((element) => mapper(element, i)).then(
18932
- (value) => {
18933
- ret[i] = value, resolvingCount--, next();
18934
- },
18935
- (error2) => {
18936
- isRejected = !0, reject(error2);
19114
+ resolvingCount++, (async () => {
19115
+ try {
19116
+ const element = await nextItem.value;
19117
+ result[index] = await mapper(element, index), resolvingCount--, next();
19118
+ } catch (error2) {
19119
+ stopOnError ? (isRejected = !0, reject(error2)) : (errors.push(error2), resolvingCount--, next());
18937
19120
  }
18938
- );
19121
+ })();
18939
19122
  };
18940
19123
  for (let i = 0; i < concurrency && (next(), !isIterableDone); i++)
18941
19124
  ;
18942
- });
18943
- return pMap.exports = pMap$1, pMap.exports.default = pMap$1, pMap.exports;
18944
- }
18945
- var hasRequiredPFilter;
18946
- function requirePFilter() {
18947
- if (hasRequiredPFilter) return pFilter$1.exports;
18948
- hasRequiredPFilter = 1;
18949
- const pMap2 = requirePMap(), pFilter2 = async (iterable, filterer, options2) => (await pMap2(
18950
- iterable,
18951
- (element, index) => Promise.all([filterer(element, index), element]),
18952
- options2
18953
- )).filter((value) => !!value[0]).map((value) => value[1]);
18954
- return pFilter$1.exports = pFilter2, pFilter$1.exports.default = pFilter2, pFilter$1.exports;
18955
- }
18956
- var pFilterExports = requirePFilter(), pFilter = /* @__PURE__ */ loadEnv.getDefaultExportFromCjs(pFilterExports);
19125
+ }), pMap$1;
19126
+ }
19127
+ var pMapExports = requirePMap(), pMap = /* @__PURE__ */ loadEnv.getDefaultExportFromCjs(pMapExports);
18957
19128
  const CLIInitStepCompleted = telemetry.defineTrace({
18958
19129
  name: "CLI Init Step Completed",
18959
19130
  version: 1,
@@ -22175,7 +22346,7 @@ function requireDumper() {
22175
22346
  function State(options2) {
22176
22347
  this.schema = options2.schema || DEFAULT_FULL_SCHEMA, this.indent = Math.max(1, options2.indent || 2), this.noArrayIndent = options2.noArrayIndent || !1, this.skipInvalid = options2.skipInvalid || !1, this.flowLevel = common2.isNothing(options2.flowLevel) ? -1 : options2.flowLevel, this.styleMap = compileStyleMap(this.schema, options2.styles || null), this.sortKeys = options2.sortKeys || !1, this.lineWidth = options2.lineWidth || 80, this.noRefs = options2.noRefs || !1, this.noCompatMode = options2.noCompatMode || !1, this.condenseFlow = options2.condenseFlow || !1, this.implicitTypes = this.schema.compiledImplicit, this.explicitTypes = this.schema.compiledExplicit, this.tag = null, this.result = "", this.duplicates = [], this.usedDuplicates = null;
22177
22348
  }
22178
- function indentString(string, spaces) {
22349
+ function indentString2(string, spaces) {
22179
22350
  for (var ind = common2.repeat(" ", spaces), position = 0, next = -1, result = "", line3, length = string.length; position < length; )
22180
22351
  next = string.indexOf(`
22181
22352
  `, position), next === -1 ? (line3 = string.slice(position), position = length) : (line3 = string.slice(position, next + 1), position = next + 1), line3.length && line3 !== `
@@ -22250,9 +22421,9 @@ function requireDumper() {
22250
22421
  case STYLE_SINGLE:
22251
22422
  return "'" + string.replace(/'/g, "''") + "'";
22252
22423
  case STYLE_LITERAL:
22253
- return "|" + blockHeader(string, state.indent) + dropEndingNewline(indentString(string, indent));
22424
+ return "|" + blockHeader(string, state.indent) + dropEndingNewline(indentString2(string, indent));
22254
22425
  case STYLE_FOLDED:
22255
- return ">" + blockHeader(string, state.indent) + dropEndingNewline(indentString(foldString(string, lineWidth), indent));
22426
+ return ">" + blockHeader(string, state.indent) + dropEndingNewline(indentString2(foldString(string, lineWidth), indent));
22256
22427
  case STYLE_DOUBLE:
22257
22428
  return '"' + escapeString(string) + '"';
22258
22429
  default:
@@ -46762,10 +46933,9 @@ const blogTemplate = {}, cleanTemplate = {}, coreAppTemplate = {
46762
46933
  },
46763
46934
  appLocation: "./src/App.tsx",
46764
46935
  scripts: {
46765
- // this will eventually run a concurrently process with another in-flight utility
46766
- dev: "sanity app dev",
46767
- build: "sanity app build",
46768
- start: "sanity app start"
46936
+ dev: "sanity dev",
46937
+ build: "sanity build",
46938
+ start: "sanity start"
46769
46939
  }
46770
46940
  }, configTemplate$3 = `
46771
46941
  import {defineConfig, isDev} from 'sanity'
@@ -52641,11 +52811,9 @@ ${err.message}`);
52641
52811
  if (!envFilename.startsWith(".env"))
52642
52812
  throw new Error("Env filename must start with .env");
52643
52813
  const hasToken = getUserConfig().get("authToken");
52644
- if (loadEnv.debug(hasToken ? "User already has a token" : "User has no token"), hasToken) {
52645
- trace.log({ step: "login", alreadyLoggedIn: !0 });
52646
- const user = await getUserData(apiClient);
52647
- success("You are logged in as %s using %s", user.email, getProviderName(user.provider));
52648
- } else unattended || (trace.log({ step: "login" }), await getOrCreateUser());
52814
+ loadEnv.debug(hasToken ? "User already has a token" : "User has no token");
52815
+ let user;
52816
+ hasToken ? (trace.log({ step: "login", alreadyLoggedIn: !0 }), user = await getUserData(apiClient), success("You are logged in as %s using %s", user.email, getProviderName(user.provider))) : unattended || (trace.log({ step: "login" }), user = await getOrCreateUser());
52649
52817
  const isCoreAppTemplate = cliFlags.template ? determineCoreAppTemplate(cliFlags.template) : !1;
52650
52818
  let introMessage = "Fetching existing projects";
52651
52819
  cliFlags.quickstart && (introMessage = "Eject your existing project's Sanity configuration"), isCoreAppTemplate || (success(introMessage), print(""));
@@ -52858,7 +53026,7 @@ ${chalk2.green("Success!")} Now, use these commands to continue:
52858
53026
  method: "POST"
52859
53027
  }).catch(lodashExports.noop)), trace.complete();
52860
53028
  async function getOrCreateUser() {
52861
- warn("No authentication credentials found in your Sanity config"), print(""), await login({ extOptions: {} }, { ...context, telemetry: trace.newContext("login") });
53029
+ return warn("No authentication credentials found in your Sanity config"), print(""), await login({ extOptions: {} }, { ...context, telemetry: trace.newContext("login") }), getUserData(apiClient);
52862
53030
  }
52863
53031
  async function getProjectDetails() {
52864
53032
  if (flags.quickstart) {
@@ -52952,7 +53120,14 @@ ${err.message}`);
52952
53120
  loadEnv.debug(
52953
53121
  isUsersFirstProject ? "No projects found for user, prompting for name" : "Using a coupon - skipping project selection"
52954
53122
  );
52955
- const projectName = await prompt2.single({ type: "input", message: "Project name:" });
53123
+ const projectName = await prompt2.single({
53124
+ type: "input",
53125
+ message: "Project name:",
53126
+ default: "My Sanity Project",
53127
+ validate(input2) {
53128
+ return !input2 || input2.trim() === "" ? "Project name cannot be empty" : input2.length > 80 ? "Project name cannot be longer than 80 characters" : !0;
53129
+ }
53130
+ });
52956
53131
  return createProject(apiClient, {
52957
53132
  displayName: projectName,
52958
53133
  organizationId: await getOrganizationId(organizations),
@@ -53184,33 +53359,45 @@ The default dataset configuration has a public dataset named "production".`;
53184
53359
  }
53185
53360
  return cliFlags;
53186
53361
  }
53187
- async function getOrganizationId(organizations) {
53188
- let orgId = flags.organization;
53189
- if (unattended)
53190
- return orgId || void 0;
53191
- if (organizations.length > 0 && !orgId) {
53192
- loadEnv.debug(`User has ${organizations.length} organization(s), checking attach access`);
53193
- const withGrant = await getOrganizationsWithAttachGrant(organizations);
53194
- if (withGrant.length === 0) {
53195
- loadEnv.debug("User lacks project attach grant in all organizations, not prompting");
53196
- return;
53362
+ async function createOrganization(props = {}) {
53363
+ const name = props.name || await prompt2.single({
53364
+ type: "input",
53365
+ message: "Organization name:",
53366
+ default: user ? user.name : void 0,
53367
+ validate(input2) {
53368
+ return input2.length === 0 ? "Organization name cannot be empty" : input2.length > 100 ? "Organization name cannot be longer than 100 characters" : !0;
53197
53369
  }
53198
- loadEnv.debug("User has attach access to %d organizations, prompting.", withGrant.length);
53199
- const organizationChoices = [
53200
- { value: "none", name: "None" },
53201
- new prompt2.Separator(),
53202
- ...withGrant.map((organization) => ({
53203
- value: organization.id,
53204
- name: `${organization.name} [${organization.id}]`
53205
- }))
53206
- ], chosenOrg = await prompt2.single({
53207
- message: `Select organization to attach ${isCoreAppTemplate ? "application" : "project"} to`,
53208
- type: "list",
53209
- choices: organizationChoices
53210
- });
53211
- chosenOrg && chosenOrg !== "none" && (orgId = chosenOrg);
53212
- } else orgId ? loadEnv.debug("User has defined organization flag explicitly (%s)", orgId) : organizations.length === 0 && loadEnv.debug("User has no organizations, skipping selection prompt");
53213
- return orgId || void 0;
53370
+ }), spinner = context.output.spinner("Creating organization").start(), organization = await apiClient({ requireProject: !1, requireUser: !0 }).request({
53371
+ uri: "/organizations",
53372
+ method: "POST",
53373
+ body: { name }
53374
+ });
53375
+ return spinner.succeed(), organization;
53376
+ }
53377
+ async function getOrganizationId(organizations) {
53378
+ if (unattended || flags.organization)
53379
+ return flags.organization || void 0;
53380
+ if (organizations.length === 0)
53381
+ return createOrganization().then((org) => org.id);
53382
+ loadEnv.debug(`User has ${organizations.length} organization(s), checking attach access`);
53383
+ const withGrantInfo = await getOrganizationsWithAttachGrantInfo(organizations), withAttach = withGrantInfo.filter(({ hasAttachGrant }) => hasAttachGrant);
53384
+ loadEnv.debug("User has attach access to %d organizations.", withAttach.length);
53385
+ const organizationChoices = [
53386
+ ...withGrantInfo.map(({ organization, hasAttachGrant }) => ({
53387
+ value: organization.id,
53388
+ name: `${organization.name} [${organization.id}]`,
53389
+ disabled: hasAttachGrant ? !1 : "Insufficient permissions"
53390
+ })),
53391
+ new prompt2.Separator(),
53392
+ { value: "-new-", name: "Create new organization" },
53393
+ new prompt2.Separator()
53394
+ ], defaultOrganizationId = withAttach.length === 1 ? withAttach[0].organization.id : organizations.find((org) => org.name === user?.name)?.id, chosenOrg = await prompt2.single({
53395
+ message: "Select organization:",
53396
+ type: "list",
53397
+ default: defaultOrganizationId || void 0,
53398
+ choices: organizationChoices
53399
+ });
53400
+ return chosenOrg === "-new-" ? createOrganization().then((org) => org.id) : chosenOrg || void 0;
53214
53401
  }
53215
53402
  async function hasProjectAttachGrant(orgId) {
53216
53403
  const requiredGrantGroup = "sanity.organization.projects", requiredGrant = "attach";
@@ -53218,8 +53405,15 @@ The default dataset configuration has a public dataset named "production".`;
53218
53405
  (resource) => resource.grants && resource.grants.some((grant) => grant.name === requiredGrant)
53219
53406
  );
53220
53407
  }
53221
- function getOrganizationsWithAttachGrant(organizations) {
53222
- return pFilter(organizations, (org) => hasProjectAttachGrant(org.id), { concurrency: 3 });
53408
+ function getOrganizationsWithAttachGrantInfo(organizations) {
53409
+ return pMap(
53410
+ organizations,
53411
+ async (organization) => ({
53412
+ hasAttachGrant: await hasProjectAttachGrant(organization.id),
53413
+ organization
53414
+ }),
53415
+ { concurrency: 3 }
53416
+ );
53223
53417
  }
53224
53418
  async function createOrAppendEnvVars(filename, framework, options2) {
53225
53419
  const envVars = {
@@ -53762,7 +53956,11 @@ const baseCommands = [
53762
53956
  enableTelemetryCommand,
53763
53957
  telemetryStatusCommand,
53764
53958
  generateTypegenCommand,
53765
- typegenGroup
53959
+ typegenGroup,
53960
+ functionsGroup,
53961
+ devFunctionsCommand,
53962
+ logsFunctionsCommand,
53963
+ testFunctionsCommand
53766
53964
  ], copyProperty = (to, from2, property, ignoreNonConfigurable) => {
53767
53965
  if (property === "length" || property === "prototype" || property === "arguments" || property === "caller")
53768
53966
  return;
@@ -78657,14 +78855,14 @@ function installProcessExitHack(finalTask) {
78657
78855
  }
78658
78856
  async function runCli(cliRoot, { cliVersion }) {
78659
78857
  installUnhandledRejectionsHandler();
78660
- const pkg = { name: "@sanity/cli", version: cliVersion }, args = parseArguments(), isInit = args.groupOrCommand === "init" && args.argsWithoutOptions[0] !== "plugin", isCoreApp = args.groupOrCommand === "app", cwd = getCurrentWorkingDirectory();
78858
+ const pkg = { name: "@sanity/cli", version: cliVersion }, args = parseArguments(), isInit = args.groupOrCommand === "init" && args.argsWithoutOptions[0] !== "plugin", cwd = getCurrentWorkingDirectory();
78661
78859
  let workDir;
78662
78860
  try {
78663
- workDir = isInit ? process.cwd() : loadEnv.resolveRootDir(cwd, isCoreApp);
78861
+ workDir = isInit ? process.cwd() : loadEnv.resolveRootDir(cwd);
78664
78862
  } catch (err) {
78665
78863
  console.error(chalk__default.default.red(err.message)), process.exit(1);
78666
78864
  }
78667
- loadAndSetEnvFromDotEnvFiles({ workDir, cmd: args.groupOrCommand, isCoreApp }), maybeFixMissingWindowsEnvVar(), await runUpdateCheck({ pkg, cwd, workDir }).notify(), telemetryDisclosure(), loadEnv.debug(`Reading CLI config from "${workDir}"`);
78865
+ loadAndSetEnvFromDotEnvFiles({ workDir, cmd: args.groupOrCommand }), maybeFixMissingWindowsEnvVar(), await runUpdateCheck({ pkg, cwd, workDir }).notify(), telemetryDisclosure(), loadEnv.debug(`Reading CLI config from "${workDir}"`);
78668
78866
  const cliConfig = await getCliConfig.getCliConfig(workDir, { forked: !0 });
78669
78867
  cliConfig || loadEnv.debug("No CLI config found");
78670
78868
  const { logger: telemetry2, flush: flushTelemetry } = createTelemetryStore({
@@ -78690,8 +78888,7 @@ async function runCli(cliRoot, { cliVersion }) {
78690
78888
  workDir,
78691
78889
  corePath: await getCoreModulePath(workDir, cliConfig),
78692
78890
  cliConfig,
78693
- telemetry: telemetry2,
78694
- isCoreApp
78891
+ telemetry: telemetry2
78695
78892
  };
78696
78893
  warnOnNonProductionEnvironment(), warnOnInferredProjectDir(isInit, cwd, workDir);
78697
78894
  const core2 = args.coreOptions, commands = await mergeCommands(baseCommands, options2.corePath, { cliVersion });
@@ -78791,11 +78988,7 @@ function warnOnNonProductionEnvironment() {
78791
78988
  )
78792
78989
  );
78793
78990
  }
78794
- function loadAndSetEnvFromDotEnvFiles({
78795
- workDir,
78796
- cmd,
78797
- isCoreApp
78798
- }) {
78991
+ function loadAndSetEnvFromDotEnvFiles({ workDir, cmd }) {
78799
78992
  if (fs$1.existsSync(path__default.default.join(workDir, "sanity.json"))) {
78800
78993
  loadEnv.debug("sanity.json exists, assuming v2 project and loading .env files using old behavior");
78801
78994
  const env = process.env.SANITY_ACTIVE_ENV || process.env.NODE_ENV || "development";
@@ -78807,7 +79000,7 @@ function loadAndSetEnvFromDotEnvFiles({
78807
79000
  let mode2 = process.env.SANITY_ACTIVE_ENV;
78808
79001
  !mode2 && (isProdCmd || process.env.NODE_ENV === "production") ? mode2 = "production" : mode2 || (mode2 = "development"), mode2 === "production" && !isProdCmd && console.warn(chalk__default.default.yellow(`[WARN] Running in ${sanityEnv} environment mode
78809
79002
  `)), loadEnv.debug("Loading environment files using %s mode", mode2);
78810
- const studioEnv = loadEnv.loadEnv(mode2, workDir, isCoreApp ? ["VITE_"] : ["SANITY_STUDIO_"]);
79003
+ const studioEnv = loadEnv.loadEnv(mode2, workDir, ["SANITY_STUDIO_"]);
78811
79004
  process.env = { ...process.env, ...studioEnv };
78812
79005
  }
78813
79006
  function maybeFixMissingWindowsEnvVar() {