storyblok 4.26.2 → 4.27.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.
package/dist/index.mjs CHANGED
@@ -13,7 +13,7 @@ import { exec, spawn } from "node:child_process";
13
13
  import { readPackageUp } from "read-package-up";
14
14
  import fs, { access, appendFile, constants, mkdir, readFile, readdir, stat, unlink, writeFile } from "node:fs/promises";
15
15
  import filenamify from "filenamify";
16
- import { createManagementApiClient, normalizeAssetUrl } from "@storyblok/management-api-client";
16
+ import { ClientError, createManagementApiClient, normalizeAssetUrl } from "@storyblok/management-api-client";
17
17
  import { confirm, input, password, select } from "@inquirer/prompts";
18
18
  import { promisify } from "node:util";
19
19
  import { minimatch } from "minimatch";
@@ -27,7 +27,7 @@ import open from "open";
27
27
  import { Octokit } from "octokit";
28
28
  import { pipeline as pipeline$1 } from "node:stream/promises";
29
29
  import { Buffer } from "node:buffer";
30
- import { ClientError, createApiClient } from "@storyblok/api-client";
30
+ import { ClientError as ClientError$1, createApiClient } from "@storyblok/api-client";
31
31
  import { compile as compile$1 } from "json-p3";
32
32
  import * as officialFieldPlugins from "@storyblok/schema/field-plugins";
33
33
  import { createTwoFilesPatch } from "diff";
@@ -746,7 +746,8 @@ const API_ACTIONS = {
746
746
  delete_datasource_entry: "Failed to delete datasource entry",
747
747
  create_space: "Failed to create space",
748
748
  pull_spaces: "Failed to pull spaces",
749
- fetch_blueprints: "Failed to fetch blueprints from GitHub"
749
+ fetch_blueprints: "Failed to fetch blueprints from GitHub",
750
+ search_strata: "Failed to search with Strata"
750
751
  };
751
752
  const API_ERRORS = {
752
753
  unauthorized: "The user is not authorized to access the API",
@@ -897,10 +898,15 @@ var CommandError = class extends Error {
897
898
  var Logger = class {
898
899
  transports = [];
899
900
  context = {};
901
+ hasReportedTransportError = false;
900
902
  constructor(options) {
901
903
  if (options?.transports) this.transports = options.transports;
902
904
  if (options?.context) this.context = options.context;
903
905
  }
906
+ setTransports(transports) {
907
+ this.transports = transports;
908
+ this.hasReportedTransportError = false;
909
+ }
904
910
  log(level, message, context) {
905
911
  const timestamp = /* @__PURE__ */ new Date();
906
912
  const mergedContext = context ? {
@@ -913,7 +919,19 @@ var Logger = class {
913
919
  message,
914
920
  context: Object.keys(mergedContext).length ? mergedContext : void 0
915
921
  };
916
- for (const transport of this.transports) transport.log(record);
922
+ for (const transport of this.transports) try {
923
+ transport.log(record);
924
+ } catch (error) {
925
+ this.reportTransportError(error);
926
+ }
927
+ }
928
+ reportTransportError(error) {
929
+ if (this.hasReportedTransportError) return;
930
+ this.hasReportedTransportError = true;
931
+ try {
932
+ const reason = error instanceof Error ? error.message : String(error);
933
+ process.stderr.write(`Logging failed, some log entries may be missing: ${reason}\n`);
934
+ } catch {}
917
935
  }
918
936
  error(message, context) {
919
937
  this.log("error", message, context);
@@ -934,7 +952,7 @@ function getLogger(options) {
934
952
  return loggerInstance;
935
953
  }
936
954
  function setLoggerTransports(transports) {
937
- if (loggerInstance) loggerInstance.transports = transports;
955
+ if (loggerInstance) loggerInstance.setTransports(transports);
938
956
  }
939
957
  //#endregion
940
958
  //#region src/utils/format.ts
@@ -1072,6 +1090,8 @@ var UI = class {
1072
1090
  console;
1073
1091
  enabled;
1074
1092
  multiBar;
1093
+ /** Whether a bar was drawn since the last stop: stopping an empty MultiBar still writes. */
1094
+ hasBars = false;
1075
1095
  constructor({ enabled }) {
1076
1096
  this.enabled = enabled;
1077
1097
  this.console = null;
@@ -1101,7 +1121,6 @@ var UI = class {
1101
1121
  if (subtitle) this.console?.log(`${chalk.bgHex(color).bold(` ${capitalize(message)} `)} ${subtitle}`);
1102
1122
  else this.console?.log(chalk.bgHex(color).bold(` ${capitalize(message)} `));
1103
1123
  this.br();
1104
- this.br();
1105
1124
  }
1106
1125
  br() {
1107
1126
  this.console?.log("");
@@ -1182,9 +1201,14 @@ var UI = class {
1182
1201
  * `cli-progress` already refuses to render on a non-terminal stream, but
1183
1202
  * `@topcli/spinner` has no such check and writes escapes unconditionally. The
1184
1203
  * guard lives here so the rule holds whichever library backs a given widget.
1204
+ *
1205
+ * A terminal on stderr is not enough when stdout is a pipe: the reader, such
1206
+ * as `jq`, usually prints to that same terminal, and each redraw moves the
1207
+ * cursor back over the lines it printed, overwriting results. A redirect to a
1208
+ * file or `/dev/null` has no such reader, so it keeps the live UI. See ADR-0027.
1185
1209
  */
1186
1210
  get canRedraw() {
1187
- return getStderrTarget() === "terminal";
1211
+ return getStderrTarget() === "terminal" && getStdoutTarget() !== "pipe";
1188
1212
  }
1189
1213
  /**
1190
1214
  * Stand-in for a spinner on a stream that cannot animate: CI logs, `2> run.log`.
@@ -1211,6 +1235,7 @@ var UI = class {
1211
1235
  if (!this.canRedraw) return noopProgressBar;
1212
1236
  const bar = this.multiBar?.create(0, 0, options);
1213
1237
  if (!bar) return noopProgressBar;
1238
+ this.hasBars = true;
1214
1239
  return {
1215
1240
  increment: (count = 1) => bar.increment(count, options),
1216
1241
  setTotal: (total) => {
@@ -1221,12 +1246,14 @@ var UI = class {
1221
1246
  };
1222
1247
  }
1223
1248
  stopAllProgressBars() {
1249
+ if (!this.hasBars) return;
1250
+ this.hasBars = false;
1224
1251
  this.multiBar?.stop();
1225
1252
  }
1226
1253
  createSpinner(title) {
1227
1254
  if (!this.enabled) return noopSpinner;
1228
1255
  if (!this.canRedraw) return this.plainSpinner(title);
1229
- const spinner = new Spinner({ verbose: getActiveConfig().verbose });
1256
+ const spinner = new Spinner();
1230
1257
  spinner.stream = process.stderr;
1231
1258
  return spinner.start(title);
1232
1259
  }
@@ -1605,9 +1632,8 @@ const OVERFLOW_SUFFIX = "more failure reason(s)";
1605
1632
  * Accumulates per-item failures keyed by their human-readable reason string
1606
1633
  * and produces a compact grouped summary for terminal output.
1607
1634
  *
1608
- * Mirrors the grouping convention in `assets/transfer/index.ts` so all
1609
- * asset-push/transfer/pipeline failure displays are consistent: one line per
1610
- * unique cause instead of one line per failed item.
1635
+ * Keeps failure displays consistent across commands (assets, migrations):
1636
+ * one line per unique cause instead of one line per failed item.
1611
1637
  *
1612
1638
  * Usage:
1613
1639
  * ```ts
@@ -1615,8 +1641,8 @@ const OVERFLOW_SUFFIX = "more failure reason(s)";
1615
1641
  * // …during processing:
1616
1642
  * failures.record(toError(error).message, asset.short_filename);
1617
1643
  * // …after processing, before/after stopping progress bars:
1618
- * for (const line of failures.toListLines()) {
1619
- * ui.warn(line); // or ui.list(failures.toListLines())
1644
+ * for (const line of failures.toListLines("push", ["asset", "assets"])) {
1645
+ * ui.warn(line);
1620
1646
  * }
1621
1647
  * ```
1622
1648
  */
@@ -1658,13 +1684,14 @@ var FailureReasonGroup = class {
1658
1684
  * - Multiple: `Failed to push N assets — reason (e.g. "a", "b")`
1659
1685
  * - Overflow: `… and N more failure reason(s)`
1660
1686
  *
1661
- * Pass `verb` to customise the opening word ("push", "read", "transfer", …).
1687
+ * `verb` is the opening word ("push", "transfer", "migrate", …) and the
1688
+ * nouns name what failed, singular and plural.
1662
1689
  */
1663
- toListLines(verb = "push") {
1690
+ toListLines(verb, [singular, plural]) {
1664
1691
  const all = this.entries();
1665
1692
  const lines = all.slice(0, MAX_REASONS).map(({ reason, count, examples }) => {
1666
1693
  if (count === 1 && examples.length > 0) return `Failed to ${verb} "${examples[0]}": ${reason}`;
1667
- return `Failed to ${verb} ${count} ${count === 1 ? "asset" : "assets"} — ${reason}${examples.length > 0 ? ` (e.g. ${examples.map((e) => `"${e}"`).join(", ")})` : ""}`;
1694
+ return `Failed to ${verb} ${count} ${count === 1 ? singular : plural} — ${reason}${examples.length > 0 ? ` (e.g. ${examples.map((e) => `"${e}"`).join(", ")})` : ""}`;
1668
1695
  });
1669
1696
  if (all.length > MAX_REASONS) lines.push(`… and ${all.length - MAX_REASONS} ${OVERFLOW_SUFFIX}`);
1670
1697
  return lines;
@@ -1971,25 +1998,32 @@ var Reporter = class Reporter {
1971
1998
  this.report.summary[key] = value;
1972
1999
  return this;
1973
2000
  }
1974
- finalize() {
2001
+ /**
2002
+ * Writes the report. Pass the error that stopped the command early, so the
2003
+ * report says the run failed even though its summaries look complete.
2004
+ */
2005
+ finalize(stoppedBy) {
1975
2006
  if (!this.enabled) return;
1976
2007
  const endedAt = /* @__PURE__ */ new Date();
1977
2008
  this.report.meta.endedAt = endedAt.toISOString();
1978
2009
  this.report.meta.durationMs = endedAt.getTime() - this.startedAt.getTime();
1979
- this.updateStatus();
2010
+ if (stoppedBy) {
2011
+ this.report.meta.error = stoppedBy.message;
2012
+ this.report.status = REPORT_STATUS.failure;
2013
+ } else this.updateStatus();
1980
2014
  saveToFileSync(this.filePath, JSON.stringify(this.report, null, 2));
1981
2015
  if (this.maxFiles !== void 0) pruneSiblingRunFiles(this.filePath, this.maxFiles);
1982
2016
  }
2017
+ /**
2018
+ * Each summary is a stage, and stages often count the same items (e.g. a
2019
+ * story that is processed and then fails to update), so counts are never
2020
+ * added up across stages: a stage where everything failed fails the run.
2021
+ */
1983
2022
  updateStatus() {
1984
- let succeededTotal = 0;
1985
- let failedTotal = 0;
1986
- for (const item of Object.values(this.report.summary)) {
1987
- succeededTotal += item.succeeded;
1988
- failedTotal += item.failed;
1989
- }
1990
- if (failedTotal === 0) this.report.status = REPORT_STATUS.success;
1991
- else if (succeededTotal > 0) this.report.status = REPORT_STATUS.partialSuccess;
1992
- else this.report.status = REPORT_STATUS.failure;
2023
+ const stages = Object.values(this.report.summary);
2024
+ if (stages.every((stage) => stage.failed === 0)) this.report.status = REPORT_STATUS.success;
2025
+ else if (stages.some((stage) => stage.failed > 0 && stage.succeeded + (stage.skipped ?? 0) === 0)) this.report.status = REPORT_STATUS.failure;
2026
+ else this.report.status = REPORT_STATUS.partialSuccess;
1993
2027
  }
1994
2028
  static pruneReportFiles(directory, keep) {
1995
2029
  return pruneRunFiles(directory, Reporter.FILE_EXTENSION, keep);
@@ -2902,7 +2936,8 @@ const upsertComponent = async (space, component, existingId) => {
2902
2936
  content_type_asset_preview: component.content_type_asset_preview,
2903
2937
  internal_tag_ids: toRequestTagIds(component.internal_tag_ids),
2904
2938
  schema: toWritableSchema(component.schema),
2905
- metadata: component.metadata === null ? {} : component.metadata
2939
+ metadata: component.metadata === null ? {} : component.metadata,
2940
+ updated_at: void 0
2906
2941
  };
2907
2942
  if (existingId) return await updateComponent(space, existingId, payload);
2908
2943
  else return await pushComponent(space, payload);
@@ -4833,6 +4868,33 @@ const ERROR_CODES = {
4833
4868
  MIGRATION_STORY_UPDATE_NULL: "MIGRATION_STORY_UPDATE_NULL"
4834
4869
  };
4835
4870
  //#endregion
4871
+ //#region src/commands/migrations/run/failed-stories.ts
4872
+ function toReason({ step, migration, error }) {
4873
+ if (step === "fetch") return `Fetch failed: ${error}`;
4874
+ if (step === "update") return `Update failed: ${error}`;
4875
+ return migration ? `${migration} failed: ${error}` : error;
4876
+ }
4877
+ /**
4878
+ * Lists failed stories grouped by reason, so one cause shared by hundreds of
4879
+ * stories reads as one line. The reason carries the API's own explanation
4880
+ * (e.g. a workflow stage that doesn't allow publishing) when there is one.
4881
+ */
4882
+ function listFailedStories(failed) {
4883
+ const group = new FailureReasonGroup();
4884
+ for (const story of failed) {
4885
+ const { id, name } = story;
4886
+ group.record(toReason(story), name && name !== id.toString() ? `${name} (id ${id})` : `id ${id}`);
4887
+ }
4888
+ return group.toListLines("migrate", ["story", "stories"]);
4889
+ }
4890
+ /**
4891
+ * Whether an error would fail every remaining story the same way (revoked
4892
+ * credentials), so continuing the run would only repeat it for each story.
4893
+ */
4894
+ function isSystemicError(error) {
4895
+ return error instanceof APIError && error.errorId === "unauthorized";
4896
+ }
4897
+ //#endregion
4836
4898
  //#region src/commands/migrations/run/streams/stories-stream.ts
4837
4899
  /**
4838
4900
  * Iterator that fetches stories
@@ -4875,21 +4937,27 @@ async function* storiesIterator(spaceId, params, onTotal) {
4875
4937
  /**
4876
4938
  * Given a stream of stories, fetches the content for each story and streams the full story.
4877
4939
  * This is necessary because the content is not included in the stories stream.
4940
+ * A story that can't be fetched is reported through `onError` and skipped, so
4941
+ * it doesn't stop the remaining stories from being migrated. An error that
4942
+ * would fail every remaining story too (e.g. revoked credentials) stops the run.
4878
4943
  */
4879
4944
  var StoriesStream = class extends Transform {
4880
4945
  spaceId;
4881
4946
  onProgress;
4947
+ onError;
4882
4948
  semaphore;
4883
- constructor(spaceId, onProgress) {
4949
+ constructor(spaceId, onProgress, onError) {
4884
4950
  super({ objectMode: true });
4885
4951
  this.spaceId = spaceId;
4886
4952
  this.onProgress = onProgress;
4953
+ this.onError = onError;
4887
4954
  this.semaphore = createPipelineBackpressureLock();
4888
4955
  }
4889
4956
  async _transform(chunk, _encoding, callback) {
4890
4957
  try {
4891
4958
  await this.semaphore.acquire();
4892
4959
  const story = await fetchStory(this.spaceId, chunk.id.toString());
4960
+ if (!story) throw new Error("The API returned no story");
4893
4961
  this.push(story);
4894
4962
  this.onProgress?.();
4895
4963
  getLogger().info("Fetched story", { storyId: chunk.id });
@@ -4898,10 +4966,17 @@ var StoriesStream = class extends Transform {
4898
4966
  const error = toError(maybeError);
4899
4967
  getLogger().error(error.message, {
4900
4968
  storyId: chunk.id,
4969
+ storyName: chunk.name,
4901
4970
  error,
4902
4971
  errorCode: ERROR_CODES.MIGRATION_STORY_FETCH_ERROR
4903
4972
  });
4904
- callback(error);
4973
+ this.onError?.({
4974
+ storyId: chunk.id,
4975
+ name: chunk.name,
4976
+ full_slug: chunk.full_slug,
4977
+ error
4978
+ });
4979
+ callback(isSystemicError(error) ? error : null);
4905
4980
  } finally {
4906
4981
  this.semaphore.release();
4907
4982
  }
@@ -4915,10 +4990,10 @@ var StoriesStream = class extends Transform {
4915
4990
  /**
4916
4991
  * Creates a stream of stories
4917
4992
  */
4918
- const createStoriesStream = async ({ spaceId, params, onTotal, onProgress }) => {
4993
+ const createStoriesStream = async ({ spaceId, params, onTotal, onProgress, onError }) => {
4919
4994
  const iterator = storiesIterator(spaceId, params, onTotal);
4920
4995
  const listStoriesStream = Readable.from(iterator);
4921
- return pipeline(listStoriesStream, new StoriesStream(spaceId, onProgress), (err) => {
4996
+ return pipeline(listStoriesStream, new StoriesStream(spaceId, onProgress, onError), (err) => {
4922
4997
  if (err) getLogger().error(err.message, {
4923
4998
  error: err,
4924
4999
  errorCode: ERROR_CODES.MIGRATION_CREATE_STORIES_PIPELINE_ERROR
@@ -5099,16 +5174,23 @@ var MigrationStream = class extends Transform {
5099
5174
  this.migrationFunctions.set(migrationFile.name, migrationFunction);
5100
5175
  return migrationFunction;
5101
5176
  }
5177
+ recordFailure(failed) {
5178
+ this.results.failed.push(failed);
5179
+ this.options.onError?.(failed);
5180
+ }
5102
5181
  async processStory(story) {
5103
5182
  const relevantMigrations = this.options.componentName ? this.options.migrationFiles.filter((file) => migrationTargetsComponent(file.name, this.options.componentName)) : this.options.migrationFiles;
5104
5183
  if (!story.content) {
5105
- this.results.failed.push({
5184
+ this.recordFailure({
5106
5185
  storyId: story.id,
5186
+ name: story.name,
5187
+ full_slug: story.full_slug,
5107
5188
  migrationNames: relevantMigrations.map((m) => m.name),
5108
5189
  error: /* @__PURE__ */ new Error("Story content is missing")
5109
5190
  });
5110
5191
  getLogger().error("Failed to process story: Content is missing", {
5111
5192
  storyId: story.id,
5193
+ storyName: story.name,
5112
5194
  errorCode: ERROR_CODES.MIGRATION_STORY_CONTENT_MISSING
5113
5195
  });
5114
5196
  return [];
@@ -5120,25 +5202,34 @@ var MigrationStream = class extends Transform {
5120
5202
  }
5121
5203
  async applyMigrationsToStory(story, migrationFiles) {
5122
5204
  const migrationNames = migrationFiles.map((f) => f.name);
5205
+ let migrationName;
5123
5206
  try {
5124
5207
  const storyContent = structuredClone(story.content);
5125
5208
  const originalContentHash = hash(storyContent);
5126
5209
  let processed = false;
5127
5210
  for (const migrationFile of migrationFiles) {
5211
+ migrationName = migrationFile.name;
5128
5212
  const migrationFunction = await this.getOrLoadMigrationFunction(migrationFile);
5129
5213
  if (!migrationFunction) {
5130
5214
  const error = /* @__PURE__ */ new Error(`Failed to load migration function from file "${migrationFile.name}"`);
5131
- this.results.failed.push({
5215
+ this.recordFailure({
5132
5216
  storyId: story.id,
5217
+ name: story.name,
5218
+ full_slug: story.full_slug,
5133
5219
  migrationNames,
5134
5220
  error
5135
5221
  });
5136
- getLogger().error(error.message, { errorCode: ERROR_CODES.MIGRATION_FILE_NOT_FOUND });
5222
+ getLogger().error(error.message, {
5223
+ storyId: story.id,
5224
+ storyName: story.name,
5225
+ errorCode: ERROR_CODES.MIGRATION_FILE_NOT_FOUND
5226
+ });
5137
5227
  return null;
5138
5228
  }
5139
5229
  const migrationProcessed = applyMigrationToAllBlocks(storyContent, migrationFunction, migrationFile.name);
5140
5230
  processed = processed || migrationProcessed;
5141
5231
  }
5232
+ migrationName = void 0;
5142
5233
  const contentChanged = originalContentHash !== hash(storyContent);
5143
5234
  if (processed && contentChanged) {
5144
5235
  await saveRollbackData({
@@ -5167,6 +5258,7 @@ var MigrationStream = class extends Transform {
5167
5258
  return {
5168
5259
  storyId: story.id,
5169
5260
  name: story.name,
5261
+ full_slug: story.full_slug,
5170
5262
  content: storyContent,
5171
5263
  published: story.published ?? void 0,
5172
5264
  unpublished_changes: story.unpublished_changes ?? void 0
@@ -5199,14 +5291,19 @@ var MigrationStream = class extends Transform {
5199
5291
  }
5200
5292
  } catch (maybeError) {
5201
5293
  const error = toError(maybeError);
5202
- this.results.failed.push({
5294
+ this.recordFailure({
5203
5295
  storyId: story.id,
5296
+ name: story.name,
5297
+ full_slug: story.full_slug,
5204
5298
  migrationNames,
5299
+ migrationName,
5205
5300
  error
5206
5301
  });
5207
5302
  getLogger().error(error.message, {
5208
5303
  storyId: story.id,
5304
+ storyName: story.name,
5209
5305
  migrationNames,
5306
+ migrationName,
5210
5307
  error,
5211
5308
  errorCode: ERROR_CODES.MIGRATION_APPLY_TO_STORY_ERROR
5212
5309
  });
@@ -5227,7 +5324,7 @@ var MigrationStream = class extends Transform {
5227
5324
  */
5228
5325
  getSummary() {
5229
5326
  const { successful, failed, skipped } = this.results;
5230
- let summary = `Migration Results: ${new Set(successful.map((result) => result.storyId)).size} stories updated, ${skipped.length} stories skipped`;
5327
+ let summary = `Migration Results: ${new Set(successful.map((result) => result.storyId)).size} stories migrated, ${skipped.length} stories skipped`;
5231
5328
  if (skipped.length > 0) {
5232
5329
  const skippedByReason = skipped.reduce((acc, item) => {
5233
5330
  if (!acc[item.reason]) acc[item.reason] = 0;
@@ -5317,7 +5414,20 @@ var UpdateStream = class extends Writable {
5317
5414
  async _write(chunk, _encoding, callback) {
5318
5415
  try {
5319
5416
  await this.semaphore.acquire();
5320
- this.updateStory(chunk).finally(() => {
5417
+ if (this.destroyed) {
5418
+ this.semaphore.release();
5419
+ callback();
5420
+ return;
5421
+ }
5422
+ this.updateStory(chunk).catch((maybeError) => {
5423
+ const error = toError(maybeError);
5424
+ getLogger().error(error.message, {
5425
+ storyId: chunk.storyId,
5426
+ storyName: chunk.name,
5427
+ error,
5428
+ errorCode: ERROR_CODES.MIGRATION_STORY_UPDATE_ERROR
5429
+ });
5430
+ }).finally(() => {
5321
5431
  this.semaphore.release();
5322
5432
  });
5323
5433
  callback();
@@ -5326,7 +5436,7 @@ var UpdateStream = class extends Writable {
5326
5436
  }
5327
5437
  }
5328
5438
  async updateStory(migrationResult) {
5329
- const { storyId, name, content, published, unpublished_changes } = migrationResult;
5439
+ const { storyId, name, full_slug, content, published, unpublished_changes } = migrationResult;
5330
5440
  const storyName = name || storyId.toString();
5331
5441
  try {
5332
5442
  const payload = {
@@ -5356,38 +5466,44 @@ var UpdateStream = class extends Writable {
5356
5466
  getLogger().info("Updated story", { storyId });
5357
5467
  } else {
5358
5468
  const error = /* @__PURE__ */ new Error("Update returned null");
5359
- this.results.failed.push({
5469
+ this.recordFailure({
5360
5470
  storyId,
5361
5471
  name: storyName,
5472
+ full_slug,
5362
5473
  error
5363
5474
  });
5364
- this.results.totalProcessed++;
5365
- this.options.onProgress?.(this.results.totalProcessed);
5366
5475
  getLogger().error(`Failed to update story: ${error.message}`, {
5367
5476
  storyId,
5477
+ storyName,
5368
5478
  errorCode: ERROR_CODES.MIGRATION_STORY_UPDATE_NULL
5369
5479
  });
5370
5480
  }
5371
5481
  } catch (maybeError) {
5372
5482
  const error = toError(maybeError);
5373
- this.results.failed.push({
5483
+ this.recordFailure({
5374
5484
  storyId,
5375
5485
  name: storyName,
5486
+ full_slug,
5376
5487
  error
5377
5488
  });
5378
- this.results.totalProcessed++;
5379
- this.options.onProgress?.(this.results.totalProcessed);
5380
5489
  getLogger().error(error.message, {
5381
5490
  storyId,
5491
+ storyName,
5382
5492
  error,
5383
5493
  errorCode: ERROR_CODES.MIGRATION_STORY_UPDATE_ERROR
5384
5494
  });
5495
+ if (isSystemicError(error)) this.destroy(error);
5385
5496
  }
5386
5497
  }
5498
+ recordFailure(failed) {
5499
+ this.results.failed.push(failed);
5500
+ this.results.totalProcessed++;
5501
+ this.options.onProgress?.(this.results.totalProcessed);
5502
+ this.options.onError?.(failed);
5503
+ }
5387
5504
  async _destroy(error, callback) {
5388
5505
  try {
5389
5506
  await this.semaphore.drain();
5390
- callback();
5391
5507
  } catch (batchError) {
5392
5508
  callback(batchError);
5393
5509
  return;
@@ -5461,6 +5577,10 @@ migrationsCommand.command("run [componentName]").description("Run migrations").o
5461
5577
  const storiesProgress = ui.createProgressBar({ title: "Fetching Stories...".padEnd(19) });
5462
5578
  const migrationsProgress = ui.createProgressBar({ title: "Applying Migrations".padEnd(19) });
5463
5579
  const updateProgress = ui.createProgressBar({ title: "Updating Stories...".padEnd(19) });
5580
+ const failedStories = [];
5581
+ let listedStories = 0;
5582
+ let fetchedStories = 0;
5583
+ let fetchFailedStories = 0;
5464
5584
  const storiesStream = await createStoriesStream({
5465
5585
  spaceId: space,
5466
5586
  params: {
@@ -5471,11 +5591,25 @@ migrationsCommand.command("run [componentName]").description("Run migrations").o
5471
5591
  })
5472
5592
  },
5473
5593
  onTotal: (total) => {
5594
+ listedStories = total;
5474
5595
  storiesProgress.setTotal(total);
5475
5596
  migrationsProgress.setTotal(total);
5476
5597
  },
5477
5598
  onProgress: () => {
5599
+ fetchedStories++;
5478
5600
  storiesProgress.increment();
5601
+ },
5602
+ onError: ({ storyId, name, full_slug, error }) => {
5603
+ fetchFailedStories++;
5604
+ storiesProgress.increment();
5605
+ migrationsProgress.increment();
5606
+ failedStories.push({
5607
+ id: storyId,
5608
+ name,
5609
+ full_slug,
5610
+ step: "fetch",
5611
+ error: error.message
5612
+ });
5479
5613
  }
5480
5614
  });
5481
5615
  const migrationStream = new MigrationStream({
@@ -5489,6 +5623,16 @@ migrationsCommand.command("run [componentName]").description("Run migrations").o
5489
5623
  },
5490
5624
  onProgress: () => {
5491
5625
  migrationsProgress.increment();
5626
+ },
5627
+ onError: ({ storyId, name, full_slug, error, migrationName }) => {
5628
+ failedStories.push({
5629
+ id: storyId,
5630
+ name,
5631
+ full_slug,
5632
+ step: "migrate",
5633
+ migration: migrationName,
5634
+ error: error.message
5635
+ });
5492
5636
  }
5493
5637
  });
5494
5638
  const updateStream = new UpdateStream({
@@ -5497,22 +5641,23 @@ migrationsCommand.command("run [componentName]").description("Run migrations").o
5497
5641
  dryRun,
5498
5642
  onProgress: () => {
5499
5643
  updateProgress.increment();
5644
+ },
5645
+ onError: ({ storyId, name, full_slug, error }) => {
5646
+ failedStories.push({
5647
+ id: storyId,
5648
+ name,
5649
+ full_slug,
5650
+ step: "update",
5651
+ error: error.message
5652
+ });
5500
5653
  }
5501
5654
  });
5502
- await new Promise((resolve, reject) => {
5655
+ const fatalError = await new Promise((resolve) => {
5503
5656
  pipeline(storiesStream, migrationStream, updateStream, (err) => {
5504
- if (err) {
5505
- reject(err);
5506
- return;
5507
- }
5508
- resolve();
5657
+ resolve(err ?? null);
5509
5658
  });
5510
5659
  });
5511
5660
  ui.stopAllProgressBars();
5512
- const migrationSummary = migrationStream.getSummary();
5513
- ui.info(migrationSummary);
5514
- const updateSummary = updateStream.getSummary();
5515
- ui.info(updateSummary);
5516
5661
  const migrationStreamResults = migrationStream.getResults();
5517
5662
  const migrationResults = {
5518
5663
  total: migrationStreamResults.totalProcessed,
@@ -5526,13 +5671,40 @@ migrationsCommand.command("run [componentName]").description("Run migrations").o
5526
5671
  succeeded: updateStreamResults.successful.length,
5527
5672
  failed: updateStreamResults.failed.length
5528
5673
  };
5674
+ const fetchResults = {
5675
+ total: fetchedStories + fetchFailedStories,
5676
+ succeeded: fetchedStories,
5677
+ failed: fetchFailedStories
5678
+ };
5679
+ if (fatalError && listedStories > 0) {
5680
+ const finishedStories = fetchResults.failed + migrationResults.failed + migrationResults.skipped + updateResults.total;
5681
+ ui.warn(`Run stopped after ${finishedStories} of ${listedStories} stories.`);
5682
+ }
5683
+ if (!fatalError || listedStories > 0) ui.info(migrationStream.getSummary());
5684
+ if (updateResults.total > 0 || !fatalError && failedStories.length === 0) ui.info(updateStream.getSummary());
5685
+ if (failedStories.length > 0) ui.list(listFailedStories(failedStories));
5686
+ const fullListPath = reporter.enabled ? reporter.filePath : logger.transports.find((transport) => transport instanceof FileTransport)?.filePath;
5529
5687
  logger.info("Migration finished", {
5688
+ fetchResults,
5530
5689
  migrationResults,
5531
5690
  updateResults
5532
5691
  });
5692
+ reporter.addSummary("fetchResults", fetchResults);
5533
5693
  reporter.addSummary("migrationResults", migrationResults);
5534
5694
  reporter.addSummary("updateResults", updateResults);
5535
- reporter.finalize();
5695
+ if (failedStories.length > 0) reporter.addMeta("failedStories", failedStories);
5696
+ try {
5697
+ reporter.finalize(fatalError ?? void 0);
5698
+ if (failedStories.length > 0 && fullListPath) ui.info(`All failed stories are listed in ${fullListPath}`);
5699
+ } catch (error) {
5700
+ if (!fatalError) throw error;
5701
+ handleError(error, verbose);
5702
+ }
5703
+ if (fatalError) {
5704
+ handleError(fatalError, verbose);
5705
+ return;
5706
+ }
5707
+ process.exitCode = failedStories.length > 0 ? 1 : 0;
5536
5708
  } catch (error) {
5537
5709
  handleError(error, verbose);
5538
5710
  }
@@ -7375,7 +7547,7 @@ const redactUrlTokens = (text) => text.replace(URL_TOKEN_PARAM, "$1[redacted]");
7375
7547
  * and are returned as is.
7376
7548
  */
7377
7549
  function redactClientError(maybeError) {
7378
- if (maybeError instanceof ClientError && maybeError.response.status > 0) return maybeError;
7550
+ if (maybeError instanceof ClientError$1 && maybeError.response.status > 0) return maybeError;
7379
7551
  const error = toError(maybeError);
7380
7552
  const redacted = new Error(redactUrlTokens(error.message));
7381
7553
  redacted.name = error.name;
@@ -9768,7 +9940,7 @@ const upsertAssetsPipeline = async ({ assetBinaryPath, assetData, directoryPath,
9768
9940
  }
9769
9941
  }));
9770
9942
  await pipeline$1(steps);
9771
- for (const line of failures.toListLines()) ui.warn(line);
9943
+ for (const line of failures.toListLines("push", ["asset", "assets"])) ui.warn(line);
9772
9944
  return [["assetResults", summary]];
9773
9945
  };
9774
9946
  const mapAssetReferencesInStoriesPipeline = async ({ logger, maps, schemas, space, transports, ui }) => {
@@ -10250,7 +10422,7 @@ assetsCommand.command("transfer [asset-id...]").option("-s, --space <space>", "s
10250
10422
  if (summary.failed > 0) {
10251
10423
  const failures = new FailureReasonGroup();
10252
10424
  for (const result of results) if (result.status === "failed") failures.record(result.reason ?? "Unknown error");
10253
- ui.list(failures.toListLines("transfer"));
10425
+ ui.list(failures.toListLines("transfer", ["asset", "assets"]));
10254
10426
  }
10255
10427
  reporter.addSummary("transferResults", summary);
10256
10428
  reporter.finalize();
@@ -10523,7 +10695,7 @@ async function createCapiContentFetcher({ spaceId, region, params }) {
10523
10695
  if (Object.keys(params).length > 0) try {
10524
10696
  await listStories({ per_page: 1 });
10525
10697
  } catch (error) {
10526
- if (!(error instanceof ClientError) || error.response.status >= 500) throw error;
10698
+ if (!(error instanceof ClientError$1) || error.response.status >= 500) throw error;
10527
10699
  const reason = error.response.data?.error ?? error.response.data?.message ?? error.message;
10528
10700
  throw new CommandError(`The CDN rejected --capi-params ${JSON.stringify(params)} (HTTP ${error.response.status}): ${String(reason)}`);
10529
10701
  }
@@ -10745,6 +10917,17 @@ function parseList(flag, raw) {
10745
10917
  return items.join(",");
10746
10918
  }
10747
10919
  /**
10920
+ * Reads `--starts-with` as the API's slug prefix.
10921
+ *
10922
+ * `""` or `/` normalizes to no prefix at all, which would widen the run to the
10923
+ * whole space: the opposite of what passing the flag asked for.
10924
+ */
10925
+ function parseStartsWith(raw) {
10926
+ const { starts_with: startsWith } = buildStoryScopeParams({ startsWith: raw });
10927
+ if (startsWith === void 0) throw new CommandError(`--starts-with expects a slug prefix, e.g. 'en/blog', and got: ${JSON.stringify(raw)}`);
10928
+ return startsWith;
10929
+ }
10930
+ /**
10748
10931
  * Rejects options the command accepts on the surface but cannot honour yet.
10749
10932
  *
10750
10933
  * Silently ignoring an explicitly passed flag is worse than failing: the user
@@ -10827,11 +11010,10 @@ function buildQueryParams(text, options, now = /* @__PURE__ */ new Date()) {
10827
11010
  const params = { with_stages: true };
10828
11011
  if (text) params.text_search = text;
10829
11012
  const scope = buildStoryScopeParams({
10830
- startsWith: options.startsWith,
11013
+ startsWith: options.startsWith === void 0 ? void 0 : parseStartsWith(options.startsWith),
10831
11014
  query: options.query,
10832
11015
  extraFilterQuery: options.containerBlock !== void 0 ? { component: { in: parseList("--container-block", options.containerBlock) } } : void 0
10833
11016
  });
10834
- if (options.startsWith !== void 0 && scope.starts_with === void 0) throw new CommandError(`--starts-with expects a slug prefix, e.g. 'en/blog', and got: ${JSON.stringify(options.startsWith)}`);
10835
11017
  Object.assign(params, scope);
10836
11018
  if (options.includesBlock !== void 0) params.contain_component = parseList("--includes-block", options.includesBlock);
10837
11019
  if (options.tag !== void 0) params.with_tag = parseList("--tag", options.tag);
@@ -10933,7 +11115,7 @@ function buildWhereFilters(expressions) {
10933
11115
  if (!expressions?.length) return [];
10934
11116
  return expressions.map((expression) => {
10935
11117
  const query = compileWhere(expression);
10936
- return (story) => query.match(toJsonValue(withoutContentSummary(story))) !== void 0;
11118
+ return (story) => query.test(toJsonValue(withoutContentSummary(story)));
10937
11119
  });
10938
11120
  }
10939
11121
  /**
@@ -11352,6 +11534,33 @@ const uniqueStoriesStream = ({ onRepeat }) => {
11352
11534
  });
11353
11535
  };
11354
11536
  /**
11537
+ * Holds every listed story, then passes them on in the order `order` gives.
11538
+ *
11539
+ * For a listing whose order is not the one the results should come in: the
11540
+ * `--mode semantic` listing comes back in the API's order, and Strata's rank has
11541
+ * to be restored before the content fetch, so `--limit` stops it after the top
11542
+ * results rather than after whichever were listed first. Only for a small,
11543
+ * bounded listing: nothing moves on until the last story has arrived.
11544
+ */
11545
+ const reorderStoriesStream = ({ order }) => {
11546
+ const buffered = [];
11547
+ return new Transform({
11548
+ objectMode: true,
11549
+ transform(story, _encoding, callback) {
11550
+ buffered.push(story);
11551
+ callback();
11552
+ },
11553
+ flush(callback) {
11554
+ try {
11555
+ for (const story of order(buffered)) this.push(story);
11556
+ callback();
11557
+ } catch (maybeError) {
11558
+ callback(toError(maybeError));
11559
+ }
11560
+ }
11561
+ });
11562
+ };
11563
+ /**
11355
11564
  * Drops stories before their content is fetched. The per-story fetch is the
11356
11565
  * expensive part of the pipeline, so any filter decidable from the list response
11357
11566
  * (such as `--publish-status`) belongs here rather than at the end.
@@ -11549,7 +11758,7 @@ async function prepareCapiFilter({ spaceId, region, capiParams, filters, attachC
11549
11758
  * `--check-references`. The run therefore moves at the pace of whatever is
11550
11759
  * reading, rather than ahead of it.
11551
11760
  */
11552
- async function runStoryPipeline({ spaceId, params, preContentFilters, filters, tracker, sink, onListed, capi, skipContent = false, signal, logger, verbose }) {
11761
+ async function runStoryPipeline({ spaceId, params, preContentFilters, filters, tracker, sink, onListed, capi, orderListed, skipContent = false, signal, logger, verbose }) {
11553
11762
  const list = tracker.phase("list");
11554
11763
  const capiFilter = tracker.phase("capiFilter");
11555
11764
  const content = tracker.phase("content");
@@ -11594,6 +11803,7 @@ async function runStoryPipeline({ spaceId, params, preContentFilters, filters, t
11594
11803
  ...params.scheduled_by_status !== void 0 ? [uniqueStoriesStream({ onRepeat: () => {
11595
11804
  list.count("repeated");
11596
11805
  } })] : [],
11806
+ ...orderListed ? [reorderStoriesStream({ order: orderListed })] : [],
11597
11807
  filterListedStoriesStream({
11598
11808
  filters: preContentFilters,
11599
11809
  onDropped: () => {
@@ -11693,7 +11903,7 @@ function findPhases({ capi, skipContent, capiLabel, processLabel }) {
11693
11903
  return [
11694
11904
  {
11695
11905
  key: "list",
11696
- label: "Fetching stories",
11906
+ label: "Listing stories",
11697
11907
  counters: [
11698
11908
  "succeeded",
11699
11909
  "repeated",
@@ -11717,7 +11927,7 @@ function findPhases({ capi, skipContent, capiLabel, processLabel }) {
11717
11927
  },
11718
11928
  {
11719
11929
  key: "content",
11720
- label: "Fetching stories content",
11930
+ label: "Fetching content",
11721
11931
  enabled: !skipContent,
11722
11932
  counters: ["succeeded", "failed"],
11723
11933
  outflow: (counts) => counts.total - counts.failed
@@ -11741,11 +11951,7 @@ function findPhases({ capi, skipContent, capiLabel, processLabel }) {
11741
11951
  * filter reaches it.
11742
11952
  */
11743
11953
  function processStageName({ skipContent, capi, filters }) {
11744
- if (skipContent) {
11745
- if (capi) return "Collecting matches";
11746
- return filters.length > 0 ? "Applying client-side filters" : "Writing results";
11747
- }
11748
- return capi ? "Collecting matches" : "Applying client-side filters";
11954
+ return skipContent && !capi && filters.length === 0 ? "Writing results" : "Filtering";
11749
11955
  }
11750
11956
  /** `1 story`, `210 stories`. */
11751
11957
  const storiesCount = (count) => `${count} ${count === 1 ? "story" : "stories"}`;
@@ -11798,11 +12004,11 @@ function findSummary({ results, elapsedMs, tracker, filters, skipContent, capi }
11798
12004
  });
11799
12005
  }
11800
12006
  /**
11801
- * Reports a deliberate stop as one: the counts that follow describe a partial
11802
- * scan, and anything less explicit than "not an error" reads as one next to them.
12007
+ * Reports a deliberate stop as one: the counts above it describe a partial scan,
12008
+ * which could otherwise read as a failure. The success mark says the rest.
11803
12009
  */
11804
- function stoppedEarlyMessage(limit) {
11805
- return (limit !== void 0 ? `Stopped early on purpose: --limit ${limit} was reached, so the rest of the scope was left unread. ` : "Stopped early on purpose: the command reading this output took what it needed and closed the pipe. ") + "This is not an error — the run exits 0. The counts cover only the part of the scope that ran.";
12010
+ function stoppedEarlyMessage(limit, { limitIsDefault = false } = {}) {
12011
+ return `${limit === void 0 ? "Stopped when the reading command closed the pipe, as expected." : limitIsDefault ? `Stopped at ${limit} results, the default. Set --limit for more.` : `Stopped at --limit ${limit}, as asked.`} The counts above cover only the part of the scope that ran.`;
11806
12012
  }
11807
12013
  /** The content phase's row in the run summary. */
11808
12014
  function contentSummary(tracker) {
@@ -11871,10 +12077,328 @@ const REF_ISSUE_COLUMNS = [...STORY_COLUMNS, {
11871
12077
  header: "issues",
11872
12078
  value: (story) => summarizeIssues(story._ref_issues)
11873
12079
  }];
12080
+ /**
12081
+ * The excerpt is the only flexible column: it can run to well over a thousand
12082
+ * characters, and the name is what identifies the story, so it must not be the
12083
+ * column that gives way.
12084
+ */
12085
+ const SEMANTIC_STORY_COLUMNS = [
12086
+ ...STORY_COLUMNS.map((column) => ({
12087
+ ...column,
12088
+ flexible: false
12089
+ })),
12090
+ {
12091
+ header: "score",
12092
+ value: (story) => story._score.toFixed(2)
12093
+ },
12094
+ {
12095
+ header: "excerpt",
12096
+ value: (story) => story._excerpt.replace(/\s+/g, " "),
12097
+ flexible: true
12098
+ }
12099
+ ];
12100
+ /**
12101
+ * Every `find` option, and whether `--mode semantic` takes it: `null` when it
12102
+ * does, or why not.
12103
+ *
12104
+ * Typed over every option, so a flag added to `find` does not compile until it
12105
+ * is classified here. An option missing from it at runtime is rejected, so the
12106
+ * list fails closed.
12107
+ *
12108
+ * Strata answers with one ranked page of at most 100 hits. A flag that reorders
12109
+ * that page, or that needs the whole space in scope, would answer a different
12110
+ * question than the one asked.
12111
+ */
12112
+ const SEMANTIC_OPTIONS = {
12113
+ space: null,
12114
+ mode: null,
12115
+ entryType: {
12116
+ reason: "Strata only searches stories, never folders",
12117
+ values: ["folder"]
12118
+ },
12119
+ startsWith: null,
12120
+ containerBlock: null,
12121
+ includesBlock: null,
12122
+ query: null,
12123
+ where: null,
12124
+ tag: null,
12125
+ workflowStage: null,
12126
+ publishStatus: null,
12127
+ created: null,
12128
+ updated: null,
12129
+ lastPublished: null,
12130
+ firstPublished: null,
12131
+ scheduled: null,
12132
+ sort: { reason: "results keep Strata's relevance order" },
12133
+ limit: null,
12134
+ references: null,
12135
+ checkReferences: { reason: "the reference check reads every story in scope, not Strata's matches" },
12136
+ skipContent: null,
12137
+ capiFilter: { reason: "Strata returns at most 100 hits, so there is nothing to prune ahead of the Management API fetch" },
12138
+ capiParams: { reason: "semantic mode searches the draft, like the stories it prints; filter by status with --publish-status" }
12139
+ };
12140
+ const isSemanticOption = (name) => Object.hasOwn(SEMANTIC_OPTIONS, name);
12141
+ /** The incompatibility a value runs into, if any. Unknown options fail closed. */
12142
+ function incompatibilityOf(name, value) {
12143
+ if (!isSemanticOption(name)) return { reason: "it is not supported in semantic mode" };
12144
+ const incompatibility = SEMANTIC_OPTIONS[name];
12145
+ if (!incompatibility) return;
12146
+ if (incompatibility.values && !incompatibility.values.includes(String(value))) return;
12147
+ return incompatibility;
12148
+ }
12149
+ /** A value that asks for nothing: an off switch, an empty string or list, or the default. */
12150
+ function isUnset(value, defaultValue) {
12151
+ return value === void 0 || value === false || value === "" || Array.isArray(value) && value.length === 0 || value === defaultValue;
12152
+ }
12153
+ /** One line naming every flag, or flag value, that semantic mode turns down. */
12154
+ function formatUnavailableFlags(command) {
12155
+ return `Not available with --mode semantic: ${command.options.flatMap((option) => {
12156
+ const name = option.attributeName();
12157
+ const incompatibility = isSemanticOption(name) ? SEMANTIC_OPTIONS[name] : void 0;
12158
+ if (!incompatibility || !option.long) return [];
12159
+ return incompatibility.values ? incompatibility.values.map((value) => `${option.long} ${value}`) : [option.long];
12160
+ }).join(", ")}.`;
12161
+ }
12162
+ /**
12163
+ * Settles the flags semantic mode cannot take.
12164
+ *
12165
+ * Set on the command line, one is a usage error that names it. Set in a config
12166
+ * file, it is a default for full-text runs, and nothing on the command line
12167
+ * could clear it (there is no `--no-sort`), so it is left out of this run
12168
+ * instead. Returns the options to run with, and the flags left out.
12169
+ */
12170
+ function resolveSemanticOptions(command, options) {
12171
+ const resolved = { ...options };
12172
+ const ignored = [];
12173
+ const reasons = [];
12174
+ for (const option of command.options) {
12175
+ const name = option.attributeName();
12176
+ const value = command.getOptionValue(name);
12177
+ if (isUnset(value, option.defaultValue)) continue;
12178
+ const incompatibility = incompatibilityOf(name, value);
12179
+ if (!incompatibility) continue;
12180
+ const flag = incompatibility.values ? `${option.long} ${String(value)}` : `${option.long}`;
12181
+ if (command.getOptionValueSource(name) === "cli") reasons.push(`${flag} is not compatible with --mode semantic: ${incompatibility.reason}.`);
12182
+ else {
12183
+ ignored.push(flag);
12184
+ Reflect.deleteProperty(resolved, name);
12185
+ }
12186
+ }
12187
+ if (reasons.length > 0) throw new CommandError([...reasons, formatUnavailableFlags(command)].join("\n"));
12188
+ return {
12189
+ options: resolved,
12190
+ ignored
12191
+ };
12192
+ }
12193
+ /** Rejects values the compatible flags cannot take in semantic mode, before any request. */
12194
+ function assertSemanticOptions(text, options) {
12195
+ if (!text?.trim()) throw new CommandError("--mode semantic needs a search text, e.g. `stories find 'pages about pricing' --mode semantic`.");
12196
+ if (options.containerBlock !== void 0) {
12197
+ if (parseList("--container-block", options.containerBlock).includes(",")) throw new CommandError(`--mode semantic accepts a single --container-block, and got: ${options.containerBlock}`);
12198
+ }
12199
+ }
12200
+ /**
12201
+ * Picks the content version Strata searches.
12202
+ *
12203
+ * The draft, like the Management API stories the command prints, and like the
12204
+ * full-text search. The one exception changes no result: stories that are
12205
+ * `published` have the same draft and published content, so searching the
12206
+ * published version finds the same ones. It leaves out stories that were never
12207
+ * published, so they take no slots of Strata's single page only to be filtered
12208
+ * out afterwards. Stories with unpublished changes are still in the published
12209
+ * version, and `--publish-status published` drops them after the search.
12210
+ */
12211
+ function strataVersion(publishStatus) {
12212
+ if (publishStatus === void 0) return "draft";
12213
+ const statuses = new Set(parsePublishStatuses(publishStatus));
12214
+ return statuses.size === 1 && statuses.has("published") ? "published" : "draft";
12215
+ }
12216
+ /**
12217
+ * Builds the Strata query from the flags it can take.
12218
+ *
12219
+ * `--starts-with` and `--container-block` are pushed down, so they narrow what
12220
+ * Strata ranks rather than what survives of its page. Every other filter runs on
12221
+ * the hydrated stories, like in a full-text run.
12222
+ *
12223
+ * Strata's page is always requested at its largest. Its `limit` counts hits, and a
12224
+ * story can be several hits, so it cannot stand in for `--limit`, which counts
12225
+ * results. The largest page also leaves the most matches for the local filters.
12226
+ *
12227
+ * The version is the draft, unless `--publish-status published` alone makes the
12228
+ * published one equivalent: see {@link strataVersion}.
12229
+ */
12230
+ function buildStrataQuery(text, options) {
12231
+ const startsWith = options.startsWith === void 0 ? void 0 : parseStartsWith(options.startsWith);
12232
+ const contentType = options.containerBlock === void 0 ? void 0 : parseList("--container-block", options.containerBlock);
12233
+ const scoped = startsWith !== void 0 || contentType !== void 0;
12234
+ return {
12235
+ q: text.trim(),
12236
+ version: strataVersion(options.publishStatus),
12237
+ limit: scoped ? 50 : 100,
12238
+ ...startsWith === void 0 ? {} : { starts_with: startsWith },
12239
+ ...contentType === void 0 ? {} : { content_type: contentType }
12240
+ };
12241
+ }
12242
+ /**
12243
+ * Reads `--limit` for a semantic search.
12244
+ *
12245
+ * Without it, the search stops at {@link SEMANTIC_DEFAULT_LIMIT} stories, the
12246
+ * search endpoint's own default: the best matches, rather than everything down
12247
+ * to Strata's weakest. Strata's page
12248
+ * is still requested at its largest, so the local filters have the most
12249
+ * matches to work with. A limit above that page can never be reached, so it is
12250
+ * rejected rather than silently capped.
12251
+ */
12252
+ function parseSemanticLimit(raw, query) {
12253
+ const limit = parseLimit(raw);
12254
+ if (limit === void 0) return {
12255
+ limit: 25,
12256
+ isDefault: true
12257
+ };
12258
+ const max = query.limit ?? 100;
12259
+ if (limit > max) throw new CommandError(`--limit is at most ${max} with --mode semantic${max < 100 ? " with --starts-with or --container-block" : ""}: Strata returns at most ${max} matches. Got: ${raw}`);
12260
+ return {
12261
+ limit,
12262
+ isDefault: false
12263
+ };
12264
+ }
12265
+ /** Collapses Strata's hits to one per story, keeping each story's best one. */
12266
+ function rankHits(hits) {
12267
+ const ranking = /* @__PURE__ */ new Map();
12268
+ for (const { story, score, excerpt } of hits) if (!ranking.has(story.id)) ranking.set(story.id, {
12269
+ score,
12270
+ excerpt
12271
+ });
12272
+ return ranking;
12273
+ }
12274
+ /**
12275
+ * Orders listed stories by their Strata rank and annotates each with it.
12276
+ *
12277
+ * A ranked story the listing did not return (filtered out server-side, or no
12278
+ * longer there) is simply absent.
12279
+ */
12280
+ function* orderByRank(stories, ranking) {
12281
+ const byId = new Map(stories.map((story) => [story.id, story]));
12282
+ for (const [id, { score, excerpt }] of ranking) {
12283
+ const story = byId.get(id);
12284
+ if (story) yield {
12285
+ ...story,
12286
+ _score: score,
12287
+ _excerpt: excerpt
12288
+ };
12289
+ }
12290
+ }
12291
+ /** The longest `Retry-After` the search waits out before it retries. */
12292
+ const STRATA_MAX_RETRY_AFTER = 2e3;
12293
+ /** The wait a 429 asks for, in milliseconds, from `Retry-After` in seconds or as a date. */
12294
+ function retryAfterMs(error) {
12295
+ const response = "response" in error ? error.response : void 0;
12296
+ if (!(response instanceof Response)) return;
12297
+ const header = response.headers.get("Retry-After");
12298
+ if (header === null) return;
12299
+ const seconds = Number(header);
12300
+ if (header.trim() !== "" && Number.isFinite(seconds)) return seconds * 1e3;
12301
+ const date = Date.parse(header);
12302
+ return Number.isNaN(date) ? void 0 : date - Date.now();
12303
+ }
12304
+ /**
12305
+ * Retries for the search request.
12306
+ *
12307
+ * A 429 from the per-second request limit clears within a second or two, so two
12308
+ * short retries absorb it. Strata's own throttling asks for a minute or more,
12309
+ * which the client's default (12 retries, each waiting the full `Retry-After`)
12310
+ * would turn into a silent wait of 12+ minutes. `maxRetryAfter` only shortens
12311
+ * each wait, so retries would still go into a throttle that rejects them: past
12312
+ * 2 seconds, `shouldRetry` makes the search fail right away and say why instead.
12313
+ */
12314
+ const STRATA_RETRY = {
12315
+ limit: 2,
12316
+ methods: ["get"],
12317
+ statusCodes: [429],
12318
+ maxRetryAfter: STRATA_MAX_RETRY_AFTER,
12319
+ backoffLimit: 2e3,
12320
+ shouldRetry: ({ error }) => {
12321
+ const wait = retryAfterMs(error);
12322
+ return wait !== void 0 && wait > STRATA_MAX_RETRY_AFTER ? false : void 0;
12323
+ }
12324
+ };
12325
+ /**
12326
+ * Runs the Strata search through the Management API, as the logged-in user.
12327
+ *
12328
+ * The search honours the user's permissions, so it only matches stories the
12329
+ * user can read, like every other request the command makes. It searches the
12330
+ * draft or the published version alike, with no token beyond the login.
12331
+ */
12332
+ async function searchStrata({ spaceId, query, ui }) {
12333
+ const spinner = ui.createSpinner("Searching with Strata...");
12334
+ try {
12335
+ const { data } = await getMapiClient().strata.search({
12336
+ query,
12337
+ path: { space_id: Number(spaceId) },
12338
+ throwOnError: true,
12339
+ fetchOptions: { retry: STRATA_RETRY }
12340
+ });
12341
+ const hits = data?.results ?? [];
12342
+ const ranking = rankHits(hits);
12343
+ spinner.succeed(`Strata matched ${pluralize$1(ranking.size, "story", "stories")} (${pluralize$1(hits.length, "hit", "hits")})`);
12344
+ return {
12345
+ ranking,
12346
+ ...query.limit !== void 0 && hits.length >= query.limit ? { fullPageOf: query.limit } : {}
12347
+ };
12348
+ } catch (error) {
12349
+ spinner.failed("Strata search failed");
12350
+ throwStrataError(error);
12351
+ }
12352
+ }
12353
+ /** Printed under the summary when Strata's page came back full. */
12354
+ function fullPageMessage(limit) {
12355
+ return `Strata returned its maximum of ${limit} hits, and has no next page, so more stories may match. Narrow the search with --starts-with or --container-block, or make the text more specific.`;
12356
+ }
12357
+ const pluralize$1 = (count, one, many) => `${count} ${count === 1 ? one : many}`;
12358
+ /** Reads the `code` of Strata's `{ error: { code, message } }` body, if the response carries one. */
12359
+ function strataErrorCode(data) {
12360
+ if (!isRecord(data) || !isRecord(data.error)) return;
12361
+ return typeof data.error.code === "string" ? data.error.code : void 0;
12362
+ }
12363
+ function strataErrorMessage(data) {
12364
+ if (!isRecord(data) || !isRecord(data.error)) return;
12365
+ return typeof data.error.message === "string" ? data.error.message : void 0;
12366
+ }
12367
+ /** What to tell the user for the Strata error codes they can act on. */
12368
+ const STRATA_ERROR_HINTS = {
12369
+ feature_disabled: "Strata is not enabled for this space or its organization (feature_disabled).",
12370
+ insufficient_scope: "The token is missing the strata:read scope (insufficient_scope). Log in with a token that has it.",
12371
+ rate_limited: "Strata is rate limiting searches (rate_limited). Try again in a minute."
12372
+ };
12373
+ /**
12374
+ * Turns a failed search into the CLI's errors.
12375
+ *
12376
+ * A 400 is the query itself: a usage error, like any other rejected flag value.
12377
+ * Everything else goes through the usual API error handling, so `--verbose`
12378
+ * shows the status and the response body like for any other request. A Strata
12379
+ * code the user can act on, e.g. `feature_disabled`, gets its own message,
12380
+ * which the bare HTTP status does not tell apart. A 401 keeps the CLI's usual
12381
+ * wording.
12382
+ */
12383
+ function throwStrataError(error) {
12384
+ if (!(error instanceof ClientError) || error.response.status === 0) throw error;
12385
+ const { status, data } = error.response;
12386
+ const code = strataErrorCode(data);
12387
+ const message = strataErrorMessage(data);
12388
+ if (status === 400) throw new CommandError(`Strata rejected the search${code ? ` (${code})` : ""}${message ? `: ${message}` : "."}`);
12389
+ const hint = (code && STRATA_ERROR_HINTS[code]) ?? (status === 429 ? STRATA_ERROR_HINTS.rate_limited : void 0);
12390
+ if (hint) handleAPIError("search_strata", error, message ? `${hint} Details: ${message}` : hint);
12391
+ if (status === 401) handleAPIError("search_strata", error);
12392
+ handleAPIError("search_strata", error, message ? `Strata search failed${code ? ` (${code})` : ""}: ${message}` : void 0);
12393
+ }
11874
12394
  //#endregion
11875
12395
  //#region src/commands/stories/find/run.ts
11876
- async function runFind({ spaceId, params, preContentFilters, filters, skipContent = false, limit, capi, ui, logger, reporter, verbose }) {
11877
- const output = createResultOutput({
12396
+ async function runFind({ spaceId, params, preContentFilters, filters, skipContent = false, limit, limitIsDefault = false, capi, semantic, ui, logger, reporter, verbose }) {
12397
+ const ranking = semantic?.ranking;
12398
+ const output = ranking ? createResultOutput({
12399
+ columns: SEMANTIC_STORY_COLUMNS,
12400
+ limit
12401
+ }) : createResultOutput({
11878
12402
  columns: STORY_COLUMNS,
11879
12403
  limit
11880
12404
  });
@@ -11895,7 +12419,7 @@ async function runFind({ spaceId, params, preContentFilters, filters, skipConten
11895
12419
  let earlyExit = false;
11896
12420
  let stoppedByLimit = false;
11897
12421
  try {
11898
- await runStoryPipeline({
12422
+ if (!ranking || ranking.size > 0) await runStoryPipeline({
11899
12423
  spaceId,
11900
12424
  params,
11901
12425
  preContentFilters,
@@ -11903,15 +12427,17 @@ async function runFind({ spaceId, params, preContentFilters, filters, skipConten
11903
12427
  tracker,
11904
12428
  sink: output.sink,
11905
12429
  capi,
12430
+ orderListed: ranking ? (stories) => orderByRank(stories, ranking) : void 0,
11906
12431
  skipContent,
11907
12432
  signal: output.signal,
11908
12433
  logger,
11909
12434
  verbose
11910
12435
  });
11911
12436
  } catch (error) {
11912
- if (!isDeliberateStop(error)) throw error;
12437
+ const reason = output.signal.aborted ? output.signal.reason : error;
12438
+ if (!isDeliberateStop(error) && !isDeliberateStop(reason)) throw error;
11913
12439
  earlyExit = true;
11914
- stoppedByLimit = isLimitReached(error);
12440
+ stoppedByLimit = isLimitReached(error) || isLimitReached(reason);
11915
12441
  } finally {
11916
12442
  tracker.stop();
11917
12443
  output.close();
@@ -11932,7 +12458,9 @@ async function runFind({ spaceId, params, preContentFilters, filters, skipConten
11932
12458
  capi: capi !== void 0
11933
12459
  })) ui.log(line);
11934
12460
  const notes = [];
11935
- if (earlyExit) notes.push(() => ui.ok(stoppedEarlyMessage(stoppedByLimit ? limit : void 0)));
12461
+ if (earlyExit) notes.push(() => ui.ok(stoppedEarlyMessage(stoppedByLimit ? limit : void 0, { limitIsDefault })));
12462
+ const fullPageOf = semantic?.fullPageOf;
12463
+ if (fullPageOf !== void 0 && !stoppedByLimit) notes.push(() => ui.warn(fullPageMessage(fullPageOf)));
11936
12464
  if (skipContent && !capi && filters.length > 0 && filtered.succeeded === 0) notes.push(() => ui.warn("--where sees list metadata only while --skip-content is set (full_slug, updated_at, content_type, tag_list, published, …), never story content. If the expression reads content, drop --skip-content, and add --capi-filter to keep the run fast."));
11937
12465
  if (list.failed > 0 && params.sort_by) notes.push(() => ui.warn(`If the error above is "Not sortable by this column", --sort ${params.sort_by} names a column the API cannot sort by. Use a story column such as updated_at, created_at, published_at, name, slug or position, or a content field with the 'content.' prefix.`));
11938
12466
  const missing = capiFilter.unresolved - capiFilter.unresolvedFolders;
@@ -12156,18 +12684,18 @@ async function runCheckReferences({ spaceId, params, preContentFilters, whereFil
12156
12684
  function collectValues(value, previous) {
12157
12685
  return previous.concat([value]);
12158
12686
  }
12159
- storiesCommand.command("find").description("Find stories matching filters and print them to stdout as JSONL, one story per line, or as a table in a terminal. Filters combine with AND.").argument("[text]", "full-text search over story name, slug and content (case-insensitive)").option("-s, --space <space>", "space ID").addOption(new Option("--entry-type <type>", "filter by entry type").choices([
12687
+ storiesCommand.command("find").description("Find stories matching filters and print them to stdout as JSONL, one story per line, or as a table in a terminal. Filters combine with AND.").argument("[text]", "full-text search over story name, slug and content (case-insensitive), or a search by meaning with --mode semantic").option("-s, --space <space>", "space ID").addOption(new Option("--mode <mode>", "how [text] matches: 'fulltext', or 'semantic' to rank stories by meaning with Strata").choices(["fulltext", "semantic"]).default("fulltext")).addOption(new Option("--entry-type <type>", "filter by entry type").choices([
12160
12688
  "all",
12161
12689
  "story",
12162
12690
  "folder"
12163
- ]).default("all")).option("--starts-with <path>", "scope to a story subtree, e.g. 'en/blog'").option("--container-block <name>", "stories whose content type (root block) is this component, e.g. 'page'").option("--includes-block <names>", "stories containing all of these blocks at any depth, comma-separated").option("-q, --query <query>", "filter on root-level content fields with filter_query syntax, e.g. '[category][in]=news'").option("--where <jsonpath>", "JSONPath (RFC 9535) filter evaluated locally on each story, repeatable, e.g. \"$..[?(@.component == 'hero')]\" for a hero block at any depth", collectValues, []).option("--tag <names>", "stories carrying any of these tags, comma-separated").option("--workflow-stage <ids>", "stories at any of these workflow stage IDs (numeric), comma-separated").option("--publish-status <statuses>", "stories in any of these publish statuses, comma-separated: published, published-with-changes, draft").option("--created <range>", "stories created in this date range: a duration like '7d', a date like '2024-06', or a range like '2024-01-01..2024-06-30' (UTC unless an offset is given)").option("--updated <range>", "stories last updated in this date range, e.g. '7d' or '..90d'").option("--last-published <range>", "stories last published in this date range, e.g. '2024-06', including ones unpublished since; add --publish-status published for live ones only. Never-published stories never match").option("--first-published <range>", "stories first published in this date range, e.g. '2024-07..2024-09'").option("--scheduled [range]", "stories with a pending scheduled publish, in any language, optionally in this date range, where durations count forward, e.g. '7d' or '7d..14d'").option("--sort <fields>", "order by a story column or 'content.<field>', comma-separated, e.g. 'updated_at:desc' or 'content.title:asc'").option("--limit <n>", "stop after this many results").option("--references <uuids>", "stories that reference all of these story UUIDs, comma-separated").option("--check-references [types]", "report stories with broken, unpublished or stale_url references, listed in a `_ref_issues` array on each story, or summarized in an issues column in a terminal. Optionally only these types, comma-separated, e.g. 'broken'").option("--skip-content", "skip the per-story content fetch and emit list metadata only (--where then sees metadata only)").option("--capi-filter", "evaluate --where against bulk CDN content first and fetch only the matches from MAPI (requires --where)").option("--capi-params <params>", "extra CDN query params for --capi-filter, e.g. 'version=published' or 'language=de'").action(async (text, options, command) => {
12691
+ ]).default("all")).option("--starts-with <path>", "scope to a story subtree, e.g. 'en/blog'. With --mode semantic, only the default-language slug matches").option("--container-block <name>", "stories whose content type (root block) is this component, e.g. 'page'").option("--includes-block <names>", "stories containing all of these blocks at any depth, comma-separated").option("-q, --query <query>", "filter on root-level content fields with filter_query syntax, e.g. '[category][in]=news'").option("--where <jsonpath>", "JSONPath (RFC 9535) filter evaluated locally on each story, repeatable, e.g. \"$..[?(@.component == 'hero')]\" for a hero block at any depth", collectValues, []).option("--tag <names>", "stories carrying any of these tags, comma-separated").option("--workflow-stage <ids>", "stories at any of these workflow stage IDs (numeric), comma-separated").option("--publish-status <statuses>", "stories in any of these publish statuses, comma-separated: published, published-with-changes, draft").option("--created <range>", "stories created in this date range: a duration like '7d', a date like '2024-06', or a range like '2024-01-01..2024-06-30' (UTC unless an offset is given)").option("--updated <range>", "stories last updated in this date range, e.g. '7d' or '..90d'").option("--last-published <range>", "stories last published in this date range, e.g. '2024-06', including ones unpublished since; add --publish-status published for live ones only. Never-published stories never match").option("--first-published <range>", "stories first published in this date range, e.g. '2024-07..2024-09'").option("--scheduled [range]", "stories with a pending scheduled publish, in any language, optionally in this date range, where durations count forward, e.g. '7d' or '7d..14d'").option("--sort <fields>", "order by a story column or 'content.<field>', comma-separated, e.g. 'updated_at:desc' or 'content.title:asc'").option("--limit <n>", "stop after this many results. With --mode semantic, 25 by default and at most 100 (50 with --starts-with or --container-block)").option("--references <uuids>", "stories that reference all of these story UUIDs, comma-separated").option("--check-references [types]", "report stories with broken, unpublished or stale_url references, listed in a `_ref_issues` array on each story, or summarized in an issues column in a terminal. Optionally only these types, comma-separated, e.g. 'broken'").option("--skip-content", "skip the per-story content fetch and emit list metadata only (--where then sees metadata only)").option("--capi-filter", "evaluate --where against bulk CDN content first and fetch only the matches from MAPI (requires --where)").option("--capi-params <params>", "extra CDN query params for --capi-filter, e.g. 'version=published' or 'language=de'").action(async (text, cliOptions, command) => {
12164
12692
  const ui = getUI();
12165
12693
  const logger = getLogger();
12166
12694
  const reporter = getReporter();
12167
12695
  ui.title(`${commands.STORIES}`, colorPalette.STORIES, "Finding stories...");
12168
12696
  logger.info("Finding stories started", {
12169
12697
  text,
12170
- ...options
12698
+ ...cliOptions
12171
12699
  });
12172
12700
  const { space, verbose } = command.optsWithGlobals();
12173
12701
  const { state } = session();
@@ -12176,13 +12704,30 @@ storiesCommand.command("find").description("Find stories matching filters and pr
12176
12704
  handleError(new CommandError("Please provide the space as argument --space YOUR_SPACE_ID."), verbose);
12177
12705
  return;
12178
12706
  }
12707
+ const semantic = cliOptions.mode === "semantic";
12179
12708
  try {
12709
+ let options = cliOptions;
12710
+ if (semantic) {
12711
+ const resolved = resolveSemanticOptions(command, cliOptions);
12712
+ options = resolved.options;
12713
+ if (resolved.ignored.length > 0) {
12714
+ logger.info("Ignoring config values semantic mode cannot take", { ignored: resolved.ignored });
12715
+ ui.info(`Ignoring config values that --mode semantic cannot take: ${resolved.ignored.join(", ")}.`);
12716
+ }
12717
+ }
12718
+ if (semantic) assertSemanticOptions(text, options);
12180
12719
  assertSupportedOptions(options);
12720
+ const strataQuery = semantic && text ? buildStrataQuery(text, options) : void 0;
12181
12721
  const now = /* @__PURE__ */ new Date();
12182
- const params = buildQueryParams(text, options, now);
12722
+ const params = semantic ? buildQueryParams(void 0, {
12723
+ ...options,
12724
+ startsWith: void 0,
12725
+ containerBlock: void 0
12726
+ }, now) : buildQueryParams(text, options, now);
12183
12727
  const preContentFilters = [...buildPublishStatusFilters(options), ...buildDateFilters(options, now)];
12184
12728
  const whereFilters = buildWhereFilters(options.where);
12185
- const limit = parseLimit(options.limit);
12729
+ const semanticLimit = strataQuery ? parseSemanticLimit(options.limit, strataQuery) : void 0;
12730
+ const limit = semanticLimit ? semanticLimit.limit : parseLimit(options.limit);
12186
12731
  const issueTypes = parseIssueTypes(options.checkReferences);
12187
12732
  const context = {
12188
12733
  spaceId: space,
@@ -12192,6 +12737,27 @@ storiesCommand.command("find").description("Find stories matching filters and pr
12192
12737
  reporter,
12193
12738
  verbose
12194
12739
  };
12740
+ if (strataQuery) {
12741
+ const search = await searchStrata({
12742
+ spaceId: space,
12743
+ query: strataQuery,
12744
+ ui
12745
+ });
12746
+ await runFind({
12747
+ ...context,
12748
+ params: {
12749
+ ...params,
12750
+ by_ids: [...search.ranking.keys()].join(",")
12751
+ },
12752
+ preContentFilters,
12753
+ filters: whereFilters,
12754
+ skipContent: options.skipContent === true,
12755
+ limit,
12756
+ limitIsDefault: semanticLimit?.isDefault,
12757
+ semantic: search
12758
+ });
12759
+ return;
12760
+ }
12195
12761
  const capi = options.capiFilter ? await prepareCapiFilter({
12196
12762
  spaceId: space,
12197
12763
  region: state.region,
@@ -17032,7 +17598,6 @@ const program = getProgram();
17032
17598
  const ui = getUI();
17033
17599
  ui.br();
17034
17600
  ui.title("Storyblok CLI", colorPalette.PRIMARY);
17035
- ui.br();
17036
17601
  program.on("command:*", () => {
17037
17602
  console.error(`Invalid command: ${program.args.join(" ")}`);
17038
17603
  console.error("");