storyblok 4.25.0 → 4.26.0

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.d.mts CHANGED
@@ -416,18 +416,10 @@ type TableFieldValue2 = {
416
416
  }>;
417
417
  };
418
418
  /**
419
- * Plugin/Custom field type - field plugin with custom structure
419
+ * Custom field value stored by a field plugin. Any JSON value.
420
420
  */
421
- type PluginFieldValue2 = {
422
- /**
423
- * Technical name of the field plugin
424
- */
425
- plugin: string;
426
- /**
427
- * Unique identifier for this plugin field instance
428
- */
429
- _uid?: string;
430
- [key: string]: unknown;
421
+ type PluginFieldValue2 = null | string | number | boolean | Array<PluginFieldValue2> | {
422
+ [key: string]: PluginFieldValue2;
431
423
  };
432
424
  /**
433
425
  * Link to an internal Storyblok story.
package/dist/index.mjs CHANGED
@@ -2838,9 +2838,11 @@ function toWritableSchema(schema) {
2838
2838
  /**
2839
2839
  * Converts component `internal_tag_ids` from the response shape (`string[]`) to
2840
2840
  * the create/update request shape (`number[]`) — a known upstream inconsistency
2841
- * where the component serializer returns tag IDs as strings.
2841
+ * where the component serializer returns tag IDs as strings. `null` maps to
2842
+ * `[]`, which clears the tags.
2842
2843
  */
2843
2844
  function toRequestTagIds(tagIds) {
2845
+ if (tagIds === null) return [];
2844
2846
  if (!tagIds) return;
2845
2847
  return tagIds.map((id) => Number(id));
2846
2848
  }
@@ -2856,7 +2858,7 @@ const pushComponent = async (space, component) => {
2856
2858
  handleAPIError("push_component", error, `Failed to push component ${component.name}`);
2857
2859
  }
2858
2860
  };
2859
- const updateComponent = async (space, componentId, component) => {
2861
+ const updateComponent = async (space, componentId, component, errorMessage = `Failed to update component ${component.name}`) => {
2860
2862
  try {
2861
2863
  const { data } = await getMapiClient().components.update(componentId, {
2862
2864
  path: { space_id: Number(space) },
@@ -2865,24 +2867,27 @@ const updateComponent = async (space, componentId, component) => {
2865
2867
  });
2866
2868
  return data?.component;
2867
2869
  } catch (error) {
2868
- handleAPIError("update_component", error, `Failed to update component ${component.name}`);
2870
+ handleAPIError("update_component", error, errorMessage);
2869
2871
  }
2870
2872
  };
2871
2873
  const upsertComponent = async (space, component, existingId) => {
2872
- const { name, display_name, description, schema, is_root, is_nestable, component_group_uuid, color, icon, preview_field, preview_tmpl, internal_tag_ids } = component;
2873
2874
  const payload = {
2874
- name,
2875
- display_name: display_name ?? void 0,
2876
- description: description ?? void 0,
2877
- schema: toWritableSchema(schema),
2878
- is_root,
2879
- is_nestable,
2880
- component_group_uuid: component_group_uuid ?? void 0,
2881
- color: color ?? void 0,
2882
- icon: icon ?? void 0,
2883
- preview_field: preview_field ?? void 0,
2884
- preview_tmpl: preview_tmpl ?? void 0,
2885
- internal_tag_ids: toRequestTagIds(internal_tag_ids)
2875
+ name: component.name,
2876
+ display_name: component.display_name,
2877
+ description: component.description,
2878
+ preview_tmpl: component.preview_tmpl,
2879
+ image: component.image,
2880
+ preview_field: component.preview_field,
2881
+ is_root: component.is_root,
2882
+ is_nestable: component.is_nestable,
2883
+ preset_id: component.preset_id,
2884
+ component_group_uuid: component.component_group_uuid,
2885
+ color: component.color,
2886
+ icon: component.icon,
2887
+ content_type_asset_preview: component.content_type_asset_preview,
2888
+ internal_tag_ids: toRequestTagIds(component.internal_tag_ids),
2889
+ schema: toWritableSchema(component.schema),
2890
+ metadata: component.metadata === null ? {} : component.metadata
2886
2891
  };
2887
2892
  if (existingId) return await updateComponent(space, existingId, payload);
2888
2893
  else return await pushComponent(space, payload);
@@ -3088,10 +3093,6 @@ function buildDependencyGraph(context) {
3088
3093
  addDependency(componentId, tagNodeId);
3089
3094
  });
3090
3095
  if (component.component_group_uuid) addDependency(componentId, `group:${component.component_group_uuid}`);
3091
- if (component.preset_id) {
3092
- const preset = spaceState.local.presets.find((p) => p.id === component.preset_id);
3093
- if (preset) addDependency(componentId, `preset:${preset.id}`);
3094
- }
3095
3096
  if (component.schema) {
3096
3097
  const dependencies = collectWhitelistDependencies(component.schema);
3097
3098
  dependencies.groupUuids.forEach((groupUuid) => {
@@ -3367,9 +3368,34 @@ var GroupNode = class extends GraphNode {
3367
3368
  }
3368
3369
  };
3369
3370
  var ComponentNode = class extends GraphNode {
3371
+ /** Default preset that did not exist in the target when references were resolved. */
3372
+ pendingPresetNodeId;
3373
+ upserted = false;
3374
+ /** Shown in the terminal once processing ends, so they don't break the progress bars. */
3375
+ warnings = [];
3370
3376
  constructor(id, data, targetComponent) {
3371
3377
  super(id, "component", data.name, data, targetComponent);
3372
3378
  }
3379
+ warn(message) {
3380
+ getLogger().warn(message);
3381
+ this.warnings.push(message);
3382
+ }
3383
+ async linkPendingPreset(space, graph) {
3384
+ if (!this.pendingPresetNodeId || !this.upserted) return;
3385
+ const presetNode = graph.nodes.get(this.pendingPresetNodeId);
3386
+ const presetId = presetNode?.targetData?.id;
3387
+ const componentId = this.targetData?.id;
3388
+ if (typeof componentId !== "number") return;
3389
+ if (typeof presetId !== "number") {
3390
+ this.warn(`Default preset "${presetNode?.name}" of component ${this.name} failed to push. The default preset was not set.`);
3391
+ return;
3392
+ }
3393
+ const errorMessage = `Failed to set the default preset of component ${this.name}`;
3394
+ if (!await updateComponent(space, componentId, {
3395
+ name: this.name,
3396
+ preset_id: presetId
3397
+ }, errorMessage)) throw new Error(errorMessage);
3398
+ }
3373
3399
  resolveReferences(graph) {
3374
3400
  const updatedData = { ...this.sourceData };
3375
3401
  if (this.sourceData.component_group_uuid) {
@@ -3388,19 +3414,22 @@ var ComponentNode = class extends GraphNode {
3388
3414
  updatedData.internal_tag_ids = resolvedTagIds;
3389
3415
  }
3390
3416
  if (this.sourceData.preset_id) {
3391
- const preset = this.findPresetById(this.sourceData.preset_id, graph);
3392
- if (preset) {
3393
- const presetNodeId = `preset:${preset.id}`;
3394
- const presetNode = graph.nodes.get(presetNodeId);
3395
- if (presetNode?.targetData) updatedData.preset_id = presetNode.targetData.id;
3417
+ const presetNodeId = `preset:${this.sourceData.preset_id}`;
3418
+ const presetNode = graph.nodes.get(presetNodeId);
3419
+ if (!(presetNode instanceof PresetNode) || !this.ownsPreset(presetNode)) {
3420
+ this.warn(`Default preset ID ${this.sourceData.preset_id} of component ${this.name} is not one of its presets in local data. Keeping the target's default preset.`);
3421
+ updatedData.preset_id = void 0;
3422
+ } else if (presetNode.targetData) updatedData.preset_id = presetNode.targetData.resource.id;
3423
+ else {
3424
+ updatedData.preset_id = void 0;
3425
+ this.pendingPresetNodeId = presetNodeId;
3396
3426
  }
3397
3427
  }
3398
3428
  if (this.sourceData.schema) updatedData.schema = this.resolveSchemaReferences(this.sourceData.schema, graph);
3399
3429
  this.sourceData = updatedData;
3400
3430
  }
3401
- findPresetById(presetId, graph) {
3402
- for (const [_nodeId, node] of graph.nodes) if (node.type === "preset" && node.sourceData.id === presetId) return node.sourceData;
3403
- return null;
3431
+ ownsPreset(presetNode) {
3432
+ return presetNode.sourceComponentId === this.sourceData.id;
3404
3433
  }
3405
3434
  resolveSchemaReferences(schema, graph) {
3406
3435
  const resolvedSchema = JSON.parse(JSON.stringify(schema));
@@ -3431,6 +3460,7 @@ var ComponentNode = class extends GraphNode {
3431
3460
  const existingId = this.targetData?.id;
3432
3461
  const result = await upsertComponent(space, this.sourceData, existingId);
3433
3462
  if (!result) throw new Error(`Failed to upsert component ${this.name}`);
3463
+ this.upserted = true;
3434
3464
  return result;
3435
3465
  }
3436
3466
  };
@@ -3443,11 +3473,14 @@ var PresetNode = class {
3443
3473
  name;
3444
3474
  type = "preset";
3445
3475
  sourceData;
3476
+ /** `sourceData.component_id` changes to the target ID once references resolve. */
3477
+ sourceComponentId;
3446
3478
  targetData;
3447
3479
  dependencies = /* @__PURE__ */ new Set();
3448
3480
  dependents = /* @__PURE__ */ new Set();
3449
3481
  constructor(preset, targetData) {
3450
3482
  this.sourceData = preset;
3483
+ this.sourceComponentId = preset.component_id;
3451
3484
  this.targetData = targetData;
3452
3485
  this.id = `preset:${preset.id}`;
3453
3486
  this.name = preset.name;
@@ -3829,10 +3862,35 @@ async function processAllResources(graph, space, backpressure = getActiveConfig(
3829
3862
  try {
3830
3863
  for (const level of levels) if (level.isCyclic) mergeResults(results, await processCyclicLevel(level, graph, space, backpressure, bars));
3831
3864
  else mergeResults(results, await processLevel(level.nodes, graph, space, backpressure, bars));
3865
+ const linkResults = await linkPendingPresets(graph, space);
3866
+ const unlinkedNames = new Set(linkResults.failed.map(({ name }) => name));
3867
+ results.successful = results.successful.filter((name) => !unlinkedNames.has(name));
3868
+ mergeResults(results, linkResults);
3832
3869
  } finally {
3833
3870
  for (const bar of bars.values()) bar.stop();
3834
3871
  ui.stopAllProgressBars();
3835
3872
  }
3873
+ for (const node of graph.nodes.values()) if (node instanceof ComponentNode) node.warnings.forEach((warning) => ui.warn(warning));
3874
+ return results;
3875
+ }
3876
+ async function linkPendingPresets(graph, space) {
3877
+ const logger = getLogger();
3878
+ const results = {
3879
+ successful: [],
3880
+ failed: []
3881
+ };
3882
+ for (const node of graph.nodes.values()) {
3883
+ if (!(node instanceof ComponentNode)) continue;
3884
+ try {
3885
+ await node.linkPendingPreset(space, graph);
3886
+ } catch (error) {
3887
+ logger.error(`Failed to link default preset: ${node.getName()}`, { error });
3888
+ results.failed.push({
3889
+ name: node.getName(),
3890
+ error
3891
+ });
3892
+ }
3893
+ }
3836
3894
  return results;
3837
3895
  }
3838
3896
  /**
@@ -12437,21 +12495,29 @@ storiesCommand.command("push").option("-s, --space <space>", "space ID").option(
12437
12495
  }
12438
12496
  const warnAboutCustomPlugins = (story) => {
12439
12497
  const warned = /* @__PURE__ */ new Set();
12498
+ const warnOnce = (pluginName) => {
12499
+ if (warned.has(pluginName)) return;
12500
+ warned.add(pluginName);
12501
+ const message = `The custom plugin "${pluginName}" may contain references that require manual updates.`;
12502
+ pendingWarnings.push(message);
12503
+ logger.warn(message, { storyId: story.uuid });
12504
+ };
12440
12505
  const visit = (node) => {
12441
12506
  if (Array.isArray(node)) {
12442
12507
  for (const item of node) visit(item);
12443
12508
  return;
12444
12509
  }
12445
- if (!node || typeof node !== "object") return;
12446
- const obj = node;
12447
- const plugin = obj.plugin;
12448
- if (typeof plugin === "string" && !warned.has(plugin)) {
12449
- warned.add(plugin);
12450
- const message = `The custom plugin "${plugin}" may contain references that require manual updates.`;
12451
- pendingWarnings.push(message);
12452
- logger.warn(message, { storyId: story.uuid });
12510
+ if (!isRecord(node)) return;
12511
+ const schema = typeof node.component === "string" ? schemas[node.component] : void 0;
12512
+ if (schema) {
12513
+ for (const [fieldName, value] of Object.entries(node)) {
12514
+ const field = schema[baseFieldName(fieldName)];
12515
+ if (field?.type !== "custom") visit(value);
12516
+ else if (value !== null && value !== void 0 && value !== "") warnOnce(typeof field.field_type === "string" ? field.field_type : fieldName);
12517
+ }
12518
+ return;
12453
12519
  }
12454
- for (const value of Object.values(obj)) visit(value);
12520
+ for (const value of Object.values(node)) visit(value);
12455
12521
  };
12456
12522
  visit(story.content);
12457
12523
  };
@@ -13228,13 +13294,19 @@ const COMPONENT_STRIP_KEYS = /* @__PURE__ */ new Set([
13228
13294
  "preset_id",
13229
13295
  "all_presets",
13230
13296
  "internal_tags_list",
13231
- "content_type_asset_preview",
13232
- "image",
13233
- "preview_tmpl",
13234
13297
  "metadata",
13235
13298
  "component_group_uuid"
13236
13299
  ]);
13237
13300
  /**
13301
+ * Optional component properties a block manages only when it sets them: an
13302
+ * absent key leaves the remote value untouched, an explicit `null` clears it.
13303
+ */
13304
+ const COMPONENT_OPTIONAL_KEYS = [
13305
+ "image",
13306
+ "preview_tmpl",
13307
+ "content_type_asset_preview"
13308
+ ];
13309
+ /**
13238
13310
  * Every wire field key holding a restriction list. An empty list means what an
13239
13311
  * absent key means — no restriction — because the editor clears all six when you
13240
13312
  * switch restriction dimension, so a field restricted one way carries empty lists
@@ -13262,6 +13334,12 @@ const DATASOURCE_DIMENSION_STRIP_KEYS = /* @__PURE__ */ new Set([
13262
13334
  "updated_at"
13263
13335
  ]);
13264
13336
  /**
13337
+ * Default values for optional datasource fields.
13338
+ * Applied to both local and remote entities before diffing to prevent false diffs
13339
+ * from auto-populated fields (e.g. MAPI returns `dimensions: []` even when unset).
13340
+ */
13341
+ const DATASOURCE_DEFAULTS = { dimensions: [] };
13342
+ /**
13265
13343
  * Default values for optional component fields.
13266
13344
  * Applied to both local and remote entities before diffing, and always included in push payloads.
13267
13345
  *
@@ -13279,13 +13357,8 @@ const DATASOURCE_DIMENSION_STRIP_KEYS = /* @__PURE__ */ new Set([
13279
13357
  * - `component_group_uuid`: stripped before diffing (see COMPONENT_STRIP_KEYS)
13280
13358
  * unless a block opts into the group escape hatch by setting it explicitly;
13281
13359
  * diffing then keeps it on both sides so a changed group is pushed
13360
+ * - {@link COMPONENT_OPTIONAL_KEYS}: left untouched when a block omits them
13282
13361
  */
13283
- /**
13284
- * Default values for optional datasource fields.
13285
- * Applied to both local and remote entities before diffing to prevent false diffs
13286
- * from auto-populated fields (e.g. MAPI returns `dimensions: []` even when unset).
13287
- */
13288
- const DATASOURCE_DEFAULTS = { dimensions: [] };
13289
13362
  const COMPONENT_DEFAULTS = {
13290
13363
  display_name: "",
13291
13364
  description: "",
@@ -13320,6 +13393,10 @@ var RawCode = class {
13320
13393
  function quoteString(value) {
13321
13394
  return `'${JSON.stringify(value).slice(1, -1).replace(/\\"/g, "\"").replace(/'/g, "\\'")}'`;
13322
13395
  }
13396
+ const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
13397
+ function formatKey(key) {
13398
+ return IDENTIFIER.test(key) ? key : quoteString(key);
13399
+ }
13323
13400
  /**
13324
13401
  * Formats a JavaScript value as a multi-line code string.
13325
13402
  * All object properties are placed on separate lines.
@@ -13339,7 +13416,7 @@ function formatValue(value, depth) {
13339
13416
  if (typeof value === "object") {
13340
13417
  const entries = Object.entries(value).filter(([, v]) => v !== void 0 && v !== null).sort(([a], [b]) => a.localeCompare(b));
13341
13418
  if (entries.length === 0) return "{}";
13342
- return `{\n${entries.map(([key, val]) => `${innerIndent}${key}: ${formatValue(val, depth + 1)},`).join("\n")}\n${indent}}`;
13419
+ return `{\n${entries.map(([key, val]) => `${innerIndent}${formatKey(key)}: ${formatValue(val, depth + 1)},`).join("\n")}\n${indent}}`;
13343
13420
  }
13344
13421
  return String(value);
13345
13422
  }
@@ -13910,11 +13987,22 @@ function toPathSpace(comp, uuidToPath, manageFolder) {
13910
13987
  copy.schema = mapSchemaGroupLists(copy.schema, (entry) => uuidToPath.get(entry) ?? entry);
13911
13988
  return copy;
13912
13989
  }
13990
+ /**
13991
+ * An optional key either side omits is unmanaged, so it must never show as a
13992
+ * diff. A block held by one side only keeps them all: that side's values are
13993
+ * what creating or deleting the block sets or discards.
13994
+ */
13995
+ function omitUnmanagedOptionalKeys(comp, other) {
13996
+ if (!other) return comp;
13997
+ const copy = { ...comp };
13998
+ for (const key of COMPONENT_OPTIONAL_KEYS) if (comp[key] === void 0 || other[key] === void 0) delete copy[key];
13999
+ return copy;
14000
+ }
13913
14001
  function diffComponent(name, fromComp, toComp, context, compareGroupUuid, manageFolder) {
13914
14002
  const { uuidToPath, fromTag, toTag } = context;
13915
14003
  const includeGroupUuid = compareGroupUuid && typeof toComp?.component_group_uuid === "string";
13916
14004
  const byTagName = comparesTagsByName(fromComp, toComp, context.from, context.to);
13917
- return buildEntityDiff("component", name, fromComp ? cleanComponent(applyDefaults(toPathSpace(toTagSpace(fromComp, fromTag, byTagName), uuidToPath, manageFolder), COMPONENT_DEFAULTS), { includeGroupUuid }) : null, toComp ? cleanComponent(applyDefaults(toPathSpace(toTagSpace(toComp, toTag, byTagName), uuidToPath, manageFolder), COMPONENT_DEFAULTS), { includeGroupUuid }) : null);
14005
+ return buildEntityDiff("component", name, fromComp ? cleanComponent(applyDefaults(toPathSpace(toTagSpace(omitUnmanagedOptionalKeys(fromComp, toComp), fromTag, byTagName), uuidToPath, manageFolder), COMPONENT_DEFAULTS), { includeGroupUuid }) : null, toComp ? cleanComponent(applyDefaults(toPathSpace(toTagSpace(omitUnmanagedOptionalKeys(toComp, fromComp), toTag, byTagName), uuidToPath, manageFolder), COMPONENT_DEFAULTS), { includeGroupUuid }) : null);
13918
14006
  }
13919
14007
  function diffDatasource(name, fromDs, toDs) {
13920
14008
  return buildEntityDiff("datasource", name, fromDs ? cleanDatasource(applyDefaults(fromDs, DATASOURCE_DEFAULTS)) : null, toDs ? cleanDatasource(applyDefaults(toDs, DATASOURCE_DEFAULTS)) : null);
@@ -14698,6 +14786,7 @@ function generateFieldPluginFile(fieldType, varName) {
14698
14786
  "",
14699
14787
  "// Placeholder: accepts any value. Replace `value` with a Standard Schema validator",
14700
14788
  "// (Zod, Valibot, ArkType, or hand-written) for the value this plugin stores.",
14789
+ "// Declare `plugin` if the plugin stores it (legacy plugins do).",
14701
14790
  `export const ${varName} = defineFieldPlugin({`,
14702
14791
  ` fieldType: ${quoteString(fieldType)},`,
14703
14792
  ` value: {`,
@@ -15347,9 +15436,20 @@ function buildComponentPayload(input) {
15347
15436
  ...isRecord(input.schema) && { schema: toSchemaRecord(input.schema) },
15348
15437
  ...typeof input.is_root === "boolean" && { is_root: input.is_root },
15349
15438
  ...typeof input.is_nestable === "boolean" && { is_nestable: input.is_nestable },
15350
- ..."component_group_uuid" in input && (typeof input.component_group_uuid === "string" || input.component_group_uuid === null) && { component_group_uuid: input.component_group_uuid }
15439
+ ..."component_group_uuid" in input && (typeof input.component_group_uuid === "string" || input.component_group_uuid === null) && { component_group_uuid: input.component_group_uuid },
15440
+ ...toOptionalProperties(input)
15441
+ };
15442
+ }
15443
+ function toOptionalProperties(input) {
15444
+ return {
15445
+ image: toOptionalString(input.image),
15446
+ preview_tmpl: toOptionalString(input.preview_tmpl),
15447
+ content_type_asset_preview: toOptionalString(input.content_type_asset_preview)
15351
15448
  };
15352
15449
  }
15450
+ function toOptionalString(value) {
15451
+ return typeof value === "string" || value === null ? value : void 0;
15452
+ }
15353
15453
  /** Converts an unknown input to a ComponentCreate-compatible payload. */
15354
15454
  function toComponentCreate(input) {
15355
15455
  return buildComponentPayload(input);
@@ -16302,7 +16402,6 @@ const API_ASSIGNED_FIELDS = [
16302
16402
  "updated_at",
16303
16403
  "real_name",
16304
16404
  "all_presets",
16305
- "image",
16306
16405
  "uuid"
16307
16406
  ];
16308
16407
  /** Removes API-assigned fields from a raw changeset snapshot before sending as a create payload. */
@@ -16312,6 +16411,18 @@ function stripApiFields(payload) {
16312
16411
  return result;
16313
16412
  }
16314
16413
  /**
16414
+ * The pre-push snapshot an update rolls back to, without the optional component
16415
+ * properties the pushed block did not set: the push left those untouched, so
16416
+ * rolling back must too.
16417
+ */
16418
+ function restorableBefore(entry) {
16419
+ const before = { ...entry.before };
16420
+ if (entry.type === "component" && entry.after) {
16421
+ for (const key of COMPONENT_OPTIONAL_KEYS) if (!(key in entry.after)) delete before[key];
16422
+ }
16423
+ return before;
16424
+ }
16425
+ /**
16315
16426
  * Lists changeset JSON files sorted newest-first.
16316
16427
  *
16317
16428
  * @param basePath - Base storage directory (e.g. `.storyblok`).
@@ -16356,7 +16467,7 @@ function buildRollbackOps(changeset) {
16356
16467
  type: entry.type,
16357
16468
  name: entry.name,
16358
16469
  action: "update",
16359
- payload: entry.before ?? {}
16470
+ payload: restorableBefore(entry)
16360
16471
  };
16361
16472
  case "delete": return {
16362
16473
  type: entry.type,
@@ -16416,7 +16527,7 @@ function formatRollbackOutput(changes) {
16416
16527
  let toStr;
16417
16528
  if (entry.type === "component") {
16418
16529
  fromStr = serializeComponent(applyDefaults(entry.after, COMPONENT_DEFAULTS));
16419
- toStr = serializeComponent(applyDefaults(entry.before, COMPONENT_DEFAULTS));
16530
+ toStr = serializeComponent(applyDefaults(restorableBefore(entry), COMPONENT_DEFAULTS));
16420
16531
  } else if (entry.type === "datasource") {
16421
16532
  fromStr = serializeDatasource(entry.after);
16422
16533
  toStr = serializeDatasource(entry.before);