@cosmicdrift/kumiko-samples 0.417.0 → 0.419.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 (114) hide show
  1. package/package.json +1 -1
  2. package/packages/bundled-features/package.json +6 -1
  3. package/packages/bundled-features/src/agent-tools/api-docs/schema-fields.ts +14 -0
  4. package/packages/bundled-features/src/agent-tools/changes.json +6 -0
  5. package/packages/bundled-features/src/auth-email-password/index.ts +1 -1
  6. package/packages/bundled-features/src/auth-email-password/signup-activation.ts +2 -5
  7. package/packages/bundled-features/src/auth-email-password/signup-token-store.ts +0 -6
  8. package/packages/bundled-features/src/cap-counter/changes.json +6 -0
  9. package/packages/bundled-features/src/cap-counter/stock-cap-guard.ts +46 -13
  10. package/packages/bundled-features/src/channel-whatsapp/changes.json +1 -1
  11. package/packages/bundled-features/src/document-ingest-foundation/changes.json +6 -0
  12. package/packages/bundled-features/src/document-ingest-foundation/feature.ts +13 -1
  13. package/packages/bundled-features/src/document-ingest-foundation/report-ingest-progress.ts +23 -6
  14. package/packages/bundled-features/src/signature/README.md +4 -4
  15. package/packages/bundled-features/src/signature/changes.json +18 -0
  16. package/packages/bundled-features/src/signature/entity.ts +3 -1
  17. package/packages/bundled-features/src/signature/feature.ts +16 -3
  18. package/packages/bundled-features/src/signature/handlers/lifecycle.write.ts +33 -1
  19. package/packages/bundled-features/src/signature/i18n.ts +1 -0
  20. package/packages/bundled-features/src/signature/list-cursor-seal.ts +59 -0
  21. package/packages/bundled-features/src/signature/options.ts +2 -2
  22. package/packages/bundled-features/src/signature/payloads.ts +14 -2
  23. package/packages/bundled-features/src/signature/png.ts +25 -4
  24. package/packages/bundled-features/src/signature/subject-queries.ts +47 -7
  25. package/packages/bundled-features/src/signature/sweep.ts +32 -8
  26. package/packages/bundled-features/src/signature/web/constants.ts +12 -0
  27. package/packages/bundled-features/src/subscription-paddle/changes.json +1 -1
  28. package/packages/bundled-features/src/subscription-stripe/changes.json +6 -0
  29. package/packages/bundled-features/src/subscription-stripe/plugin-methods.ts +2 -0
  30. package/packages/bundled-features/src/subscription-stripe/verify-webhook.ts +21 -16
  31. package/packages/bundled-features/src/template-resolver/changes.json +38 -0
  32. package/packages/bundled-features/src/template-resolver/compile-document-body.ts +3 -8
  33. package/packages/bundled-features/src/template-resolver/compile-document-styles.ts +102 -0
  34. package/packages/bundled-features/src/template-resolver/document-frames.ts +25 -0
  35. package/packages/bundled-features/src/template-resolver/document-op-blocks.ts +568 -0
  36. package/packages/bundled-features/src/template-resolver/document-ops.ts +136 -126
  37. package/packages/bundled-features/src/template-resolver/document-print-only.ts +41 -0
  38. package/packages/bundled-features/src/template-resolver/document-sanitizer.ts +41 -19
  39. package/packages/bundled-features/src/template-resolver/feature.ts +15 -0
  40. package/packages/bundled-features/src/template-resolver/handlers/apply-layout.write.ts +137 -0
  41. package/packages/bundled-features/src/template-resolver/handlers/create-layout.write.ts +87 -0
  42. package/packages/bundled-features/src/template-resolver/handlers/document-base.ts +2 -2
  43. package/packages/bundled-features/src/template-resolver/handlers/document-blocks.query.ts +13 -8
  44. package/packages/bundled-features/src/template-resolver/handlers/document-region.ts +47 -0
  45. package/packages/bundled-features/src/template-resolver/handlers/failure-reason.ts +13 -0
  46. package/packages/bundled-features/src/template-resolver/handlers/import-bundle-system.write.ts +3 -0
  47. package/packages/bundled-features/src/template-resolver/handlers/layout-source.query.ts +17 -5
  48. package/packages/bundled-features/src/template-resolver/handlers/overview.query.ts +16 -4
  49. package/packages/bundled-features/src/template-resolver/handlers/patch-draft.write.ts +19 -6
  50. package/packages/bundled-features/src/template-resolver/handlers/publish-templates.write.ts +69 -0
  51. package/packages/bundled-features/src/template-resolver/handlers/set.write.ts +7 -0
  52. package/packages/bundled-features/src/template-resolver/handlers/template-write.ts +15 -3
  53. package/packages/bundled-features/src/template-resolver/handlers/tenant-settings.ts +122 -0
  54. package/packages/bundled-features/src/template-resolver/handlers/toggle-status.write.ts +25 -10
  55. package/packages/bundled-features/src/template-resolver/handlers/upsert-system.write.ts +7 -3
  56. package/packages/bundled-features/src/template-resolver/handlers/usage.query.ts +131 -18
  57. package/packages/bundled-features/src/template-resolver/handlers/validate.query.ts +10 -0
  58. package/packages/bundled-features/src/template-resolver/i18n.ts +3 -0
  59. package/packages/bundled-features/src/template-resolver/index.ts +29 -0
  60. package/packages/bundled-features/src/template-resolver/layout-regions.ts +54 -16
  61. package/packages/bundled-features/src/template-resolver/print-document.ts +3 -1
  62. package/packages/bundled-features/src/template-resolver/seeding.ts +4 -0
  63. package/packages/bundled-features/src/template-resolver/template-delivery-policy.ts +11 -1
  64. package/packages/bundled-features/src/template-resolver/template-edit-policy.ts +37 -1
  65. package/packages/bundled-features/src/template-resolver/template-meta.ts +25 -6
  66. package/packages/bundled-features/src/template-resolver/template-preview.ts +6 -7
  67. package/packages/bundled-features/src/template-resolver/template-validation.ts +10 -3
  68. package/packages/bundled-features/src/template-resolver/web/constants.ts +29 -0
  69. package/packages/bundled-features/src/template-resolver/web/document-blocks.ts +5 -0
  70. package/packages/bundled-features/src/template-resolver/web/document-editor-extensions.ts +34 -2
  71. package/packages/bundled-features/src/template-resolver/web/document-editor-fonts.ts +13 -0
  72. package/packages/bundled-features/src/template-resolver/web/document-fonts.ts +21 -0
  73. package/packages/bundled-features/src/template-resolver/web/document-frame-control.ts +428 -0
  74. package/packages/bundled-features/src/template-resolver/web/document-frame-node-view.tsx +207 -0
  75. package/packages/bundled-features/src/template-resolver/web/document-print-decorations.ts +196 -0
  76. package/packages/bundled-features/src/template-resolver/web/document-print-defaults.ts +59 -0
  77. package/packages/bundled-features/src/template-resolver/web/document-print-style.ts +246 -0
  78. package/packages/bundled-features/src/template-resolver/web/document-repeat-strip.ts +104 -0
  79. package/packages/bundled-features/src/template-resolver/web/document-schema.ts +29 -9
  80. package/packages/bundled-features/src/template-resolver/web/document-style-css.ts +107 -0
  81. package/packages/bundled-features/src/template-resolver/web/document-tiptap-bubble.tsx +24 -2
  82. package/packages/bundled-features/src/template-resolver/web/document-tiptap-content.tsx +66 -7
  83. package/packages/bundled-features/src/template-resolver/web/document-tiptap-context.ts +13 -1
  84. package/packages/bundled-features/src/template-resolver/web/document-tiptap-editor.tsx +24 -4
  85. package/packages/bundled-features/src/template-resolver/web/document-tiptap-helpers.ts +149 -4
  86. package/packages/bundled-features/src/template-resolver/web/document-tiptap-toolbar-groups.tsx +290 -10
  87. package/packages/bundled-features/src/template-resolver/web/document-tiptap-toolbar.tsx +90 -8
  88. package/packages/bundled-features/src/template-resolver/web/document-toolbar-blocks.ts +20 -0
  89. package/packages/bundled-features/src/template-resolver/web/fontsource-css.d.ts +2 -0
  90. package/packages/bundled-features/src/template-resolver/web/i18n.ts +28 -0
  91. package/packages/bundled-features/src/template-resolver/web/index.ts +34 -0
  92. package/packages/bundled-features/src/template-resolver/web/pdf-constants.ts +6 -0
  93. package/packages/bundled-features/src/template-resolver/web/qualified-names.ts +7 -0
  94. package/packages/bundled-features/src/template-resolver/web/use-document-tiptap-model.ts +74 -5
  95. package/packages/bundled-features/src/tenant/company-config.ts +48 -0
  96. package/packages/bundled-features/src/tenant/feature.ts +11 -0
  97. package/packages/bundled-features/src/tenant/i18n.ts +14 -0
  98. package/packages/bundled-features/src/tenant-inactivity/handlers/keep-account.write.ts +7 -3
  99. package/packages/bundled-features/src/tenant-lifecycle/changes.json +6 -0
  100. package/packages/bundled-features/src/tenant-lifecycle/run-tenant-destroy.ts +90 -42
  101. package/samples/apps/ui-walkthrough/src/app/auth-constants.ts +51 -0
  102. package/samples/apps/ui-walkthrough/src/app/seed-print-editor-tenants.ts +118 -0
  103. package/samples/apps/ui-walkthrough/src/app/seed-templates.ts +2 -0
  104. package/samples/apps/ui-walkthrough/src/app/server.ts +9 -1
  105. package/samples/apps/ui-walkthrough/src/app/template-seed-data.ts +27 -1
  106. package/samples/apps/ui-walkthrough/src/run-config.ts +1 -0
  107. package/samples/apps/use-all-bundled/feature-manifest.json +238 -1
  108. package/samples/recipes/crypto-shredding-hr/README.md +1 -1
  109. package/samples/recipes/crypto-shredding-hr/src/feature.ts +1 -1
  110. package/samples/recipes/list-table-options/README.md +9 -3
  111. package/samples/recipes/list-table-options/src/feature.ts +123 -3
  112. package/samples/recipes/pdf-letterhead/README.md +23 -0
  113. package/samples/recipes/pdf-letterhead/package.json +12 -0
  114. package/samples/recipes/pdf-letterhead/src/letterhead.ts +92 -0
@@ -1,13 +1,23 @@
1
1
  import type { FieldIssue } from "@cosmicdrift/kumiko-framework/errors";
2
2
  import { getSchema, type JSONContent } from "@tiptap/core";
3
3
  import * as z from "zod";
4
+ import {
5
+ type BlockInput,
6
+ type BuildContext,
7
+ blockFormatSchema,
8
+ blockInputSchema,
9
+ blockNode,
10
+ countBlocks,
11
+ FORMATTABLE_NODE_TYPES,
12
+ formatNode,
13
+ MAX_BODY_BLOCKS,
14
+ patchIssue,
15
+ refusePrintStyling,
16
+ } from "./document-op-blocks.ts";
4
17
  import { toVariableDef } from "./template-validation.ts";
5
- import type { DocumentHtmlKind } from "./web/constants.ts";
6
- import { documentBlocksForKind } from "./web/document-blocks.ts";
18
+ import type { DocumentOpsKind } from "./web/constants.ts";
7
19
  import {
8
- DOCUMENT_TEXT_ALIGNMENTS,
9
20
  documentExtensions,
10
- isDocumentPlaceholderHref,
11
21
  isDocumentReferenceName,
12
22
  isDocumentResourceKey,
13
23
  } from "./web/document-schema.ts";
@@ -24,6 +34,7 @@ export type DocumentBlockType =
24
34
  | "list"
25
35
  | "table"
26
36
  | "repeat"
37
+ | "frame"
27
38
  | "image"
28
39
  | "button"
29
40
  | "divider"
@@ -42,6 +53,15 @@ export type DocumentBlock = {
42
53
  readonly alt?: string;
43
54
  readonly href?: string;
44
55
  readonly each?: string;
56
+ readonly frame?: FrameBox;
57
+ };
58
+
59
+ export type FrameBox = {
60
+ readonly xMm: number;
61
+ readonly yMm: number;
62
+ readonly widthMm: number;
63
+ readonly heightMm: number;
64
+ readonly preset?: string;
45
65
  };
46
66
 
47
67
  const TEXT_BLOCK_TYPES: ReadonlySet<string> = new Set(["paragraph", "heading", "button"]);
@@ -62,6 +82,8 @@ function blockTypeOf(node: JSONContent): DocumentBlockType | null {
62
82
  return eachOf(node) === undefined ? "table" : "repeat";
63
83
  case "resource":
64
84
  return "image";
85
+ case "documentFrame":
86
+ return "frame";
65
87
  default:
66
88
  return null;
67
89
  }
@@ -112,6 +134,23 @@ function setTypeSpecificAttrs(block: MutableBlock, node: JSONContent): void {
112
134
  if (block.type === "button" && href !== undefined) block.href = href;
113
135
  const each = eachOf(node);
114
136
  if (block.type === "repeat" && each !== undefined) block.each = each;
137
+ if (block.type === "frame") block.frame = frameBoxOf(node);
138
+ }
139
+
140
+ function numberAttr(node: JSONContent, name: string): number {
141
+ const value: unknown = node.attrs?.[name];
142
+ return typeof value === "number" ? value : 0;
143
+ }
144
+
145
+ function frameBoxOf(node: JSONContent): FrameBox {
146
+ const preset = stringAttr(node, "preset");
147
+ return {
148
+ xMm: numberAttr(node, "xMm"),
149
+ yMm: numberAttr(node, "yMm"),
150
+ widthMm: numberAttr(node, "widthMm"),
151
+ heightMm: numberAttr(node, "heightMm"),
152
+ ...(preset === undefined ? {} : { preset }),
153
+ };
115
154
  }
116
155
 
117
156
  function blockOf(node: JSONContent, id: string): DocumentBlock | null {
@@ -133,30 +172,8 @@ export function documentBlocksOf(doc: JSONContent): DocumentBlock[] {
133
172
  }
134
173
 
135
174
  const blockIdSchema = z.string().min(1).max(20);
136
- const singleLineText = z.string().max(2000);
137
-
138
- const blockInputSchema = z.discriminatedUnion("type", [
139
- z.object({
140
- type: z.literal("paragraph"),
141
- text: singleLineText,
142
- align: z.enum(DOCUMENT_TEXT_ALIGNMENTS).optional(),
143
- }),
144
- z.object({
145
- type: z.literal("heading"),
146
- level: z.number().int().min(1).max(3),
147
- text: singleLineText,
148
- }),
149
- z.object({
150
- type: z.literal("image"),
151
- resource: z.string().min(1).max(200),
152
- alt: z.string().max(500).optional(),
153
- }),
154
- z.object({ type: z.literal("button"), text: singleLineText, href: z.string().max(300) }),
155
- z.object({ type: z.literal("divider") }),
156
- z.object({ type: z.literal("pageBreak") }),
157
- ]);
158
175
 
159
- export type BlockInput = z.infer<typeof blockInputSchema>;
176
+ export type { BlockInput };
160
177
 
161
178
  export const documentOpSchema = z.discriminatedUnion("op", [
162
179
  z.object({
@@ -171,6 +188,11 @@ export const documentOpSchema = z.discriminatedUnion("op", [
171
188
  replace: z.string().max(2000),
172
189
  }),
173
190
  z.object({ op: z.literal("removeBlock"), blockId: blockIdSchema }),
191
+ z.object({
192
+ op: z.literal("replaceBody"),
193
+ blocks: z.array(blockInputSchema).min(1).max(MAX_BODY_BLOCKS),
194
+ }),
195
+ blockFormatSchema.extend({ op: z.literal("formatBlock"), blockId: blockIdSchema }),
174
196
  z.object({
175
197
  op: z.literal("setResource"),
176
198
  blockId: blockIdSchema,
@@ -193,7 +215,7 @@ export type DocumentOpsInput = {
193
215
  readonly doc: JSONContent;
194
216
  readonly meta: Readonly<Record<string, unknown>>;
195
217
  readonly variableSchema: Readonly<Record<string, unknown>>;
196
- readonly kind: DocumentHtmlKind;
218
+ readonly kind: DocumentOpsKind;
197
219
  readonly ops: readonly DocumentOp[];
198
220
  };
199
221
 
@@ -208,20 +230,6 @@ export type DocumentOpsResult =
208
230
 
209
231
  type Entry = { node: JSONContent; removed: boolean; readonly insertedAfter: JSONContent[] };
210
232
 
211
- function patchIssue(
212
- path: string,
213
- code: string,
214
- params?: Readonly<Record<string, unknown>>,
215
- ): FieldIssue {
216
- const camel = code.replace(/_([a-z])/g, (_match, letter: string) => letter.toUpperCase());
217
- return {
218
- path,
219
- code,
220
- i18nKey: `templateResolver.errors.patch.${camel}`,
221
- ...(params === undefined ? {} : { params }),
222
- };
223
- }
224
-
225
233
  function textNodesIn(nodes: readonly JSONContent[]): JSONContent[] {
226
234
  return nodes.flatMap((node) => (node.type === "text" ? [node] : textNodesIn(node.content ?? [])));
227
235
  }
@@ -263,58 +271,6 @@ function replaceInContent(
263
271
  });
264
272
  }
265
273
 
266
- function nodeOfInput(input: BlockInput): JSONContent {
267
- switch (input.type) {
268
- case "paragraph":
269
- return {
270
- type: "paragraph",
271
- ...(input.align === undefined ? {} : { attrs: { textAlign: input.align } }),
272
- content: lineToContent(singleLine(input.text)),
273
- };
274
- case "heading":
275
- return {
276
- type: "heading",
277
- attrs: { level: input.level },
278
- content: lineToContent(singleLine(input.text)),
279
- };
280
- case "image":
281
- return { type: "resource", attrs: { resource: input.resource, alt: input.alt ?? null } };
282
- case "button":
283
- return {
284
- type: "button",
285
- attrs: { href: input.href },
286
- content: lineToContent(singleLine(input.text)),
287
- };
288
- case "divider":
289
- case "pageBreak":
290
- return { type: input.type };
291
- }
292
- }
293
-
294
- const TOOLBAR_BLOCK_OF_INPUT = {
295
- image: "image",
296
- button: "button",
297
- divider: "divider",
298
- pageBreak: "pageBreak",
299
- } as const;
300
-
301
- function isBlockAllowed(input: BlockInput, kind: DocumentHtmlKind): boolean {
302
- if (input.type === "paragraph" || input.type === "heading") return true;
303
- return documentBlocksForKind(kind).includes(TOOLBAR_BLOCK_OF_INPUT[input.type]);
304
- }
305
-
306
- function inputIssue(input: BlockInput, path: string): FieldIssue | null {
307
- if (input.type === "image" && !isDocumentResourceKey(input.resource)) {
308
- return patchIssue(`${path}.block.resource`, "invalid_resource_key", {
309
- resource: input.resource,
310
- });
311
- }
312
- if (input.type === "button" && !isDocumentPlaceholderHref(input.href)) {
313
- return patchIssue(`${path}.block.href`, "invalid_button_href", { href: input.href });
314
- }
315
- return null;
316
- }
317
-
318
274
  let cachedSchema: ReturnType<typeof getSchema> | null = null;
319
275
 
320
276
  function documentSchema(): ReturnType<typeof getSchema> {
@@ -332,7 +288,8 @@ function isValidDocument(doc: JSONContent): boolean {
332
288
  }
333
289
 
334
290
  type OpState = {
335
- readonly kind: DocumentHtmlKind;
291
+ readonly kind: DocumentOpsKind;
292
+ replacement: JSONContent[] | null;
336
293
  readonly entries: Map<string, Entry>;
337
294
  readonly insertedAtStart: JSONContent[];
338
295
  readonly meta: Record<string, unknown>;
@@ -350,32 +307,75 @@ function lookupEntry(state: OpState, blockId: string, fieldPath: string): EntryL
350
307
 
351
308
  type InsertBlockOp = Extract<DocumentOp, { op: "insertBlock" }>;
352
309
 
353
- function blockInputIssue(
354
- op: InsertBlockOp,
310
+ function buildBlocks(
311
+ state: OpState,
312
+ blocks: readonly BlockInput[],
313
+ pathOf: (index: number) => string,
314
+ ): { readonly nodes: JSONContent[]; readonly issues: FieldIssue[] } {
315
+ const ctx: BuildContext = { kind: state.kind, issues: [] };
316
+ const nodes = blocks.map((block, index) => blockNode(ctx, pathOf(index), block));
317
+ nodes.forEach((node, index) => {
318
+ const refused = refusePrintStyling(state.kind, node, pathOf(index));
319
+ if (refused !== null) ctx.issues.push(refused);
320
+ });
321
+ return { nodes, issues: ctx.issues };
322
+ }
323
+
324
+ function insertBlockOp(state: OpState, op: InsertBlockOp, path: string): FieldIssue[] {
325
+ const anchor = op.after === null ? null : lookupEntry(state, op.after, `${path}.after`);
326
+ if (anchor !== null && "issue" in anchor) return [anchor.issue];
327
+ const built = buildBlocks(state, [op.block], () => `${path}.block`);
328
+ if (built.issues.length > 0) return built.issues;
329
+ const target = anchor === null ? state.insertedAtStart : anchor.entry.insertedAfter;
330
+ target.push(...built.nodes);
331
+ return [];
332
+ }
333
+
334
+ function replaceBodyOp(
335
+ state: OpState,
336
+ op: Extract<DocumentOp, { op: "replaceBody" }>,
355
337
  path: string,
356
- kind: DocumentHtmlKind,
357
- ): FieldIssue | null {
358
- if (!isBlockAllowed(op.block, kind)) {
359
- return patchIssue(`${path}.block.type`, "block_not_allowed", { type: op.block.type, kind });
338
+ ): FieldIssue[] {
339
+ if (countBlocks(op.blocks) > MAX_BODY_BLOCKS) {
340
+ return [patchIssue(`${path}.blocks`, "too_many_blocks", { max: MAX_BODY_BLOCKS })];
360
341
  }
361
- if (
362
- op.block.type === "paragraph" &&
363
- op.block.align !== undefined &&
364
- !documentBlocksForKind(kind).includes("align")
365
- ) {
366
- return patchIssue(`${path}.block.align`, "block_not_allowed", { type: "align", kind });
342
+ const built = buildBlocks(state, op.blocks, (index) => `${path}.blocks.${index}`);
343
+ if (built.issues.length > 0) return built.issues;
344
+ for (const entry of state.entries.values()) {
345
+ entry.removed = true;
346
+ entry.insertedAfter.length = 0;
367
347
  }
368
- return inputIssue(op.block, path);
348
+ state.insertedAtStart.length = 0;
349
+ state.replacement = built.nodes;
350
+ return [];
369
351
  }
370
352
 
371
- function insertBlockOp(state: OpState, op: InsertBlockOp, path: string): FieldIssue | null {
372
- const anchor = op.after === null ? null : lookupEntry(state, op.after, `${path}.after`);
373
- if (anchor !== null && "issue" in anchor) return anchor.issue;
374
- const invalid = blockInputIssue(op, path, state.kind);
375
- if (invalid !== null) return invalid;
376
- const target = anchor === null ? state.insertedAtStart : anchor.entry.insertedAfter;
377
- target.push(nodeOfInput(op.block));
378
- return null;
353
+ function formatBlockOp(
354
+ state: OpState,
355
+ op: Extract<DocumentOp, { op: "formatBlock" }>,
356
+ path: string,
357
+ ): FieldIssue[] {
358
+ const found = lookupEntry(state, op.blockId, `${path}.blockId`);
359
+ if ("issue" in found) return [found.issue];
360
+ const { entry } = found;
361
+ if (op.align === undefined && op.style === undefined && op.textStyle === undefined) {
362
+ return [patchIssue(path, "empty_format")];
363
+ }
364
+ if (!FORMATTABLE_NODE_TYPES.has(entry.node.type ?? "")) {
365
+ return [
366
+ patchIssue(`${path}.blockId`, "block_type_mismatch", {
367
+ expected: "paragraph, heading or list",
368
+ actual: entry.node.type ?? "unknown",
369
+ }),
370
+ ];
371
+ }
372
+ const ctx: BuildContext = { kind: state.kind, issues: [] };
373
+ const formatted = formatNode(ctx, path, entry.node, op);
374
+ const refused = refusePrintStyling(state.kind, formatted, path);
375
+ if (refused !== null) ctx.issues.push(refused);
376
+ if (ctx.issues.length > 0) return ctx.issues;
377
+ entry.node = formatted;
378
+ return [];
379
379
  }
380
380
 
381
381
  function removeBlockOp(
@@ -484,23 +484,31 @@ function setVariableOp(
484
484
  return null;
485
485
  }
486
486
 
487
- function applyOp(state: OpState, op: DocumentOp, path: string): FieldIssue | null {
487
+ function applyOp(state: OpState, op: DocumentOp, path: string): FieldIssue[] {
488
488
  switch (op.op) {
489
489
  case "insertBlock":
490
490
  return insertBlockOp(state, op, path);
491
+ case "replaceBody":
492
+ return replaceBodyOp(state, op, path);
493
+ case "formatBlock":
494
+ return formatBlockOp(state, op, path);
491
495
  case "removeBlock":
492
- return removeBlockOp(state, op, path);
496
+ return singleIssue(removeBlockOp(state, op, path));
493
497
  case "replaceText":
494
- return replaceTextOp(state, op, path);
498
+ return singleIssue(replaceTextOp(state, op, path));
495
499
  case "setResource":
496
- return setResourceOp(state, op, path);
500
+ return singleIssue(setResourceOp(state, op, path));
497
501
  case "setMeta":
498
- return setMetaOp(state, op, path);
502
+ return singleIssue(setMetaOp(state, op, path));
499
503
  case "setVariable":
500
- return setVariableOp(state, op, path);
504
+ return singleIssue(setVariableOp(state, op, path));
501
505
  }
502
506
  }
503
507
 
508
+ function singleIssue(issue: FieldIssue | null): FieldIssue[] {
509
+ return issue === null ? [] : [issue];
510
+ }
511
+
504
512
  // Ops address blocks by the ids of the document as it was read, so inserted blocks are
505
513
  // collected per anchor and the list is assembled once at the end.
506
514
  export function applyDocumentOps(input: DocumentOpsInput): DocumentOpsResult {
@@ -514,19 +522,21 @@ export function applyDocumentOps(input: DocumentOpsInput): DocumentOpsResult {
514
522
  });
515
523
  const state: OpState = {
516
524
  kind: input.kind,
525
+ replacement: null,
517
526
  entries,
518
527
  insertedAtStart: [],
519
528
  meta: { ...input.meta },
520
529
  variableSchema: { ...input.variableSchema },
521
530
  };
522
- const issues = input.ops.flatMap((op, index) => applyOp(state, op, `ops.${index}`) ?? []);
531
+ const issues = input.ops.flatMap((op, index) => applyOp(state, op, `ops.${index}`));
523
532
  if (issues.length > 0) return { ok: false, issues };
524
533
 
525
534
  const content = [
526
535
  ...state.insertedAtStart,
527
- ...[...entries.values()].flatMap((entry) =>
528
- entry.removed ? entry.insertedAfter : [entry.node, ...entry.insertedAfter],
529
- ),
536
+ ...(state.replacement ??
537
+ [...entries.values()].flatMap((entry) =>
538
+ entry.removed ? entry.insertedAfter : [entry.node, ...entry.insertedAfter],
539
+ )),
530
540
  ];
531
541
  const doc: JSONContent = { ...input.doc, content };
532
542
  if (!isValidDocument(doc)) return { ok: false, issues: [patchIssue("ops", "invalid_document")] };
@@ -0,0 +1,41 @@
1
+ // Server-only (happy-dom). Features of the shared document model that only a PDF can render:
2
+ // a mail body would keep them through the rebuild, so every other kind refuses them on write.
3
+ import type { Element as ScanElement } from "happy-dom";
4
+
5
+ export const IMAGES_BLOCK_SELECTOR = "div[data-images]";
6
+
7
+ export const PRINT_STYLE_SELECTORS = [
8
+ "div[data-frame]",
9
+ "span[data-text-style]",
10
+ "[data-line-height]",
11
+ "[data-space-before]",
12
+ "[data-space-after]",
13
+ "table[data-borders]",
14
+ "[data-background]",
15
+ "[data-colwidth]",
16
+ "img[data-bleed]",
17
+ ] as const;
18
+
19
+ export type PrintOnlyFeatures = {
20
+ readonly hasImagesBlock: boolean;
21
+ readonly printStyleSelectors: readonly string[];
22
+ };
23
+
24
+ export function scanPrintOnlyFeatures(body: ScanElement): PrintOnlyFeatures {
25
+ return {
26
+ hasImagesBlock: body.querySelector(IMAGES_BLOCK_SELECTOR) !== null,
27
+ printStyleSelectors: PRINT_STYLE_SELECTORS.filter(
28
+ (selector) => body.querySelector(selector) !== null,
29
+ ),
30
+ };
31
+ }
32
+
33
+ export function hasNestedFrame(body: ScanElement): boolean {
34
+ return Array.from(body.querySelectorAll("div[data-frame]")).some(
35
+ (frame) => frame.parentElement !== body,
36
+ );
37
+ }
38
+
39
+ export function hasFrame(body: ScanElement): boolean {
40
+ return body.querySelector("div[data-frame]") !== null;
41
+ }
@@ -5,6 +5,7 @@ import { isOneOf } from "@cosmicdrift/kumiko-types/type-guards";
5
5
  import type { JSONContent } from "@tiptap/core";
6
6
  import { generateHTML, generateJSON } from "@tiptap/html/server";
7
7
  import { type Element as ScanElement, Window } from "happy-dom";
8
+ import { hasNestedFrame, scanPrintOnlyFeatures } from "./document-print-only.ts";
8
9
  import type { ContentFormat } from "./web/constants.ts";
9
10
  import { DOCUMENT_HTML_KINDS } from "./web/constants.ts";
10
11
  import {
@@ -29,6 +30,8 @@ export type DocumentViolationCode =
29
30
  | "embedded_content"
30
31
  | "unsafe_attribute_value"
31
32
  | "images_block_pdf_only"
33
+ | "print_style_pdf_only"
34
+ | "frame_not_top_level"
32
35
  | "button_href_not_placeholder"
33
36
  | "document_requires_html_format"
34
37
  | "layout_requires_mjml_format"
@@ -262,6 +265,15 @@ function scanDocumentHtml(html: string): DocumentViolation[] {
262
265
  for (const element of [body, ...Array.from(body.querySelectorAll("*"))]) {
263
266
  scanElement(element, violations);
264
267
  }
268
+ if (hasNestedFrame(body)) {
269
+ violations.push(
270
+ violation(
271
+ "frame_not_top_level",
272
+ "div[data-frame]",
273
+ "A frame must sit directly in the document body, not inside another block",
274
+ ),
275
+ );
276
+ }
265
277
  });
266
278
  return violations;
267
279
  }
@@ -330,30 +342,38 @@ function requiredFormatViolation(
330
342
  return null;
331
343
  }
332
344
 
333
- const IMAGES_BLOCK_KIND = "document-pdf";
345
+ const PDF_ONLY_KIND = "document-pdf";
334
346
 
335
- // The node is part of the shared document model, so a mail body would keep it after the
336
- // rebuild; only a PDF resolves the record's images.
337
- function imagesBlockViolation(input: SanitizeBodyInput): DocumentViolation | null {
347
+ // These nodes and attributes are part of the shared document model, so a mail body would keep
348
+ // them after the rebuild; only a PDF resolves the record's images and applies print styling.
349
+ function pdfOnlyViolations(input: SanitizeBodyInput): DocumentViolation[] {
338
350
  if (
339
- input.kind === IMAGES_BLOCK_KIND ||
351
+ input.kind === PDF_ONLY_KIND ||
340
352
  !isSanitizedBody(input) ||
341
353
  input.contentFormat !== "html" ||
342
354
  input.content === null
343
355
  ) {
344
- return null;
356
+ return [];
345
357
  }
346
- const hasImagesBlock = withParsedDocument(
347
- input.content,
348
- (body) => body.querySelector("div[data-images]") !== null,
349
- );
350
- return hasImagesBlock
351
- ? violation(
352
- "images_block_pdf_only",
353
- input.kind,
354
- `Record images blocks are only allowed in templates of kind ${IMAGES_BLOCK_KIND}`,
355
- )
356
- : null;
358
+ const found = withParsedDocument(input.content, scanPrintOnlyFeatures);
359
+ return [
360
+ ...(found.hasImagesBlock
361
+ ? [
362
+ violation(
363
+ "images_block_pdf_only",
364
+ input.kind,
365
+ `Record images blocks are only allowed in templates of kind ${PDF_ONLY_KIND}`,
366
+ ),
367
+ ]
368
+ : []),
369
+ ...found.printStyleSelectors.map((selector) =>
370
+ violation(
371
+ "print_style_pdf_only",
372
+ selector,
373
+ `Print styling (${selector}) is only allowed in templates of kind ${PDF_ONLY_KIND}`,
374
+ ),
375
+ ),
376
+ ];
357
377
  }
358
378
 
359
379
  // Mails and PDFs have no base address, so compileDocumentBody turns a relative href into "#"; refuse it
@@ -378,8 +398,8 @@ function relativeLinkViolations(html: string): DocumentViolation[] {
378
398
  export function sanitizeTemplateBody(input: SanitizeBodyInput): SanitizeBodyResult {
379
399
  const formatViolation = requiredFormatViolation(input.kind, input.contentFormat);
380
400
  if (formatViolation !== null) return { ok: false, violations: [formatViolation] };
381
- const imagesViolation = imagesBlockViolation(input);
382
- if (imagesViolation !== null) return { ok: false, violations: [imagesViolation] };
401
+ const pdfOnly = pdfOnlyViolations(input);
402
+ if (pdfOnly.length > 0) return { ok: false, violations: pdfOnly };
383
403
  if (!isSanitizedBody(input) || input.contentFormat !== "html" || input.content === null) {
384
404
  return { ok: true, content: input.content };
385
405
  }
@@ -402,6 +422,8 @@ const VIOLATION_I18N_KEYS: Readonly<Record<DocumentViolationCode, string>> = {
402
422
  embedded_content: "templateResolver.errors.document.embeddedContent",
403
423
  unsafe_attribute_value: "templateResolver.errors.document.unsafeAttributeValue",
404
424
  images_block_pdf_only: "templateResolver.errors.document.imagesBlockPdfOnly",
425
+ print_style_pdf_only: "templateResolver.errors.document.printStylePdfOnly",
426
+ frame_not_top_level: "templateResolver.errors.document.frameNotTopLevel",
405
427
  button_href_not_placeholder: "templateResolver.errors.document.buttonHrefNotPlaceholder",
406
428
  document_requires_html_format: "templateResolver.errors.document.documentRequiresHtmlFormat",
407
429
  layout_requires_mjml_format: "templateResolver.errors.document.layoutRequiresMjmlFormat",
@@ -2,10 +2,12 @@ import {
2
2
  bootRuleError,
3
3
  type ContentCollectionDefinition,
4
4
  createSystemConfig,
5
+ createTenantConfig,
5
6
  defineFeature,
6
7
  type TreeAction,
7
8
  } from "@cosmicdrift/kumiko-framework/engine";
8
9
  import { TEMPLATE_RESOLVER_BOOT_RULES } from "./boot-rules.ts";
10
+ import { makeApplyLayoutWrite } from "./handlers/apply-layout.write.ts";
9
11
  import { makeBodyPreviewQuery } from "./handlers/body-preview.query.ts";
10
12
  import { bySlugQuery } from "./handlers/by-slug.query.ts";
11
13
  import { byTenantQuery } from "./handlers/by-tenant.query.ts";
@@ -13,6 +15,7 @@ import { makeCollectionItemQuery } from "./handlers/collection-item.query.ts";
13
15
  import { makeCollectionListQuery } from "./handlers/collection-list.query.ts";
14
16
  import { makeCollectionSetWrite } from "./handlers/collection-set.write.ts";
15
17
  import { makeCopyLocaleWrite } from "./handlers/copy-locale.write.ts";
18
+ import { makeCreateLayoutWrite } from "./handlers/create-layout.write.ts";
16
19
  import { diffToSystemQuery } from "./handlers/diff-to-system.query.ts";
17
20
  import {
18
21
  makeDiscardDraftSystemWrite,
@@ -28,6 +31,7 @@ import { listQuery } from "./handlers/list.query.ts";
28
31
  import { makeOverviewQuery } from "./handlers/overview.query.ts";
29
32
  import { makePatchDraftWrite } from "./handlers/patch-draft.write.ts";
30
33
  import { previewQuery } from "./handlers/preview.query.ts";
34
+ import { makePublishTemplatesWrite } from "./handlers/publish-templates.write.ts";
31
35
  import { makeResetToSystemWrite } from "./handlers/reset-to-system.write.ts";
32
36
  import { makeResourceLinkPdfWrite } from "./handlers/resource-link-pdf.write.ts";
33
37
  import { makeResourceRemoveWrite } from "./handlers/resource-remove.write.ts";
@@ -159,6 +163,14 @@ export function createTemplateResolverFeature(opts: TemplateResolverOptions = {}
159
163
  r.config({
160
164
  keys: {
161
165
  resourceMaxBytes: createSystemConfig("number", { default: 2_097_152, bounds: { min: 1 } }),
166
+ // Empty means the built-in default layout.
167
+ defaultPdfLayoutSlug: createTenantConfig("text", {
168
+ default: "",
169
+ pattern: {
170
+ regex:
171
+ "^(?:[a-z0-9]{1,40}(?:-[a-z0-9]{1,40}){0,5}(?::[a-z0-9]{1,40}(?:-[a-z0-9]{1,40}){0,5}){0,3})?$",
172
+ },
173
+ }),
162
174
  },
163
175
  });
164
176
  r.translations({ keys: TEMPLATE_RESOLVER_I18N });
@@ -188,6 +200,9 @@ export function createTemplateResolverFeature(opts: TemplateResolverOptions = {}
188
200
  resourceLinkPdf: r.writeHandler(makeResourceLinkPdfWrite(policy)),
189
201
  sendTest: r.writeHandler(makeSendTestWrite(policy)),
190
202
  patchDraft: r.writeHandler(makePatchDraftWrite(policy)),
203
+ applyLayout: r.writeHandler(makeApplyLayoutWrite(policy)),
204
+ createLayout: r.writeHandler(makeCreateLayoutWrite(policy)),
205
+ publishTemplates: r.writeHandler(makePublishTemplatesWrite(policy)),
191
206
  };
192
207
 
193
208
  const queries = {