@polotno/schema 0.2.0 → 0.4.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.
Files changed (55) hide show
  1. package/README.md +2 -2
  2. package/lib/bleed.d.ts +0 -1
  3. package/lib/bleed.js +0 -1
  4. package/lib/defaults.d.ts +44 -434
  5. package/lib/defaults.js +92 -243
  6. package/lib/design.schema.json +5 -0
  7. package/lib/errors.d.ts +23 -6
  8. package/lib/errors.js +5 -1
  9. package/lib/index.d.ts +3 -1
  10. package/lib/index.js +3 -1
  11. package/lib/migrate.d.ts +18 -3
  12. package/lib/migrate.js +120 -45
  13. package/lib/normalize.d.ts +20 -3
  14. package/lib/normalize.js +196 -50
  15. package/lib/schema.d.ts +14 -1
  16. package/lib/schema.js +537 -134
  17. package/lib/types-parity.d.ts +0 -1
  18. package/lib/types-parity.js +0 -1
  19. package/lib/types.d.ts +2 -1
  20. package/lib/types.js +0 -1
  21. package/package.json +8 -8
  22. package/lib/bleed.d.ts.map +0 -1
  23. package/lib/bleed.js.map +0 -1
  24. package/lib/constants.d.ts +0 -6
  25. package/lib/constants.d.ts.map +0 -1
  26. package/lib/constants.js +0 -61
  27. package/lib/constants.js.map +0 -1
  28. package/lib/defaults.d.ts.map +0 -1
  29. package/lib/defaults.js.map +0 -1
  30. package/lib/errors.d.ts.map +0 -1
  31. package/lib/errors.js.map +0 -1
  32. package/lib/index.d.ts.map +0 -1
  33. package/lib/index.js.map +0 -1
  34. package/lib/migrate.d.ts.map +0 -1
  35. package/lib/migrate.js.map +0 -1
  36. package/lib/normalize.d.ts.map +0 -1
  37. package/lib/normalize.js.map +0 -1
  38. package/lib/processors.d.ts +0 -13
  39. package/lib/processors.d.ts.map +0 -1
  40. package/lib/processors.js +0 -170
  41. package/lib/processors.js.map +0 -1
  42. package/lib/schema.d.ts.map +0 -1
  43. package/lib/schema.js.map +0 -1
  44. package/lib/traverse.d.ts +0 -3
  45. package/lib/traverse.d.ts.map +0 -1
  46. package/lib/traverse.js +0 -32
  47. package/lib/traverse.js.map +0 -1
  48. package/lib/types-parity.d.ts.map +0 -1
  49. package/lib/types-parity.js.map +0 -1
  50. package/lib/types.d.ts.map +0 -1
  51. package/lib/types.js.map +0 -1
  52. package/lib/validate.d.ts +0 -19
  53. package/lib/validate.d.ts.map +0 -1
  54. package/lib/validate.js +0 -383
  55. package/lib/validate.js.map +0 -1
package/lib/defaults.js CHANGED
@@ -1,254 +1,103 @@
1
- // Canonical default values for every Polotno element / container, extracted
2
- // verbatim from the core MST models (`packages/polotno/src/model/*-model.ts`).
3
- //
4
- // `normalizeDesign` / `validateDesign` read these. INTERIM STATE: core still
5
- // declares its own `.props({...})` literals (e.g. text-model.ts) — these tables
6
- // are currently a mirror, NOT yet the single source. The golden equivalence
7
- // test (`packages/polotno/src/model/schema-equivalence.test.ts`) makes any drift
8
- // between the two fail CI. Making core spread these back (so each literal lives
9
- // exactly once) is the deferred follow-up — see the plan's task #5.
10
- //
11
- // Rules:
12
- // - Only SCALAR defaults live here. Structural MST-typed fields (arrays, maps:
13
- // `animations`, `filters`, `children`, `cells`, `dash`, `colorsReplace`,
14
- // `colWidths`, `rowHeights`) are handled by the normalizer, not stored here.
15
- // - `id` (identifier) has no default; `custom` (frozen) defaults to undefined and
16
- // is only present when set — neither is listed.
17
- // - Private (`_`-prefixed) props are stripped on serialization — not listed.
18
- // - `legacyBackground` (maybe) has no default — only present when a migration sets it.
19
- export const NODE_DEFAULTS = {
20
- type: 'none',
21
- name: '',
22
- opacity: 1,
23
- visible: true,
24
- selectable: true,
25
- removable: true,
26
- alwaysOnTop: false,
27
- showInExport: true,
28
- };
29
- export const SHAPE_DEFAULTS = {
30
- ...NODE_DEFAULTS,
31
- x: 0,
32
- y: 0,
33
- width: 100,
34
- height: 100,
35
- rotation: 0,
36
- opacity: 1,
37
- blurEnabled: false,
38
- blurRadius: 10,
39
- brightnessEnabled: false,
40
- brightness: 0,
41
- sepiaEnabled: false,
42
- grayscaleEnabled: false,
43
- shadowEnabled: false,
44
- shadowBlur: 5,
45
- shadowOffsetX: 0,
46
- shadowOffsetY: 0,
47
- shadowColor: 'black',
48
- shadowOpacity: 1,
49
- visible: true,
50
- draggable: true,
51
- resizable: true,
52
- selectable: true,
53
- contentEditable: true,
54
- styleEditable: true,
55
- alwaysOnTop: false,
56
- showInExport: true,
57
- };
58
- export const IMAGE_DEFAULTS = {
59
- ...SHAPE_DEFAULTS,
60
- type: 'image',
61
- width: 100,
62
- height: 100,
63
- src: '',
64
- cropX: 0,
65
- cropY: 0,
66
- cropWidth: 1,
67
- cropHeight: 1,
68
- cornerRadius: 0,
69
- flipX: false,
70
- flipY: false,
71
- clipSrc: '',
72
- borderColor: 'black',
73
- borderSize: 0,
74
- keepRatio: false,
75
- stretchEnabled: false,
1
+ // Canonical text RENDERING defaults — the values every renderer assumes when a
2
+ // field is missing. Single source of truth: the zod text schema builds its
3
+ // `.default()`s from this map, and @polotno/core (`text-types.ts`) applies it
4
+ // to loose, un-normalized elements at render/measure time. zod-free on purpose
5
+ // so runtime consumers can import `@polotno/schema/defaults` without pulling
6
+ // the validator.
7
+ // Table-cell properties that inherit from the table element when a cell
8
+ // leaves them undefined. Shared by the editor's table model and the svg/html
9
+ // exporters so the inheritance vocabulary can't drift. (pdf-export uses a
10
+ // deliberate subset without stroke/strokeWidth — see its table.ts.)
11
+ export const TABLE_CELL_OVERRIDABLE_KEYS = [
12
+ 'fontSize',
13
+ 'fontFamily',
14
+ 'fontWeight',
15
+ 'fontStyle',
16
+ 'textDecoration',
17
+ 'textTransform',
18
+ 'fill',
19
+ 'align',
20
+ 'verticalAlign',
21
+ 'lineHeight',
22
+ 'letterSpacing',
23
+ 'strokeWidth',
24
+ 'stroke',
25
+ 'cellBackground',
26
+ 'cellPadding',
27
+ ];
28
+ /**
29
+ * Resolve cell inheritance: every overridable text property a cell leaves
30
+ * undefined is filled from the table element (canvas parity — no fallback
31
+ * literals downstream). Returns shallow clones; the input is untouched
32
+ * (source may be frozen JSON).
33
+ */
34
+ export const resolveTableCellDefaults = (element) => (element.cells || []).map((cell) => {
35
+ if (!cell)
36
+ return cell;
37
+ const c = { ...cell };
38
+ for (const key of TABLE_CELL_OVERRIDABLE_KEYS) {
39
+ if (c[key] === undefined)
40
+ c[key] = element[key];
41
+ }
42
+ return c;
43
+ });
44
+ /**
45
+ * Per-side border resolution: a cell's `borders[side]` overrides win over
46
+ * the table element's `border{Width,Style,Color}` (canvas table-model
47
+ * parity). Shared by the svg/html/pdf exporters.
48
+ */
49
+ export const resolveTableCellBorder = (cell, element, side) => {
50
+ const overrides = cell.borders?.[side];
51
+ return {
52
+ width: overrides?.width ?? element.borderWidth,
53
+ style: overrides?.style ?? element.borderStyle,
54
+ color: overrides?.color ?? element.borderColor,
55
+ };
56
+ };
57
+ /**
58
+ * How many pixels each border eats from a cell's interior — the inset between
59
+ * the cell rect and the box its text is laid out in.
60
+ *
61
+ * Outer perimeter borders are fully inset (the whole stroke lies inside the
62
+ * cell); inner gridlines are centred on the shared boundary, so only half the
63
+ * stroke intrudes and the other half lives in the neighbour. `cell` must carry
64
+ * its grid position (`row`, `col`, and the spans when it spans).
65
+ *
66
+ * Mirrors the editor's `TableCell.borderInsets` (polotno's table-model.ts),
67
+ * which is what the canvas places cell text with — that model still owns its
68
+ * own copy because it resolves borders through MST views with an isAlive
69
+ * guard.
70
+ */
71
+ export const tableCellBorderInsets = (cell, element) => {
72
+ const rowSpan = cell.rowSpan || 1;
73
+ const colSpan = cell.colSpan || 1;
74
+ const inset = (side, isOuter) => {
75
+ const b = resolveTableCellBorder(cell, element, side);
76
+ if (b.style === 'none' || !b.width)
77
+ return 0;
78
+ return isOuter ? b.width : b.width / 2;
79
+ };
80
+ return {
81
+ top: inset('top', cell.row === 0),
82
+ bottom: inset('bottom', cell.row + rowSpan === element.rows),
83
+ left: inset('left', cell.col === 0),
84
+ right: inset('right', cell.col + colSpan === element.cols),
85
+ };
76
86
  };
77
87
  export const TEXT_DEFAULTS = {
78
- ...SHAPE_DEFAULTS,
79
- type: 'text',
80
- text: '',
81
- placeholder: '',
82
88
  fontSize: 14,
83
89
  fontFamily: 'Roboto',
84
- fontStyle: 'normal',
85
90
  fontWeight: 'normal',
86
- textDecoration: '',
87
- textTransform: 'none',
88
- fill: 'black',
89
- align: 'center',
90
- width: 100,
91
- height: 0, // afterCreate sets round(fontSize * lineHeight) when falsy
92
- verticalAlign: 'top',
93
- strokeWidth: 0,
94
- stroke: 'black',
91
+ fontStyle: 'normal',
95
92
  lineHeight: 1.2,
96
93
  letterSpacing: 0,
97
- backgroundEnabled: false,
98
- backgroundColor: '#7ED321',
99
- backgroundOpacity: 1,
100
- backgroundCornerRadius: 0.5,
101
- backgroundPadding: 0.5,
102
- curveEnabled: false,
103
- curvePower: 0.5,
104
- };
105
- export const SVG_DEFAULTS = {
106
- ...SHAPE_DEFAULTS,
107
- type: 'svg',
108
- src: '',
109
- maskSrc: '',
110
- cropX: 0,
111
- cropY: 0,
112
- cropWidth: 1,
113
- cropHeight: 1,
114
- keepRatio: true,
115
- stretchEnabled: true,
116
- flipX: false,
117
- flipY: false,
118
- width: 100,
119
- height: 100,
120
- borderColor: 'black',
121
- borderSize: 0,
122
- cornerRadius: 0,
123
- };
124
- export const LINE_DEFAULTS = {
125
- ...SHAPE_DEFAULTS,
126
- type: 'line',
127
- width: 400,
128
- height: 10,
129
- color: 'black',
130
- startHead: '',
131
- endHead: '',
132
- };
133
- export const FIGURE_DEFAULTS = {
134
- ...SHAPE_DEFAULTS,
135
- type: 'figure',
136
- subType: 'rect',
137
- fill: 'rgb(0, 161, 255)',
138
- strokeWidth: 0,
139
- stroke: 'rgba(98, 197, 255, 1)',
140
- cornerRadius: 0,
141
- };
142
- export const GIF_DEFAULTS = {
143
- ...IMAGE_DEFAULTS,
144
- type: 'gif',
145
- duration: 0,
146
- keepRatio: true,
147
- };
148
- export const VIDEO_DEFAULTS = {
149
- ...IMAGE_DEFAULTS,
150
- type: 'video',
151
- duration: 0,
152
- startTime: 0,
153
- endTime: 1,
154
- volume: 1,
155
- speed: 1,
156
- };
157
- // TableElement inherits Shape (so blur/shadow are FILLED then stripped by the
158
- // table postProcessor — keep them here to match MST's fill-then-strip).
159
- export const TABLE_DEFAULTS = {
160
- ...SHAPE_DEFAULTS,
161
- type: 'table',
162
- width: 300,
163
- height: 200,
164
- rows: 3,
165
- cols: 3,
166
- borderColor: '#000000',
167
- borderWidth: 1,
168
- borderStyle: 'solid',
169
- fontSize: 30,
170
- fontFamily: 'Roboto',
171
- fontWeight: 'normal',
172
- fontStyle: 'normal',
173
- textDecoration: '',
174
94
  textTransform: 'none',
175
- fill: 'black',
95
+ textDecoration: '',
176
96
  align: 'center',
177
- verticalAlign: 'middle',
178
- lineHeight: 1.2,
179
- letterSpacing: 0,
180
- strokeWidth: 0,
97
+ fill: 'black',
181
98
  stroke: 'black',
182
- cellBackground: 'transparent',
183
- cellPadding: 4,
184
- };
185
- export const GROUP_DEFAULTS = {
186
- ...NODE_DEFAULTS,
187
- type: 'group',
188
- };
189
- // TableCell direct defaults (overridable `_`-prefixed styling props inherit from
190
- // the table and are not defaulted here).
191
- export const TABLE_CELL_DEFAULTS = {
192
- type: 'tablecell',
193
- text: '',
194
- opacity: 1,
195
- rowSpan: 1,
196
- colSpan: 1,
197
- name: '',
198
- };
199
- export const PAGE_DEFAULTS = {
200
- width: 'auto',
201
- height: 'auto',
202
- background: 'white',
203
- bleed: 0,
204
- duration: 5000,
205
- };
206
- export const AUDIO_DEFAULTS = {
207
- src: '',
208
- duration: 0,
209
- startTime: 0,
210
- endTime: 1,
211
- volume: 1,
212
- delay: 0,
213
- speed: 1,
214
- };
215
- export const FONT_DEFAULTS = {
216
- url: '',
217
- };
218
- // Serialized store-level fields (the subset `store.toJSON()` emits).
219
- export const STORE_DEFAULTS = {
220
- width: 1080,
221
- height: 1080,
222
- unit: 'px',
223
- dpi: 72,
224
- schemaVersion: 4,
225
- };
226
- export const CURRENT_SCHEMA_VERSION = 4;
227
- // Maps a built-in element `type` to its default table. Unknown/custom types
228
- // fall back to SHAPE_DEFAULTS (base normalization + passthrough).
229
- export const DEFAULTS_BY_TYPE = {
230
- image: IMAGE_DEFAULTS,
231
- text: TEXT_DEFAULTS,
232
- svg: SVG_DEFAULTS,
233
- line: LINE_DEFAULTS,
234
- figure: FIGURE_DEFAULTS,
235
- gif: GIF_DEFAULTS,
236
- video: VIDEO_DEFAULTS,
237
- table: TABLE_DEFAULTS,
238
- group: GROUP_DEFAULTS,
239
- };
240
- // Structural (MST-typed) empty defaults per element type — the arrays/maps MST
241
- // serializes as []/{} (DEFAULTS_BY_TYPE carries only scalars). Single source for
242
- // both normalize (fills them) and validate (marks them optional in partial mode).
243
- export const STRUCTURAL_DEFAULTS_BY_TYPE = {
244
- image: { animations: [], filters: {} },
245
- text: { animations: [], filters: {} },
246
- svg: { animations: [], filters: {}, colorsReplace: {} },
247
- line: { animations: [], filters: {}, dash: [] },
248
- figure: { animations: [], filters: {}, dash: [] },
249
- gif: { animations: [], filters: {} },
250
- video: { animations: [], filters: {} },
251
- table: { animations: [], filters: {}, colWidths: [], rowHeights: [], cells: [] },
252
- group: { animations: [], children: [] },
99
+ strokeWidth: 0,
100
+ strokeLineJoin: 'round',
101
+ curveEnabled: false,
102
+ curvePower: 0.5,
253
103
  };
254
- //# sourceMappingURL=defaults.js.map
@@ -175,6 +175,11 @@
175
175
  "type": "string",
176
176
  "description": "Unique identifier for the audio track."
177
177
  },
178
+ "name": {
179
+ "default": "",
180
+ "description": "Display name shown on the timeline.",
181
+ "type": "string"
182
+ },
178
183
  "src": {
179
184
  "default": "",
180
185
  "description": "URL or data URI of the audio file.",
package/lib/errors.d.ts CHANGED
@@ -5,13 +5,30 @@
5
5
  * release — never match on them. No classes, no instanceof — a code check
6
6
  * works on any copy of any package. See the error-codes table in the repo
7
7
  * root CLAUDE.md.
8
+ *
9
+ * `@polotno/schema` is the layer *below* `@polotno/core`, so it can't import
10
+ * core's shared error map — it defines its own. It only ever throws
11
+ * `DESIGN_INVALID`; the `details` shape here is kept identical to core's entry
12
+ * for that code, so a consumer sees the same fields whichever layer threw it.
8
13
  */
9
14
  /** Codes thrown by this package. Append-only. */
10
15
  export type PolotnoErrorCode = 'DESIGN_INVALID';
11
- export interface PolotnoError extends Error {
12
- code: PolotnoErrorCode;
13
- details?: Record<string, any>;
14
- cause?: unknown;
16
+ /** Exhaustive `details` shape per code (only `DESIGN_INVALID` here). */
17
+ export interface PolotnoErrorDetailsMap {
18
+ DESIGN_INVALID: {
19
+ errors: {
20
+ path: string;
21
+ message: string;
22
+ }[];
23
+ /** Recognised element types, when the design references an unknown one. */
24
+ knownTypes?: string[];
25
+ };
15
26
  }
16
- export declare function polotnoError(code: PolotnoErrorCode, message: string, details?: Record<string, any>, cause?: unknown): PolotnoError;
17
- //# sourceMappingURL=errors.d.ts.map
27
+ export type PolotnoError<Code extends PolotnoErrorCode = PolotnoErrorCode> = {
28
+ [K in Code]: Error & {
29
+ code: K;
30
+ details?: PolotnoErrorDetailsMap[K];
31
+ cause?: unknown;
32
+ };
33
+ }[Code];
34
+ export declare function polotnoError<Code extends PolotnoErrorCode>(code: Code, message: string, details?: PolotnoErrorDetailsMap[Code], cause?: unknown): PolotnoError<Code>;
package/lib/errors.js CHANGED
@@ -5,6 +5,11 @@
5
5
  * release — never match on them. No classes, no instanceof — a code check
6
6
  * works on any copy of any package. See the error-codes table in the repo
7
7
  * root CLAUDE.md.
8
+ *
9
+ * `@polotno/schema` is the layer *below* `@polotno/core`, so it can't import
10
+ * core's shared error map — it defines its own. It only ever throws
11
+ * `DESIGN_INVALID`; the `details` shape here is kept identical to core's entry
12
+ * for that code, so a consumer sees the same fields whichever layer threw it.
8
13
  */
9
14
  export function polotnoError(code, message, details, cause) {
10
15
  const err = new Error(message);
@@ -15,4 +20,3 @@ export function polotnoError(code, message, details, cause) {
15
20
  err.cause = cause;
16
21
  return err;
17
22
  }
18
- //# sourceMappingURL=errors.js.map
package/lib/index.d.ts CHANGED
@@ -1,9 +1,11 @@
1
1
  export type { PolotnoError, PolotnoErrorCode } from './errors.js';
2
2
  export { normalizeDesign, parseDesign } from './normalize.js';
3
3
  export type { ParseOptions } from './normalize.js';
4
+ export { migrateDesign } from './migrate.js';
5
+ export type { MigrateOptions } from './migrate.js';
4
6
  export { resolveBleed, ZERO_BLEED } from './bleed.js';
5
7
  export type { ResolvedBleed } from './bleed.js';
8
+ export { TEXT_DEFAULTS, TABLE_CELL_OVERRIDABLE_KEYS, resolveTableCellDefaults, resolveTableCellBorder, tableCellBorderInsets, } from './defaults.js';
6
9
  export { validateDesign, assertValidDesign, designSchemaLenient, designSchemaCanonical, CURRENT_SCHEMA_VERSION, } from './schema.js';
7
10
  export type { DesignInput, ValidationError, ValidationResult, ValidateOptions, } from './schema.js';
8
11
  export type * from './types.js';
9
- //# sourceMappingURL=index.d.ts.map
package/lib/index.js CHANGED
@@ -3,6 +3,8 @@
3
3
  // the generated JSON Schema; `./types` are the hand-written public TypeScript
4
4
  // types. zod is a regular dependency (normalize parses with it).
5
5
  export { normalizeDesign, parseDesign } from './normalize.js';
6
+ export { migrateDesign } from './migrate.js';
6
7
  export { resolveBleed, ZERO_BLEED } from './bleed.js';
8
+ // Also available zod-free via the `@polotno/schema/defaults` subpath.
9
+ export { TEXT_DEFAULTS, TABLE_CELL_OVERRIDABLE_KEYS, resolveTableCellDefaults, resolveTableCellBorder, tableCellBorderInsets, } from './defaults.js';
7
10
  export { validateDesign, assertValidDesign, designSchemaLenient, designSchemaCanonical, CURRENT_SCHEMA_VERSION, } from './schema.js';
8
- //# sourceMappingURL=index.js.map
package/lib/migrate.d.ts CHANGED
@@ -1,6 +1,21 @@
1
1
  export interface MigrateOptions {
2
- applyHtmlTextMigrations: boolean;
2
+ /**
3
+ * Whether the consumer renders text with the modern engines (HTML /
4
+ * render-tag). Two migrations only make sense there, and the editor can still
5
+ * be switched to the legacy Konva.Text renderer. Defaults to true because
6
+ * every converter uses the modern path; the editor passes its actual flag.
7
+ */
8
+ modernTextRenderer?: boolean;
9
+ /**
10
+ * Skip the v2→3 `legacyBackground` stamp, so a pre-v3 text background renders
11
+ * with the new per-line polygon instead of being frozen as a full rect.
12
+ * Default false — preserve the original visuals.
13
+ */
3
14
  modernizeTextBackground?: boolean;
4
15
  }
5
- export declare function migrateDesign(json: any, opts: MigrateOptions): any;
6
- //# sourceMappingURL=migrate.d.ts.map
16
+ /**
17
+ * Bring a design up to `CURRENT_SCHEMA_VERSION`. Returns a new object; the
18
+ * input is never mutated. A design already at the current version is returned
19
+ * unchanged apart from the clone.
20
+ */
21
+ export declare function migrateDesign<T>(json: T, options?: MigrateOptions): T;
package/lib/migrate.js CHANGED
@@ -1,58 +1,133 @@
1
- // Pure version of the schemaVersion migrations that live inline in core's
2
- // `store.loadJSON` (packages/polotno/src/model/store.ts). Extracted so both core
3
- // and standalone consumers share one implementation.
1
+ // Design-format migrations, one version step per block.
4
2
  //
5
- // Two steps (v1 letterSpacing, v3 legacyBackground) depend on which text
6
- // renderer is active — knowledge that lives in core `flags`, not in a schema
7
- // module. The caller passes that resolved boolean explicitly; core computes it
8
- // from `flags.htmlRenderEnabled || flags.renderTagTextEnabled`.
9
- import { forEveryNode } from './traverse.js';
10
- const ROOT_FONT_PX = 16;
11
- // Returns a deep-cloned, migrated design with `schemaVersion` removed. Safe to
12
- // pass straight into normalize (no extra clone needed).
13
- export function migrateDesign(json, opts) {
14
- const data = JSON.parse(JSON.stringify(json));
15
- const oldSchemaVersion = data.schemaVersion || 0;
16
- if (oldSchemaVersion < 1) {
17
- if (opts.applyHtmlTextMigrations) {
18
- // Old letterSpacing was authored in "rem" for HTML render; convert to the
19
- // canvas-consistent px-relative value.
20
- forEveryNode({ children: data.pages }, (element) => {
21
- if (element.type === 'text') {
22
- const oldSpacePx = element.letterSpacing * ROOT_FONT_PX;
23
- element.letterSpacing = oldSpacePx / element.fontSize;
24
- }
25
- });
3
+ // These used to live inside `polotno`'s `store.loadJSON`, which meant only the
4
+ // editor ran them: every converter received raw JSON and rendered a pre-v3
5
+ // document with post-v3 semantics. A design's meaning must not depend on which
6
+ // package opened it, so the migrations live here, in the layer below everything.
7
+ //
8
+ // Two rules keep this file honest:
9
+ //
10
+ // 1. **Pure JSON in, pure JSON out.** No DOM, no measurement, no MST. Schema is
11
+ // the bottom layer and dependency-free, and migrations run before any model
12
+ // or renderer exists. A change that can only be decided by measuring text
13
+ // is not a migration — stamp intent instead and let each renderer resolve it
14
+ // at paint time. `legacyBackground` (v2→3) is exactly that pattern: it
15
+ // records "this predates the per-line background" rather than baking in a
16
+ // rect, and every renderer branches on it.
17
+ // 2. **A missing `schemaVersion` means 0**, the oldest format — not the current
18
+ // one. Designs written before the field existed are precisely the ones that
19
+ // need migrating, so absence has to mean "old". `store.toJSON()` always
20
+ // stamps the current version, so a round-tripped design is never re-migrated.
21
+ import { CURRENT_SCHEMA_VERSION } from './schema.js';
22
+ import { TEXT_DEFAULTS } from './defaults.js';
23
+ /** Named effects that never used the -100..100 intensity range. */
24
+ const UNSCALED_FILTERS = ['warm', 'cold', 'natural'];
25
+ /**
26
+ * Local element walk. Schema sits below core, so it cannot use core's
27
+ * `forEveryNode` — but it visits the same element nodes: nested `children`
28
+ * recursively AND table `cells` one level deep. Miss the cells and a table's
29
+ * text silently skips every migration while the rest of the design gets it.
30
+ *
31
+ * Deliberately NOT the page objects themselves, which `forEveryNode` does hand
32
+ * to its callback (it treats pages as the root's children). Every migration
33
+ * here is element-scoped and no page-level key exists to migrate, so a page
34
+ * would only ever be a node the callback ignores. A future page-level migration
35
+ * needs its own `data.pages` loop — do not widen this one.
36
+ */
37
+ function forEveryElement(pages, cb) {
38
+ if (!Array.isArray(pages))
39
+ return;
40
+ const walk = (node) => {
41
+ if (Array.isArray(node.children)) {
42
+ for (const child of node.children) {
43
+ if (!child || typeof child !== 'object')
44
+ continue;
45
+ cb(child);
46
+ walk(child);
47
+ }
48
+ }
49
+ if (Array.isArray(node.cells)) {
50
+ for (const cell of node.cells) {
51
+ if (cell && typeof cell === 'object')
52
+ cb(cell);
53
+ }
26
54
  }
55
+ };
56
+ for (const page of pages) {
57
+ if (page && typeof page === 'object')
58
+ walk(page);
59
+ }
60
+ }
61
+ /**
62
+ * Bring a design up to `CURRENT_SCHEMA_VERSION`. Returns a new object; the
63
+ * input is never mutated. A design already at the current version is returned
64
+ * unchanged apart from the clone.
65
+ */
66
+ export function migrateDesign(json, options = {}) {
67
+ const { modernTextRenderer = true, modernizeTextBackground = false } = options;
68
+ // Guard BEFORE the round-trip: JSON.parse(JSON.stringify(undefined)) throws a
69
+ // raw SyntaxError, and a circular object throws TypeError. Non-designs must
70
+ // reach the zod pass untouched so they surface as a structured
71
+ // DESIGN_INVALID, per the error contract in the root CLAUDE.md.
72
+ if (!json || typeof json !== 'object')
73
+ return json;
74
+ const data = JSON.parse(JSON.stringify(json));
75
+ const from = data.schemaVersion || 0;
76
+ if (from < 1 && modernTextRenderer) {
77
+ // letterSpacing used to be applied as `rem` in the HTML render, which does
78
+ // not match the canvas. It became `letterSpacing * fontSize` in px, so the
79
+ // stored ratio has to be rebased from the 16px root font size.
80
+ const ROOT_FONT_PX = 16;
81
+ forEveryElement(data.pages, (element) => {
82
+ if (element.type !== 'text')
83
+ return;
84
+ // Guard the arithmetic: an element that never stored letterSpacing would
85
+ // otherwise be stamped with NaN, which serializes to null and fails
86
+ // validation downstream. Number.isFinite (not the global) so a
87
+ // stringly-typed value is rejected rather than coerced.
88
+ const { letterSpacing } = element;
89
+ if (!Number.isFinite(letterSpacing))
90
+ return;
91
+ // `fontSize` is OPTIONAL in raw JSON — the schema fills it from
92
+ // TEXT_DEFAULTS, but that happens AFTER migration, so reading it here
93
+ // finds nothing. Mirror the default instead of bailing: bailing leaves
94
+ // the rem-based value in place and the text renders with wrong spacing,
95
+ // silently. Division by zero is still a bail — no default rescues that.
96
+ const fontSize = Number.isFinite(element.fontSize)
97
+ ? element.fontSize
98
+ : TEXT_DEFAULTS.fontSize;
99
+ if (fontSize === 0)
100
+ return;
101
+ element.letterSpacing = (letterSpacing * ROOT_FONT_PX) / fontSize;
102
+ });
27
103
  }
28
- if (oldSchemaVersion < 2) {
29
- // Convert filter intensity from old -100..100 range to -1..1.
30
- forEveryNode({ children: data.pages }, (element) => {
31
- if (element.filters) {
32
- Object.keys(element.filters).forEach((filterType) => {
33
- if (['warm', 'cold', 'natural'].includes(filterType)) {
34
- return;
35
- }
36
- const filter = element.filters[filterType];
37
- if (filter && typeof filter.intensity === 'number') {
38
- filter.intensity = filter.intensity / 100;
39
- }
40
- });
104
+ if (from < 2) {
105
+ // Filter intensity moved from a -100..100 range to -1..1.
106
+ forEveryElement(data.pages, (element) => {
107
+ if (!element.filters)
108
+ return;
109
+ for (const filterType of Object.keys(element.filters)) {
110
+ // warm / cold / natural never used the numeric range.
111
+ if (UNSCALED_FILTERS.includes(filterType))
112
+ continue;
113
+ const filter = element.filters[filterType];
114
+ if (filter && typeof filter.intensity === 'number') {
115
+ filter.intensity = filter.intensity / 100;
116
+ }
41
117
  }
42
118
  });
43
119
  }
44
- if (oldSchemaVersion < 3 &&
45
- opts.applyHtmlTextMigrations &&
46
- !opts.modernizeTextBackground) {
47
- // Stamp pre-v3 text backgrounds so the old full-rect render is preserved.
48
- forEveryNode({ children: data.pages }, (element) => {
120
+ if (from < 3 && modernTextRenderer && !modernizeTextBackground) {
121
+ // Freeze pre-v3 rich-text backgrounds as full rects, so the old render is
122
+ // preserved exactly. See rule 2 in the header: intent, not geometry.
123
+ forEveryElement(data.pages, (element) => {
49
124
  if (element.type === 'text' && element.backgroundEnabled) {
50
125
  element.legacyBackground = true;
51
126
  }
52
127
  });
53
128
  }
54
- // oldSchemaVersion < 4: marker only (video time-anchor change), no transform.
55
- delete data.schemaVersion;
129
+ // v3→4 is a marker only: v4 is the video time-anchor render change. Nothing
130
+ // to transform, but the bump lets a future migration target pre-v4 designs.
131
+ data.schemaVersion = CURRENT_SCHEMA_VERSION;
56
132
  return data;
57
133
  }
58
- //# sourceMappingURL=migrate.js.map