sanity 3.26.2-canary.52 → 3.26.2-canary.69

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 (112) hide show
  1. package/lib/_chunks/{_internal-2CJ5wSKF.js → _internal-6Pl2wJGj.js} +422 -201
  2. package/lib/_chunks/_internal-6Pl2wJGj.js.map +1 -0
  3. package/lib/_chunks/{_internal-79flWvL8.js → _internal-yQwMw2ht.js} +419 -203
  4. package/lib/_chunks/_internal-yQwMw2ht.js.map +1 -0
  5. package/lib/_chunks/{_internalBrowser-QAFz3SKp.js → _internalBrowser-HWvRXvlU.js} +22 -22
  6. package/lib/_chunks/_internalBrowser-HWvRXvlU.js.map +1 -0
  7. package/lib/_chunks/{_internalBrowser-Y0qKZ-GA.js → _internalBrowser-TWIhitgI.js} +22 -22
  8. package/lib/_chunks/_internalBrowser-TWIhitgI.js.map +1 -0
  9. package/lib/_chunks/{deployApiAction-SHteit1G.js → deployApiAction-TZcCtXan.js} +2 -2
  10. package/lib/_chunks/{deployApiAction-SHteit1G.js.map → deployApiAction-TZcCtXan.js.map} +1 -1
  11. package/lib/_chunks/{deployApiAction-bRyJpGOS.js → deployApiAction-rVL67VYW.js} +2 -2
  12. package/lib/_chunks/{deployApiAction-bRyJpGOS.js.map → deployApiAction-rVL67VYW.js.map} +1 -1
  13. package/lib/_chunks/{getStudioConfig-JSkc4GE0.js → getStudioWorkspaces-HX9o9-hl.js} +20 -4
  14. package/lib/_chunks/getStudioWorkspaces-HX9o9-hl.js.map +1 -0
  15. package/lib/_chunks/{index-EO9iRnDS.js → index-2kSxso3r.js} +2 -2
  16. package/lib/_chunks/{index-EO9iRnDS.js.map → index-2kSxso3r.js.map} +1 -1
  17. package/lib/_chunks/{index-FQCCBbuC.js → index-751ZLh3z.js} +6 -6
  18. package/lib/_chunks/{index-FQCCBbuC.js.map → index-751ZLh3z.js.map} +1 -1
  19. package/lib/_chunks/{index-VNSHvpZr.js → index-HcF369ru.js} +2 -2
  20. package/lib/_chunks/{index-VNSHvpZr.js.map → index-HcF369ru.js.map} +1 -1
  21. package/lib/_chunks/{index-Xs2xnLUV.js → index-MAAxgUnl.js} +6 -6
  22. package/lib/_chunks/{index-Xs2xnLUV.js.map → index-MAAxgUnl.js.map} +1 -1
  23. package/lib/_chunks/{index-AaK2CidU.js → index-NweJPfGb.js} +2 -2
  24. package/lib/_chunks/{index-AaK2CidU.js.map → index-NweJPfGb.js.map} +1 -1
  25. package/lib/_chunks/{index-R7R6AyHF.js → index-zobOqko7.js} +2 -2
  26. package/lib/_chunks/{index-R7R6AyHF.js.map → index-zobOqko7.js.map} +1 -1
  27. package/lib/_chunks/{listApisAction-6lGkFZrU.js → listApisAction-IvKV4iAd.js} +2 -2
  28. package/lib/_chunks/{listApisAction-6lGkFZrU.js.map → listApisAction-IvKV4iAd.js.map} +1 -1
  29. package/lib/_chunks/{listApisAction-CqCkBz-F.js → listApisAction-oca2uykY.js} +2 -2
  30. package/lib/_chunks/{listApisAction-CqCkBz-F.js.map → listApisAction-oca2uykY.js.map} +1 -1
  31. package/lib/_chunks/pane-9HEeITpx.js +5 -0
  32. package/lib/_chunks/pane-9HEeITpx.js.map +1 -0
  33. package/lib/_chunks/pane-QyVrOLqS.js +2 -0
  34. package/lib/_chunks/pane-QyVrOLqS.js.map +1 -0
  35. package/lib/_chunks/pane-TXXUUvdc.js +5 -0
  36. package/lib/_chunks/pane-TXXUUvdc.js.map +1 -0
  37. package/lib/_chunks/pane-cQxQtBcL.js +2 -0
  38. package/lib/_chunks/pane-cQxQtBcL.js.map +1 -0
  39. package/lib/_chunks/{structure-qJLnDJXq.js → structure-iqIDIH7-.js} +3 -3
  40. package/lib/_chunks/structure-iqIDIH7-.js.map +1 -0
  41. package/lib/_chunks/{structure-588eAwLd.js → structure-o_wMXC_G.js} +3 -3
  42. package/lib/_chunks/structure-o_wMXC_G.js.map +1 -0
  43. package/lib/_chunks/validateAction-4Jl_y_iB.js +154 -0
  44. package/lib/_chunks/validateAction-4Jl_y_iB.js.map +1 -0
  45. package/lib/_chunks/{validateAction-GUvMkXiN.js → validateAction-6q8Sqwaz.js} +25 -73
  46. package/lib/_chunks/validateAction-6q8Sqwaz.js.map +1 -0
  47. package/lib/_chunks/validateAction-Bz67ApRP.js +143 -0
  48. package/lib/_chunks/validateAction-Bz67ApRP.js.map +1 -0
  49. package/lib/_chunks/{validateAction-NIrqtyYJ.js → validateAction-shi462sq.js} +27 -75
  50. package/lib/_chunks/validateAction-shi462sq.js.map +1 -0
  51. package/lib/_internal/cli/threads/getGraphQLAPIs.js +2 -2
  52. package/lib/_internal/cli/threads/getGraphQLAPIs.js.map +1 -1
  53. package/lib/_internal/cli/threads/validateDocuments.js +5 -3
  54. package/lib/_internal/cli/threads/validateDocuments.js.map +1 -1
  55. package/lib/_internal/cli/threads/validateSchema.js +55 -0
  56. package/lib/_internal/cli/threads/validateSchema.js.map +1 -0
  57. package/lib/_internal.esm.js +1 -1
  58. package/lib/_internal.js +1 -1
  59. package/lib/_internalBrowser.esm.js +1 -1
  60. package/lib/_internalBrowser.js +1 -1
  61. package/lib/desk.esm.js +1 -1
  62. package/lib/desk.js +1 -1
  63. package/lib/exports/index.d.ts +25 -0
  64. package/lib/index.cjs.mjs +1 -0
  65. package/lib/index.esm.js +2 -2
  66. package/lib/index.js +2 -1
  67. package/lib/index.js.map +1 -1
  68. package/lib/structure.esm.js +1 -1
  69. package/lib/structure.js +1 -1
  70. package/package.json +15 -15
  71. package/src/_internal/cli/actions/schema/formatSchemaValidation.ts +96 -0
  72. package/src/_internal/cli/actions/schema/validateAction.ts +120 -0
  73. package/src/_internal/cli/actions/validation/reporters/prettyReporter/formatDocumentValidation.ts +17 -95
  74. package/src/_internal/cli/commands/index.ts +2 -0
  75. package/src/_internal/cli/commands/migration/createMigrationCommand.ts +18 -10
  76. package/src/_internal/cli/commands/migration/listMigrationsCommand.ts +34 -31
  77. package/src/_internal/cli/commands/migration/prettyMutationFormatter.ts +214 -0
  78. package/src/_internal/cli/commands/migration/runMigrationCommand.ts +102 -58
  79. package/src/_internal/cli/commands/migration/templates/minimalAdvanced.ts +1 -1
  80. package/src/_internal/cli/commands/migration/templates/minimalSimple.ts +1 -1
  81. package/src/_internal/cli/commands/migration/templates/renameField.ts +3 -3
  82. package/src/_internal/cli/commands/migration/templates/renameType.ts +1 -1
  83. package/src/_internal/cli/commands/migration/templates/stringToPTE.ts +1 -1
  84. package/src/_internal/cli/commands/migration/utils/mutationFormatter.ts +1 -1
  85. package/src/_internal/cli/commands/schema/validateSchemaCommand.ts +35 -0
  86. package/src/_internal/cli/threads/getGraphQLAPIs.ts +2 -2
  87. package/src/_internal/cli/threads/validateDocuments.ts +6 -3
  88. package/src/_internal/cli/threads/validateSchema.ts +73 -0
  89. package/src/_internal/cli/util/{getStudioConfig.ts → getStudioWorkspaces.ts} +30 -8
  90. package/src/_internal/cli/util/tree.ts +110 -0
  91. package/src/core/config/index.ts +1 -0
  92. package/src/core/config/prepareConfig.ts +2 -5
  93. package/src/core/config/resolveSchemaTypes.ts +29 -0
  94. package/src/core/studio/screens/schemaErrors/SchemaProblemGroups.tsx +4 -2
  95. package/src/structure/comments/src/components/pte/blocks/MentionInlineBlock.tsx +13 -6
  96. package/lib/_chunks/_internal-2CJ5wSKF.js.map +0 -1
  97. package/lib/_chunks/_internal-79flWvL8.js.map +0 -1
  98. package/lib/_chunks/_internalBrowser-QAFz3SKp.js.map +0 -1
  99. package/lib/_chunks/_internalBrowser-Y0qKZ-GA.js.map +0 -1
  100. package/lib/_chunks/getStudioConfig-JSkc4GE0.js.map +0 -1
  101. package/lib/_chunks/pane-QmJb9ZTN.js +0 -2
  102. package/lib/_chunks/pane-QmJb9ZTN.js.map +0 -1
  103. package/lib/_chunks/pane-SK7FWNTJ.js +0 -2
  104. package/lib/_chunks/pane-SK7FWNTJ.js.map +0 -1
  105. package/lib/_chunks/pane-y4hpcKe1.js +0 -5
  106. package/lib/_chunks/pane-y4hpcKe1.js.map +0 -1
  107. package/lib/_chunks/pane-yQXBQyyI.js +0 -5
  108. package/lib/_chunks/pane-yQXBQyyI.js.map +0 -1
  109. package/lib/_chunks/structure-588eAwLd.js.map +0 -1
  110. package/lib/_chunks/structure-qJLnDJXq.js.map +0 -1
  111. package/lib/_chunks/validateAction-GUvMkXiN.js.map +0 -1
  112. package/lib/_chunks/validateAction-NIrqtyYJ.js.map +0 -1
@@ -41,7 +41,8 @@ var deburr = require('lodash/deburr');
41
41
  var mkdirp = require('mkdirp');
42
42
  var node = require('esbuild-register/dist/node');
43
43
  var migrate = require('@sanity/migrate');
44
- var PathUtils = require('@sanity/util/paths');
44
+ var tty = require('tty');
45
+ var sanity = require('sanity');
45
46
  function _interopDefaultCompat(e) {
46
47
  return e && typeof e === 'object' && 'default' in e ? e : {
47
48
  default: e
@@ -76,7 +77,7 @@ var size__default = /*#__PURE__*/_interopDefaultCompat(size);
76
77
  var fs__default$2 = /*#__PURE__*/_interopDefaultCompat(fs$3);
77
78
  var deburr__default = /*#__PURE__*/_interopDefaultCompat(deburr);
78
79
  var mkdirp__default = /*#__PURE__*/_interopDefaultCompat(mkdirp);
79
- const helpText$s = "\nOptions\n --source-maps Enable source maps for built bundles (increases size of bundle)\n --no-minify Skip minifying built JavaScript (speeds up build, increases size of bundle)\n -y, --yes Use unattended mode, accepting defaults and using only flags for choices\n\nExamples\n sanity build\n sanity build --no-minify --source-maps\n";
80
+ const helpText$t = "\nOptions\n --source-maps Enable source maps for built bundles (increases size of bundle)\n --no-minify Skip minifying built JavaScript (speeds up build, increases size of bundle)\n -y, --yes Use unattended mode, accepting defaults and using only flags for choices\n\nExamples\n sanity build\n sanity build --no-minify --source-maps\n";
80
81
  const buildCommand = {
81
82
  name: "build",
82
83
  signature: "[OUTPUT_DIR]",
@@ -85,7 +86,7 @@ const buildCommand = {
85
86
  const buildAction = await getBuildAction();
86
87
  return buildAction(args, context, overrides);
87
88
  },
88
- helpText: helpText$s
89
+ helpText: helpText$t
89
90
  };
90
91
  async function getBuildAction() {
91
92
  const mod = await Promise.resolve().then(function () {
@@ -124,7 +125,7 @@ var datasetGroup = {
124
125
  isGroupRoot: true,
125
126
  description: "Interact with datasets in your project"
126
127
  };
127
- const helpText$r = "\nOptions\n --source-maps Enable source maps for built bundles (increases size of bundle)\n --no-minify Skip minifying built JavaScript (speeds up build, increases size of bundle)\n --no-build Don't build the studio prior to deploy, instead deploying the version currently in `dist/`\n\nExamples\n sanity deploy\n sanity deploy --no-minify --source-maps\n";
128
+ const helpText$s = "\nOptions\n --source-maps Enable source maps for built bundles (increases size of bundle)\n --no-minify Skip minifying built JavaScript (speeds up build, increases size of bundle)\n --no-build Don't build the studio prior to deploy, instead deploying the version currently in `dist/`\n\nExamples\n sanity deploy\n sanity deploy --no-minify --source-maps\n";
128
129
  const deployCommand = {
129
130
  name: "deploy",
130
131
  signature: "[SOURCE_DIR] [--no-build] [--source-maps] [--no-minify]",
@@ -135,9 +136,9 @@ const deployCommand = {
135
136
  });
136
137
  return mod.default(args, context);
137
138
  },
138
- helpText: helpText$r
139
+ helpText: helpText$s
139
140
  };
140
- const helpText$q = "\nExamples\n sanity undeploy\n";
141
+ const helpText$r = "\nExamples\n sanity undeploy\n";
141
142
  const undeployCommand = {
142
143
  name: "undeploy",
143
144
  signature: "",
@@ -148,7 +149,7 @@ const undeployCommand = {
148
149
  });
149
150
  return mod.default(args, context);
150
151
  },
151
- helpText: helpText$q
152
+ helpText: helpText$r
152
153
  };
153
154
  const MAX_DATASET_NAME_LENGTH$1 = 64;
154
155
  function validateDatasetAliasName(datasetName) {
@@ -273,13 +274,13 @@ function promptForDatasetName(prompt) {
273
274
  ...options
274
275
  });
275
276
  }
276
- const helpText$p = "\nOptions\n --visibility <mode> Set visibility for this dataset (public/private)\n\nExamples\n sanity dataset create\n sanity dataset create <name>\n sanity dataset create <name> --visibility private\n";
277
+ const helpText$q = "\nOptions\n --visibility <mode> Set visibility for this dataset (public/private)\n\nExamples\n sanity dataset create\n sanity dataset create <name>\n sanity dataset create <name> --visibility private\n";
277
278
  const allowedModes = ["private", "public", "custom"];
278
279
  const createDatasetCommand = {
279
280
  name: "create",
280
281
  group: "dataset",
281
282
  signature: "[NAME]",
282
- helpText: helpText$p,
283
+ helpText: helpText$q,
283
284
  description: "Create a new dataset within your project",
284
285
  action: async (args, context) => {
285
286
  const {
@@ -389,7 +390,7 @@ const datasetVisibilityCommand = {
389
390
  output.print("Dataset visibility changed");
390
391
  }
391
392
  };
392
- const helpText$o = "\nOptions\n --force Do not prompt for delete confirmation - forcefully delete\n\nExamples\n sanity dataset delete\n sanity dataset delete my-dataset\n sanity dataset delete my-dataset --force\n";
393
+ const helpText$p = "\nOptions\n --force Do not prompt for delete confirmation - forcefully delete\n\nExamples\n sanity dataset delete\n sanity dataset delete my-dataset\n sanity dataset delete my-dataset --force\n";
393
394
  function parseCliFlags$4(args) {
394
395
  return yargs__default.default(helpers.hideBin(args.argv || process.argv).slice(2)).option("force", {
395
396
  type: "boolean"
@@ -398,7 +399,7 @@ function parseCliFlags$4(args) {
398
399
  const deleteDatasetCommand = {
399
400
  name: "delete",
400
401
  group: "dataset",
401
- helpText: helpText$o,
402
+ helpText: helpText$p,
402
403
  signature: "[datasetName]",
403
404
  description: "Delete a dataset within your project",
404
405
  action: async (args, context) => {
@@ -471,7 +472,7 @@ async function chooseDatasetPrompt(context) {
471
472
  return selected;
472
473
  }
473
474
  const noop = () => null;
474
- const helpText$n = "\nOptions\n --raw Extract only documents, without rewriting asset references\n --no-assets Export only non-asset documents and remove references to image assets\n --no-drafts Export only published versions of documents\n --no-compress Skips compressing tarball entries (still generates a gzip file)\n --types Defines which document types to export\n --overwrite Overwrite any file with the same name\n --asset-concurrency <num> Concurrent number of asset downloads\n\nExamples\n sanity dataset export moviedb localPath.tar.gz\n sanity dataset export moviedb assetless.tar.gz --no-assets\n sanity dataset export staging staging.tar.gz --raw\n sanity dataset export staging staging.tar.gz --types products,shops\n";
475
+ const helpText$o = "\nOptions\n --raw Extract only documents, without rewriting asset references\n --no-assets Export only non-asset documents and remove references to image assets\n --no-drafts Export only published versions of documents\n --no-compress Skips compressing tarball entries (still generates a gzip file)\n --types Defines which document types to export\n --overwrite Overwrite any file with the same name\n --asset-concurrency <num> Concurrent number of asset downloads\n\nExamples\n sanity dataset export moviedb localPath.tar.gz\n sanity dataset export moviedb assetless.tar.gz --no-assets\n sanity dataset export staging staging.tar.gz --raw\n sanity dataset export staging staging.tar.gz --types products,shops\n";
475
476
  function parseFlags$1(rawFlags) {
476
477
  const flags = {};
477
478
  if (rawFlags.types) {
@@ -502,7 +503,7 @@ const exportDatasetCommand = {
502
503
  group: "dataset",
503
504
  signature: "[NAME] [DESTINATION]",
504
505
  description: "Export dataset to local filesystem as a gzipped tarball",
505
- helpText: helpText$n,
506
+ helpText: helpText$o,
506
507
  action: async (args, context) => {
507
508
  const {
508
509
  apiClient,
@@ -612,7 +613,7 @@ async function getOutputPath(destination, dataset, prompt, flags) {
612
613
  return finalPath;
613
614
  }
614
615
  const yellow = str => "\x1B[33m".concat(str, "\x1B[39m");
615
- const helpText$m = '\nOptions\n --missing On duplicate document IDs, skip importing document in question\n --replace On duplicate document IDs, replace existing document with imported document\n --allow-failing-assets Skip assets that cannot be fetched/uploaded\n --replace-assets Skip reuse of existing assets\n --skip-cross-dataset-references Skips references to other datasets\n\nRarely used options (should generally not be used)\n --allow-assets-in-different-dataset Allow asset documents to reference different project/dataset\n\nExamples\n # Import "moviedb.ndjson" from the current directory to the dataset called "moviedb"\n sanity dataset import moviedb.ndjson moviedb\n\n # Import "moviedb.tar.gz" from the current directory to the dataset called "moviedb",\n # replacing any documents encountered that have the same document IDs\n sanity dataset import moviedb.tar.gz moviedb --replace\n\n # Import from a folder containing an ndjson file, such as an extracted tarball\n # retrieved through "sanity dataset export".\n sanity dataset import ~/some/folder moviedb\n\n # Import from a remote URL. Will download and extract the tarball to a temporary\n # location before importing it.\n sanity dataset import https://some.url/moviedb.tar.gz moviedb --replace\n';
616
+ const helpText$n = '\nOptions\n --missing On duplicate document IDs, skip importing document in question\n --replace On duplicate document IDs, replace existing document with imported document\n --allow-failing-assets Skip assets that cannot be fetched/uploaded\n --replace-assets Skip reuse of existing assets\n --skip-cross-dataset-references Skips references to other datasets\n\nRarely used options (should generally not be used)\n --allow-assets-in-different-dataset Allow asset documents to reference different project/dataset\n\nExamples\n # Import "moviedb.ndjson" from the current directory to the dataset called "moviedb"\n sanity dataset import moviedb.ndjson moviedb\n\n # Import "moviedb.tar.gz" from the current directory to the dataset called "moviedb",\n # replacing any documents encountered that have the same document IDs\n sanity dataset import moviedb.tar.gz moviedb --replace\n\n # Import from a folder containing an ndjson file, such as an extracted tarball\n # retrieved through "sanity dataset export".\n sanity dataset import ~/some/folder moviedb\n\n # Import from a remote URL. Will download and extract the tarball to a temporary\n # location before importing it.\n sanity dataset import https://some.url/moviedb.tar.gz moviedb --replace\n';
616
617
  function toBoolIfSet(flag) {
617
618
  return typeof flag === "undefined" ? void 0 : Boolean(flag);
618
619
  }
@@ -639,7 +640,7 @@ const importDatasetCommand = {
639
640
  group: "dataset",
640
641
  signature: "[FILE | FOLDER | URL] [TARGET_DATASET]",
641
642
  description: "Import documents to given dataset from either an ndjson file or a gzipped tarball",
642
- helpText: helpText$m,
643
+ helpText: helpText$n,
643
644
  // eslint-disable-next-line max-statements
644
645
  action: async (args, context) => {
645
646
  const {
@@ -995,7 +996,7 @@ const getClientUrl = function (client, uri) {
995
996
  const base = useCdn ? config.cdnUrl : config.url;
996
997
  return "".concat(base, "/").concat(uri.replace(/^\//, ""));
997
998
  };
998
- const helpText$l = "\nOptions\n --detach Start the copy without waiting for it to finish\n --attach <job-id> Attach to the running copy process to show progress\n --skip-history Don't preserve document history on copy\n --list Lists all dataset copy jobs corresponding to a certain criteria.\n --offset Start position in the list of jobs. Default 0. With --list.\n --limit Maximum number of jobs returned. Default 10. Maximum 1000. With --list.\n\nExamples\n sanity dataset copy\n sanity dataset copy <source-dataset>\n sanity dataset copy <source-dataset> <target-dataset>\n sanity dataset copy --skip-history <source-dataset> <target-dataset>\n sanity dataset copy --detach <source-dataset> <target-dataset>\n sanity dataset copy --attach <job-id>\n sanity dataset copy --list\n sanity dataset copy --list --offset=2\n sanity dataset copy --list --offset=2 --limit=10\n";
999
+ const helpText$m = "\nOptions\n --detach Start the copy without waiting for it to finish\n --attach <job-id> Attach to the running copy process to show progress\n --skip-history Don't preserve document history on copy\n --list Lists all dataset copy jobs corresponding to a certain criteria.\n --offset Start position in the list of jobs. Default 0. With --list.\n --limit Maximum number of jobs returned. Default 10. Maximum 1000. With --list.\n\nExamples\n sanity dataset copy\n sanity dataset copy <source-dataset>\n sanity dataset copy <source-dataset> <target-dataset>\n sanity dataset copy --skip-history <source-dataset> <target-dataset>\n sanity dataset copy --detach <source-dataset> <target-dataset>\n sanity dataset copy --attach <job-id>\n sanity dataset copy --list\n sanity dataset copy --list --offset=2\n sanity dataset copy --list --offset=2 --limit=10\n";
999
1000
  function parseCliFlags$3(args) {
1000
1001
  return yargs__default.default(helpers.hideBin(args.argv || process.argv).slice(2)).option("attach", {
1001
1002
  type: "string"
@@ -1088,7 +1089,7 @@ const copyDatasetCommand = {
1088
1089
  name: "copy",
1089
1090
  group: "dataset",
1090
1091
  signature: "[SOURCE_DATASET] [TARGET_DATASET]",
1091
- helpText: helpText$l,
1092
+ helpText: helpText$m,
1092
1093
  description: "Manages dataset copying, including starting a new copy job, listing copy jobs and following the progress of a running copy job",
1093
1094
  action: async (args, context) => {
1094
1095
  const {
@@ -1383,12 +1384,12 @@ var __template$1 = (cooked, raw) => __freeze$1(__defProp$1(cooked, "raw", {
1383
1384
  value: __freeze$1(raw || cooked.slice())
1384
1385
  }));
1385
1386
  var _a$1;
1386
- const helpText$k = "\nBelow are examples of the alias subcommand\n\nCreate Alias\n sanity dataset alias create\n sanity dataset alias create <alias-name>\n sanity dataset alias create <alias-name> <target-dataset>\n\nDelete Alias\n Options\n --force Skips security prompt and forces link command\n\n Usage\n sanity dataset alias delete <alias-name>\n sanity dataset alias delete <alias-name> --force\n\nLink Alias\n Options\n --force Skips security prompt and forces link command\n\n Usage\n sanity dataset alias link\n sanity dataset alias link <alias-name>\n sanity dataset alias link <alias-name> <target-dataset>\n sanity dataset alias link <alias-name> <target-dataset> --force\n\nUn-link Alias\n Options\n --force Skips security prompt and forces link command\n\n Usage\n sanity dataset alias unlink\n sanity dataset alias unlink <alias-name>\n sanity dataset alias unlink <alias-name> --force\n";
1387
+ const helpText$l = "\nBelow are examples of the alias subcommand\n\nCreate Alias\n sanity dataset alias create\n sanity dataset alias create <alias-name>\n sanity dataset alias create <alias-name> <target-dataset>\n\nDelete Alias\n Options\n --force Skips security prompt and forces link command\n\n Usage\n sanity dataset alias delete <alias-name>\n sanity dataset alias delete <alias-name> --force\n\nLink Alias\n Options\n --force Skips security prompt and forces link command\n\n Usage\n sanity dataset alias link\n sanity dataset alias link <alias-name>\n sanity dataset alias link <alias-name> <target-dataset>\n sanity dataset alias link <alias-name> <target-dataset> --force\n\nUn-link Alias\n Options\n --force Skips security prompt and forces link command\n\n Usage\n sanity dataset alias unlink\n sanity dataset alias unlink <alias-name>\n sanity dataset alias unlink <alias-name> --force\n";
1387
1388
  const aliasCommand = {
1388
1389
  name: "alias",
1389
1390
  group: "dataset",
1390
1391
  signature: "SUBCOMMAND [ALIAS_NAME, TARGET_DATASET]",
1391
- helpText: helpText$k,
1392
+ helpText: helpText$l,
1392
1393
  description: "You can manage your dataset alias using this command.",
1393
1394
  action: async (args, context) => {
1394
1395
  const [verb] = args.argsWithoutOptions;
@@ -1441,12 +1442,12 @@ function colorizeJson(input, chalk) {
1441
1442
  return formatter(token.raw);
1442
1443
  }).join("");
1443
1444
  }
1444
- const helpText$j = "\nGet and print a document from the projects configured dataset\n\nOptions\n --pretty colorized JSON output\n --dataset NAME to override dataset\n\nExamples\n # Get the document with the ID \"myDocId\"\n sanity documents get myDocId\n\n # ID wrapped in double or single quote works equally well\n sanity documents get 'myDocId'\n";
1445
+ const helpText$k = "\nGet and print a document from the projects configured dataset\n\nOptions\n --pretty colorized JSON output\n --dataset NAME to override dataset\n\nExamples\n # Get the document with the ID \"myDocId\"\n sanity documents get myDocId\n\n # ID wrapped in double or single quote works equally well\n sanity documents get 'myDocId'\n";
1445
1446
  const getDocumentsCommand = {
1446
1447
  name: "get",
1447
1448
  group: "documents",
1448
1449
  signature: "[DOCUMENT_ID]",
1449
- helpText: helpText$j,
1450
+ helpText: helpText$k,
1450
1451
  description: "Get and print a document by ID",
1451
1452
  action: async (args, context) => {
1452
1453
  const {
@@ -1477,12 +1478,12 @@ const getDocumentsCommand = {
1477
1478
  }
1478
1479
  };
1479
1480
  const defaultApiVersion = "v2022-06-01";
1480
- const helpText$i = "\nRun a query against the projects configured dataset\n\nOptions\n --pretty colorized JSON output\n --dataset NAME to override dataset\n --project PROJECT to override project ID\n --anonymous Send the query without any authorization token\n --api-version API version to use (defaults to `".concat(defaultApiVersion, '`)\n\nEnvironment variables\n `SANITY_CLI_QUERY_API_VERSION` - will use the defined API version,\n unless `--api-version` is specified.\n\nExamples\n # Fetch 5 documents of type "movie"\n sanity documents query \'*[_type == "movie"][0..4]\'\n\n # Fetch title of the oldest movie in the dataset named "staging"\n sanity documents query \'*[_type == "movie"]|order(releaseDate asc)[0]{title}\' --dataset staging\n\n # Use API version v2021-06-07 and do a query\n sanity documents query --api-version v2021-06-07 \'*[_id == "header"] { "headerText": pt::text(body) }\'\n');
1481
+ const helpText$j = "\nRun a query against the projects configured dataset\n\nOptions\n --pretty colorized JSON output\n --dataset NAME to override dataset\n --project PROJECT to override project ID\n --anonymous Send the query without any authorization token\n --api-version API version to use (defaults to `".concat(defaultApiVersion, '`)\n\nEnvironment variables\n `SANITY_CLI_QUERY_API_VERSION` - will use the defined API version,\n unless `--api-version` is specified.\n\nExamples\n # Fetch 5 documents of type "movie"\n sanity documents query \'*[_type == "movie"][0..4]\'\n\n # Fetch title of the oldest movie in the dataset named "staging"\n sanity documents query \'*[_type == "movie"]|order(releaseDate asc)[0]{title}\' --dataset staging\n\n # Use API version v2021-06-07 and do a query\n sanity documents query --api-version v2021-06-07 \'*[_id == "header"] { "headerText": pt::text(body) }\'\n');
1481
1482
  var queryDocumentsCommand = {
1482
1483
  name: "query",
1483
1484
  group: "documents",
1484
1485
  signature: "[QUERY]",
1485
- helpText: helpText$i,
1486
+ helpText: helpText$j,
1486
1487
  description: "Query for documents",
1487
1488
  action: async (args, context) => {
1488
1489
  var _a, _b;
@@ -1556,12 +1557,12 @@ function parseCliFlags(args) {
1556
1557
  default: fallbackApiVersion
1557
1558
  }).argv;
1558
1559
  }
1559
- const helpText$h = '\nDelete a document from the projects configured dataset\n\nOptions\n --dataset NAME to override dataset\n\nExample\n # Delete the document with the ID "myDocId"\n sanity documents delete myDocId\n\n # ID wrapped in double or single quote works equally well\n sanity documents delete \'myDocId\'\n\n # Delete document with ID "someDocId" from dataset "blog"\n sanity documents delete --dataset=blog someDocId\n\n # Delete the document with ID "doc1" and "doc2"\n sanity documents delete doc1 doc2\n';
1560
+ const helpText$i = '\nDelete a document from the projects configured dataset\n\nOptions\n --dataset NAME to override dataset\n\nExample\n # Delete the document with the ID "myDocId"\n sanity documents delete myDocId\n\n # ID wrapped in double or single quote works equally well\n sanity documents delete \'myDocId\'\n\n # Delete document with ID "someDocId" from dataset "blog"\n sanity documents delete --dataset=blog someDocId\n\n # Delete the document with ID "doc1" and "doc2"\n sanity documents delete doc1 doc2\n';
1560
1561
  const deleteDocumentsCommand = {
1561
1562
  name: "delete",
1562
1563
  group: "documents",
1563
1564
  signature: "[ID] [...IDS]",
1564
- helpText: helpText$h,
1565
+ helpText: helpText$i,
1565
1566
  description: "Delete a document by ID",
1566
1567
  action: async (args, context) => {
1567
1568
  const {
@@ -1597,12 +1598,12 @@ const deleteDocumentsCommand = {
1597
1598
  }
1598
1599
  }
1599
1600
  };
1600
- const helpText$g = '\nOptions\n --replace On duplicate document IDs, replace existing document with specified document(s)\n --missing On duplicate document IDs, don\'t modify the target document(s)\n --watch Write the documents whenever the target file or buffer changes\n --json5 Use JSON5 file type to allow a "simplified" version of JSON\n --id <id> Specify a document ID to use. Will fetch remote document ID and populate editor.\n --dataset NAME to override dataset\n\nExamples\n # Create the document specified in "myDocument.json".\n sanity documents create myDocument.json\n\n # Open configured $EDITOR and create the specified document(s)\n sanity documents create\n\n # Fetch document with the ID "myDocId" and open configured $EDITOR with the\n # current document content (if any). Replace document with the edited version\n # when the editor closes\n sanity documents create --id myDocId --replace\n\n # Open configured $EDITOR and replace the document with the given content\n # on each save. Use JSON5 file extension and parser for simplified syntax.\n sanity documents create --id myDocId --watch --replace --json5\n';
1601
+ const helpText$h = '\nOptions\n --replace On duplicate document IDs, replace existing document with specified document(s)\n --missing On duplicate document IDs, don\'t modify the target document(s)\n --watch Write the documents whenever the target file or buffer changes\n --json5 Use JSON5 file type to allow a "simplified" version of JSON\n --id <id> Specify a document ID to use. Will fetch remote document ID and populate editor.\n --dataset NAME to override dataset\n\nExamples\n # Create the document specified in "myDocument.json".\n sanity documents create myDocument.json\n\n # Open configured $EDITOR and create the specified document(s)\n sanity documents create\n\n # Fetch document with the ID "myDocId" and open configured $EDITOR with the\n # current document content (if any). Replace document with the edited version\n # when the editor closes\n sanity documents create --id myDocId --replace\n\n # Open configured $EDITOR and replace the document with the given content\n # on each save. Use JSON5 file extension and parser for simplified syntax.\n sanity documents create --id myDocId --watch --replace --json5\n';
1601
1602
  const createDocumentsCommand = {
1602
1603
  name: "create",
1603
1604
  group: "documents",
1604
1605
  signature: "[FILE]",
1605
- helpText: helpText$g,
1606
+ helpText: helpText$h,
1606
1607
  description: "Create one or more documents",
1607
1608
  // eslint-disable-next-line complexity
1608
1609
  action: async (args, context) => {
@@ -1786,22 +1787,22 @@ function getEditor() {
1786
1787
  args
1787
1788
  };
1788
1789
  }
1789
- const description = "Downloads and validates all document specified in a workspace";
1790
- const helpText$f = "\nOptions\n -y, --yes Skips the first confirmation prompt.\n --workspace <name> The name of the workspace to use when downloading and validating all documents.\n --dataset <name> Override the dataset used. By default, this is derived from the given workspace.\n --file <filepath> Provide a path to either an .ndjson file or a tarball containing an .ndjson file.\n --format <pretty|ndjson|json> The output format used to print the found validation markers and report progress.\n --level <error|warning|info> The minimum level reported out. Defaults to warning.\n --max-custom-validation-concurrency <number> Specify how many custom validators can run concurrently. Defaults to 5.\n\nExamples\n # Validates all documents in a Sanity project with more than one workspace\n sanity documents validate --workspace default\n\n # Override the dataset specified in the workspace\n sanity documents validate --workspace default --dataset staging\n\n # Save the results of the report into a file\n sanity documents validate > report.txt\n\n # Report out info level validation markers too\n sanity documents validate --level info\n";
1791
- const validateDocumentsCommand = {
1790
+ const description$1 = "Downloads and validates all document specified in a workspace";
1791
+ const helpText$g = "\nOptions\n -y, --yes Skips the first confirmation prompt.\n --workspace <name> The name of the workspace to use when downloading and validating all documents.\n --dataset <name> Override the dataset used. By default, this is derived from the given workspace.\n --file <filepath> Provide a path to either an .ndjson file or a tarball containing an .ndjson file.\n --format <pretty|ndjson|json> The output format used to print the found validation markers and report progress.\n --level <error|warning|info> The minimum level reported out. Defaults to warning.\n --max-custom-validation-concurrency <number> Specify how many custom validators can run concurrently. Defaults to 5.\n\nExamples\n # Validates all documents in a Sanity project with more than one workspace\n sanity documents validate --workspace default\n\n # Override the dataset specified in the workspace\n sanity documents validate --workspace default --dataset staging\n\n # Save the results of the report into a file\n sanity documents validate > report.txt\n\n # Report out info level validation markers too\n sanity documents validate --level info\n";
1792
+ const validateDocumentsCommand$1 = {
1792
1793
  name: "validate",
1793
1794
  group: "documents",
1794
1795
  signature: "",
1795
- description,
1796
- helpText: helpText$f,
1796
+ description: description$1,
1797
+ helpText: helpText$g,
1797
1798
  action: async (args, context) => {
1798
1799
  const mod = await Promise.resolve().then(function () {
1799
- return require('./validateAction-NIrqtyYJ.js');
1800
+ return require('./validateAction-shi462sq.js');
1800
1801
  });
1801
1802
  return mod.default(args, context);
1802
1803
  }
1803
1804
  };
1804
- const helpText$e = '\nNotes\n Changing the hostname or port number might require a new entry to the CORS-origins allow list.\n\nOptions\n --port <port> TCP port to start server on. [default: 3333]\n --host <host> The local network interface at which to listen. [default: "127.0.0.1"]\n\nExamples\n sanity dev --host=0.0.0.0\n sanity dev --port=1942\n';
1805
+ const helpText$f = '\nNotes\n Changing the hostname or port number might require a new entry to the CORS-origins allow list.\n\nOptions\n --port <port> TCP port to start server on. [default: 3333]\n --host <host> The local network interface at which to listen. [default: "127.0.0.1"]\n\nExamples\n sanity dev --host=0.0.0.0\n sanity dev --port=1942\n';
1805
1806
  const devCommand = {
1806
1807
  name: "dev",
1807
1808
  signature: "[--port <port>] [--host <host>]",
@@ -1810,7 +1811,7 @@ const devCommand = {
1810
1811
  const devAction = await getDevAction();
1811
1812
  return devAction(args, context);
1812
1813
  },
1813
- helpText: helpText$e
1814
+ helpText: helpText$f
1814
1815
  };
1815
1816
  async function getDevAction() {
1816
1817
  const mod = await Promise.resolve().then(function () {
@@ -1819,7 +1820,7 @@ async function getDevAction() {
1819
1820
  return mod.default;
1820
1821
  }
1821
1822
  const isInteractive = process.stdout.isTTY && process.env.TERM !== "dumb" && !("CI" in process.env);
1822
- const helpText$d = '\nNotes\n Changing the hostname or port number might require a new CORS-entry to be added.\n\nOptions\n --port <port> TCP port to start server on. [default: 3333]\n --host <host> The local network interface at which to listen. [default: "127.0.0.1"]\n\nExamples\n sanity start --host=0.0.0.0\n sanity start --port=1942\n sanity start some/build-output-dir\n';
1823
+ const helpText$e = '\nNotes\n Changing the hostname or port number might require a new CORS-entry to be added.\n\nOptions\n --port <port> TCP port to start server on. [default: 3333]\n --host <host> The local network interface at which to listen. [default: "127.0.0.1"]\n\nExamples\n sanity start --host=0.0.0.0\n sanity start --port=1942\n sanity start some/build-output-dir\n';
1823
1824
  const startCommand = {
1824
1825
  name: "start",
1825
1826
  signature: "[BUILD_OUTPUT_DIR] [--port <port>] [--host <host>]",
@@ -1864,7 +1865,7 @@ const startCommand = {
1864
1865
  }
1865
1866
  }
1866
1867
  },
1867
- helpText: helpText$d
1868
+ helpText: helpText$e
1868
1869
  };
1869
1870
  async function getPreviewAction$1() {
1870
1871
  const mod = await Promise.resolve().then(function () {
@@ -1872,6 +1873,21 @@ async function getPreviewAction$1() {
1872
1873
  });
1873
1874
  return mod.default;
1874
1875
  }
1876
+ const description = "Validates all schema types specified in a workspace.";
1877
+ const helpText$d = "\nOptions\n --workspace <name> The name of the workspace to use when validating all schema types.\n --format <pretty|ndjson|json> The output format used to print schema errors and warnings.\n --level <error|warning> The minimum level reported out. Defaults to warning.\n\nExamples\n # Validates all schema types in a Sanity project with more than one workspace\n sanity schema validate --workspace default\n\n # Save the results of the report into a file\n sanity schema validate > report.txt\n\n # Report out only errors\n sanity schema validate --level error\n";
1878
+ const validateDocumentsCommand = {
1879
+ name: "validate",
1880
+ group: "schema",
1881
+ signature: "",
1882
+ description,
1883
+ helpText: helpText$d,
1884
+ action: async (args, context) => {
1885
+ const mod = await Promise.resolve().then(function () {
1886
+ return require('./validateAction-4Jl_y_iB.js');
1887
+ });
1888
+ return mod.default(args, context);
1889
+ }
1890
+ };
1875
1891
  const helpText$c = '\nNotes\n Changing the hostname or port number might require a new entry to the CORS-origins allow list.\n\nOptions\n --port <port> TCP port to start server on. [default: 3333]\n --host <host> The local network interface at which to listen. [default: "127.0.0.1"]\n\nExamples\n sanity preview --host=0.0.0.0\n sanity preview --port=1942\n sanity preview some/build-output-dir\n';
1876
1892
  const previewCommand = {
1877
1893
  name: "preview",
@@ -2483,7 +2499,7 @@ const listGraphQLAPIsCommand = {
2483
2499
  description: "Lists all the GraphQL endpoints deployed for this project",
2484
2500
  action: async (args, context) => {
2485
2501
  const mod = await Promise.resolve().then(function () {
2486
- return require('./listApisAction-6lGkFZrU.js');
2502
+ return require('./listApisAction-IvKV4iAd.js');
2487
2503
  });
2488
2504
  return mod.default(args, context);
2489
2505
  },
@@ -2497,7 +2513,7 @@ const deployGraphQLAPICommand = {
2497
2513
  description: "Deploy a GraphQL API from the current Sanity schema",
2498
2514
  action: async (args, context) => {
2499
2515
  const mod = await Promise.resolve().then(function () {
2500
- return require('./deployApiAction-bRyJpGOS.js');
2516
+ return require('./deployApiAction-rVL67VYW.js');
2501
2517
  });
2502
2518
  return mod.default(args, context);
2503
2519
  },
@@ -2712,37 +2728,37 @@ const renameType = _ref4 => {
2712
2728
  migrationName,
2713
2729
  documentTypes
2714
2730
  } = _ref4;
2715
- return "import {defineMigration, at, set} from 'sanity/migrate'\n\nconst oldType = 'old'\nconst newType = 'new'\n\nexport default defineMigration({\n name: '".concat(migrationName, "',\n").concat(documentTypes.length > 0 ? " documentTypes: [".concat(documentTypes.map(t => JSON.stringify(t)).join(", "), "],\n") : "", "\n migrate: {\n object(object, path, context) {\n if (object._type === oldType) {\n return at('_type', set(newType))\n }\n }\n }\n})\n");
2731
+ return "import {defineMigration, at, set} from 'sanity/migrate'\n\nconst oldType = 'old'\nconst newType = 'new'\n\nexport default defineMigration({\n title: '".concat(migrationName, "',\n").concat(documentTypes.length > 0 ? " documentTypes: [".concat(documentTypes.map(t => JSON.stringify(t)).join(", "), "],\n") : "", "\n migrate: {\n object(object, path, context) {\n if (object._type === oldType) {\n return at('_type', set(newType))\n }\n }\n }\n})\n");
2716
2732
  };
2717
2733
  const stringToPTE = _ref5 => {
2718
2734
  let {
2719
2735
  migrationName,
2720
2736
  documentTypes
2721
2737
  } = _ref5;
2722
- return "import {pathsAreEqual, stringToPath} from 'sanity'\nimport {defineMigration, set} from 'sanity/migrate'\n\nconst targetPath = stringToPath('some.path')\n\nexport default defineMigration({\n name: '".concat(migrationName, "',\n").concat(documentTypes.length > 0 ? " documentTypes: [".concat(documentTypes.map(t => JSON.stringify(t)).join(", "), "],\n") : "", "\n migrate: {\n string(node, path, ctx) {\n if (pathsAreEqual(path, targetPath)) {\n return set([\n {\n style: 'normal',\n _type: 'block',\n children: [\n {\n _type: 'span',\n marks: [],\n text: node,\n },\n ],\n markDefs: [],\n },\n ])\n }\n },\n },\n})\n");
2738
+ return "import {pathsAreEqual, stringToPath} from 'sanity'\nimport {defineMigration, set} from 'sanity/migrate'\n\nconst targetPath = stringToPath('some.path')\n\nexport default defineMigration({\n title: '".concat(migrationName, "',\n").concat(documentTypes.length > 0 ? " documentTypes: [".concat(documentTypes.map(t => JSON.stringify(t)).join(", "), "],\n") : "", "\n migrate: {\n string(node, path, ctx) {\n if (pathsAreEqual(path, targetPath)) {\n return set([\n {\n style: 'normal',\n _type: 'block',\n children: [\n {\n _type: 'span',\n marks: [],\n text: node,\n },\n ],\n markDefs: [],\n },\n ])\n }\n },\n },\n})\n");
2723
2739
  };
2724
2740
  const minimalSimple = _ref6 => {
2725
2741
  let {
2726
2742
  migrationName,
2727
2743
  documentTypes
2728
2744
  } = _ref6;
2729
- return "import {defineMigration} from 'sanity/migrate'\n\nexport default defineMigration({\n name: '".concat(migrationName, "',\n").concat(documentTypes.length > 0 ? " documentTypes: [".concat(documentTypes.map(t => JSON.stringify(t)).join(", "), "],\n") : "", "\n migrate: {\n document(doc, context) {\n // this will be called for every document of the matching type\n // any patch returned will be applied to the document\n // you can also return mutations that touches other documents\n },\n node(node, path, context) {\n // this will be called for every node in every document of the matching type\n // any patch returned will be applied to the document\n // you can also return mutations that touches other documents\n },\n object(node, path, context) {\n // this will be called for every object node in every document of the matching type\n // any patch returned will be applied to the document\n // you can also return mutations that touches other documents\n },\n array(node, path, context) {\n // this will be called for every array node in every document of the matching type\n // any patch returned will be applied to the document\n // you can also return mutations that touches other documents\n },\n string(node, path, context) {\n // this will be called for every string node in every document of the matching type\n // any patch returned will be applied to the document\n // you can also return mutations that touches other documents\n },\n number(node, path, context) {\n // this will be called for every number node in every document of the matching type\n // any patch returned will be applied to the document\n // you can also return mutations that touches other documents\n },\n boolean(node, path, context) {\n // this will be called for every boolean node in every document of the matching type\n // any patch returned will be applied to the document\n // you can also return mutations that touches other documents\n },\n null(node, path, context) {\n // this will be called for every null node in every document of the matching type\n // any patch returned will be applied to the document\n // you can also return mutations that touches other documents\n },\n },\n})\n");
2745
+ return "import {defineMigration} from 'sanity/migrate'\n\nexport default defineMigration({\n title: '".concat(migrationName, "',\n").concat(documentTypes.length > 0 ? " documentTypes: [".concat(documentTypes.map(t => JSON.stringify(t)).join(", "), "],\n") : "", "\n migrate: {\n document(doc, context) {\n // this will be called for every document of the matching type\n // any patch returned will be applied to the document\n // you can also return mutations that touches other documents\n },\n node(node, path, context) {\n // this will be called for every node in every document of the matching type\n // any patch returned will be applied to the document\n // you can also return mutations that touches other documents\n },\n object(node, path, context) {\n // this will be called for every object node in every document of the matching type\n // any patch returned will be applied to the document\n // you can also return mutations that touches other documents\n },\n array(node, path, context) {\n // this will be called for every array node in every document of the matching type\n // any patch returned will be applied to the document\n // you can also return mutations that touches other documents\n },\n string(node, path, context) {\n // this will be called for every string node in every document of the matching type\n // any patch returned will be applied to the document\n // you can also return mutations that touches other documents\n },\n number(node, path, context) {\n // this will be called for every number node in every document of the matching type\n // any patch returned will be applied to the document\n // you can also return mutations that touches other documents\n },\n boolean(node, path, context) {\n // this will be called for every boolean node in every document of the matching type\n // any patch returned will be applied to the document\n // you can also return mutations that touches other documents\n },\n null(node, path, context) {\n // this will be called for every null node in every document of the matching type\n // any patch returned will be applied to the document\n // you can also return mutations that touches other documents\n },\n },\n})\n");
2730
2746
  };
2731
2747
  const minimalAdvanced = _ref7 => {
2732
2748
  let {
2733
2749
  migrationName,
2734
2750
  documentTypes
2735
2751
  } = _ref7;
2736
- return "import {defineMigration, patch, at, setIfMissing} from 'sanity/migrate'\n\n/**\n * this migration will set `Default title` on all documents that are missing a title\n * and make `true` the default value for the `enabled` field\n */\nexport default defineMigration({\n name: '".concat(migrationName, "',\n").concat(documentTypes.length > 0 ? " documentTypes: [".concat(documentTypes.map(t => JSON.stringify(t)).join(", "), "],\n") : "", "\n async *migrate(documents, context) {\n for await (const document of documents()) {\n yield patch(document._id, [\n at('title', setIfMissing('Default title')),\n at('enabled', setIfMissing(true)),\n ])\n }\n }\n})\n");
2752
+ return "import {defineMigration, patch, at, setIfMissing} from 'sanity/migrate'\n\n/**\n * this migration will set `Default title` on all documents that are missing a title\n * and make `true` the default value for the `enabled` field\n */\nexport default defineMigration({\n title: '".concat(migrationName, "',\n").concat(documentTypes.length > 0 ? " documentTypes: [".concat(documentTypes.map(t => JSON.stringify(t)).join(", "), "],\n") : "", "\n async *migrate(documents, context) {\n for await (const document of documents()) {\n yield patch(document._id, [\n at('title', setIfMissing('Default title')),\n at('enabled', setIfMissing(true)),\n ])\n }\n }\n})\n");
2737
2753
  };
2738
2754
  const renameField = _ref8 => {
2739
2755
  let {
2740
2756
  migrationName,
2741
2757
  documentTypes
2742
2758
  } = _ref8;
2743
- return "import {defineMigration, at, setIfMissing, unset} from 'sanity/migrate'\n\nconst from = 'oldFieldName'\nconst to = 'newFieldName'\n\nexport default defineMigration({\n name: '".concat(migrationName, "',\n").concat(documentTypes.length > 0 ? " documentTypes: [".concat(documentTypes.map(t => JSON.stringify(t)).join(", "), "],\n") : "", "\n migrate: {\n document(doc, path, context) {\n return [\n at(to, setIfMissing(doc[from]))\n at(from, unset())\n ]\n }\n }\n})\n");
2759
+ return "import {defineMigration, at, setIfMissing, unset} from 'sanity/migrate'\n\nconst from = 'oldFieldName'\nconst to = 'newFieldName'\n\nexport default defineMigration({\n title: '".concat(migrationName, "',\n").concat(documentTypes.length > 0 ? " documentTypes: [".concat(documentTypes.map(t => JSON.stringify(t)).join(", "), "],\n") : "", "\n migrate: {\n document(doc, context) {\n return [\n at(to, setIfMissing(doc[from])),\n at(from, unset())\n ]\n }\n }\n})\n");
2744
2760
  };
2745
- const helpText$2 = "\nCreate a new migration within your project\n";
2761
+ const helpText$2 = '\nCreate a new migration within your project\n\nExamples:\n # Create a new migration, you will be prompted to provide a type\n sanity migration create\n\n # Create a new migration, specifying the title\n sanity migration create "Rename field from location to address"\n';
2746
2762
  const TEMPLATES = [{
2747
2763
  name: "Minimalistic migration to get you started",
2748
2764
  template: minimalSimple
@@ -2759,10 +2775,10 @@ const TEMPLATES = [{
2759
2775
  name: "Advanced template using async iterators providing more fine grained control",
2760
2776
  template: minimalAdvanced
2761
2777
  }];
2762
- const createMigrationCommand$2 = {
2778
+ const createMigrationCommand$1 = {
2763
2779
  name: "create",
2764
2780
  group: "migration",
2765
- signature: "[NAME]",
2781
+ signature: "[TITLE]",
2766
2782
  helpText: helpText$2,
2767
2783
  description: "Create a new content migration within your project",
2768
2784
  action: async (args, context) => {
@@ -2772,15 +2788,15 @@ const createMigrationCommand$2 = {
2772
2788
  workDir,
2773
2789
  chalk
2774
2790
  } = context;
2775
- let name = "";
2776
- while (!name.trim()) {
2777
- name = await prompt.single({
2791
+ let [title] = args.argsWithoutOptions;
2792
+ while (!(title == null ? void 0 : title.trim())) {
2793
+ title = await prompt.single({
2778
2794
  type: "input",
2779
- suffix: " (e.g. rename field from location to address)",
2780
- message: "Name of migration"
2795
+ suffix: ' (e.g. "Rename field from location to address")',
2796
+ message: "Title of migration"
2781
2797
  });
2782
- if (!name.trim()) {
2783
- output.print(chalk.red("Name cannot be empty"));
2798
+ if (!title.trim()) {
2799
+ output.error(chalk.red("Name cannot be empty"));
2784
2800
  }
2785
2801
  }
2786
2802
  const types = await prompt.single({
@@ -2797,7 +2813,7 @@ const createMigrationCommand$2 = {
2797
2813
  value: definedTemplate.name
2798
2814
  }))
2799
2815
  });
2800
- const sluggedName = deburr__default.default(name.toLowerCase()).replace(/\s+/g, "-").replace(/[^a-z0-9-]/g, "");
2816
+ const sluggedName = deburr__default.default(title.toLowerCase()).replace(/\s+/g, "-").replace(/[^a-z0-9-]/g, "");
2801
2817
  const destDir = path__default.default.join(MIGRATIONS_DIRECTORY, sluggedName);
2802
2818
  if (node_fs.existsSync(destDir)) {
2803
2819
  if (!(await prompt.single({
@@ -2810,7 +2826,7 @@ const createMigrationCommand$2 = {
2810
2826
  }
2811
2827
  mkdirp__default.default.sync(destDir);
2812
2828
  const renderedTemplate = (templatesByName[template].template || minimalSimple)({
2813
- migrationName: name,
2829
+ migrationName: title,
2814
2830
  documentTypes: types.split(",").map(t => t.trim()).filter(Boolean)
2815
2831
  });
2816
2832
  const definitionFile = path__default.default.join(destDir, "index.ts");
@@ -2826,71 +2842,302 @@ const createMigrationCommand$2 = {
2826
2842
  output.print("\u{1F449} Learn more about schema and content migrations at ".concat(chalk.bold("https://www.sanity.io/docs/schema-and-content-migrations")));
2827
2843
  }
2828
2844
  };
2845
+ function resolveMigrationScript$1(workDir, migrationName) {
2846
+ return [migrationName, path__default.default.join(migrationName, "index")].flatMap(location => MIGRATION_SCRIPT_EXTENSIONS.map(ext => {
2847
+ const relativePath = path__default.default.join(MIGRATIONS_DIRECTORY, "".concat(location, ".").concat(ext));
2848
+ const absolutePath = path__default.default.resolve(workDir, relativePath);
2849
+ let mod;
2850
+ try {
2851
+ mod = require(absolutePath);
2852
+ } catch (err) {}
2853
+ return {
2854
+ relativePath,
2855
+ absolutePath,
2856
+ mod
2857
+ };
2858
+ }));
2859
+ }
2860
+ const helpText$1 = "";
2861
+ const createMigrationCommand = {
2862
+ name: "list",
2863
+ group: "migration",
2864
+ signature: "[NAME]",
2865
+ helpText: helpText$1,
2866
+ description: "List available migrations",
2867
+ action: async (args, context) => {
2868
+ const {
2869
+ workDir,
2870
+ output
2871
+ } = context;
2872
+ const migrations = await resolveMigrations(workDir);
2873
+ const table = new consoleTablePrinter.Table({
2874
+ title: "Found ".concat(migrations.length, " migrations in project"),
2875
+ columns: [{
2876
+ name: "id",
2877
+ title: "ID",
2878
+ alignment: "left"
2879
+ }, {
2880
+ name: "title",
2881
+ title: "Title",
2882
+ alignment: "left"
2883
+ }]
2884
+ });
2885
+ migrations.forEach(definedMigration => {
2886
+ table.addRow({
2887
+ id: definedMigration.dirname,
2888
+ title: definedMigration.migration.title
2889
+ });
2890
+ });
2891
+ table.printTable();
2892
+ output.print("\nRun `sanity migration run <ID>` to run a migration");
2893
+ }
2894
+ };
2895
+ async function resolveMigrations(workDir) {
2896
+ {
2897
+ node.register({
2898
+ target: "node".concat(process.version.slice(1))
2899
+ });
2900
+ }
2901
+ const directories = (await fs$3.readdir(path__default.default.join(workDir, MIGRATIONS_DIRECTORY), {
2902
+ withFileTypes: true
2903
+ })).filter(ent => ent.isDirectory());
2904
+ return directories.map(ent => {
2905
+ const candidates = resolveMigrationScript$1(workDir, ent.name);
2906
+ const found = candidates.find(candidate => {
2907
+ var _a;
2908
+ return (_a = candidate.mod) == null ? void 0 : _a.default;
2909
+ });
2910
+ if (!found) {
2911
+ return null;
2912
+ }
2913
+ return {
2914
+ dirname: ent.name,
2915
+ migration: found.mod.default
2916
+ };
2917
+ }).filter(Boolean);
2918
+ }
2919
+ const maxKeyLength = function () {
2920
+ let children = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
2921
+ let depth = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
2922
+ return Object.entries(children).map(_ref9 => {
2923
+ let [key, child] = _ref9;
2924
+ return Math.max(key.length + depth * 2, maxKeyLength(child.children, depth + 1));
2925
+ }).reduce((max, next) => next > max ? next : max, 0);
2926
+ };
2927
+ const formatTree = _ref10 => {
2928
+ let {
2929
+ node = {},
2930
+ paddingLength,
2931
+ indent = "",
2932
+ getNodes: getLeaves = _ref11 => {
2933
+ let {
2934
+ nodes
2935
+ } = _ref11;
2936
+ return nodes;
2937
+ },
2938
+ getMessage
2939
+ } = _ref10;
2940
+ const entries = Object.entries(node);
2941
+ return entries.map((_ref12, index) => {
2942
+ let [key, child] = _ref12;
2943
+ const isLast = index === entries.length - 1;
2944
+ const nextIndent = "".concat(indent).concat(isLast ? " " : "\u2502 ");
2945
+ const leaves = getLeaves(child);
2946
+ const nested = formatTree({
2947
+ node: child.children,
2948
+ paddingLength,
2949
+ indent: nextIndent,
2950
+ getNodes: getLeaves,
2951
+ getMessage
2952
+ });
2953
+ if (!(leaves == null ? void 0 : leaves.length)) {
2954
+ const current2 = "".concat(indent).concat(isLast ? "\u2514" : "\u251C", "\u2500 ").concat(key);
2955
+ return [current2, nested].filter(Boolean).join("\n");
2956
+ }
2957
+ const [first, ...rest] = leaves;
2958
+ const firstPadding = ".".repeat(paddingLength - indent.length - key.length);
2959
+ const elbow = isLast ? "\u2514" : "\u251C";
2960
+ const subsequentPadding = " ".repeat(paddingLength - indent.length + 2);
2961
+ const firstMessage = "".concat(indent).concat(elbow, "\u2500 ").concat(key, " ").concat(firstPadding, " ").concat(getMessage(first));
2962
+ const subsequentMessages = rest.map(marker => "".concat(nextIndent).concat(subsequentPadding, " ").concat(getMessage(marker))).join("\n");
2963
+ const current = [firstMessage, subsequentMessages].filter(Boolean).join("\n");
2964
+ return [current, nested].filter(Boolean).join("\n");
2965
+ }).join("\n");
2966
+ };
2967
+ function convertToTree(nodes) {
2968
+ const root = {};
2969
+ function addNode(node) {
2970
+ let tree = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : root;
2971
+ if (!node.path.length) {
2972
+ if (!tree.nodes) tree.nodes = [];
2973
+ tree.nodes.push(node);
2974
+ return;
2975
+ }
2976
+ const [current, ...rest] = node.path;
2977
+ const key = sanity.pathToString([current]);
2978
+ if (!tree.children) tree.children = {};
2979
+ if (!(key in tree.children)) tree.children[key] = {};
2980
+ addNode({
2981
+ ...node,
2982
+ path: rest
2983
+ }, tree.children[key]);
2984
+ }
2985
+ for (const node of nodes) addNode(node);
2986
+ return root;
2987
+ }
2988
+ const isTty = tty.isatty(1);
2989
+ function prettyFormat(_ref13) {
2990
+ let {
2991
+ chalk,
2992
+ subject,
2993
+ migration,
2994
+ indentSize = 0
2995
+ } = _ref13;
2996
+ return (Array.isArray(subject) ? subject : [subject]).map(subjectEntry => {
2997
+ if (subjectEntry.type === "transaction") {
2998
+ return [[badge("transaction", "info", chalk), typeof subjectEntry.id === "undefined" ? null : chalk.underline(subjectEntry.id)].filter(Boolean).join(" "), indent(prettyFormat({
2999
+ chalk,
3000
+ subject: subjectEntry.mutations,
3001
+ migration,
3002
+ indentSize
3003
+ }))].join("\n\n");
3004
+ }
3005
+ return prettyFormatMutation({
3006
+ chalk,
3007
+ subject: subjectEntry,
3008
+ migration,
3009
+ indentSize
3010
+ });
3011
+ }).join("\n\n");
3012
+ }
2829
3013
  function encodeItemRef(ref) {
2830
3014
  return typeof ref === "number" ? ref : ref._key;
2831
3015
  }
2832
- function formatTransaction(chalk, mutation) {
2833
- var _a;
2834
- if (mutation.type === "transaction") {
2835
- return mutation.mutations.flatMap(m => formatTransaction(chalk, m)).join("\n");
2836
- }
2837
- if (mutation.type === "create" || mutation.type === "createIfNotExists" || mutation.type === "createOrReplace") {
2838
- return [chalk.bold(mutation.type), ": ", JSON.stringify(mutation.document)].join("");
3016
+ function badgeStyle(chalk, variant) {
3017
+ const styles = {
3018
+ info: chalk.bgWhite.black,
3019
+ incremental: chalk.bgGreen.black.bold,
3020
+ maybeDestructive: chalk.bgYellow.black.bold,
3021
+ destructive: chalk.bgRed.black.bold
3022
+ };
3023
+ return styles[variant];
3024
+ }
3025
+ function badge(label, variant, chalk) {
3026
+ if (!isTty) {
3027
+ return "[".concat(label, "]");
2839
3028
  }
2840
- if (mutation.type === "delete") {
2841
- return ["".concat(chalk.red.bold("delete"), " "), mutation.id].join(": ");
3029
+ return badgeStyle(chalk, variant)(" ".concat(label, " "));
3030
+ }
3031
+ const mutationImpact = {
3032
+ create: "incremental",
3033
+ createIfNotExists: "incremental",
3034
+ createOrReplace: "maybeDestructive",
3035
+ delete: "destructive",
3036
+ patch: "maybeDestructive"
3037
+ };
3038
+ function documentId(mutation) {
3039
+ if ("id" in mutation) {
3040
+ return mutation.id;
2842
3041
  }
2843
- if (mutation.type === "patch") {
2844
- const ifRevision = (_a = mutation.options) == null ? void 0 : _a.ifRevision;
2845
- return [chalk.blue.bold("patch"), "", "(".concat(mutation.id, ")"), ifRevision ? " (if revision==".concat(ifRevision, ")") : "", ":\n", mutation.patches.map(nodePatch => " ".concat(formatPatchMutation(chalk, nodePatch))).join("\n")].join("");
3042
+ if ("document" in mutation) {
3043
+ return mutation.document._id;
2846
3044
  }
2847
- throw new Error("Invalid mutation type: ".concat(mutation.type));
3045
+ return void 0;
3046
+ }
3047
+ const listFormatter = new Intl.ListFormat("en-US", {
3048
+ type: "disjunction"
3049
+ });
3050
+ function mutationHeader(chalk, mutation, migration) {
3051
+ var _a;
3052
+ const mutationType = badge(mutation.type, mutationImpact[mutation.type], chalk);
3053
+ const documentType = "document" in mutation || migration.documentTypes ? badge("document" in mutation ? mutation.document._type : listFormatter.format((_a = migration.documentTypes) != null ? _a : []), "info", chalk) : null;
3054
+ return [mutationType, documentType, chalk.underline(documentId(mutation))].filter(Boolean).join(" ");
3055
+ }
3056
+ function prettyFormatMutation(_ref14) {
3057
+ let {
3058
+ chalk,
3059
+ subject,
3060
+ migration,
3061
+ indentSize = 0
3062
+ } = _ref14;
3063
+ var _a;
3064
+ const lock = "options" in subject ? chalk.cyan("(if revision==".concat((_a = subject.options) == null ? void 0 : _a.ifRevision, ")")) : "";
3065
+ const header = [mutationHeader(chalk, subject, migration), lock].join(" ");
3066
+ const padding = " ".repeat(indentSize);
3067
+ if (subject.type === "create" || subject.type === "createIfNotExists" || subject.type === "createOrReplace") {
3068
+ return [header, "\n", indent(JSON.stringify(subject.document, null, 2), indentSize)].join("");
3069
+ }
3070
+ if (subject.type === "patch") {
3071
+ const tree = convertToTree(subject.patches.flat());
3072
+ const paddingLength = Math.max(maxKeyLength(tree.children) + 2, 30);
3073
+ return [header, "\n", formatTree({
3074
+ node: tree.children,
3075
+ paddingLength,
3076
+ indent: padding,
3077
+ getMessage: patch => formatPatchMutation(chalk, patch)
3078
+ })].join("");
3079
+ }
3080
+ return header;
2848
3081
  }
2849
3082
  function formatPatchMutation(chalk, patch) {
2850
3083
  const {
2851
3084
  op
2852
3085
  } = patch;
2853
- const path = chalk.grey(PathUtils.toString(patch.path));
2854
3086
  const formattedType = chalk.bold(op.type);
2855
3087
  if (op.type === "unset") {
2856
- return [path, "".concat(formattedType, "()")].join(": ");
3088
+ return "".concat(chalk.red(formattedType), "()");
2857
3089
  }
2858
3090
  if (op.type === "diffMatchPatch") {
2859
- return [path, "".concat(formattedType, "(").concat(op.value, ")")].join(": ");
3091
+ return "".concat(chalk.yellow(formattedType), "(").concat(op.value, ")");
2860
3092
  }
2861
3093
  if (op.type === "inc" || op.type === "dec") {
2862
- return [path, "".concat(formattedType, "(").concat(op.amount, ")")].join(": ");
3094
+ return "".concat(chalk.yellow(formattedType), "(").concat(op.amount, ")");
2863
3095
  }
2864
- if (op.type === "set" || op.type === "setIfMissing") {
2865
- return [path, "".concat(formattedType, "(").concat(JSON.stringify(op.value), ")")].join(": ");
3096
+ if (op.type === "set") {
3097
+ return "".concat(chalk.yellow(formattedType), "(").concat(JSON.stringify(op.value), ")");
3098
+ }
3099
+ if (op.type === "setIfMissing") {
3100
+ return "".concat(chalk.green(formattedType), "(").concat(JSON.stringify(op.value), ")");
2866
3101
  }
2867
3102
  if (op.type === "assign") {
2868
- return [path, "".concat(formattedType, "(").concat(JSON.stringify(op.value), ")")].join(": ");
3103
+ return "".concat(chalk.yellow(formattedType), "(").concat(JSON.stringify(op.value), ")");
2869
3104
  }
2870
3105
  if (op.type === "unassign") {
2871
- return [path, "".concat(formattedType, "(").concat(JSON.stringify(op.keys), ")")].join(": ");
3106
+ return "".concat(chalk.red(formattedType), "(").concat(JSON.stringify(op.keys), ")");
3107
+ }
3108
+ if (op.type === "insert") {
3109
+ return "".concat(chalk.green(formattedType), "(").concat(op.position, ", ").concat(encodeItemRef(op.referenceItem), ", ").concat(JSON.stringify(op.items), ")");
2872
3110
  }
2873
- if (op.type === "insert" || op.type === "upsert") {
2874
- return [path, "".concat(formattedType, "(").concat(op.position, ", ").concat(encodeItemRef(op.referenceItem), ", ").concat(JSON.stringify(op.items), ")")].join(": ");
3111
+ if (op.type === "upsert") {
3112
+ return "".concat(chalk.yellow(formattedType), "(").concat(op.position, ", ").concat(encodeItemRef(op.referenceItem), ", ").concat(JSON.stringify(op.items), ")");
2875
3113
  }
2876
3114
  if (op.type === "replace") {
2877
- return [path, "".concat(formattedType, "(").concat(encodeItemRef(op.referenceItem), ", ").concat(JSON.stringify(op.items), ")")].join(": ");
3115
+ return "".concat(chalk.yellow(formattedType), "(").concat(encodeItemRef(op.referenceItem), ", ").concat(JSON.stringify(op.items), ")");
2878
3116
  }
2879
3117
  if (op.type === "truncate") {
2880
- return [path, "".concat(formattedType, "(").concat(op.startIndex, ", ").concat(op.endIndex)].join(": ");
3118
+ return "".concat(chalk.red(formattedType), "(").concat(op.startIndex, ", ").concat(op.endIndex, ")");
2881
3119
  }
2882
3120
  throw new Error("Invalid operation type: ".concat(op.type));
2883
3121
  }
2884
- const helpText$1 = "\nOptions\n --dry <boolean> Whether or not to dry run the migration. Default to true, to actually run the migration, pass --no-dry\n --from-export <export.tar.gz> Use a local dataset export as source for migration instead of calling the Sanity API. Note: this is only supported for dry runs.\n --concurrency <concurrent> How many mutation requests to run in parallel. Must be between 1 and ".concat(migrate.MAX_MUTATION_CONCURRENCY, ". Default: ").concat(migrate.DEFAULT_MUTATION_CONCURRENCY, ".\n --no-progress Don't output progress. Useful if you want debug your migration script and see the output of console.log() statements.\n --dataset <dataset> Dataset to migrate. Defaults to the dataset configured in your Sanity CLI config.\n --projectId <project id> Project ID of the dataset to migrate. Defaults to the projectId configured in your Sanity CLI config.\n --no-confirm Skip the confirmation prompt before running the migration. Make sure you know what you're doing before using this flag.\n\n\nExamples\n # dry run the migration\n sanity migration run <name>\n\n # execute the migration against a dataset\n sanity migration run <name> --no-dry --projectId xyz --dataset staging\n\n # run the migration using the dataset export as the source\n sanity migration run <name> --dry false --from-export=production.tar.gz --projectId xyz --dataset staging\n");
3122
+ function indent(subject) {
3123
+ let size = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;
3124
+ const padding = " ".repeat(size);
3125
+ return subject.split("\n").map(line => padding + line).join("\n");
3126
+ }
3127
+ const helpText = "\nOptions\n --dry <boolean> Whether or not to dry run the migration. Default to true, to actually run the migration, pass --no-dry\n --concurrency <concurrent> How many mutation requests to run in parallel. Must be between 1 and ".concat(migrate.MAX_MUTATION_CONCURRENCY, ". Default: ").concat(migrate.DEFAULT_MUTATION_CONCURRENCY, ".\n --no-progress Don't output progress. Useful if you want debug your migration script and see the output of console.log() statements.\n --dataset <dataset> Dataset to migrate. Defaults to the dataset configured in your Sanity CLI config.\n --projectId <project id> Project ID of the dataset to migrate. Defaults to the projectId configured in your Sanity CLI config.\n --no-confirm Skip the confirmation prompt before running the migration. Make sure you know what you're doing before using this flag.\n --from-export <export.tar.gz> Use a local dataset export as source for migration instead of calling the Sanity API. Note: this is only supported for dry runs.\n\n\nExamples\n # dry run the migration\n sanity migration run <id>\n\n # execute the migration against a dataset\n sanity migration run <id> --no-dry --projectId xyz --dataset staging\n\n # run the migration using the dataset export as the source\n sanity migration run <id> --dry false --from-export=production.tar.gz --projectId xyz --dataset staging\n");
2885
3128
  const tryExtensions = ["mjs", "js", "ts", "cjs"];
2886
- function resolveMigrationScript$1(workDir, migrationName) {
2887
- return [migrationName, path__default.default.join(migrationName, "index")].flatMap(location => tryExtensions.map(ext => {
3129
+ function resolveMigrationScript(workDir, migrationId) {
3130
+ return [migrationId, path__default.default.join(migrationId, "index")].flatMap(location => tryExtensions.map(ext => {
2888
3131
  const relativePath = path__default.default.join("migrations", "".concat(location, ".").concat(ext));
2889
3132
  const absolutePath = path__default.default.resolve(workDir, relativePath);
2890
3133
  let mod;
2891
3134
  try {
2892
3135
  mod = require(absolutePath);
2893
- } catch (err) {}
3136
+ } catch (err) {
3137
+ if (err.code !== "MODULE_NOT_FOUND") {
3138
+ throw new Error("Error: ".concat(err.message, '"'));
3139
+ }
3140
+ }
2894
3141
  return {
2895
3142
  relativePath,
2896
3143
  absolutePath,
@@ -2898,11 +3145,11 @@ function resolveMigrationScript$1(workDir, migrationName) {
2898
3145
  };
2899
3146
  }));
2900
3147
  }
2901
- const createMigrationCommand$1 = {
3148
+ const runMigrationCommand = {
2902
3149
  name: "run",
2903
3150
  group: "migration",
2904
- signature: "[NAME] [MIGRATION NAME]",
2905
- helpText: helpText$1,
3151
+ signature: "ID",
3152
+ helpText,
2906
3153
  description: "Run a migration against a dataset",
2907
3154
  action: async (args, context) => {
2908
3155
  const {
@@ -2912,29 +3159,51 @@ const createMigrationCommand$1 = {
2912
3159
  chalk,
2913
3160
  workDir
2914
3161
  } = context;
2915
- const [migrationName] = args.argsWithoutOptions;
3162
+ const [id] = args.argsWithoutOptions;
2916
3163
  const [fromExport, dry, showProgress, dataset, projectId, shouldConfirm] = [args.extOptions["from-export"], args.extOptions.dry !== false, args.extOptions.progress !== false, args.extOptions.dataset, args.extOptions["project-id"], args.extOptions.confirm !== false];
2917
3164
  if (dataset && !projectId || projectId && !dataset) {
2918
3165
  throw new Error("If either --dataset or --projectId is provided, both must be provided");
2919
3166
  }
2920
- if (!migrationName) {
2921
- throw new Error("MIGRATION NAME must be provided. `sanity migration run <name>`");
3167
+ if (!id) {
3168
+ output.error(chalk.red("Error: Migration ID must be provided"));
3169
+ const migrations = await resolveMigrations(workDir);
3170
+ const table = new consoleTablePrinter.Table({
3171
+ title: "Migrations found in project",
3172
+ columns: [{
3173
+ name: "id",
3174
+ title: "ID",
3175
+ alignment: "left"
3176
+ }, {
3177
+ name: "title",
3178
+ title: "Title",
3179
+ alignment: "left"
3180
+ }]
3181
+ });
3182
+ migrations.forEach(definedMigration => {
3183
+ table.addRow({
3184
+ id: definedMigration.dirname,
3185
+ title: definedMigration.migration.title
3186
+ });
3187
+ });
3188
+ table.printTable();
3189
+ output.print("\nRun `sanity migration run <ID>` to run a migration");
3190
+ return;
2922
3191
  }
2923
3192
  {
2924
3193
  node.register({
2925
3194
  target: "node".concat(process.version.slice(1))
2926
3195
  });
2927
3196
  }
2928
- const candidates = resolveMigrationScript$1(workDir, migrationName);
3197
+ const candidates = resolveMigrationScript(workDir, id);
2929
3198
  const resolvedScripts = candidates.filter(candidate => {
2930
3199
  var _a;
2931
3200
  return (_a = candidate.mod) == null ? void 0 : _a.default;
2932
3201
  });
2933
3202
  if (resolvedScripts.length > 1) {
2934
- throw new Error('Found multiple migrations for "'.concat(migrationName, '" in current directory ').concat(candidates.map(candidate => candidate.relativePath).join(", ")));
3203
+ throw new Error('Found multiple migrations for "'.concat(id, '" in current directory ').concat(candidates.map(candidate => candidate.relativePath).join(", ")));
2935
3204
  }
2936
3205
  if (resolvedScripts.length === 0) {
2937
- throw new Error('No migration found for "'.concat(migrationName, '" in current directory. Make sure that the migration file exists and exports a valid migration as its default export.\n\n Tried the following files:\n -').concat(candidates.map(candidate => candidate.relativePath).join("\n - ")));
3206
+ throw new Error('No migration found for "'.concat(id, '" in current directory. Make sure that the migration file exists and exports a valid migration as its default export.\n\n Tried the following files:\n -').concat(candidates.map(candidate => candidate.relativePath).join("\n - ")));
2938
3207
  }
2939
3208
  const script = resolvedScripts[0];
2940
3209
  const mod = script.mod;
@@ -2966,134 +3235,86 @@ const createMigrationCommand$1 = {
2966
3235
  apiVersion: "v2024-01-29"
2967
3236
  };
2968
3237
  if (dry) {
2969
- const spinner = output.spinner('Running migration "'.concat(migrationName, '" in dry mode')).start();
2970
- if (fromExport) {
2971
- await migrate.runFromArchive(migration, fromExport, {
2972
- api: apiConfig,
2973
- concurrency,
2974
- onProgress: createProgress(spinner)
2975
- });
2976
- return;
2977
- }
2978
- migrate.dryRun({
2979
- api: apiConfig
2980
- }, migration);
2981
- spinner.stop();
2982
- } else {
2983
- const response = shouldConfirm && (await prompt.single({
2984
- message: "This migration will run on the ".concat(chalk.yellow(chalk.bold(apiConfig.dataset)), " dataset in ").concat(chalk.yellow(chalk.bold(apiConfig.projectId)), " project. Are you sure?"),
2985
- type: "confirm"
2986
- }));
2987
- if (response === false) {
2988
- debug("User aborted migration");
2989
- return;
2990
- }
2991
- const spinner = output.spinner('Running migration "'.concat(migrationName, '"')).start();
2992
- await migrate.run({
2993
- api: apiConfig,
2994
- concurrency,
2995
- onProgress: createProgress(spinner)
2996
- }, migration);
2997
- spinner.stop();
2998
- }
2999
- function createProgress(spinner) {
3238
+ dryRunHandler();
3239
+ return;
3240
+ }
3241
+ const response = shouldConfirm && (await prompt.single({
3242
+ message: "This migration will run on the ".concat(chalk.yellow(chalk.bold(apiConfig.dataset)), " dataset in ").concat(chalk.yellow(chalk.bold(apiConfig.projectId)), " project. Are you sure?"),
3243
+ type: "confirm"
3244
+ }));
3245
+ if (response === false) {
3246
+ debug("User aborted migration");
3247
+ return;
3248
+ }
3249
+ const spinner = output.spinner('Running migration "'.concat(id, '"')).start();
3250
+ await migrate.run({
3251
+ api: apiConfig,
3252
+ concurrency,
3253
+ onProgress: createProgress(spinner)
3254
+ }, migration);
3255
+ spinner.stop();
3256
+ function createProgress(progressSpinner) {
3000
3257
  return function onProgress(progress) {
3001
3258
  if (!showProgress) {
3002
- spinner.stop();
3259
+ progressSpinner.stop();
3003
3260
  return;
3004
3261
  }
3005
3262
  if (progress.done) {
3006
- spinner.text = 'Migration "'.concat(migrationName, '" completed.\n\n Project id: ').concat(chalk.bold(projectId), "\n Dataset: ").concat(chalk.bold(dataset), "\n\n ").concat(progress.documents, " documents processed.\n ").concat(progress.mutations, " mutations generated.\n ").concat(chalk.green(progress.completedTransactions.length), " transactions committed.");
3007
- spinner.stopAndPersist({
3263
+ progressSpinner.text = 'Migration "'.concat(id, '" completed.\n\n Project id: ').concat(chalk.bold(apiConfig.projectId), "\n Dataset: ").concat(chalk.bold(apiConfig.dataset), "\n\n ").concat(progress.documents, " documents processed.\n ").concat(progress.mutations, " mutations generated.\n ").concat(chalk.green(progress.completedTransactions.length), " transactions committed.");
3264
+ progressSpinner.stopAndPersist({
3008
3265
  symbol: chalk.green("\u2714")
3009
3266
  });
3010
3267
  return;
3011
3268
  }
3012
3269
  [null, ...progress.currentTransactions].forEach(transaction => {
3013
3270
  var _a;
3014
- spinner.text = 'Running migration "'.concat(migrationName, '"\u2026\n\n Project id: ').concat(chalk.bold(projectId), "\n Dataset: ").concat(chalk.bold(dataset), "\n Document type: ").concat(chalk.bold((_a = migration.documentTypes) == null ? void 0 : _a.join(",")), "\n\n ").concat(progress.documents, " documents processed\u2026\n ").concat(progress.mutations, " mutations generated\u2026\n ").concat(chalk.blue(progress.pending), " requests pending\u2026\n ").concat(chalk.green(progress.completedTransactions.length), " transactions committed.\n\n ").concat(transaction && !progress.done ? "\xBB ".concat(chalk.grey(formatTransaction(chalk, transaction))) : "");
3271
+ progressSpinner.text = 'Running migration "'.concat(id, '" ').concat(dry ? "in dry mode..." : "...", "\n\n Project id: ").concat(chalk.bold(apiConfig.projectId), "\n Dataset: ").concat(chalk.bold(apiConfig.dataset), "\n Document type: ").concat(chalk.bold((_a = migration.documentTypes) == null ? void 0 : _a.join(",")), "\n\n ").concat(progress.documents, " documents processed\u2026\n ").concat(progress.mutations, " mutations generated\u2026\n ").concat(chalk.blue(progress.pending), " requests pending\u2026\n ").concat(chalk.green(progress.completedTransactions.length), " transactions committed.\n\n ").concat(transaction && !progress.done ? "\xBB ".concat(prettyFormat({
3272
+ chalk,
3273
+ subject: transaction,
3274
+ migration,
3275
+ indentSize: 2
3276
+ })) : "");
3015
3277
  });
3016
3278
  };
3017
3279
  }
3018
- }
3019
- };
3020
- function resolveMigrationScript(workDir, migrationName) {
3021
- return [migrationName, path__default.default.join(migrationName, "index")].flatMap(location => MIGRATION_SCRIPT_EXTENSIONS.map(ext => {
3022
- const relativePath = path__default.default.join(MIGRATIONS_DIRECTORY, "".concat(location, ".").concat(ext));
3023
- const absolutePath = path__default.default.resolve(workDir, relativePath);
3024
- let mod;
3025
- try {
3026
- mod = require(absolutePath);
3027
- } catch (err) {}
3028
- return {
3029
- relativePath,
3030
- absolutePath,
3031
- mod
3032
- };
3033
- }));
3034
- }
3035
- const helpText = "";
3036
- const createMigrationCommand = {
3037
- name: "list",
3038
- group: "migration",
3039
- signature: "[NAME]",
3040
- helpText,
3041
- description: "List available migrations",
3042
- action: async (args, context) => {
3043
- const {
3044
- output,
3045
- workDir
3046
- } = context;
3047
- {
3048
- node.register({
3049
- target: "node".concat(process.version.slice(1))
3050
- });
3051
- }
3052
- const directories = (await fs$3.readdir(path__default.default.join(workDir, MIGRATIONS_DIRECTORY), {
3053
- withFileTypes: true
3054
- })).filter(ent => ent.isDirectory());
3055
- const migrationModules = directories.map(ent => {
3056
- const candidates = resolveMigrationScript(workDir, ent.name);
3057
- const found = candidates.find(candidate => {
3058
- var _a;
3059
- return (_a = candidate.mod) == null ? void 0 : _a.default;
3060
- });
3061
- if (!found) {
3062
- return null;
3280
+ async function dryRunHandler() {
3281
+ if (fromExport) {
3282
+ const dryRunSpinner = output.spinner('Running migration "'.concat(id, '" in dry mode')).start();
3283
+ await migrate.runFromArchive(migration, fromExport, {
3284
+ api: apiConfig,
3285
+ concurrency,
3286
+ onProgress: createProgress(dryRunSpinner)
3287
+ });
3288
+ dryRunSpinner.stop();
3289
+ } else {
3290
+ output.print('Running migration "'.concat(id, '" in dry mode'));
3291
+ output.print();
3292
+ output.print("Project id: ".concat(chalk.bold(apiConfig.projectId)));
3293
+ output.print("Dataset: ".concat(chalk.bold(apiConfig.dataset)));
3294
+ for await (const mutation of migrate.dryRun({
3295
+ api: apiConfig
3296
+ }, migration)) {
3297
+ if (!mutation) continue;
3298
+ output.print();
3299
+ output.print(prettyFormat({
3300
+ chalk,
3301
+ subject: mutation,
3302
+ migration
3303
+ }));
3304
+ }
3063
3305
  }
3064
- return {
3065
- dirname: ent.name,
3066
- migration: found.mod.default
3067
- };
3068
- }).filter(Boolean);
3069
- const table = new consoleTablePrinter.Table({
3070
- title: "Found ".concat(migrationModules.length, " migrations in project"),
3071
- columns: [{
3072
- name: "id",
3073
- title: "ID",
3074
- alignment: "left"
3075
- }, {
3076
- name: "name",
3077
- title: "Name",
3078
- alignment: "left"
3079
- }]
3080
- });
3081
- migrationModules.forEach(definedMigration => {
3082
- table.addRow({
3083
- id: definedMigration.dirname,
3084
- name: definedMigration.migration.name
3085
- });
3086
- });
3087
- table.printTable();
3088
- output.print('\nRun "sanity migration run <MIGRATION ID>" to run a migration');
3306
+ }
3089
3307
  }
3090
3308
  };
3091
- const commands = [buildCommand, checkCommand, configCheckCommand, datasetGroup, deployCommand, undeployCommand, listDatasetsCommand, createDatasetCommand, datasetVisibilityCommand, exportDatasetCommand, importDatasetCommand, deleteDatasetCommand, copyDatasetCommand, aliasCommand, corsGroup, listCorsOriginsCommand, addCorsOriginCommand, deleteCorsOriginCommand, usersGroup, inviteUserCommand, listUsersCommand, hookGroup, listHooksCommand, createHookCommand, migrationGroup, createMigrationCommand$2, createMigrationCommand$1, createMigrationCommand, deleteHookCommand, listHookLogsCommand, printHookAttemptCommand, documentsGroup, getDocumentsCommand, queryDocumentsCommand, deleteDocumentsCommand, createDocumentsCommand, validateDocumentsCommand, graphqlGroup, listGraphQLAPIsCommand, deployGraphQLAPICommand, deleteGraphQLAPICommand, devCommand, startCommand, previewCommand, uninstallCommand, execCommand];
3309
+ const commands = [buildCommand, checkCommand, configCheckCommand, datasetGroup, deployCommand, undeployCommand, listDatasetsCommand, createDatasetCommand, datasetVisibilityCommand, exportDatasetCommand, importDatasetCommand, deleteDatasetCommand, copyDatasetCommand, aliasCommand, corsGroup, listCorsOriginsCommand, addCorsOriginCommand, deleteCorsOriginCommand, usersGroup, inviteUserCommand, listUsersCommand, hookGroup, listHooksCommand, createHookCommand, migrationGroup, createMigrationCommand$1, runMigrationCommand, createMigrationCommand, deleteHookCommand, listHookLogsCommand, printHookAttemptCommand, documentsGroup, getDocumentsCommand, queryDocumentsCommand, deleteDocumentsCommand, createDocumentsCommand, validateDocumentsCommand$1, graphqlGroup, listGraphQLAPIsCommand, deployGraphQLAPICommand, deleteGraphQLAPICommand, devCommand, startCommand, validateDocumentsCommand, previewCommand, uninstallCommand, execCommand];
3092
3310
  const cliProjectCommands = {
3093
3311
  requiredCliVersionRange: "^3.0.0",
3094
3312
  commands
3095
3313
  };
3096
3314
  exports.cliProjectCommands = cliProjectCommands;
3315
+ exports.convertToTree = convertToTree;
3097
3316
  exports.debug = debug;
3317
+ exports.formatTree = formatTree;
3098
3318
  exports.getClientUrl = getClientUrl;
3099
- //# sourceMappingURL=_internal-2CJ5wSKF.js.map
3319
+ exports.maxKeyLength = maxKeyLength;
3320
+ //# sourceMappingURL=_internal-6Pl2wJGj.js.map