@perkyzz/emvb 1.3.0 → 1.4.1

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 (161) hide show
  1. package/README.md +2 -2
  2. package/package.json +2 -2
  3. package/src/admin/bulk-api.ts +5 -1
  4. package/src/admin/content-item.ts +3 -0
  5. package/src/admin/copy-rich-text.ts +99 -9
  6. package/src/admin/editor/A11yCopilot.tsx +3 -1
  7. package/src/admin/editor/Editor.tsx +28 -3
  8. package/src/admin/editor/Timeline.tsx +1 -8
  9. package/src/admin/editor/canvas/DeviceBar.tsx +7 -2
  10. package/src/admin/editor/canvas/EmptyCanvas.tsx +11 -2
  11. package/src/admin/editor/canvas/use-canvas-dnd.ts +1 -20
  12. package/src/admin/editor/canvas/vnode-react.tsx +2 -0
  13. package/src/admin/editor/co-design.ts +36 -1
  14. package/src/admin/editor/collection-previews.ts +7 -8
  15. package/src/admin/editor/dnd/dragged-source.ts +22 -0
  16. package/src/admin/editor/dnd/layer-drop.ts +141 -0
  17. package/src/admin/editor/dnd/new-element.ts +16 -0
  18. package/src/admin/editor/editor-css.ts +9 -1
  19. package/src/admin/editor/element-chrome.ts +6 -0
  20. package/src/admin/editor/extensions/ExtensionPanels.tsx +33 -1
  21. package/src/admin/editor/extensions-context.tsx +16 -1
  22. package/src/admin/editor/feature-css.ts +27 -0
  23. package/src/admin/editor/inert-links.ts +8 -0
  24. package/src/admin/editor/panels/ColorControl.tsx +2 -2
  25. package/src/admin/editor/panels/ConditionsEditor.tsx +18 -0
  26. package/src/admin/editor/panels/ElementPanel.tsx +2 -2
  27. package/src/admin/editor/panels/FontFaces.tsx +342 -0
  28. package/src/admin/editor/panels/LayersPanel.tsx +56 -6
  29. package/src/admin/editor/panels/LeftPanel.tsx +153 -29
  30. package/src/admin/editor/panels/SettingsPanel.tsx +1 -0
  31. package/src/admin/editor/panels/SiteStylesDrawer.tsx +5 -0
  32. package/src/admin/editor/panels/TemplatesPanel.tsx +205 -0
  33. package/src/admin/editor/panels/TokenScales.tsx +2 -0
  34. package/src/admin/editor/panels/TriggersEditor.tsx +203 -9
  35. package/src/admin/editor/panels/VariableSection.tsx +111 -7
  36. package/src/admin/editor/panels/color-space.ts +71 -6
  37. package/src/admin/editor/panels/settings/AudienceEditor.tsx +3 -0
  38. package/src/admin/editor/panels/settings/FieldControl.tsx +33 -0
  39. package/src/admin/editor/panels/settings/FormBindControl.tsx +27 -31
  40. package/src/admin/editor/panels/settings/ImageFieldControl.tsx +106 -0
  41. package/src/admin/editor/panels/settings/LoopItemBindControl.tsx +9 -3
  42. package/src/admin/editor/panels/settings/StickyControl.tsx +97 -0
  43. package/src/admin/editor/panels/settings/StyleRow.tsx +14 -0
  44. package/src/admin/editor/panels/settings/loop-context.ts +34 -3
  45. package/src/admin/editor/panels/settings/style-sections.ts +19 -2
  46. package/src/admin/editor/panels/url-rules.ts +43 -0
  47. package/src/admin/editor/panels/use-layers-drop.ts +232 -0
  48. package/src/admin/editor/store.ts +4 -2
  49. package/src/admin/editor/useExtensions.ts +3 -1
  50. package/src/admin/editor/useNodeActions.ts +74 -1
  51. package/src/admin/editor/useSave.ts +116 -85
  52. package/src/admin/export-api.ts +27 -2
  53. package/src/admin/extension-outputs.ts +236 -0
  54. package/src/admin/font-files-api.ts +38 -0
  55. package/src/admin/import-forms.ts +133 -0
  56. package/src/admin/pages/ImportButton.tsx +15 -4
  57. package/src/admin/pages/ImportElementorDialog.tsx +53 -187
  58. package/src/admin/pages/ImportForms.tsx +71 -0
  59. package/src/admin/pages/ImportHtmlDialog.tsx +209 -0
  60. package/src/admin/pages/ImportImageCopies.tsx +167 -0
  61. package/src/admin/pages/ImportReport.tsx +63 -0
  62. package/src/admin/pages/NewPageDialog.tsx +54 -32
  63. package/src/admin/pages/PageList.tsx +9 -0
  64. package/src/admin/pages/ThemePartList.tsx +9 -0
  65. package/src/admin/setup/plan.ts +2 -0
  66. package/src/admin/ui.ts +7 -0
  67. package/src/admin/widgets/ConvertToRichText.tsx +3 -2
  68. package/src/astro/EmVBPage.astro +5 -2
  69. package/src/astro/extension-styles.ts +35 -0
  70. package/src/astro/forms/EmVBFormsClient.astro +3 -0
  71. package/src/astro/forms/enhance.ts +107 -0
  72. package/src/astro/popups/runtime.ts +47 -2
  73. package/src/astro/render.ts +25 -4
  74. package/src/astro/resolve-theme.ts +11 -4
  75. package/src/astro/resolve.ts +2 -0
  76. package/src/astro/theme-posts.ts +17 -23
  77. package/src/astro/visitor.ts +14 -5
  78. package/src/astro/widgets/EmVBStickyRuntime.astro +9 -0
  79. package/src/astro/widgets/EmVBThemeRuntime.astro +9 -0
  80. package/src/astro/widgets/EmVBWidgetRuntimes.astro +12 -0
  81. package/src/astro/widgets/alerts.ts +16 -2
  82. package/src/astro/widgets/carousel.ts +65 -24
  83. package/src/astro/widgets/countdown.ts +18 -7
  84. package/src/astro/widgets/extension-runtimes.ts +27 -0
  85. package/src/astro/widgets/headline.ts +14 -5
  86. package/src/astro/widgets/sticky.ts +87 -0
  87. package/src/astro/widgets/theme.ts +52 -0
  88. package/src/constants.ts +1 -1
  89. package/src/core/a11y/audit.ts +150 -2
  90. package/src/core/arrange.ts +19 -1
  91. package/src/core/css/font-face.ts +72 -0
  92. package/src/core/css/generate.ts +41 -2
  93. package/src/core/css/trace.ts +8 -0
  94. package/src/core/data/bindings.ts +7 -4
  95. package/src/core/elements/dynamic-elements.ts +1 -1
  96. package/src/core/elements/element-nouns.ts +48 -0
  97. package/src/core/elements/form-elements.ts +119 -9
  98. package/src/core/elements/icon-svg.ts +14 -0
  99. package/src/core/elements/index.ts +24 -4
  100. package/src/core/elements/input-limits.ts +44 -0
  101. package/src/core/elements/menu.ts +109 -47
  102. package/src/core/elements/site.ts +108 -0
  103. package/src/core/elements/widgets.ts +13 -3
  104. package/src/core/export/runtimes.generated.ts +7 -5
  105. package/src/core/export/site.ts +53 -4
  106. package/src/core/extensions/classes.ts +114 -0
  107. package/src/core/extensions/index.ts +19 -2
  108. package/src/core/extensions/normalize.ts +13 -0
  109. package/src/core/extensions/placeholder.ts +7 -2
  110. package/src/core/extensions/registry.ts +134 -10
  111. package/src/core/extensions/render-ext.ts +115 -36
  112. package/src/core/extensions/safe-nodes.ts +67 -11
  113. package/src/core/extensions/types.ts +48 -1
  114. package/src/core/fonts/files.ts +74 -0
  115. package/src/core/fonts/google.ts +112 -0
  116. package/src/core/fonts/test-font.ts +9 -0
  117. package/src/core/import/elementor/context.ts +42 -4
  118. package/src/core/import/elementor/index.ts +55 -23
  119. package/src/core/import/elementor/widgets.ts +242 -20
  120. package/src/core/import/html/blocks.ts +602 -0
  121. package/src/core/import/html/index.ts +155 -0
  122. package/src/core/import/html/map.ts +958 -0
  123. package/src/core/import/html/parse.ts +430 -0
  124. package/src/core/index.ts +54 -0
  125. package/src/core/migrate/v18.ts +3 -0
  126. package/src/core/public-attributes.ts +17 -0
  127. package/src/core/render/extras.ts +31 -7
  128. package/src/core/render/form.ts +103 -10
  129. package/src/core/render/index.ts +165 -16
  130. package/src/core/render/section.ts +31 -1
  131. package/src/core/render/spacer-basis.ts +102 -0
  132. package/src/core/render/theme-boot.ts +16 -0
  133. package/src/core/render/vnode.ts +1 -1
  134. package/src/core/sanitize/css.ts +68 -3
  135. package/src/core/sanitize/motion.ts +12 -0
  136. package/src/core/schema/design.ts +40 -0
  137. package/src/core/schema/layout.ts +118 -6
  138. package/src/core/schema/style.ts +28 -0
  139. package/src/core/templates/index.ts +218 -0
  140. package/src/core/templates/pages.ts +29 -0
  141. package/src/core/templates/sections.ts +794 -0
  142. package/src/core/templates/types.ts +9 -0
  143. package/src/core/theme/dynamic.ts +9 -6
  144. package/src/core/theme/media-value.ts +88 -0
  145. package/src/core/theme/popup-markup.ts +21 -2
  146. package/src/core/theme/popup-rules.ts +36 -0
  147. package/src/core/theme/triggers.ts +64 -5
  148. package/src/core/translatable.ts +5 -2
  149. package/src/core/visitor-cookie.ts +91 -0
  150. package/src/extension-build.ts +331 -0
  151. package/src/index.ts +53 -4
  152. package/src/mcp/agent-defaults.ts +40 -0
  153. package/src/mcp/brief.ts +191 -0
  154. package/src/mcp/extensions.ts +138 -0
  155. package/src/mcp/prompts.ts +33 -0
  156. package/src/mcp/read.ts +84 -20
  157. package/src/mcp/tools.ts +42 -3
  158. package/src/mcp/write.ts +124 -9
  159. package/src/server/extension-routes.ts +110 -0
  160. package/src/server/font-routes.ts +301 -0
  161. package/src/server/plugin.ts +15 -0
package/src/mcp/write.ts CHANGED
@@ -2,13 +2,16 @@ import { z } from "zod";
2
2
  import { boundedArray } from "../core/bounded-array.ts";
3
3
  import {
4
4
  byteLength,
5
- defaultElement,
6
5
  findNode,
7
6
  MAX_LAYOUT_BYTES,
8
7
  nameKey,
9
8
  nestingIssues,
9
+ PAGE_TEMPLATES,
10
10
  recipeNode,
11
11
  SECTION_RECIPES,
12
+ SECTION_TEMPLATES,
13
+ templatePageLayout,
14
+ templateSectionNode,
12
15
  summarizeIssues,
13
16
  validateDesign,
14
17
  validateLayout,
@@ -20,6 +23,7 @@ import {
20
23
  import { stableJson } from "../core/stable-json.ts";
21
24
  import { addNode, moveNode, withFreshIds } from "../core/arrange.ts";
22
25
  import { ELEMENT_DESCRIPTORS } from "../core/elements/index.ts";
26
+ import { isExtensionType, liveElement } from "../core/extensions/index.ts";
23
27
  import { nodeChildren, pageSlug, removeNode, starterLayout, updateNode } from "../core/tree-ops.ts";
24
28
  import { isSafeFontStack } from "../core/sanitize/css.ts";
25
29
  import { sanitizeMediaUrl } from "../core/sanitize/media-url.ts";
@@ -32,8 +36,10 @@ import {
32
36
  patchNestedStyle,
33
37
  upgradeLegacyNode,
34
38
  } from "../core/migrate/v18.ts";
39
+ import { agentDefaultElement } from "./agent-defaults.ts";
40
+ import { checkedExtensionProps } from "./extensions.ts";
35
41
  import { McpToolError } from "./errors.ts";
36
- import type { EmvbPorts } from "./ports.ts";
42
+ import type { EmvbPorts, PageRecord } from "./ports.ts";
37
43
  import { queued } from "./queue.ts";
38
44
  import { nestsDeeperThan, resolveDesignRefs } from "./refs.ts";
39
45
  import {
@@ -99,7 +105,10 @@ export async function mutatePage(
99
105
  tool: string,
100
106
  pageId: string,
101
107
  expectedRev: string | undefined,
102
- apply: (layout: Layout) => { layout: Layout; changed: string[]; summary: string },
108
+ apply: (
109
+ layout: Layout,
110
+ page: PageRecord,
111
+ ) => { layout: Layout; changed: string[]; summary: string },
103
112
  ): Promise<WriteResult> {
104
113
  return queued(`page:${pageId}`, async () => {
105
114
  // The retry must read, write and log in order.
@@ -128,7 +137,7 @@ export async function mutatePage(
128
137
  "The stored layout can't be read. Repair it in the editor.",
129
138
  );
130
139
  }
131
- const next = apply(current.layout);
140
+ const next = apply(current.layout, page);
132
141
  refuseUnsafeImageSources(current.layout, next.layout);
133
142
  refuseUnsafeLinks(current.layout, next.layout);
134
143
  refuseUnsafeSvg(current.layout, next.layout);
@@ -302,13 +311,27 @@ const BoundedElementSpec = z.preprocess((value, ctx) => {
302
311
  return upgradeLegacyNode(value);
303
312
  }, ElementSpec);
304
313
 
314
+ /**
315
+ * W-1089 (#38): a registered extension element, its props checked by the extension's schema.
316
+ * Extension elements hold no children (their render output is built-in elements).
317
+ */
318
+ function buildExtensionNode(spec: ElementSpecT): LayoutNode {
319
+ const { type, props, children, ...rest } = spec;
320
+ delete (rest as { id?: unknown }).id;
321
+ const checked = checkedExtensionProps(type, props ?? {});
322
+ if (children?.length) refused(`${type} is an extension element and holds no children.`);
323
+ return { ...rest, id: "new", type, props: checked } as LayoutNode;
324
+ }
325
+
305
326
  function buildNode(spec: ElementSpecT): LayoutNode {
327
+ if (isExtensionType(spec.type)) return buildExtensionNode(spec);
306
328
  if (!KNOWN_TYPES.has(spec.type)) {
307
329
  refused(`Unknown element type ${spec.type}. Call list_element_types.`);
308
330
  }
309
331
  const { type, props, children, ...rest } = spec;
310
332
  delete (rest as { id?: unknown }).id;
311
- const base = defaultElement(type as ElementType, "new") as LayoutNode & {
333
+ // W-1089 (#29): the type's defaults without the Add panel's sample content.
334
+ const base = agentDefaultElement(type as ElementType, "new") as LayoutNode & {
312
335
  props?: Record<string, unknown>;
313
336
  };
314
337
  const node = { ...base, ...rest, props: { ...base.props, ...props } } as LayoutNode;
@@ -327,6 +350,13 @@ export const CreatePageInput = z.strictObject({
327
350
  .array(z.enum(SECTION_RECIPES.map((r) => r.id) as [string, ...string[]]))
328
351
  .max(12)
329
352
  .optional(),
353
+ /** W-1068: start from a starter page template (see list_templates) instead of recipes. */
354
+ template: z.enum(PAGE_TEMPLATES.map((t) => t.id) as [string, ...string[]]).optional(),
355
+ /**
356
+ * W-1089 (#28): a page without a template or a hero recipe starts with an H1 of its title.
357
+ * `false` leaves it out, for an agent that adds its own H1. Unset keeps it.
358
+ */
359
+ titleHeading: z.boolean().optional(),
330
360
  });
331
361
  export const CreatePageOutput = z.object({ pageId: z.string(), slug: z.string(), rev: z.string() });
332
362
 
@@ -372,7 +402,11 @@ export async function createPage(ports: EmvbPorts, input: z.infer<typeof CreateP
372
402
  const slug = pageSlug(input.title);
373
403
  if (!slug) refused("Give the page a title with letters or digits.");
374
404
  const { design } = await ports.getDesign();
375
- let layout = starterLayout(input.title);
405
+ if (input.template && input.recipes?.length) {
406
+ refused("Use either a page template or recipes, not both.");
407
+ }
408
+ let layout =
409
+ (input.template && templatePageLayout(input.template, design)) || starterLayout(input.title);
376
410
  const recipes = input.recipes ?? [];
377
411
  if (recipes.length > 0) {
378
412
  // W-474: sections sit edge to edge, and a hero first carries the page's one h1 itself
@@ -383,6 +417,9 @@ export async function createPage(ports: EmvbPorts, input: z.infer<typeof CreateP
383
417
  };
384
418
  if (recipes[0] === "hero") layout = { ...layout, root: { ...layout.root, children: [] } };
385
419
  }
420
+ if (input.titleHeading === false && !input.template) {
421
+ layout = { ...layout, root: { ...layout.root, children: [] } };
422
+ }
386
423
  for (const id of recipes) {
387
424
  const node = recipeNode(id, design, layout);
388
425
  if (node)
@@ -419,22 +456,57 @@ export const AddElementInput = z.strictObject({
419
456
  expectedRev: Rev.optional(),
420
457
  });
421
458
 
459
+ const isH1 = (node: LayoutNode): boolean =>
460
+ (node.type === "heading" || node.type === "headline") && propsOf(node)["level"] === 1;
461
+ const h1Ids = (node: LayoutNode): string[] => [
462
+ ...(isH1(node) ? [node.id] : []),
463
+ ...nodeChildren(node).flatMap(h1Ids),
464
+ ];
465
+
466
+ /**
467
+ * W-1089 (#28): the H1 create_page starts a page with, as long as nobody changed it: a heading
468
+ * straight in the root with the page's title as its only text and nothing else set.
469
+ */
470
+ function untouchedTitleHeading(layout: Layout, title: string): LayoutNode | undefined {
471
+ return nodeChildren(layout.root).find((node) => {
472
+ if (
473
+ node.type !== "heading" ||
474
+ Object.keys(node).some((k) => !["id", "type", "props"].includes(k))
475
+ )
476
+ return false;
477
+ const props = propsOf(node);
478
+ return (
479
+ Object.keys(props).length === 2 && props["level"] === 1 && props["text"] === title.trim()
480
+ );
481
+ });
482
+ }
483
+
422
484
  export async function addElement(ports: EmvbPorts, input: z.infer<typeof AddElementInput>) {
423
485
  const element = resolveDesignRefs(input.element, (await ports.getDesign()).design);
424
- return mutatePage(ports, "add_element", input.pageId, input.expectedRev, (layout) => {
486
+ return mutatePage(ports, "add_element", input.pageId, input.expectedRev, (layout, page) => {
425
487
  if (!findNode(layout, input.parentId)) {
426
488
  refused(
427
489
  `No element with id ${input.parentId} on this page to add into. Call get_layout for the ids.`,
428
490
  );
429
491
  }
430
492
  const node = withFreshIds(layout, buildNode(element));
431
- const next = arranged(
493
+ let next = arranged(
432
494
  addNode(layout, node, {
433
495
  parentId: input.parentId,
434
496
  index: input.index ?? Number.MAX_SAFE_INTEGER,
435
497
  }),
436
498
  );
437
- return { layout: next, changed: [node.id], summary: `Added ${node.type} ${node.id}` };
499
+ const changed = [node.id];
500
+ let summary = `Added ${node.type} ${node.id}`;
501
+ // W-1089 (#28): an agent that builds the page's own H1 replaces the title heading
502
+ // create_page started it with, instead of leaving two H1s with the title out of place.
503
+ const title = h1Ids(node).length > 0 ? untouchedTitleHeading(layout, page.title) : undefined;
504
+ if (title && h1Ids(layout.root).length === 1 && input.parentId !== title.id) {
505
+ next = removeNode(next, title.id).layout;
506
+ changed.push(title.id);
507
+ summary += `; removed the page's title heading ${title.id} (the new element has the page's H1)`;
508
+ }
509
+ return { layout: next, changed, summary };
438
510
  });
439
511
  }
440
512
 
@@ -574,6 +646,19 @@ export async function updateElement(ports: EmvbPorts, input: z.infer<typeof Upda
574
646
  if (isRecord(style)) copy[top] = patchNestedStyle(style, { [sub]: undefined });
575
647
  } else if (isRecord(copy[top])) delete copy[top][sub];
576
648
  }
649
+ // W-1089 (#38): an extension element changes only while its extension is registered, and
650
+ // its props must still pass the extension's schema.
651
+ if (isExtensionType(node.type)) {
652
+ if (!liveElement(node.type)) {
653
+ refused(
654
+ `${node.type} can't be changed: no extension on this site provides it. Remove it or install the extension.`,
655
+ );
656
+ }
657
+ const touchesProps =
658
+ "props" in set ||
659
+ (input.unset ?? []).some((path) => path === "props" || path.startsWith("props."));
660
+ if (touchesProps) copy["props"] = checkedExtensionProps(node.type, copy["props"]);
661
+ }
577
662
  return copy as LayoutNode;
578
663
  });
579
664
  return { layout: next, changed: [input.nodeId], summary: `Updated ${input.nodeId}` };
@@ -631,6 +716,36 @@ export async function applySectionRecipe(
631
716
  });
632
717
  }
633
718
 
719
+ // ---------------------------------------------------------------- insert_template
720
+
721
+ export const InsertTemplateInput = z.strictObject({
722
+ pageId: PageId,
723
+ templateId: z.enum(SECTION_TEMPLATES.map((t) => t.id) as [string, ...string[]]),
724
+ parentId: NodeIdInput.optional(),
725
+ index: z.number().int().min(0).optional(),
726
+ expectedRev: Rev.optional(),
727
+ });
728
+
729
+ /** W-1068: a starter section template, in the site's styles, with fresh ids. */
730
+ export async function insertTemplate(ports: EmvbPorts, input: z.infer<typeof InsertTemplateInput>) {
731
+ const { design } = await ports.getDesign();
732
+ return mutatePage(ports, "insert_template", input.pageId, input.expectedRev, (layout) => {
733
+ const node = templateSectionNode(input.templateId, design, layout);
734
+ if (!node) return refused(`Unknown template ${input.templateId}.`);
735
+ const next = arranged(
736
+ addNode(layout, node, {
737
+ parentId: input.parentId ?? layout.root.id,
738
+ index: input.index ?? Number.MAX_SAFE_INTEGER,
739
+ }),
740
+ );
741
+ return {
742
+ layout: next,
743
+ changed: [node.id],
744
+ summary: `Added the ${input.templateId} template ${node.id}`,
745
+ };
746
+ });
747
+ }
748
+
634
749
  // ---------------------------------------------------------------- restore_version
635
750
 
636
751
  export const RestoreVersionInput = z.strictObject({
@@ -0,0 +1,110 @@
1
+ import type { PluginRoute } from "emdash";
2
+ import { z } from "zod";
3
+ import {
4
+ extensionOutputKey,
5
+ isExtensionType,
6
+ liveExtensionOutput,
7
+ resolveExtensionSource,
8
+ withExtensionClasses,
9
+ type ExtensionManifest,
10
+ } from "../core/extensions/index.ts";
11
+ import { MAX_DEPTH, MAX_LAYOUT_BYTES } from "../core/limits.ts";
12
+
13
+ /** Elements one request may render: a page's worth (the admin batches the rest). */
14
+ const MAX_EXTENSION_RENDERS = 100;
15
+ /** Props deeper or larger than any stored layout holds are refused before they are keyed. */
16
+ const MAX_PROPS_DEPTH = MAX_DEPTH;
17
+ const MAX_PROPS_BYTES = MAX_LAYOUT_BYTES;
18
+
19
+ /** True when `value` nests at most `MAX_PROPS_DEPTH` levels; walked without recursion. */
20
+ function shallowEnough(value: unknown): boolean {
21
+ const stack: { value: unknown; depth: number }[] = [{ value, depth: 0 }];
22
+ while (stack.length > 0) {
23
+ const item = stack.pop() as { value: unknown; depth: number };
24
+ if (!item.value || typeof item.value !== "object") continue;
25
+ if (item.depth >= MAX_PROPS_DEPTH) return false;
26
+ for (const child of Object.values(item.value))
27
+ stack.push({ value: child, depth: item.depth + 1 });
28
+ }
29
+ return true;
30
+ }
31
+
32
+ /**
33
+ * W-1086: `extensionOutputKey` serializes props recursively, so props from the request are
34
+ * bounded first: depth (the check above), then size.
35
+ */
36
+ const boundedProps = z
37
+ .record(z.string(), z.unknown())
38
+ // `abort`: the size check below would serialize props that are too deep.
39
+ .refine(shallowEnough, {
40
+ message: `props nest deeper than ${MAX_PROPS_DEPTH} levels`,
41
+ abort: true,
42
+ })
43
+ .refine((props) => new TextEncoder().encode(JSON.stringify(props)).length <= MAX_PROPS_BYTES, {
44
+ message: `props are larger than ${MAX_PROPS_BYTES / 1024} KB`,
45
+ });
46
+
47
+ const RenderInput = z.object({
48
+ nodes: z
49
+ .array(
50
+ z.object({
51
+ type: z.string().max(200),
52
+ props: boundedProps.optional(),
53
+ }),
54
+ )
55
+ .max(MAX_EXTENSION_RENDERS),
56
+ });
57
+
58
+ /**
59
+ * W-1086: the admin has no extension code, so the editor canvas and the HTML export ask here for
60
+ * the output of each extension element (by type and props). The output is the same checked node
61
+ * tree the public page renders, with its allowlisted classes in `extClasses`; the admin checks it
62
+ * again. `nodes: null` when the extension is missing, render throws or nothing legal is left.
63
+ */
64
+ export const extensionRenderRoute: PluginRoute<z.infer<typeof RenderInput>> = {
65
+ permission: "content:edit_any",
66
+ input: RenderInput,
67
+ handler: async (ctx) => ({
68
+ outputs: ctx.input.nodes.map((node) => {
69
+ const key = extensionOutputKey(node);
70
+ if (!isExtensionType(node.type)) return { key, nodes: null };
71
+ const nodes = liveExtensionOutput(node);
72
+ return { key, nodes: nodes ? withExtensionClasses(nodes) : null };
73
+ }),
74
+ }),
75
+ };
76
+
77
+ /** One source's values for the editor's panels; `values: null` when it can't be read here. */
78
+ type ExtensionSourceValues = { id: string; values: Record<string, string> | null };
79
+
80
+ /**
81
+ * W-1088 (#36): the values of every source an extension panel names, for the editor's left panel,
82
+ * which lists them read-only. Sources are read-only resolvers; their values are cleaned like bound
83
+ * values. `values: null` when the source's code isn't in this server (an extension without
84
+ * `module` on Workers or a production build), it throws, or it doesn't answer in time.
85
+ */
86
+ export function extensionSourcesRoute(manifests: readonly ExtensionManifest[]): PluginRoute {
87
+ return {
88
+ permission: "content:edit_any",
89
+ handler: async () => {
90
+ const wanted = new Map<string, { pkg: string; name: string }>();
91
+ for (const manifest of manifests) {
92
+ for (const panel of manifest.panels) {
93
+ if (!panel.source) continue;
94
+ if (!manifest.sources.some((source) => source.name === panel.source)) continue;
95
+ wanted.set(`ext:${manifest.id}/${panel.source}`, {
96
+ pkg: manifest.id,
97
+ name: panel.source,
98
+ });
99
+ }
100
+ }
101
+ const sources: ExtensionSourceValues[] = await Promise.all(
102
+ [...wanted].map(async ([id, { pkg, name }]) => ({
103
+ id,
104
+ values: (await resolveExtensionSource(pkg, name)) ?? null,
105
+ })),
106
+ );
107
+ return { sources };
108
+ },
109
+ };
110
+ }
@@ -0,0 +1,301 @@
1
+ import { pluginResponse, PluginRouteError, type PluginRoute, type RouteContext } from "emdash";
2
+ import { z } from "zod";
3
+ import {
4
+ base64ToBytes,
5
+ bytesToBase64,
6
+ DEFAULT_GOOGLE_SUBSETS,
7
+ FONT_FILE_LIMIT,
8
+ FONT_ID,
9
+ FONT_MAX_BYTES,
10
+ fontFileId,
11
+ fontFileProblem,
12
+ fontFileUrl,
13
+ GOOGLE_CSS_HOST,
14
+ GOOGLE_FAMILY,
15
+ GOOGLE_FILE_HOST,
16
+ GOOGLE_FILES_PER_FACE,
17
+ GOOGLE_SUBSET,
18
+ GOOGLE_USER_AGENT,
19
+ googleCssUrl,
20
+ parseGoogleFontCss,
21
+ pickGoogleFaces,
22
+ type FontFace,
23
+ } from "../core/index.ts";
24
+
25
+ /**
26
+ * Custom fonts (W-1072). EmDash's media library refuses `font/woff2` on 1.4 and 1.5, so font
27
+ * files live in EmVB's plugin storage (as W-239 keeps uploaded SVG icons) and the public `font`
28
+ * route serves them with their real type and a year-long immutable cache: a file's id is the hash
29
+ * of its bytes, so a URL never changes what it serves.
30
+ */
31
+
32
+ export type StoredFont = {
33
+ name: string;
34
+ size: number;
35
+ /** The WOFF2 file, base64. */
36
+ data: string;
37
+ uploadedAt: string;
38
+ source: "upload" | "google";
39
+ };
40
+
41
+ type FontStore = {
42
+ get(id: string): Promise<StoredFont | null>;
43
+ put(id: string, data: StoredFont): Promise<void>;
44
+ exists(id: string): Promise<boolean>;
45
+ count(): Promise<number>;
46
+ };
47
+
48
+ const store = (ctx: RouteContext<unknown>) => ctx.storage["fonts"] as unknown as FontStore;
49
+
50
+ /** A file name as a label: no folder, control characters or direction marks, at most 80. */
51
+ const fileLabel = (name: string) =>
52
+ Array.from(name.replace(/^.*[\\/]/, ""), (ch) => (ch.charCodeAt(0) < 32 ? " " : ch))
53
+ .join("")
54
+ .replace(/[\u007F-\u009F​-‏‪-‮⁠⁦-⁩]/g, "")
55
+ .trim()
56
+ .slice(0, 80) || "Font";
57
+
58
+ /** Stores a checked font file once (content-addressed) and answers its id and URL. */
59
+ async function storeFontFile(
60
+ files: FontStore,
61
+ bytes: Uint8Array,
62
+ meta: { name: string; source: StoredFont["source"] },
63
+ ): Promise<{ id: string; url: string; duplicate: boolean }> {
64
+ const problem = fontFileProblem(bytes);
65
+ if (problem) throw new PluginRouteError("INVALID_FONT", problem, 422);
66
+ const id = await fontFileId(bytes);
67
+ if (await files.exists(id)) return { id, url: fontFileUrl(id), duplicate: true };
68
+ if ((await files.count()) >= FONT_FILE_LIMIT) {
69
+ throw new PluginRouteError(
70
+ "FONTS_FULL",
71
+ `This site keeps up to ${FONT_FILE_LIMIT} font files.`,
72
+ 409,
73
+ );
74
+ }
75
+ await files.put(id, {
76
+ name: fileLabel(meta.name),
77
+ size: bytes.byteLength,
78
+ data: bytesToBase64(bytes),
79
+ uploadedAt: new Date().toISOString(),
80
+ source: meta.source,
81
+ });
82
+ return { id, url: fontFileUrl(id), duplicate: false };
83
+ }
84
+
85
+ const missing = () => new PluginRouteError("NOT_FOUND", "No such font.", 404);
86
+
87
+ /** Anyone: one stored font file, as `font/woff2`, cached for a year. */
88
+ export const fontRoute: PluginRoute = {
89
+ public: true,
90
+ methods: ["GET", "HEAD"],
91
+ response: "raw",
92
+ cacheControl: "public, max-age=31536000, immutable",
93
+ handler: async (ctx) => {
94
+ const id = (ctx.input as { id?: unknown } | undefined)?.id;
95
+ if (typeof id !== "string" || !FONT_ID.test(id)) throw missing();
96
+ const row = await store(ctx).get(id);
97
+ const bytes = typeof row?.data === "string" ? base64ToBytes(row.data) : undefined;
98
+ // A row written past the upload route is served only if it is still a real WOFF2.
99
+ if (!bytes || fontFileProblem(bytes)) throw missing();
100
+ return pluginResponse({
101
+ status: 200,
102
+ headers: { "content-type": "font/woff2", etag: `"${id}"` },
103
+ body: { kind: "bytes", value: bytes },
104
+ });
105
+ },
106
+ };
107
+
108
+ const UploadInput = z.object({
109
+ name: z.string().max(255),
110
+ data: z
111
+ .string()
112
+ .min(1)
113
+ .max(Math.ceil(FONT_MAX_BYTES / 3) * 4),
114
+ });
115
+
116
+ /** Editors and above: stores an uploaded WOFF2 after checking it again on the server. */
117
+ export const fontUploadRoute: PluginRoute<z.infer<typeof UploadInput>> = {
118
+ permission: "content:edit_any",
119
+ input: UploadInput,
120
+ // The default JSON limit is 1 MiB; a 1 MiB font is about 1.4 MB as base64.
121
+ request: { body: "json", maxBytes: 1_600_000 },
122
+ handler: async (ctx) => {
123
+ const bytes = base64ToBytes(ctx.input.data);
124
+ if (!bytes) throw new PluginRouteError("INVALID_FONT", "The file didn't arrive whole.", 422);
125
+ const file = await storeFontFile(store(ctx), bytes, {
126
+ name: ctx.input.name,
127
+ source: "upload",
128
+ });
129
+ return { file };
130
+ },
131
+ };
132
+
133
+ const GoogleInput = z.object({
134
+ family: z.string().regex(GOOGLE_FAMILY, "Type a Google Fonts family name, such as Open Sans"),
135
+ weight: z.number().int().min(100).max(900).multipleOf(100),
136
+ style: z.enum(["normal", "italic"]),
137
+ subsets: z.array(z.string().regex(GOOGLE_SUBSET)).min(1).max(12).optional(),
138
+ });
139
+ type GoogleInput = z.infer<typeof GoogleInput>;
140
+
141
+ type Fetch = (url: string, init: RequestInit) => Promise<Response>;
142
+
143
+ const CSS_MAX_BYTES = 256 * 1024;
144
+ const TIMEOUT_MS = 20_000;
145
+
146
+ /**
147
+ * GET from Google's two font hosts only. Redirects are not followed (a redirect could leave
148
+ * those hosts), and the body is read up to `maxBytes`.
149
+ */
150
+ async function googleGet(fetcher: Fetch, url: string, maxBytes: number): Promise<Response> {
151
+ const host = new URL(url).hostname;
152
+ if (host !== GOOGLE_CSS_HOST && host !== GOOGLE_FILE_HOST) {
153
+ throw new PluginRouteError("GOOGLE_FONTS", "Fonts are only downloaded from Google.", 502);
154
+ }
155
+ let response: Response;
156
+ try {
157
+ response = await fetcher(url, {
158
+ method: "GET",
159
+ redirect: "manual",
160
+ headers: { "user-agent": GOOGLE_USER_AGENT, accept: "text/css,font/woff2,*/*;q=0.1" },
161
+ signal: AbortSignal.timeout(TIMEOUT_MS),
162
+ });
163
+ } catch (error) {
164
+ // PluginRouteError's fourth argument is sent to the client, so the cause is set apart.
165
+ const failed = new PluginRouteError(
166
+ "GOOGLE_FONTS",
167
+ "Couldn't reach Google Fonts. Try again.",
168
+ 502,
169
+ );
170
+ failed.cause = error;
171
+ throw failed;
172
+ }
173
+ const declared = Number(response.headers.get("content-length"));
174
+ if (Number.isFinite(declared) && declared > maxBytes) {
175
+ await response.body?.cancel();
176
+ throw new PluginRouteError("GOOGLE_FONTS", "Google Fonts sent a file that is too large.", 502);
177
+ }
178
+ return response;
179
+ }
180
+
181
+ /** The body, refused once it passes `maxBytes` (a missing or wrong Content-Length can't help). */
182
+ async function readCapped(response: Response, maxBytes: number): Promise<Uint8Array> {
183
+ const reader = response.body?.getReader();
184
+ if (!reader) return new Uint8Array();
185
+ const chunks: Uint8Array[] = [];
186
+ let size = 0;
187
+ for (;;) {
188
+ // oxlint-disable-next-line no-await-in-loop -- a stream is read one chunk after another
189
+ const { done, value } = await reader.read();
190
+ if (done) break;
191
+ size += value.byteLength;
192
+ if (size > maxBytes) {
193
+ void reader.cancel().catch(() => undefined);
194
+ throw new PluginRouteError(
195
+ "GOOGLE_FONTS",
196
+ "Google Fonts sent a file that is too large.",
197
+ 502,
198
+ );
199
+ }
200
+ chunks.push(value);
201
+ }
202
+ const out = new Uint8Array(size);
203
+ let at = 0;
204
+ for (const chunk of chunks) {
205
+ out.set(chunk, at);
206
+ at += chunk.byteLength;
207
+ }
208
+ return out;
209
+ }
210
+
211
+ /** Downloads one WOFF2 file from fonts.gstatic.com and stores it; answers its site URL. */
212
+ async function downloadGoogleFile(
213
+ deps: { fetch: Fetch; files: FontStore },
214
+ url: string,
215
+ name: string,
216
+ ): Promise<string> {
217
+ const response = await googleGet(deps.fetch, url, FONT_MAX_BYTES);
218
+ if (response.status !== 200) {
219
+ await response.body?.cancel();
220
+ throw new PluginRouteError("GOOGLE_FONTS", "Google Fonts didn't send a font file.", 502);
221
+ }
222
+ const bytes = await readCapped(response, FONT_MAX_BYTES);
223
+ return (await storeFontFile(deps.files, bytes, { name, source: "google" })).url;
224
+ }
225
+
226
+ /**
227
+ * Downloads one family, weight and style from Google Fonts and stores its WOFF2 files like
228
+ * uploads. Answers the faces, pointing at the site's own font route.
229
+ */
230
+ export async function importGoogleFace(
231
+ input: GoogleInput,
232
+ deps: { fetch: Fetch; files: FontStore },
233
+ ): Promise<{ family: string; faces: FontFace[] }> {
234
+ const cssResponse = await googleGet(
235
+ deps.fetch,
236
+ googleCssUrl(input.family, input.weight, input.style),
237
+ CSS_MAX_BYTES,
238
+ );
239
+ if (cssResponse.status === 400 || cssResponse.status === 404) {
240
+ await cssResponse.body?.cancel();
241
+ throw new PluginRouteError(
242
+ "GOOGLE_FONT_UNKNOWN",
243
+ `Google Fonts has no "${input.family}" in weight ${input.weight}${input.style === "italic" ? " italic" : ""}.`,
244
+ 404,
245
+ );
246
+ }
247
+ const type = cssResponse.headers.get("content-type") ?? "";
248
+ if (cssResponse.status !== 200 || !type.toLowerCase().startsWith("text/css")) {
249
+ await cssResponse.body?.cancel();
250
+ throw new PluginRouteError("GOOGLE_FONTS", "Google Fonts didn't answer. Try again.", 502);
251
+ }
252
+ const css = new TextDecoder().decode(await readCapped(cssResponse, CSS_MAX_BYTES));
253
+ const picked = pickGoogleFaces(parseGoogleFontCss(css), {
254
+ weight: input.weight,
255
+ style: input.style,
256
+ subsets: input.subsets ?? DEFAULT_GOOGLE_SUBSETS,
257
+ });
258
+ if (picked.length === 0) {
259
+ throw new PluginRouteError(
260
+ "GOOGLE_FONT_UNKNOWN",
261
+ `Google Fonts has no WOFF2 file of "${input.family}" for these subsets.`,
262
+ 404,
263
+ );
264
+ }
265
+ if (picked.length > GOOGLE_FILES_PER_FACE) {
266
+ throw new PluginRouteError(
267
+ "GOOGLE_FONTS",
268
+ `"${input.family}" comes in ${picked.length} files per weight. Pick fewer subsets.`,
269
+ 422,
270
+ );
271
+ }
272
+ const stored = new Map<string, string>();
273
+ const faces: FontFace[] = [];
274
+ for (const face of picked) {
275
+ let src = stored.get(face.url);
276
+ if (!src) {
277
+ const name = `${input.family} ${input.weight}${input.style === "italic" ? " italic" : ""}${face.subset ? ` ${face.subset}` : ""}.woff2`;
278
+ // oxlint-disable-next-line no-await-in-loop -- one download at a time keeps memory low
279
+ src = await downloadGoogleFile(deps, face.url, name);
280
+ stored.set(face.url, src);
281
+ }
282
+ faces.push({
283
+ weight: face.weight,
284
+ style: face.style,
285
+ src,
286
+ ...(face.unicodeRange ? { unicodeRange: face.unicodeRange } : {}),
287
+ });
288
+ }
289
+ return { family: input.family, faces };
290
+ }
291
+
292
+ /** Editors and above: self-hosts one weight and style of a Google font. */
293
+ export const fontGoogleRoute: PluginRoute<GoogleInput> = {
294
+ permission: "content:edit_any",
295
+ input: GoogleInput,
296
+ handler: async (ctx) =>
297
+ importGoogleFace(ctx.input, {
298
+ fetch: (url, init) => globalThis.fetch(url, init),
299
+ files: store(ctx),
300
+ }),
301
+ };