uncial 0.0.7 → 2.0.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 (93) hide show
  1. package/README.md +82 -15
  2. package/dist/core/attributes.d.ts +21 -3
  3. package/dist/core/attributes.js +86 -15
  4. package/dist/core/defineBlock.js +26 -12
  5. package/dist/core/index.d.ts +3 -1
  6. package/dist/core/index.js +2 -1
  7. package/dist/core/issues.d.ts +7 -0
  8. package/dist/core/issues.js +9 -0
  9. package/dist/core/meta.js +2 -7
  10. package/dist/core/migrations.d.ts +30 -0
  11. package/dist/core/migrations.js +50 -0
  12. package/dist/core/normalize.d.ts +12 -1
  13. package/dist/core/normalize.js +123 -22
  14. package/dist/core/registry.d.ts +7 -0
  15. package/dist/core/registry.js +35 -4
  16. package/dist/core/runtime.d.ts +7 -0
  17. package/dist/core/types.d.ts +31 -3
  18. package/dist/core/validate.js +27 -7
  19. package/dist/editor/AttributeFieldControl.svelte +155 -7
  20. package/dist/editor/AttributeFieldControl.svelte.d.ts +1 -0
  21. package/dist/editor/BlockAttributesPanel.svelte +76 -44
  22. package/dist/editor/BlockAttributesPanel.svelte.d.ts +9 -1
  23. package/dist/editor/Editor.svelte +149 -27
  24. package/dist/editor/Editor.svelte.d.ts +37 -0
  25. package/dist/editor/RichTextAttributeEditor.svelte +75 -145
  26. package/dist/editor/RichTextAttributeEditor.svelte.d.ts +2 -1
  27. package/dist/editor/Toolbar.svelte +2 -3
  28. package/dist/editor/attributeTargets.d.ts +23 -0
  29. package/dist/editor/attributeTargets.js +21 -0
  30. package/dist/editor/attributesController.d.ts +12 -0
  31. package/dist/editor/attributesController.js +142 -230
  32. package/dist/editor/bindEditor.d.ts +7 -0
  33. package/dist/editor/bindEditor.js +141 -27
  34. package/dist/editor/chooseAttribute.d.ts +26 -0
  35. package/dist/editor/chooseAttribute.js +10 -0
  36. package/dist/editor/containerChildOps.d.ts +33 -0
  37. package/dist/editor/containerChildOps.js +115 -0
  38. package/dist/editor/dropdownDismiss.d.ts +18 -0
  39. package/dist/editor/dropdownDismiss.js +46 -0
  40. package/dist/editor/dropdownFloat.d.ts +16 -0
  41. package/dist/editor/dropdownFloat.js +127 -0
  42. package/dist/editor/index.d.ts +3 -1
  43. package/dist/editor/index.js +2 -1
  44. package/dist/editor/linkController.d.ts +19 -0
  45. package/dist/editor/linkController.js +72 -0
  46. package/dist/editor/toolbarFeatures.d.ts +12 -0
  47. package/dist/editor/toolbarFeatures.js +36 -0
  48. package/dist/index.d.ts +1 -0
  49. package/dist/index.js +1 -0
  50. package/dist/render/Renderer.svelte +1 -1
  51. package/dist/render/RichContent.svelte +12 -4
  52. package/dist/render/RichContent.svelte.d.ts +2 -0
  53. package/dist/render/RichNode.svelte +80 -10
  54. package/dist/render/RichNode.svelte.d.ts +2 -0
  55. package/dist/render/Tab.svelte +27 -0
  56. package/dist/render/Tab.svelte.d.ts +10 -0
  57. package/dist/render/Tabs.svelte +57 -0
  58. package/dist/render/Tabs.svelte.d.ts +10 -0
  59. package/dist/render/index.d.ts +3 -0
  60. package/dist/render/index.js +6 -0
  61. package/dist/render/sanitize.d.ts +6 -0
  62. package/dist/render/sanitize.js +20 -1
  63. package/dist/render/tabSelection.svelte.d.ts +8 -0
  64. package/dist/render/tabSelection.svelte.js +40 -0
  65. package/dist/runtime/reactiveProps.svelte.d.ts +16 -0
  66. package/dist/runtime/reactiveProps.svelte.js +16 -0
  67. package/dist/runtime/svelte.d.ts +2 -1
  68. package/dist/runtime/svelte.js +26 -6
  69. package/dist/shared/EditorBlockFixture.svelte +24 -0
  70. package/dist/shared/EditorBlockFixture.svelte.d.ts +9 -0
  71. package/dist/shared/content.js +2 -1
  72. package/dist/shared/documentIdentity.d.ts +6 -0
  73. package/dist/shared/documentIdentity.js +64 -0
  74. package/dist/shared/guards.d.ts +13 -0
  75. package/dist/shared/guards.js +16 -0
  76. package/dist/shared/richText.js +20 -4
  77. package/dist/shared/runtimeId.d.ts +8 -0
  78. package/dist/shared/runtimeId.js +8 -0
  79. package/dist/shared/syntaxHighlight.d.ts +14 -0
  80. package/dist/shared/syntaxHighlight.js +36 -3
  81. package/dist/shared/tiptap.js +140 -27
  82. package/dist/styles/base.css +177 -0
  83. package/dist/styles/prose.css +26 -0
  84. package/dist/styles/tokens.css +53 -69
  85. package/dist/tabs.d.ts +6 -0
  86. package/dist/tabs.js +36 -0
  87. package/dist/web-components/UncialEditor.svelte +23 -7
  88. package/dist/web-components/UncialEditor.svelte.d.ts +7 -2
  89. package/dist/web-components/index.d.ts +45 -10
  90. package/dist/web-components/index.js +98 -36
  91. package/dist/web-components/reactiveProps.svelte.d.ts +10 -0
  92. package/dist/web-components/reactiveProps.svelte.js +13 -0
  93. package/package.json +134 -133
package/README.md CHANGED
@@ -73,9 +73,7 @@ Then register and use that component as an Uncial block:
73
73
  label: 'Promo Card',
74
74
  attributes: {
75
75
  title: '',
76
- featured: false,
77
- priority: 0,
78
- metadata: { default: { theme: 'sand' }, input: 'json' }
76
+ body: { default: '', input: 'textarea' }
79
77
  },
80
78
  component: PromoCard
81
79
  });
@@ -110,17 +108,56 @@ Object.assign(renderer, { blocks, schema, content: document });
110
108
 
111
109
  const editor = document.querySelector('uncial-editor');
112
110
  Object.assign(editor, { blocks, schema, json: document, attributesController });
111
+
112
+ // Document metadata mirrors the document body: set `metaFields` to render the
113
+ // metadata editor and read/write `meta` for the current values.
114
+ Object.assign(editor, { metaFields, meta: document.meta });
113
115
  ```
114
116
 
115
117
  ```html
116
118
  <uncial-editor></uncial-editor> <uncial-renderer></uncial-renderer>
117
119
  ```
118
120
 
121
+ Property assignments update the mounted component in place. Setting `editor.json = nextDocument` syncs the existing Tiptap editor through `setContent` instead of recreating it, so focus, selection, and undo history survive external document updates.
122
+
123
+ > **Configuration is via JS properties, not HTML attributes — by design.** The
124
+ > element inputs (`blocks`, `schema`, `json`, `meta`, `metaFields`, `extensions`,
125
+ > controllers, …) are structured objects, functions, and Svelte components that
126
+ > do not round-trip through string HTML attributes, so `<uncial-editor json="…">`
127
+ > is intentionally **not** observed. The one exception is `stylesheet` (a plain
128
+ > URL string), which is reflected as an attribute (see below). Set everything else
129
+ > as a property (`el.json = …`) after the element is in the DOM.
130
+
131
+ ### Styling the shadow root
132
+
133
+ Both elements render into an open shadow root, so page-level stylesheets do not reach them. Pass one or more whitespace-separated stylesheet URLs through the `stylesheet` attribute (or matching DOM property); each URL is rendered as a `<link rel="stylesheet">` inside the shadow root:
134
+
135
+ ```html
136
+ <uncial-editor stylesheet="https://unpkg.com/uncial/dist/styles/index.css"></uncial-editor>
137
+ ```
138
+
139
+ With a bundler such as Vite, resolve the packaged CSS to a URL:
140
+
141
+ ```ts
142
+ import uncialStylesHref from 'uncial/styles?url';
143
+
144
+ const editor = document.querySelector('uncial-editor');
145
+ editor.stylesheet = uncialStylesHref;
146
+ ```
147
+
148
+ A URL-based hook is used because the package ships its default CSS as plain files (`uncial/styles`, `uncial/styles/chrome`, ...) that any bundler, CDN, or asset pipeline can serve, and the `@import` chains inside them resolve relative to the linked URL — something constructed stylesheets (`adoptedStyleSheets`) do not support. Because the shadow root is open, advanced hosts can still inject constructed stylesheets themselves via `element.shadowRoot.adoptedStyleSheets`. The `--uncial-*` custom properties inherit across the shadow boundary, so token-based theming on a wrapper element keeps working (see [Styling and customization](#styling-and-customization)).
149
+
150
+ ### Events
151
+
119
152
  Validation callbacks are emitted as bubbling, composed DOM events. Editor document updates are emitted as `uncial-change` because non-Svelte hosts cannot use `bind:json`:
120
153
 
121
154
  ```ts
122
155
  editor.addEventListener('uncial-change', (event) => {
123
- document = event.detail;
156
+ document = event.detail; // the normalized document JSON; editor.json reflects the same value
157
+ });
158
+
159
+ editor.addEventListener('uncial-meta-change', (event) => {
160
+ meta = event.detail; // the committed document metadata; editor.meta reflects the same value
124
161
  });
125
162
 
126
163
  renderer.addEventListener('uncial-issue', (event) => {
@@ -128,6 +165,8 @@ renderer.addEventListener('uncial-issue', (event) => {
128
165
  });
129
166
  ```
130
167
 
168
+ `uncial-change` fires for edits made inside the editor, and at most once after an external `editor.json` assignment (only when normalization changes the incoming document, for example by stamping a version). Feeding a previously emitted document back into `editor.json` is a no-op, so hosts can mirror the value into their own state without creating an update loop. `uncial-meta-change` fires when document metadata is committed through the metadata editor and mirrors the value onto `editor.meta`, exactly as `uncial-change` does for `editor.json`. `uncial-issue` fires on both elements whenever normalization or validation reports a problem.
169
+
131
170
  For SSR frameworks, import `uncial/web-components` on the client only. Svelte blocks still render through the Svelte renderer for SSR; non-Svelte block runtimes should provide their own full-document renderer rather than relying on mixed component islands.
132
171
 
133
172
  ## Runtime plugins
@@ -284,27 +323,35 @@ Use `component` when the same Svelte component should render in both the editor
284
323
  const hero = defineSvelteBlock({
285
324
  id: 'hero',
286
325
  label: 'Hero',
326
+ description: 'Full-width intro banner', // optional; shown in the insert menu
287
327
  attributes: {
288
328
  title: '',
289
329
  subtitle: { default: '', input: 'textarea' },
290
330
  featured: false,
291
331
  priority: 1,
332
+ align: { default: 'left', options: ['left', 'center', 'right'] },
292
333
  settings: { default: { align: 'left' }, input: 'json' }
293
334
  },
294
335
  component: Hero
295
336
  });
296
337
  ```
297
338
 
298
- Attribute specs support:
339
+ A bare value (`title: ''`) is shorthand for `{ default: '' }`. The full attribute
340
+ spec supports:
299
341
 
300
342
  - `default`: required default value
301
343
  - `required`: require a value at validation time
302
344
  - `validate`: custom validation predicate
303
345
  - `parse`: custom coercion from editor or serialized input
304
346
  - `serialize`: custom serialization for HTML persistence
305
- - `input`: one of `text`, `textarea`, `number`, `checkbox`, or `json`
347
+ - `input`: editor control hint — `text`, `textarea`, `number`, `checkbox`, `json`, `select`, `richtext`, or `hidden`. When omitted it is inferred from the default value (and from `options`, which implies `select`).
348
+ - `options`: allowed values for `select` inputs, either plain values or `{ value, label, description }` objects
349
+ - `richText`: for `richtext` inputs, a `{ features, placeholder }` object controlling the nested rich-text feature allowlist
306
350
  - `placeholder`: optional editor placeholder
307
351
 
352
+ Blocks themselves also accept an optional `description` and `icon` (an icon name,
353
+ inline markup, or a Svelte component) that surface in the editor's insert menu.
354
+
308
355
  Blocks can also opt into child content:
309
356
 
310
357
  ```ts
@@ -368,8 +415,7 @@ Use `validateDocument(...)` directly or pass `onIssue` into `Editor` or `Rendere
368
415
  {schema}
369
416
  bind:json={document}
370
417
  onIssue={(issue) => console.warn(issue.code, issue.path)}
371
- /
372
- >
418
+ />
373
419
  ```
374
420
 
375
421
  ## Rendering and security
@@ -379,28 +425,49 @@ Use `validateDocument(...)` directly or pass `onIssue` into `Editor` or `Rendere
379
425
  - Links are sanitized to allow only `http`, `https`, `mailto`, `tel`, relative paths, and hash links
380
426
  - Custom block components and `html.render` hooks are trusted application code; sanitize any raw HTML or navigation attributes they emit
381
427
 
428
+ ## SSR usage
429
+
430
+ The renderer is safe to import in a server bundle. Import from the granular entry points so
431
+ the editor mount stack (Tiptap, `BlockNodeView`, `mount()`/`unmount()`) never reaches your
432
+ server:
433
+
434
+ ```ts
435
+ import { Renderer } from 'uncial/render';
436
+ import { defineSvelteBlock, createBlockRegistry, createSchema } from 'uncial/core';
437
+ ```
438
+
439
+ `uncial/render` and `uncial/core` are free of browser-only editor machinery — a regression
440
+ test walks the `render/` import graph and fails if an editor/runtime import creeps back in.
441
+
442
+ The package root barrel (`import … from 'uncial'`) re-exports `uncial/editor` as well, so
443
+ importing from the root **does** pull the editor graph into your bundle. For SSR, prefer the
444
+ `uncial/render` + `uncial/core` entry points over the root barrel.
445
+
446
+ > TODO: a future major may drop `./editor` from the root barrel so `import 'uncial'` is
447
+ > SSR-lean by default. Until then, use the granular entry points on the server.
448
+
382
449
  ## Development
383
450
 
384
451
  ```sh
385
- bun run check
386
- bun run test:unit -- --run
387
- bun run build
452
+ pnpm run check
453
+ pnpm run test:unit -- --run
454
+ pnpm run build
388
455
  ```
389
456
 
390
457
  Additional suites:
391
458
 
392
- - `bun run test:browser -- --run` for browser-backed Svelte component tests
393
- - `bun run test:e2e` for Playwright end-to-end tests
459
+ - `pnpm run test:browser -- --run` for browser-backed Svelte component tests
460
+ - `pnpm run test:e2e` for Playwright end-to-end tests
394
461
 
395
462
  Browser-backed tests require Playwright browsers to be installed:
396
463
 
397
464
  ```sh
398
- bunx playwright install
465
+ pnpm exec playwright install
399
466
  ```
400
467
 
401
468
  ## Releasing
402
469
 
403
- For user-facing library changes, run `bun run changeset` and commit the generated changeset with your PR. After regular PRs merge into `main`, Changesets opens or updates a version PR. Merging that version PR publishes `uncial` to npm with trusted publishing/provenance and creates the GitHub release.
470
+ For user-facing library changes, run `pnpm run changeset` and commit the generated changeset with your PR. After regular PRs merge into `main`, Changesets opens or updates a version PR. Merging that version PR publishes `uncial` to npm with trusted publishing/provenance and creates the GitHub release.
404
471
 
405
472
  ## Status
406
473
 
@@ -1,5 +1,17 @@
1
- import type { AttributeInputKind, AttributeOption, AttributeSpec, BlockDefinition } from './types.js';
2
- export type AttributeDefinition = Pick<BlockDefinition, 'attributes'>;
1
+ import type { AttributeConfig, AttributeInputKind, AttributeListSpec, AttributeOption, AttributeSpec, BlockDefinition } from './types.js';
2
+ export type AttributeDefinition = Pick<BlockDefinition, 'attributes'> & {
3
+ readOnly?: boolean;
4
+ };
5
+ export declare function isAttributeSpecConfig<T>(value: AttributeConfig<T>): value is AttributeSpec<T>;
6
+ export declare function toAttributeSpec<T>(value: AttributeConfig<T>): AttributeSpec<T>;
7
+ /**
8
+ * The fields of one list item, as specs. Empty for a list of single values,
9
+ * which {@link attributeListValueSpec} describes instead.
10
+ */
11
+ export declare function attributeListFields(list: AttributeListSpec): Array<[string, AttributeSpec<unknown>]>;
12
+ export declare function attributeListValueSpec(list: AttributeListSpec): AttributeSpec<unknown> | null;
13
+ /** A new item carrying each declared default, ready to append to a list. */
14
+ export declare function createAttributeListItem(list: AttributeListSpec): unknown;
3
15
  export declare function normalizeAttributeOptions<T>(spec: AttributeSpec<T>): AttributeOption<T>[] | undefined;
4
16
  export declare function inferAttributeInputKind(spec: AttributeSpec<unknown>): AttributeInputKind;
5
17
  export declare function coerceAttributeValue<T>(spec: AttributeSpec<T>, value: unknown): T;
@@ -8,4 +20,10 @@ export declare function serializeAttributeValue<T>(spec: AttributeSpec<T>, value
8
20
  export declare function serializeBlockAttributes(block: AttributeDefinition, attrs: Record<string, unknown>): string;
9
21
  export declare function toAttributeDraftValue(spec: AttributeSpec<unknown>, value: unknown): unknown;
10
22
  export declare function toAttributeDraftValues(block: AttributeDefinition, attrs: Record<string, unknown>): Record<string, unknown>;
11
- export declare function parseBlockDraftAttributes(block: AttributeDefinition, draftAttrs: Record<string, unknown>): Record<string, unknown>;
23
+ /**
24
+ * @deprecated Alias of {@link normalizeBlockAttributes}. Parsing draft (form)
25
+ * attribute values back into stored values is exactly attribute normalization:
26
+ * both coerce every declared attribute through `coerceAttributeValue`. Kept as a
27
+ * named export for the editor's attributes controller and existing callers.
28
+ */
29
+ export declare const parseBlockDraftAttributes: typeof normalizeBlockAttributes;
@@ -1,6 +1,47 @@
1
1
  import { coerceRichTextDocument } from '../shared/richText.js';
2
- function isPlainObject(value) {
3
- return typeof value === 'object' && value !== null && !Array.isArray(value);
2
+ import { isPlainObject, isAttributeOption } from '../shared/guards.js';
3
+ /**
4
+ * The keys that mark an object as an {@link AttributeSpec} *configuration*
5
+ * rather than a shorthand object default. An object carrying any of these is a
6
+ * config; to use an object literal AS the default, wrap it explicitly:
7
+ * `{ default: { ... } }`.
8
+ */
9
+ const CONFIG_KEYS = [
10
+ 'default',
11
+ 'required',
12
+ 'validate',
13
+ 'parse',
14
+ 'serialize',
15
+ 'input',
16
+ 'placeholder',
17
+ 'options',
18
+ 'list',
19
+ 'richText'
20
+ ];
21
+ export function isAttributeSpecConfig(value) {
22
+ return isPlainObject(value) && CONFIG_KEYS.some((key) => key in value);
23
+ }
24
+ export function toAttributeSpec(value) {
25
+ return isAttributeSpecConfig(value)
26
+ ? { ...value }
27
+ : { default: value };
28
+ }
29
+ /**
30
+ * The fields of one list item, as specs. Empty for a list of single values,
31
+ * which {@link attributeListValueSpec} describes instead.
32
+ */
33
+ export function attributeListFields(list) {
34
+ return Object.entries(list.fields ?? {}).map(([name, config]) => [name, toAttributeSpec(config)]);
35
+ }
36
+ export function attributeListValueSpec(list) {
37
+ return list.fields ? null : list.value === undefined ? null : toAttributeSpec(list.value);
38
+ }
39
+ /** A new item carrying each declared default, ready to append to a list. */
40
+ export function createAttributeListItem(list) {
41
+ const valueSpec = attributeListValueSpec(list);
42
+ if (valueSpec)
43
+ return cloneDefault(valueSpec.default);
44
+ return Object.fromEntries(attributeListFields(list).map(([name, spec]) => [name, cloneDefault(spec.default)]));
4
45
  }
5
46
  function parseJsonValue(raw) {
6
47
  try {
@@ -10,8 +51,17 @@ function parseJsonValue(raw) {
10
51
  return undefined;
11
52
  }
12
53
  }
13
- function isAttributeOption(value) {
14
- return typeof value === 'object' && value !== null && !Array.isArray(value) && 'value' in value;
54
+ /**
55
+ * Returns a fresh copy of an attribute default before handing it out, so two
56
+ * block instances that both fall back to an object/array default never share one
57
+ * mutable reference (mutating one block's attrs would otherwise leak into every
58
+ * other block using the same spec). Primitive defaults are returned as-is.
59
+ */
60
+ function cloneDefault(value) {
61
+ if (value !== null && typeof value === 'object') {
62
+ return structuredClone(value);
63
+ }
64
+ return value;
15
65
  }
16
66
  export function normalizeAttributeOptions(spec) {
17
67
  if (!spec.options || spec.options.length === 0)
@@ -33,6 +83,8 @@ export function normalizeAttributeOptions(spec) {
33
83
  export function inferAttributeInputKind(spec) {
34
84
  if (spec.input)
35
85
  return spec.input;
86
+ if (spec.list)
87
+ return 'list';
36
88
  if (spec.options && spec.options.length > 0)
37
89
  return 'select';
38
90
  if (typeof spec.default === 'boolean')
@@ -46,12 +98,23 @@ export function inferAttributeInputKind(spec) {
46
98
  return 'text';
47
99
  }
48
100
  export function coerceAttributeValue(spec, value) {
49
- if (value === undefined || value === null || value === '') {
50
- return spec.default;
101
+ // Only `undefined`/`null` are "missing" and fall back to the default. An empty
102
+ // string is a real value (e.g. a text attribute cleared by the author), so it
103
+ // must NOT be treated as missing — otherwise string attrs could never be
104
+ // cleared back to "". Each type branch below still rejects "" where it cannot
105
+ // be coerced (number/boolean/array/object) and falls back to the default there.
106
+ //
107
+ // Deliberately NOT run here: `spec.validate`. Dropping a value that fails a
108
+ // semantic validator back to the default would be silent data loss and would
109
+ // defeat the editor's out-of-range-value preservation (the select control's
110
+ // "(current)" option). Semantic validity is reported separately by
111
+ // `validateDocument` (INVALID_ATTR), which is the channel that surfaces it.
112
+ if (value === undefined || value === null) {
113
+ return cloneDefault(spec.default);
51
114
  }
52
115
  if (spec.parse) {
53
116
  const parsed = spec.parse(value);
54
- return parsed === undefined ? spec.default : parsed;
117
+ return parsed === undefined ? cloneDefault(spec.default) : parsed;
55
118
  }
56
119
  const fallback = spec.default;
57
120
  if (spec.input === 'richtext') {
@@ -90,7 +153,7 @@ export function coerceAttributeValue(spec, value) {
90
153
  if (Array.isArray(parsed))
91
154
  return parsed;
92
155
  }
93
- return fallback;
156
+ return cloneDefault(fallback);
94
157
  }
95
158
  if (isPlainObject(fallback)) {
96
159
  if (isPlainObject(value))
@@ -100,11 +163,13 @@ export function coerceAttributeValue(spec, value) {
100
163
  if (isPlainObject(parsed))
101
164
  return parsed;
102
165
  }
103
- return fallback;
166
+ return cloneDefault(fallback);
104
167
  }
105
168
  return value;
106
169
  }
107
170
  export function normalizeBlockAttributes(block, attrs = {}) {
171
+ if (block.readOnly)
172
+ return attrs;
108
173
  return Object.fromEntries(Object.entries(block.attributes).map(([name, spec]) => [
109
174
  name,
110
175
  coerceAttributeValue(spec, attrs[name])
@@ -117,6 +182,8 @@ export function serializeAttributeValue(spec, value) {
117
182
  return value;
118
183
  }
119
184
  export function serializeBlockAttributes(block, attrs) {
185
+ if (block.readOnly)
186
+ return JSON.stringify(attrs);
120
187
  return JSON.stringify(Object.fromEntries(Object.entries(block.attributes).map(([name, spec]) => [
121
188
  name,
122
189
  serializeAttributeValue(spec, coerceAttributeValue(spec, attrs[name]))
@@ -133,6 +200,9 @@ export function toAttributeDraftValue(spec, value) {
133
200
  return normalized;
134
201
  if (input === 'json')
135
202
  return JSON.stringify(normalized, null, 2);
203
+ // A list is edited as the array itself, one control per item.
204
+ if (input === 'list')
205
+ return Array.isArray(normalized) ? normalized : [];
136
206
  return String(normalized ?? '');
137
207
  }
138
208
  export function toAttributeDraftValues(block, attrs) {
@@ -141,9 +211,10 @@ export function toAttributeDraftValues(block, attrs) {
141
211
  toAttributeDraftValue(spec, attrs[name])
142
212
  ]));
143
213
  }
144
- export function parseBlockDraftAttributes(block, draftAttrs) {
145
- return Object.fromEntries(Object.entries(block.attributes).map(([name, spec]) => [
146
- name,
147
- coerceAttributeValue(spec, draftAttrs[name])
148
- ]));
149
- }
214
+ /**
215
+ * @deprecated Alias of {@link normalizeBlockAttributes}. Parsing draft (form)
216
+ * attribute values back into stored values is exactly attribute normalization:
217
+ * both coerce every declared attribute through `coerceAttributeValue`. Kept as a
218
+ * named export for the editor's attributes controller and existing callers.
219
+ */
220
+ export const parseBlockDraftAttributes = normalizeBlockAttributes;
@@ -1,14 +1,10 @@
1
- function isAttributeSpec(value) {
2
- return typeof value === 'object' && value !== null && 'default' in value;
3
- }
4
- function isAttributeOption(value) {
5
- return typeof value === 'object' && value !== null && !Array.isArray(value) && 'value' in value;
6
- }
1
+ import { isAttributeOption } from '../shared/guards.js';
2
+ import { isAttributeSpecConfig, toAttributeSpec } from './attributes.js';
7
3
  function optionValues(options) {
8
4
  return options.map((option) => (isAttributeOption(option) ? option.value : option));
9
5
  }
10
6
  function normalizeAttribute(value) {
11
- const spec = isAttributeSpec(value) ? { ...value } : { default: value };
7
+ const spec = toAttributeSpec(value);
12
8
  if (spec.options && spec.options.length > 0 && !spec.validate) {
13
9
  const allowed = optionValues(spec.options);
14
10
  spec.validate = (candidate) => allowed.includes(candidate);
@@ -31,9 +27,20 @@ function validateConfig(config) {
31
27
  throw new Error(`Block "${config.id}" must have a non-empty label`);
32
28
  }
33
29
  for (const [name, attr] of Object.entries(config.attributes)) {
34
- const normalized = normalizeAttribute(attr);
35
- if (!('default' in normalized)) {
36
- throw new Error(`Attribute "${name}" in block "${config.id}" must define a default value`);
30
+ // A plain object that carries config keys but no `default` is a config
31
+ // object that forgot its default (previously misparsed as an object-valued
32
+ // default, making this check unreachable). Objects with no config keys are
33
+ // valid shorthand object defaults and pass through.
34
+ if (isAttributeSpecConfig(attr) && !('default' in attr)) {
35
+ throw new Error(`Attribute "${name}" in block "${config.id}" is a configuration object but does not ` +
36
+ `define a "default" value. If you meant an object as the default value, wrap it ` +
37
+ `explicitly as { default: { ... } }.`);
38
+ }
39
+ // A list with no item shape has nothing to render a field from, and would
40
+ // silently fall back to raw JSON — the thing `list` exists to replace.
41
+ if (isAttributeSpecConfig(attr) && attr.list && !attr.list.fields && attr.list.value === undefined) {
42
+ throw new Error(`Attribute "${name}" in block "${config.id}" declares "list" but neither ` +
43
+ `"list.fields" nor "list.value", so the editor has no item shape to render.`);
37
44
  }
38
45
  }
39
46
  if (config.content && config.behaviors?.inline) {
@@ -42,8 +49,8 @@ function validateConfig(config) {
42
49
  }
43
50
  function normalizeComponents(runtime, config) {
44
51
  const shared = config.component;
45
- const editor = config.components?.editor ?? shared ?? config.components?.render;
46
52
  const render = config.components?.render ?? shared ?? config.components?.editor;
53
+ const editor = config.readOnly ? render : config.components?.editor ?? shared ?? render;
47
54
  if (!editor || !render) {
48
55
  throw new Error(`Block "${config.id}" must provide either "component" or both "components.editor" and "components.render"`);
49
56
  }
@@ -53,8 +60,14 @@ function normalizeContent(content) {
53
60
  if (!content) {
54
61
  return undefined;
55
62
  }
63
+ // An empty `allowedBlocks` names no block and cannot be meant as "admits
64
+ // nothing", so it normalizes to unconstrained.
65
+ const allowedBlocks = content.allowedBlocks?.length
66
+ ? Object.freeze([...content.allowedBlocks])
67
+ : undefined;
56
68
  return {
57
- kind: content.kind
69
+ kind: content.kind,
70
+ ...(allowedBlocks ? { allowedBlocks } : {})
58
71
  };
59
72
  }
60
73
  export function defineRuntimeBlock(runtime, config) {
@@ -65,6 +78,7 @@ export function defineRuntimeBlock(runtime, config) {
65
78
  label: config.label,
66
79
  description: config.description,
67
80
  icon: config.icon,
81
+ readOnly: config.readOnly ?? false,
68
82
  attributes: normalizeAttributes(config.attributes),
69
83
  components: normalizeComponents(runtime, config),
70
84
  behaviors: {
@@ -2,7 +2,9 @@ export { defineRuntimeBlock } from './defineBlock.js';
2
2
  export { coerceAttributeValue, inferAttributeInputKind, normalizeAttributeOptions, normalizeBlockAttributes, parseBlockDraftAttributes, serializeBlockAttributes, toAttributeDraftValues } from './attributes.js';
3
3
  export { normalizeMeta, parseMetaDraftValues, serializeMeta, toMetaDraftValues, validateMeta } from './meta.js';
4
4
  export { createBlockRegistry, createSchema, resolveRegistry } from './registry.js';
5
- export { CURRENT_DOCUMENT_VERSION, normalizeDocument } from './normalize.js';
5
+ export { CURRENT_DOCUMENT_VERSION, registerDocumentMigration, runDocumentMigrations } from './migrations.js';
6
+ export type { DocumentMigration } from './migrations.js';
7
+ export { normalizeDocument } from './normalize.js';
6
8
  export { validateDocument } from './validate.js';
7
9
  export type { BlockEditorMountHandle, BlockEditorMountOptions, BlockRuntimePlugin, NormalizedBlockComponentDefinition } from './runtime.js';
8
10
  export { coerceRichTextDocument, emptyRichTextDocument, hasRichTextContent, isRichTextDocument, richTextDocument, resolveRichTextFeatures } from '../shared/richText.js';
@@ -2,6 +2,7 @@ export { defineRuntimeBlock } from './defineBlock.js';
2
2
  export { coerceAttributeValue, inferAttributeInputKind, normalizeAttributeOptions, normalizeBlockAttributes, parseBlockDraftAttributes, serializeBlockAttributes, toAttributeDraftValues } from './attributes.js';
3
3
  export { normalizeMeta, parseMetaDraftValues, serializeMeta, toMetaDraftValues, validateMeta } from './meta.js';
4
4
  export { createBlockRegistry, createSchema, resolveRegistry } from './registry.js';
5
- export { CURRENT_DOCUMENT_VERSION, normalizeDocument } from './normalize.js';
5
+ export { CURRENT_DOCUMENT_VERSION, registerDocumentMigration, runDocumentMigrations } from './migrations.js';
6
+ export { normalizeDocument } from './normalize.js';
6
7
  export { validateDocument } from './validate.js';
7
8
  export { coerceRichTextDocument, emptyRichTextDocument, hasRichTextContent, isRichTextDocument, richTextDocument, resolveRichTextFeatures } from '../shared/richText.js';
@@ -0,0 +1,7 @@
1
+ import type { ValidateDocumentOptions, ValidationIssue } from './types.js';
2
+ /**
3
+ * Appends a validation issue to the running list and forwards it to the optional
4
+ * `onIssue` sink. Previously duplicated byte-for-byte in `validate.ts` and
5
+ * `meta.ts`; kept as one shared internal helper.
6
+ */
7
+ export declare function pushIssue(issues: ValidationIssue[], options: ValidateDocumentOptions | undefined, issue: ValidationIssue): void;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Appends a validation issue to the running list and forwards it to the optional
3
+ * `onIssue` sink. Previously duplicated byte-for-byte in `validate.ts` and
4
+ * `meta.ts`; kept as one shared internal helper.
5
+ */
6
+ export function pushIssue(issues, options, issue) {
7
+ issues.push(issue);
8
+ options?.onIssue?.(issue);
9
+ }
package/dist/core/meta.js CHANGED
@@ -1,11 +1,6 @@
1
1
  import { coerceAttributeValue, serializeAttributeValue, toAttributeDraftValue } from './attributes.js';
2
- function isRecord(value) {
3
- return typeof value === 'object' && value !== null && !Array.isArray(value);
4
- }
5
- function pushIssue(issues, options, issue) {
6
- issues.push(issue);
7
- options?.onIssue?.(issue);
8
- }
2
+ import { pushIssue } from './issues.js';
3
+ import { isPlainObject as isRecord } from '../shared/guards.js';
9
4
  export function normalizeMeta(meta, metaFields) {
10
5
  const source = isRecord(meta) ? meta : {};
11
6
  return Object.fromEntries(Array.from(metaFields, ([name, spec]) => [name, coerceAttributeValue(spec, source[name])]));
@@ -0,0 +1,30 @@
1
+ import type { PMDoc } from '../shared/document.js';
2
+ /**
3
+ * The document version stamped onto documents produced by `normalizeDocument`.
4
+ * Bump this when the persisted document shape changes, and register a
5
+ * migration for each intermediate version so older documents can be upgraded.
6
+ */
7
+ export declare const CURRENT_DOCUMENT_VERSION = 2;
8
+ export interface DocumentMigration {
9
+ /** The document version this migration upgrades from (to `from + 1`). */
10
+ from: number;
11
+ /** Upgrades a document from version `from` to version `from + 1`. */
12
+ migrate: (document: PMDoc) => PMDoc;
13
+ }
14
+ /**
15
+ * Registers a migration that upgrades documents from version `from` to
16
+ * `from + 1`. Returns a disposer that removes the registration (useful for
17
+ * tests and hot-reload scenarios).
18
+ */
19
+ export declare function registerDocumentMigration(migration: DocumentMigration): () => void;
20
+ /**
21
+ * Runs registered migrations stepwise from `fromVersion` up to `toVersion`
22
+ * (defaults to CURRENT_DOCUMENT_VERSION). Versions without a registered
23
+ * migration are passed through unchanged. The `version` field is not
24
+ * stamped here; callers such as `normalizeDocument` stamp the result.
25
+ *
26
+ * Only the registered migration versions inside `[fromVersion, toVersion)`
27
+ * are visited (in ascending order), so hostile version ranges from untrusted
28
+ * documents cannot make this loop over billions of integers.
29
+ */
30
+ export declare function runDocumentMigrations(document: PMDoc, fromVersion: number, toVersion?: number): PMDoc;
@@ -0,0 +1,50 @@
1
+ import { stampDocumentIdentity } from '../shared/documentIdentity.js';
2
+ /**
3
+ * The document version stamped onto documents produced by `normalizeDocument`.
4
+ * Bump this when the persisted document shape changes, and register a
5
+ * migration for each intermediate version so older documents can be upgraded.
6
+ */
7
+ export const CURRENT_DOCUMENT_VERSION = 2;
8
+ const migrations = new Map([[1, stampDocumentIdentity]]);
9
+ /**
10
+ * Registers a migration that upgrades documents from version `from` to
11
+ * `from + 1`. Returns a disposer that removes the registration (useful for
12
+ * tests and hot-reload scenarios).
13
+ */
14
+ export function registerDocumentMigration(migration) {
15
+ if (!Number.isInteger(migration.from)) {
16
+ throw new Error(`Document migration "from" must be an integer, got ${migration.from}`);
17
+ }
18
+ const previous = migrations.get(migration.from);
19
+ migrations.set(migration.from, migration.migrate);
20
+ return () => {
21
+ if (migrations.get(migration.from) === migration.migrate) {
22
+ if (previous) {
23
+ migrations.set(migration.from, previous);
24
+ }
25
+ else {
26
+ migrations.delete(migration.from);
27
+ }
28
+ }
29
+ };
30
+ }
31
+ /**
32
+ * Runs registered migrations stepwise from `fromVersion` up to `toVersion`
33
+ * (defaults to CURRENT_DOCUMENT_VERSION). Versions without a registered
34
+ * migration are passed through unchanged. The `version` field is not
35
+ * stamped here; callers such as `normalizeDocument` stamp the result.
36
+ *
37
+ * Only the registered migration versions inside `[fromVersion, toVersion)`
38
+ * are visited (in ascending order), so hostile version ranges from untrusted
39
+ * documents cannot make this loop over billions of integers.
40
+ */
41
+ export function runDocumentMigrations(document, fromVersion, toVersion = CURRENT_DOCUMENT_VERSION) {
42
+ const applicable = [...migrations.entries()]
43
+ .filter(([version]) => version >= fromVersion && version < toVersion)
44
+ .sort(([a], [b]) => a - b);
45
+ let migrated = document;
46
+ for (const [, migrate] of applicable) {
47
+ migrated = migrate(migrated);
48
+ }
49
+ return migrated;
50
+ }
@@ -1,5 +1,16 @@
1
1
  import type { PMDoc } from '../shared/document.js';
2
2
  import type { ContentSchema } from './types.js';
3
3
  import { resolveRegistry } from './registry.js';
4
- export declare const CURRENT_DOCUMENT_VERSION = 1;
4
+ export { CURRENT_DOCUMENT_VERSION } from './migrations.js';
5
+ /**
6
+ * Sanitizes the structural shape of a raw document (object nodes with string
7
+ * types, valid text nodes, array content/marks, object attrs — no schema or
8
+ * block-attribute normalization) and runs the registered migrations on the
9
+ * result, so migration callbacks never receive hostile shapes. A throwing
10
+ * migration never propagates: on throw the sanitized-but-unmigrated document
11
+ * is returned so normalization can proceed.
12
+ *
13
+ * Exported for tests; hosts run migrations via `normalizeDocument`.
14
+ */
15
+ export declare function migrateDocument(source: Partial<PMDoc>, fromVersion: number, toVersion?: number): PMDoc;
5
16
  export declare function normalizeDocument(document: Partial<PMDoc> | null | undefined, blocks: Parameters<typeof resolveRegistry>[0], schema?: ContentSchema): PMDoc;