storyblok 4.23.2 → 4.23.3

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
@@ -17,6 +17,7 @@ import { confirm, input, password, select } from "@inquirer/prompts";
17
17
  import { exec, spawn } from "node:child_process";
18
18
  import { promisify } from "node:util";
19
19
  import { minimatch } from "minimatch";
20
+ import { createHash } from "node:crypto";
20
21
  import { Readable, Transform, Writable, pipeline } from "node:stream";
21
22
  import { Sema } from "async-sema";
22
23
  import { hash } from "ohash";
@@ -3906,6 +3907,89 @@ getProgram().command(commands.LANGUAGES).alias("lang").description(`Manage your
3906
3907
  });
3907
3908
  const migrationsCommand = getProgram().command(commands.MIGRATIONS).alias("mig").description(`Manage your space's migrations`);
3908
3909
  //#endregion
3910
+ //#region src/commands/migrations/migration-filename.ts
3911
+ /**
3912
+ * Migration files are named `<component>[.<suffix>].js`. A component name is
3913
+ * unconstrained remote data, so it is sanitized before it becomes a file name.
3914
+ *
3915
+ * Two things make that mapping ambiguous, and both are closed by rewriting the
3916
+ * name and appending a digest of the original:
3917
+ *
3918
+ * - Sanitizing is many-to-one: `hero:v2`, `hero/v2` and `hero?v2` all collapse
3919
+ * to `hero_v2`.
3920
+ * - A dot separates the component from the optional suffix, so `my.component`
3921
+ * is indistinguishable from component `my` with suffix `component`. A
3922
+ * generated name therefore never contains a dot, which makes the first dot in
3923
+ * a file name always the start of the suffix.
3924
+ *
3925
+ * Names are compared in NFC because the sanitizer emits NFD while the API
3926
+ * returns NFC, and macOS stores either.
3927
+ */
3928
+ const DIGEST_LENGTH = 6;
3929
+ const GLOB_WILDCARD = "*";
3930
+ const SUFFIX_SEPARATOR = ".";
3931
+ const SEPARATOR_REPLACEMENT = "_";
3932
+ const prefixCache = /* @__PURE__ */ new Map();
3933
+ const normalize = (value) => value.normalize("NFC");
3934
+ const sanitize = (value) => normalize(sanitizeFilename(value));
3935
+ /**
3936
+ * The file name a component's migrations live under, without the `.js`
3937
+ * extension or an optional suffix. Empty when the component name cannot be
3938
+ * mapped to a file name at all.
3939
+ */
3940
+ const getMigrationComponentPrefix = (componentName) => {
3941
+ const cached = prefixCache.get(componentName);
3942
+ if (cached !== void 0) return cached;
3943
+ const normalizedName = normalize(componentName);
3944
+ const sanitized = sanitize(normalizedName);
3945
+ const isUnambiguous = sanitized === normalizedName && !normalizedName.includes(SUFFIX_SEPARATOR);
3946
+ const digest = createHash("sha256").update(normalizedName).digest("hex").slice(0, DIGEST_LENGTH);
3947
+ const dotless = sanitized.replaceAll(SUFFIX_SEPARATOR, SEPARATOR_REPLACEMENT);
3948
+ const prefix = !sanitized || isUnambiguous ? sanitized : `${dotless}-${digest}`;
3949
+ prefixCache.set(componentName, prefix);
3950
+ return prefix;
3951
+ };
3952
+ /**
3953
+ * The file name CLI versions before the sanitizer wrote for a component, which
3954
+ * is the raw name. Only names the sanitizer alters have one: every other name
3955
+ * was already written the way it is written today. Empty when there is none.
3956
+ */
3957
+ const getLegacyMigrationComponentPrefix = (componentName) => {
3958
+ const normalizedName = normalize(componentName);
3959
+ return sanitize(normalizedName) === normalizedName ? "" : normalizedName;
3960
+ };
3961
+ const buildMigrationFilename = (componentName, suffix) => {
3962
+ const prefix = getMigrationComponentPrefix(componentName);
3963
+ return suffix ? `${prefix}.${suffix}.js` : `${prefix}.js`;
3964
+ };
3965
+ const migrationFilenameMatchesPrefix = (filename, prefix) => {
3966
+ if (!prefix) return false;
3967
+ const normalizedFilename = normalize(filename);
3968
+ return normalizedFilename === `${prefix}.js` || normalizedFilename.startsWith(`${prefix}.`) && normalizedFilename.endsWith(".js");
3969
+ };
3970
+ /**
3971
+ * Whether a file was written under a name the sanitizer would not produce, i.e.
3972
+ * by a CLI version that wrote component names verbatim. Recognizable from the
3973
+ * file name alone, so it does not need the space's component list.
3974
+ */
3975
+ const isLegacyMigrationFilename = (filename) => {
3976
+ const basename = normalize(filename).replace(/\.js$/, "");
3977
+ return basename !== sanitize(basename);
3978
+ };
3979
+ const migrationTargetsComponent = (filename, componentName) => typeof componentName === "string" && (migrationFilenameMatchesPrefix(filename, getMigrationComponentPrefix(componentName)) || migrationFilenameMatchesPrefix(filename, getLegacyMigrationComponentPrefix(componentName)));
3980
+ /**
3981
+ * Whether a `--filter` glob selects a file. The glob is matched against the
3982
+ * file name, against the file name the same glob's literal parts would be
3983
+ * written under, and against the file the filter targets when it is a plain
3984
+ * component name — so a user can filter by the name they know the component by
3985
+ * without knowing how it was mapped to a file name.
3986
+ */
3987
+ const migrationFilterMatches = (filename, filter) => {
3988
+ const normalizedFilename = normalize(filename);
3989
+ const sanitizedFilter = filter.split(GLOB_WILDCARD).map(sanitize).join(GLOB_WILDCARD);
3990
+ return createRegexFromGlob(filter).test(normalizedFilename) || createRegexFromGlob(sanitizedFilter).test(normalizedFilename) || migrationTargetsComponent(filename, filter);
3991
+ };
3992
+ //#endregion
3909
3993
  //#region src/commands/migrations/generate/actions.ts
3910
3994
  const getMigrationTemplate = () => {
3911
3995
  return `export default function (block) {
@@ -3924,13 +4008,13 @@ const getMigrationTemplate = () => {
3924
4008
  };
3925
4009
  const generateMigration = async (space, path, component, suffix) => {
3926
4010
  const resolvedPath = resolvePath(path, `migrations/${space}`);
3927
- const fileName = suffix ? `${component.name}.${suffix}.js` : `${component.name}.js`;
3928
- const migrationPath = join(resolvedPath, fileName);
4011
+ const migrationPath = join(resolvedPath, buildMigrationFilename(component.name, suffix));
3929
4012
  try {
3930
4013
  await saveToFile(migrationPath, getMigrationTemplate());
3931
4014
  } catch (error) {
3932
4015
  handleFileSystemError("write", error);
3933
4016
  }
4017
+ return migrationPath;
3934
4018
  };
3935
4019
  //#endregion
3936
4020
  //#region src/commands/migrations/generate/index.ts
@@ -3949,6 +4033,10 @@ migrationsCommand.command("generate [componentName]").description("Generate a mi
3949
4033
  handleError(new CommandError(`Please provide the component name as argument ${chalk.hex(colorPalette.MIGRATIONS)("storyblok migrations generate YOUR_COMPONENT_NAME.")}`), verbose);
3950
4034
  return;
3951
4035
  }
4036
+ if (suffix && sanitizeFilename(suffix) !== suffix) {
4037
+ handleError(new CommandError(`Invalid suffix "${suffix}". The suffix becomes part of the file name, so it cannot contain path separators or characters that are not allowed in file names.`), verbose);
4038
+ return;
4039
+ }
3952
4040
  const { state } = session();
3953
4041
  if (!requireAuthentication(state, verbose)) return;
3954
4042
  if (!space) {
@@ -3963,14 +4051,14 @@ migrationsCommand.command("generate [componentName]").description("Generate a mi
3963
4051
  handleError(new CommandError(`No component found with name "${componentName}"`), verbose);
3964
4052
  return;
3965
4053
  }
3966
- await generateMigration(space, path, component, suffix);
4054
+ const migrationPath = await generateMigration(space, path, component, suffix);
4055
+ const relativePath = relative(process.cwd(), migrationPath);
4056
+ const displayPath = relativePath.startsWith("..") ? migrationPath : relativePath;
3967
4057
  spinner.succeed(`Migration generated for component ${chalk.hex(colorPalette.MIGRATIONS)(componentName)} - Completed in ${spinner.elapsedTime.toFixed(2)}ms`);
3968
- const fileName = suffix ? `${component.name}.${suffix}.js` : `${component.name}.js`;
3969
- const migrationPath = path ? `${path}/migrations/${space}/${fileName}` : `.storyblok/migrations/${space}/${fileName}`;
3970
- ui.ok(`You can find the migration file in ${chalk.hex(colorPalette.MIGRATIONS)(migrationPath)}`);
4058
+ ui.ok(`You can find the migration file in ${chalk.hex(colorPalette.MIGRATIONS)(displayPath)}`);
3971
4059
  logger.info("Migration generation finished", {
3972
4060
  componentName: component.name,
3973
- migrationPath,
4061
+ migrationPath: displayPath,
3974
4062
  space,
3975
4063
  suffix
3976
4064
  });
@@ -4315,10 +4403,9 @@ async function readMigrationFiles(options) {
4315
4403
  try {
4316
4404
  const dirFiles = await readdir(resolvedPath);
4317
4405
  const migrationFiles = [];
4318
- const filterRegex = filter ? createRegexFromGlob(filter) : null;
4319
4406
  if (dirFiles.length > 0) for (const file of dirFiles) {
4320
4407
  if (!file.endsWith(".js")) continue;
4321
- if (filterRegex && !filterRegex.test(file)) continue;
4408
+ if (filter && !migrationFilterMatches(file, filter)) continue;
4322
4409
  migrationFiles.push({ name: file });
4323
4410
  }
4324
4411
  return migrationFiles;
@@ -4359,15 +4446,14 @@ async function getMigrationFunction(fileName, space, basePath) {
4359
4446
  * Recursively applies a migration function to all blocks in a content object that match the target component
4360
4447
  * @param content - The content object to process
4361
4448
  * @param migrationFunction - The migration function to apply
4362
- * @param targetComponent - The component name to target for migration
4449
+ * @param migrationFilename - The migration file name, which identifies the component it targets
4363
4450
  * @returns Whether any blocks were modified
4364
4451
  */
4365
- function applyMigrationToAllBlocks(content, migrationFunction, targetComponent) {
4452
+ function applyMigrationToAllBlocks(content, migrationFunction, migrationFilename) {
4366
4453
  let processed = false;
4367
4454
  if (!content || typeof content !== "object") return processed;
4368
- const baseTargetComponent = targetComponent.split(".")[0];
4369
4455
  let migratedContent = null;
4370
- if (content.component === baseTargetComponent) {
4456
+ if (migrationTargetsComponent(migrationFilename, content.component)) {
4371
4457
  migratedContent = migrationFunction({ ...content });
4372
4458
  processed = true;
4373
4459
  }
@@ -4382,11 +4468,11 @@ function applyMigrationToAllBlocks(content, migrationFunction, targetComponent)
4382
4468
  }
4383
4469
  if (Array.isArray(content[key])) {
4384
4470
  for (const value of content[key]) if (value && typeof value === "object" && "_uid" in value && "component" in value) {
4385
- const blockProcessed = applyMigrationToAllBlocks(value, migrationFunction, targetComponent);
4471
+ const blockProcessed = applyMigrationToAllBlocks(value, migrationFunction, migrationFilename);
4386
4472
  processed = processed || blockProcessed;
4387
4473
  }
4388
4474
  } else if (content[key] && typeof content[key] === "object" && "_uid" in content[key] && "component" in content[key]) {
4389
- const blockProcessed = applyMigrationToAllBlocks(content[key], migrationFunction, targetComponent);
4475
+ const blockProcessed = applyMigrationToAllBlocks(content[key], migrationFunction, migrationFilename);
4390
4476
  processed = processed || blockProcessed;
4391
4477
  }
4392
4478
  }
@@ -4484,9 +4570,7 @@ var MigrationStream = class extends Transform {
4484
4570
  return migrationFunction;
4485
4571
  }
4486
4572
  async processStory(story) {
4487
- const relevantMigrations = this.options.componentName ? this.options.migrationFiles.filter((file) => {
4488
- return getComponentNameFromFilename(file.name).split(".")[0] === this.options.componentName;
4489
- }) : this.options.migrationFiles;
4573
+ const relevantMigrations = this.options.componentName ? this.options.migrationFiles.filter((file) => migrationTargetsComponent(file.name, this.options.componentName)) : this.options.migrationFiles;
4490
4574
  if (!story.content) {
4491
4575
  this.results.failed.push({
4492
4576
  storyId: story.id,
@@ -4522,7 +4606,7 @@ var MigrationStream = class extends Transform {
4522
4606
  getLogger().error(error.message, { errorCode: ERROR_CODES.MIGRATION_FILE_NOT_FOUND });
4523
4607
  return null;
4524
4608
  }
4525
- const migrationProcessed = applyMigrationToAllBlocks(storyContent, migrationFunction, this.options.componentName || getComponentNameFromFilename(migrationFile.name));
4609
+ const migrationProcessed = applyMigrationToAllBlocks(storyContent, migrationFunction, migrationFile.name);
4526
4610
  processed = processed || migrationProcessed;
4527
4611
  }
4528
4612
  const contentChanged = originalContentHash !== hash(storyContent);
@@ -4570,9 +4654,7 @@ var MigrationStream = class extends Transform {
4570
4654
  });
4571
4655
  return null;
4572
4656
  } else {
4573
- const reason = migrationFiles.map((migrationFile) => {
4574
- return (this.options.componentName || getComponentNameFromFilename(migrationFile.name)).split(".")[0] === this.options.componentName ? `No matching components found for ${migrationFile.name}` : `Different component target ${migrationFile.name}`;
4575
- }).join("\n");
4657
+ const reason = migrationFiles.map((migrationFile) => `No matching components found for ${migrationFile.name}`).join("\n");
4576
4658
  this.results.skipped.push({
4577
4659
  storyId: story.id,
4578
4660
  name: story.name,
@@ -4832,9 +4914,7 @@ migrationsCommand.command("run [componentName]").description("Run migrations").o
4832
4914
  path,
4833
4915
  filter
4834
4916
  });
4835
- const filteredMigrations = componentName ? migrationFiles.filter((file) => {
4836
- return file.name.match(new RegExp(`^${componentName}(\\..*)?.js$`));
4837
- }) : migrationFiles;
4917
+ const filteredMigrations = componentName ? migrationFiles.filter((file) => migrationTargetsComponent(file.name, componentName)) : migrationFiles;
4838
4918
  if (filteredMigrations.length === 0) {
4839
4919
  spinner.failed(`No migration files found${componentName ? ` for component "${componentName}"` : ""}${filter ? ` matching filter "${filter}"` : ""} in space "${fromSpace}".`);
4840
4920
  logger.warn("No migration files found");
@@ -4842,6 +4922,12 @@ migrationsCommand.command("run [componentName]").description("Run migrations").o
4842
4922
  return;
4843
4923
  }
4844
4924
  spinner.succeed(`Found ${filteredMigrations.length} migration files.`);
4925
+ const legacyMigrations = filteredMigrations.filter((file) => isLegacyMigrationFilename(file.name));
4926
+ if (legacyMigrations.length > 0) {
4927
+ const names = legacyMigrations.map((file) => file.name).join(", ");
4928
+ ui.warn(`These migration files were generated by an older version and are still applied by their file name: ${names}. Regenerate them with "storyblok migrations generate <component-name>" so they keep working.`);
4929
+ logger.warn("Applying migration files generated under legacy names", { migrationNames: legacyMigrations.map((file) => file.name) });
4930
+ }
4845
4931
  const storiesProgress = ui.createProgressBar({ title: "Fetching Stories...".padEnd(19) });
4846
4932
  const migrationsProgress = ui.createProgressBar({ title: "Applying Migrations".padEnd(19) });
4847
4933
  const updateProgress = ui.createProgressBar({ title: "Updating Stories...".padEnd(19) });