storyblok 4.23.1 → 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) });
@@ -5002,6 +5088,69 @@ const STORYBLOK_PROPERTY_TYPES = {
5002
5088
  };
5003
5089
  const isStoryblokPropertyType = (type) => typeof type === "string" && Object.hasOwn(STORYBLOK_PROPERTY_TYPES, type);
5004
5090
  //#endregion
5091
+ //#region src/utils/user-module.ts
5092
+ /**
5093
+ * A missing file is a bad invocation, so it surfaces as a {@link CommandError}
5094
+ * instead of Node's resolution failure with its `Require stack:` dump. The file
5095
+ * is checked before the import rather than by inspecting the failure: a module
5096
+ * the file itself imports and cannot resolve raises `Cannot find module
5097
+ * '<specifier>'` with a `Require stack:` naming the file, so matching the path
5098
+ * against the message reported a missing dependency as a missing file.
5099
+ */
5100
+ async function resolveExistingFile(path, fileDescription) {
5101
+ const absolutePath = resolve(path);
5102
+ try {
5103
+ await stat(absolutePath);
5104
+ } catch {
5105
+ throw new CommandError(`${fileDescription} not found at "${path}".`);
5106
+ }
5107
+ return absolutePath;
5108
+ }
5109
+ /**
5110
+ * The path is resolved to an absolute path first, so jiti's base URL does not
5111
+ * affect which file is loaded; `tsconfigPaths` does read a tsconfig relative to
5112
+ * that base URL, but jiti evaluates each module through a child instance rooted
5113
+ * at the module itself, so the aliases applied to the file come from the user's
5114
+ * project and not from the CLI's own tsconfig.
5115
+ */
5116
+ async function createUserModuleJiti(options) {
5117
+ const { createJiti } = await import("jiti");
5118
+ return createJiti(import.meta.url, {
5119
+ interopDefault: options.interopDefault,
5120
+ tsconfigPaths: process.env.JITI_TSCONFIG_PATHS !== "false"
5121
+ });
5122
+ }
5123
+ /**
5124
+ * Loads a user-provided `.ts`, `.js`, `.mjs`, `.cjs`, or `.json` file and
5125
+ * returns all of its exports.
5126
+ */
5127
+ async function importUserModule(path, fileDescription) {
5128
+ const absolutePath = await resolveExistingFile(path, fileDescription);
5129
+ return await (await createUserModuleJiti({ interopDefault: true })).import(absolutePath);
5130
+ }
5131
+ /**
5132
+ * Loads a user-provided `.ts`, `.js`, `.mjs`, `.cjs`, or `.json` file and
5133
+ * returns its default export (`module.exports` for CommonJS, the parsed content
5134
+ * for JSON), or `undefined` when it has none. Named exports are never used in
5135
+ * its place, so a file without a default export can be reported as such.
5136
+ */
5137
+ async function importUserModuleDefault(path, fileDescription) {
5138
+ const absolutePath = await resolveExistingFile(path, fileDescription);
5139
+ if (extname(absolutePath) === ".json") return parseJsonFile(absolutePath, path, fileDescription);
5140
+ const userModule = await (await createUserModuleJiti({ interopDefault: false })).import(absolutePath);
5141
+ return await (isEsModuleNamespace(userModule) ? userModule.default : userModule);
5142
+ }
5143
+ async function parseJsonFile(absolutePath, path, fileDescription) {
5144
+ try {
5145
+ return JSON.parse(await readFile(absolutePath, "utf8"));
5146
+ } catch (error) {
5147
+ throw new CommandError(`${fileDescription} at "${path}" is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
5148
+ }
5149
+ }
5150
+ function isEsModuleNamespace(value) {
5151
+ return Object.prototype.toString.call(value) === "[object Module]" || isRecord(value) && value.__esModule === true;
5152
+ }
5153
+ //#endregion
5005
5154
  //#region src/commands/types/generate/utils.ts
5006
5155
  /**
5007
5156
  * Explicit type-name overrides for Storyblok field types where the generated
@@ -5258,7 +5407,7 @@ const getComponentPropertiesTypeAnnotations = async (component, options, spaceDa
5258
5407
  if (isLayoutFieldType(propertyType)) return acc;
5259
5408
  const propertyTypeAnnotation = { [key]: getPropertyTypeAnnotation(schema, options.typePrefix, options.typeSuffix) };
5260
5409
  if (propertyType === "custom" && customFieldsParser) {
5261
- const customField = typeof customFieldsParser === "function" ? customFieldsParser(key, schema) : {};
5410
+ const customField = customFieldsParser(key, schema);
5262
5411
  return {
5263
5412
  ...acc,
5264
5413
  ...customField
@@ -5299,17 +5448,18 @@ const getComponentPropertiesTypeAnnotations = async (component, options, spaceDa
5299
5448
  };
5300
5449
  }, Promise.resolve({}));
5301
5450
  };
5302
- const loadCustomFieldsParser = async (path) => {
5303
- try {
5304
- return (await import(pathToFileURL(resolve(path)).href)).default;
5305
- } catch (error) {
5306
- handleError(error);
5307
- return;
5308
- }
5309
- };
5451
+ function isCustomFieldsParser(value) {
5452
+ return typeof value === "function";
5453
+ }
5454
+ async function loadCustomFieldsParser(path) {
5455
+ const parser = await importUserModuleDefault(path, "Custom fields parser file");
5456
+ if (!isCustomFieldsParser(parser)) throw new CommandError(`The custom fields parser file at "${path}" must default-export a function.`);
5457
+ return parser;
5458
+ }
5310
5459
  async function loadCompilerOptions(path) {
5311
- if (path) return (await import(pathToFileURL(resolve(path)).href)).default;
5312
- return {};
5460
+ const compilerOptions = await importUserModuleDefault(path, "Compiler options file");
5461
+ if (!isRecord(compilerOptions)) throw new CommandError(`The compiler options file at "${path}" must default-export an options object.`);
5462
+ return compilerOptions;
5313
5463
  }
5314
5464
  const generateTypes = async (spaceData, options = { strict: false }) => {
5315
5465
  try {
@@ -10055,36 +10205,13 @@ function collectSchemaExports(moduleExports) {
10055
10205
  };
10056
10206
  }
10057
10207
  /**
10058
- * Loads a TypeScript schema entry file via jiti and returns its raw module
10059
- * exports. The path is resolved to an absolute path first, so jiti's base URL
10060
- * does not affect which file is loaded; `tsconfigPaths` does read a tsconfig
10061
- * relative to that base URL, but jiti evaluates each module through a child
10062
- * instance rooted at the module itself, so the aliases applied to the entry
10063
- * file come from the user's project and not from the CLI's own tsconfig.
10208
+ * Loads a TypeScript schema entry file and returns its raw module exports.
10064
10209
  * Shared by `schema push` (wire mapping) and the validate commands (DSL
10065
- * shape). The jiti import throws when the path cannot be resolved — fatal for
10210
+ * shape). Throws when the file is missing or fails to evaluate — fatal for
10066
10211
  * the callers.
10067
- *
10068
- * A missing entry file is a bad invocation, so it surfaces as a
10069
- * {@link CommandError} instead of Node's resolution failure with its `Require
10070
- * stack:` dump. The file is checked before the import rather than by inspecting
10071
- * the failure: a module the entry file itself imports and cannot resolve raises
10072
- * `Cannot find module '<specifier>'` with a `Require stack:` naming the entry
10073
- * file, so matching the entry path against the message reported a missing
10074
- * dependency as a missing entry file.
10075
10212
  */
10076
10213
  async function loadSchemaModule(entryPath) {
10077
- const entryAbs = resolve(entryPath);
10078
- try {
10079
- await stat(entryAbs);
10080
- } catch {
10081
- throw new CommandError(`Schema entry file not found at "${entryPath}".`);
10082
- }
10083
- const { createJiti } = await import("jiti");
10084
- return await createJiti(import.meta.url, {
10085
- interopDefault: true,
10086
- tsconfigPaths: process.env.JITI_TSCONFIG_PATHS !== "false"
10087
- }).import(entryAbs);
10214
+ return await importUserModule(entryPath, "Schema entry file");
10088
10215
  }
10089
10216
  //#endregion
10090
10217
  //#region src/lib/validation/adapter.ts