@cosmicdrift/kumiko-samples 0.419.0 → 0.421.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 (47) hide show
  1. package/package.json +1 -1
  2. package/packages/bundled-features/package.json +6 -1
  3. package/packages/bundled-features/src/auth-email-password/seeding.ts +29 -1
  4. package/packages/bundled-features/src/shared/index.ts +6 -0
  5. package/packages/bundled-features/src/shared/tenant-scoped-subject.ts +28 -0
  6. package/packages/bundled-features/src/signature/changes.json +6 -0
  7. package/packages/bundled-features/src/signature/feature.ts +1 -1
  8. package/packages/bundled-features/src/signature/grant.ts +13 -14
  9. package/packages/bundled-features/src/signature/png.ts +33 -12
  10. package/packages/bundled-features/src/template-resolver/api.ts +17 -7
  11. package/packages/bundled-features/src/template-resolver/changes.json +24 -0
  12. package/packages/bundled-features/src/template-resolver/compile-document-body.ts +7 -1
  13. package/packages/bundled-features/src/template-resolver/compile-document-styles.ts +70 -2
  14. package/packages/bundled-features/src/template-resolver/document-frames.ts +43 -0
  15. package/packages/bundled-features/src/template-resolver/document-op-blocks.ts +135 -21
  16. package/packages/bundled-features/src/template-resolver/document-ops.ts +35 -3
  17. package/packages/bundled-features/src/template-resolver/document-print-only.ts +24 -0
  18. package/packages/bundled-features/src/template-resolver/document-sanitizer.ts +13 -1
  19. package/packages/bundled-features/src/template-resolver/handlers/create-layout.write.ts +1 -1
  20. package/packages/bundled-features/src/template-resolver/handlers/patch-draft.write.ts +2 -1
  21. package/packages/bundled-features/src/template-resolver/handlers/tenant-settings.ts +51 -14
  22. package/packages/bundled-features/src/template-resolver/index.ts +11 -1
  23. package/packages/bundled-features/src/template-resolver/template-meta.ts +7 -1
  24. package/packages/bundled-features/src/template-resolver/template-preview.ts +25 -4
  25. package/packages/bundled-features/src/template-resolver/web/constants.ts +4 -0
  26. package/packages/bundled-features/src/template-resolver/web/document-editor-extensions.ts +60 -24
  27. package/packages/bundled-features/src/template-resolver/web/document-editor.tsx +4 -1
  28. package/packages/bundled-features/src/template-resolver/web/document-print-decorations.ts +55 -5
  29. package/packages/bundled-features/src/template-resolver/web/document-print-style.ts +137 -2
  30. package/packages/bundled-features/src/template-resolver/web/document-repeat-strip.ts +2 -26
  31. package/packages/bundled-features/src/template-resolver/web/document-schema.ts +61 -13
  32. package/packages/bundled-features/src/template-resolver/web/document-style-css.ts +109 -2
  33. package/packages/bundled-features/src/template-resolver/web/document-tiptap-bubble.tsx +161 -14
  34. package/packages/bundled-features/src/template-resolver/web/document-tiptap-content.tsx +4 -0
  35. package/packages/bundled-features/src/template-resolver/web/document-tiptap-editor.tsx +2 -1
  36. package/packages/bundled-features/src/template-resolver/web/document-tiptap-helpers.ts +132 -24
  37. package/packages/bundled-features/src/template-resolver/web/document-tiptap-toolbar-groups.tsx +160 -1
  38. package/packages/bundled-features/src/template-resolver/web/document-tiptap-toolbar.tsx +18 -9
  39. package/packages/bundled-features/src/template-resolver/web/i18n.ts +4 -0
  40. package/packages/bundled-features/src/template-resolver/web/index.ts +4 -0
  41. package/packages/bundled-features/src/template-resolver/web/pdf-constants.ts +10 -0
  42. package/packages/bundled-features/src/template-resolver/web/placeholder-text.ts +6 -3
  43. package/packages/bundled-features/src/tenant/seeding.ts +70 -0
  44. package/samples/apps/ui-walkthrough/src/features/rental/i18n.ts +8 -0
  45. package/samples/apps/ui-walkthrough/src/features/rental/screens.ts +1 -0
  46. package/samples/recipes/prod-boot-options/README.md +8 -1
  47. package/samples/recipes/prod-boot-options/src/app.ts +3 -1
@@ -1,6 +1,7 @@
1
1
  import type { FieldIssue } from "@cosmicdrift/kumiko-framework/errors";
2
2
  import type { JSONContent } from "@tiptap/core";
3
3
  import * as z from "zod";
4
+ import type { LayoutRegionName } from "./layout-regions.ts";
4
5
  import type { DocumentOpsKind } from "./web/constants.ts";
5
6
  import {
6
7
  type DocumentToolbarBlock,
@@ -9,14 +10,21 @@ import {
9
10
  } from "./web/document-blocks.ts";
10
11
  import { DOCUMENT_FONTS } from "./web/document-fonts.ts";
11
12
  import {
13
+ CELL_PADDING_MM_RANGE,
12
14
  COLWIDTH_PX_RANGE,
15
+ DIVIDER_WEIGHT_PT_RANGE,
16
+ DOCUMENT_IMAGE_ALIGNMENTS,
17
+ DOCUMENT_TABLE_ALIGNMENTS,
13
18
  FRAME_MM_RANGE,
14
19
  FRAME_PRESETS,
20
+ IMAGE_WIDTH_MM_RANGE,
15
21
  LINE_HEIGHT_RANGE,
16
22
  PARAGRAPH_SPACE_PT_RANGE,
23
+ TABLE_WIDTH_MM_RANGE,
17
24
  TEXT_SIZE_PT_RANGE,
18
25
  } from "./web/document-print-style.ts";
19
26
  import {
27
+ DOCUMENT_DATE_STYLES,
20
28
  DOCUMENT_TEXT_ALIGNMENTS,
21
29
  isDocumentPlaceholderHref,
22
30
  isDocumentReferenceName,
@@ -98,8 +106,14 @@ const runSchema = textStyleSchema.extend({
98
106
  bold: z.boolean().optional(),
99
107
  italic: z.boolean().optional(),
100
108
  underline: z.boolean().optional(),
109
+ dateStyle: z.enum(DOCUMENT_DATE_STYLES).optional(),
101
110
  });
102
- const runsSchema = z.array(runSchema).min(1).max(50);
111
+ // A line break inside a paragraph or table cell; the lines around it keep their own formatting.
112
+ const hardBreakSchema = z.object({ hardBreak: z.literal(true) });
113
+ const runsSchema = z
114
+ .array(z.union([runSchema, hardBreakSchema]))
115
+ .min(1)
116
+ .max(50);
103
117
 
104
118
  const blockStyleSchema = z.object({
105
119
  lineHeight: rangeNumber(LINE_HEIGHT_RANGE).optional(),
@@ -121,7 +135,16 @@ const cellSchema = z.object({
121
135
  background: hexColor.optional(),
122
136
  align: alignSchema.optional(),
123
137
  });
124
- const rowSchema = z.object({ cells: z.array(cellSchema).min(1).max(20) });
138
+ // A rule over or under a row, e.g. the dark line under a table header or above a total.
139
+ const rowLineSchema = z.object({
140
+ color: hexColor,
141
+ weightPt: rangeNumber(DIVIDER_WEIGHT_PT_RANGE),
142
+ });
143
+ const rowSchema = z.object({
144
+ cells: z.array(cellSchema).min(1).max(20),
145
+ lineAbove: rowLineSchema.optional(),
146
+ lineBelow: rowLineSchema.optional(),
147
+ });
125
148
 
126
149
  const paragraphSchema = z.object({
127
150
  type: z.literal("paragraph"),
@@ -146,15 +169,27 @@ const listSchema = z.object({
146
169
  const tableSchema = z.object({
147
170
  type: z.literal("table"),
148
171
  borders: z.literal("none").optional(),
172
+ cellPaddingMm: rangeNumber(CELL_PADDING_MM_RANGE).optional(),
173
+ widthMm: rangeNumber(TABLE_WIDTH_MM_RANGE).optional(),
174
+ align: z.enum(DOCUMENT_TABLE_ALIGNMENTS).optional(),
149
175
  columnWidthsPx: z.array(rangeNumber(COLWIDTH_PX_RANGE)).min(1).max(20).optional(),
150
176
  header: rowSchema.optional(),
151
177
  rows: z.array(rowSchema).max(100),
152
178
  repeat: z.object({ each: z.string().min(1).max(100), row: rowSchema }).optional(),
179
+ rowsAfterRepeat: z.array(rowSchema).max(100).optional(),
153
180
  });
154
181
  const imageSchema = z.object({
155
182
  type: z.literal("image"),
156
183
  resource: z.string().min(1).max(200),
157
184
  alt: z.string().max(500).optional(),
185
+ widthMm: rangeNumber(IMAGE_WIDTH_MM_RANGE).optional(),
186
+ align: z.enum(DOCUMENT_IMAGE_ALIGNMENTS).optional(),
187
+ bleed: z.boolean().optional(),
188
+ });
189
+ const dividerSchema = z.object({
190
+ type: z.literal("divider"),
191
+ color: hexColor.optional(),
192
+ weightPt: rangeNumber(DIVIDER_WEIGHT_PT_RANGE).optional(),
158
193
  });
159
194
 
160
195
  const frameSchema = z.object({
@@ -187,7 +222,7 @@ export const blockInputSchema = z.discriminatedUnion("type", [
187
222
  frameSchema,
188
223
  imageSchema,
189
224
  z.object({ type: z.literal("button"), text: singleLineText, href: z.string().max(300) }),
190
- z.object({ type: z.literal("divider") }),
225
+ dividerSchema,
191
226
  z.object({ type: z.literal("pageBreak") }),
192
227
  ]);
193
228
 
@@ -197,13 +232,18 @@ export type TextFormat = z.infer<typeof blockFormatSchema>;
197
232
  type Mark = NonNullable<JSONContent["marks"]>[number];
198
233
  type TextStyle = z.infer<typeof textStyleSchema>;
199
234
  type Run = z.infer<typeof runSchema>;
235
+ type RunOrBreak = z.infer<typeof runsSchema>[number];
200
236
  type Row = z.infer<typeof rowSchema>;
201
237
  type InlineSource = {
202
238
  readonly text?: string | undefined;
203
- readonly runs?: readonly Run[] | undefined;
239
+ readonly runs?: readonly RunOrBreak[] | undefined;
204
240
  };
205
241
 
206
- export type BuildContext = { readonly kind: DocumentOpsKind; readonly issues: FieldIssue[] };
242
+ export type BuildContext = {
243
+ readonly kind: DocumentOpsKind;
244
+ readonly region?: LayoutRegionName | undefined;
245
+ readonly issues: FieldIssue[];
246
+ };
207
247
 
208
248
  function report(
209
249
  ctx: BuildContext,
@@ -272,11 +312,13 @@ function inlineNodes(
272
312
  if (runs === undefined) {
273
313
  return withMarks(lineToContent(singleLine(text ?? "")), textStyleMarks(base));
274
314
  }
275
- return runs.flatMap((run) =>
276
- withMarks(lineToContent(singleLine(run.text)), [
277
- ...runMarks(run),
278
- ...textStyleMarks({ ...base, ...definedStyle(run) }),
279
- ]),
315
+ return runs.flatMap((run): JSONContent[] =>
316
+ "hardBreak" in run
317
+ ? [{ type: "hardBreak" }]
318
+ : withMarks(lineToContent(singleLine(run.text), run.dateStyle), [
319
+ ...runMarks(run),
320
+ ...textStyleMarks({ ...base, ...definedStyle(run) }),
321
+ ]),
280
322
  );
281
323
  }
282
324
 
@@ -344,9 +386,14 @@ function rowNode(
344
386
  problem: "columnWidthsPx must match the cells per row",
345
387
  });
346
388
  }
389
+ const attrs = {
390
+ ...options.attrs,
391
+ ...(row.lineAbove === undefined ? {} : { lineAbove: row.lineAbove }),
392
+ ...(row.lineBelow === undefined ? {} : { lineBelow: row.lineBelow }),
393
+ };
347
394
  return {
348
395
  type: "tableRow",
349
- ...(options.attrs === undefined ? {} : { attrs: options.attrs }),
396
+ ...(Object.keys(attrs).length === 0 ? {} : { attrs }),
350
397
  content: row.cells.map((cell, index): JSONContent => {
351
398
  const width = options.widths?.[index];
352
399
  const attrs = {
@@ -363,17 +410,38 @@ function rowNode(
363
410
  };
364
411
  }
365
412
 
413
+ function reportInvalidRepeat(
414
+ ctx: BuildContext,
415
+ path: string,
416
+ repeat: Extract<BlockInput, { type: "table" }>["repeat"],
417
+ ): void {
418
+ if (repeat === undefined) return;
419
+ if (!isDocumentReferenceName(repeat.each)) {
420
+ report(ctx, `${path}.repeat.each`, "invalid_repeat_variable", { each: repeat.each });
421
+ }
422
+ if (!allowedBlocksFor(ctx.kind).includes("repeat")) {
423
+ report(ctx, `${path}.repeat`, "block_not_allowed", { type: "repeat", kind: ctx.kind });
424
+ }
425
+ }
426
+
427
+ function tableAttrsOf(block: Extract<BlockInput, { type: "table" }>) {
428
+ return {
429
+ ...(block.borders === undefined ? {} : { borders: block.borders }),
430
+ ...(block.cellPaddingMm === undefined ? {} : { cellPaddingMm: block.cellPaddingMm }),
431
+ ...(block.widthMm === undefined ? {} : { widthMm: block.widthMm }),
432
+ ...(block.align === undefined ? {} : { align: block.align }),
433
+ };
434
+ }
435
+
366
436
  function tableNode(ctx: BuildContext, path: string, block: Extract<BlockInput, { type: "table" }>) {
367
437
  const widths = block.columnWidthsPx;
368
- const { header, repeat } = block;
369
- if (repeat !== undefined) {
370
- if (!isDocumentReferenceName(repeat.each)) {
371
- report(ctx, `${path}.repeat.each`, "invalid_repeat_variable", { each: repeat.each });
372
- }
373
- if (!allowedBlocksFor(ctx.kind).includes("repeat")) {
374
- report(ctx, `${path}.repeat`, "block_not_allowed", { type: "repeat", kind: ctx.kind });
375
- }
438
+ const { header, repeat, rowsAfterRepeat } = block;
439
+ if (rowsAfterRepeat !== undefined && repeat === undefined) {
440
+ report(ctx, `${path}.rowsAfterRepeat`, "invalid_table", {
441
+ problem: "rowsAfterRepeat needs a repeat row to follow",
442
+ });
376
443
  }
444
+ reportInvalidRepeat(ctx, path, repeat);
377
445
  const rows = [
378
446
  ...(header === undefined
379
447
  ? []
@@ -396,6 +464,9 @@ function tableNode(ctx: BuildContext, path: string, block: Extract<BlockInput, {
396
464
  attrs: { each: repeat.each },
397
465
  }),
398
466
  ]),
467
+ ...(rowsAfterRepeat ?? []).map((row, index) =>
468
+ rowNode(ctx, `${path}.rowsAfterRepeat.${index}`, row, { header: false, widths }),
469
+ ),
399
470
  ];
400
471
  const cellCounts = new Set(rows.map((row) => row.content?.length ?? 0));
401
472
  if (rows.length === 0 || cellCounts.size > 1) {
@@ -403,9 +474,10 @@ function tableNode(ctx: BuildContext, path: string, block: Extract<BlockInput, {
403
474
  problem: "needs a row and the same number of cells in every row",
404
475
  });
405
476
  }
477
+ const tableAttrs = tableAttrsOf(block);
406
478
  return {
407
479
  type: "table",
408
- ...(block.borders === undefined ? {} : { attrs: { borders: block.borders } }),
480
+ ...(Object.keys(tableAttrs).length === 0 ? {} : { attrs: tableAttrs }),
409
481
  content: rows,
410
482
  };
411
483
  }
@@ -429,6 +501,19 @@ function frameNode(
429
501
  };
430
502
  }
431
503
 
504
+ // Only the header and footer print outside the page margins, so only they can reach the paper edge.
505
+ function isBleedRegion(region: LayoutRegionName | undefined): boolean {
506
+ return region === "header" || region === "footer";
507
+ }
508
+
509
+ function dividerNode(input: Extract<BlockInput, { type: "divider" }>): JSONContent {
510
+ const attrs = {
511
+ ...(input.color === undefined ? {} : { color: input.color }),
512
+ ...(input.weightPt === undefined ? {} : { weightPt: input.weightPt }),
513
+ };
514
+ return { type: "divider", ...(Object.keys(attrs).length === 0 ? {} : { attrs }) };
515
+ }
516
+
432
517
  function imageNode(
433
518
  ctx: BuildContext,
434
519
  path: string,
@@ -437,7 +522,19 @@ function imageNode(
437
522
  if (!isDocumentResourceKey(input.resource)) {
438
523
  report(ctx, `${path}.resource`, "invalid_resource_key", { resource: input.resource });
439
524
  }
440
- return { type: "resource", attrs: { resource: input.resource, alt: input.alt ?? null } };
525
+ if (input.bleed === true && !(ctx.kind === "pdf-layout" && isBleedRegion(ctx.region))) {
526
+ report(ctx, `${path}.bleed`, "bleed_not_allowed", { kind: ctx.kind });
527
+ }
528
+ return {
529
+ type: "resource",
530
+ attrs: {
531
+ resource: input.resource,
532
+ alt: input.alt ?? null,
533
+ ...(input.widthMm === undefined ? {} : { widthMm: input.widthMm }),
534
+ ...(input.align === undefined ? {} : { align: input.align }),
535
+ ...(input.bleed === true ? { bleed: true } : {}),
536
+ },
537
+ };
441
538
  }
442
539
 
443
540
  function buttonNode(
@@ -475,6 +572,7 @@ export function blockNode(ctx: BuildContext, path: string, input: BlockInput): J
475
572
  case "button":
476
573
  return buttonNode(ctx, path, input);
477
574
  case "divider":
575
+ return dividerNode(input);
478
576
  case "pageBreak":
479
577
  return { type: input.type };
480
578
  }
@@ -487,16 +585,32 @@ const PRINT_ATTRIBUTES = [
487
585
  "background",
488
586
  "colwidth",
489
587
  "borders",
588
+ "cellPaddingMm",
589
+ "lineAbove",
590
+ "lineBelow",
490
591
  ] as const;
491
592
 
492
593
  function isPresent(value: unknown): boolean {
493
594
  return value !== undefined && value !== null;
494
595
  }
495
596
 
597
+ // An image's bleed defaults to false, so a present attribute alone says nothing there.
598
+ function hasPrintOnlyBoxAttributes(node: JSONContent): boolean {
599
+ const attrs = node.attrs;
600
+ if (node.type === "resource") {
601
+ return (
602
+ attrs?.["bleed"] === true || isPresent(attrs?.["widthMm"]) || isPresent(attrs?.["align"])
603
+ );
604
+ }
605
+ if (node.type === "table") return isPresent(attrs?.["widthMm"]) || isPresent(attrs?.["align"]);
606
+ return node.type === "divider" && (isPresent(attrs?.["color"]) || isPresent(attrs?.["weightPt"]));
607
+ }
608
+
496
609
  // Frames are refused as blocks, so only the styling that would ride along in other blocks counts here.
497
610
  export function usesPrintStyling(node: JSONContent): boolean {
498
611
  if (node.marks?.some((mark) => mark.type === "documentTextStyle")) return true;
499
612
  if (PRINT_ATTRIBUTES.some((name) => isPresent(node.attrs?.[name]))) return true;
613
+ if (hasPrintOnlyBoxAttributes(node)) return true;
500
614
  return (node.content ?? []).some(usesPrintStyling);
501
615
  }
502
616
 
@@ -14,6 +14,7 @@ import {
14
14
  patchIssue,
15
15
  refusePrintStyling,
16
16
  } from "./document-op-blocks.ts";
17
+ import type { LayoutRegionName } from "./layout-regions.ts";
17
18
  import { toVariableDef } from "./template-validation.ts";
18
19
  import type { DocumentOpsKind } from "./web/constants.ts";
19
20
  import {
@@ -51,6 +52,10 @@ export type DocumentBlock = {
51
52
  readonly showIf?: string;
52
53
  readonly resource?: string;
53
54
  readonly alt?: string;
55
+ readonly widthMm?: number;
56
+ readonly bleed?: boolean;
57
+ readonly color?: string;
58
+ readonly weightPt?: number;
54
59
  readonly href?: string;
55
60
  readonly each?: string;
56
61
  readonly frame?: FrameBox;
@@ -102,8 +107,15 @@ function eachOf(table: JSONContent): string | undefined {
102
107
  return undefined;
103
108
  }
104
109
 
110
+ // A line break reads back as "\n"; writing text collapses it again, so a break is set with runs.
111
+ function lineWithBreaks(content: readonly JSONContent[] | undefined): string {
112
+ return (content ?? [])
113
+ .map((node) => (node.type === "hardBreak" ? "\n" : contentToLine([node])))
114
+ .join("");
115
+ }
116
+
105
117
  function textLinesOf(node: JSONContent): string[] {
106
- if (TEXT_BLOCK_TYPES.has(node.type ?? "")) return [contentToLine(node.content)];
118
+ if (TEXT_BLOCK_TYPES.has(node.type ?? "")) return [lineWithBreaks(node.content)];
107
119
  return (node.content ?? []).flatMap(textLinesOf);
108
120
  }
109
121
 
@@ -123,6 +135,21 @@ function setOptionalAttrs(block: MutableBlock, node: JSONContent): void {
123
135
  if (showIf !== undefined) block.showIf = showIf;
124
136
  }
125
137
 
138
+ function setImagePrintAttrs(block: MutableBlock, node: JSONContent): void {
139
+ const widthMm: unknown = node.attrs?.["widthMm"];
140
+ if (typeof widthMm === "number") block.widthMm = widthMm;
141
+ if (node.attrs?.["bleed"] === true) block.bleed = true;
142
+ const align = stringAttr(node, "align");
143
+ if (align !== undefined) block.align = align;
144
+ }
145
+
146
+ function setDividerAttrs(block: MutableBlock, node: JSONContent): void {
147
+ const color = stringAttr(node, "color");
148
+ if (color !== undefined) block.color = color;
149
+ const weightPt: unknown = node.attrs?.["weightPt"];
150
+ if (typeof weightPt === "number") block.weightPt = weightPt;
151
+ }
152
+
126
153
  function setTypeSpecificAttrs(block: MutableBlock, node: JSONContent): void {
127
154
  const level: unknown = node.attrs?.["level"];
128
155
  if (block.type === "heading" && typeof level === "number") block.level = level;
@@ -130,6 +157,8 @@ function setTypeSpecificAttrs(block: MutableBlock, node: JSONContent): void {
130
157
  if (block.type === "image" && resource !== undefined) block.resource = resource;
131
158
  const alt = stringAttr(node, "alt");
132
159
  if (block.type === "image" && alt !== undefined) block.alt = alt;
160
+ if (block.type === "image") setImagePrintAttrs(block, node);
161
+ if (block.type === "divider") setDividerAttrs(block, node);
133
162
  const href = stringAttr(node, "href");
134
163
  if (block.type === "button" && href !== undefined) block.href = href;
135
164
  const each = eachOf(node);
@@ -216,6 +245,7 @@ export type DocumentOpsInput = {
216
245
  readonly meta: Readonly<Record<string, unknown>>;
217
246
  readonly variableSchema: Readonly<Record<string, unknown>>;
218
247
  readonly kind: DocumentOpsKind;
248
+ readonly region?: LayoutRegionName | undefined;
219
249
  readonly ops: readonly DocumentOp[];
220
250
  };
221
251
 
@@ -289,6 +319,7 @@ function isValidDocument(doc: JSONContent): boolean {
289
319
 
290
320
  type OpState = {
291
321
  readonly kind: DocumentOpsKind;
322
+ readonly region: LayoutRegionName | undefined;
292
323
  replacement: JSONContent[] | null;
293
324
  readonly entries: Map<string, Entry>;
294
325
  readonly insertedAtStart: JSONContent[];
@@ -312,7 +343,7 @@ function buildBlocks(
312
343
  blocks: readonly BlockInput[],
313
344
  pathOf: (index: number) => string,
314
345
  ): { readonly nodes: JSONContent[]; readonly issues: FieldIssue[] } {
315
- const ctx: BuildContext = { kind: state.kind, issues: [] };
346
+ const ctx: BuildContext = { kind: state.kind, region: state.region, issues: [] };
316
347
  const nodes = blocks.map((block, index) => blockNode(ctx, pathOf(index), block));
317
348
  nodes.forEach((node, index) => {
318
349
  const refused = refusePrintStyling(state.kind, node, pathOf(index));
@@ -444,7 +475,7 @@ function setResourceOp(
444
475
  return patchIssue(`${path}.resource`, "invalid_resource_key", { resource: op.resource });
445
476
  }
446
477
  const alt = op.alt === undefined ? (entry.node.attrs?.["alt"] ?? null) : op.alt;
447
- entry.node = { ...entry.node, attrs: { resource: op.resource, alt } };
478
+ entry.node = { ...entry.node, attrs: { ...entry.node.attrs, resource: op.resource, alt } };
448
479
  return null;
449
480
  }
450
481
 
@@ -522,6 +553,7 @@ export function applyDocumentOps(input: DocumentOpsInput): DocumentOpsResult {
522
553
  });
523
554
  const state: OpState = {
524
555
  kind: input.kind,
556
+ region: input.region,
525
557
  replacement: null,
526
558
  entries,
527
559
  insertedAtStart: [],
@@ -1,6 +1,8 @@
1
1
  // Server-only (happy-dom). Features of the shared document model that only a PDF can render:
2
2
  // a mail body would keep them through the rebuild, so every other kind refuses them on write.
3
3
  import type { Element as ScanElement } from "happy-dom";
4
+ import { readFrameAttributes } from "./web/document-print-style.ts";
5
+ import { PDF_MAX_PAGE_EDGE_MM } from "./web/pdf-constants.ts";
4
6
 
5
7
  export const IMAGES_BLOCK_SELECTOR = "div[data-images]";
6
8
 
@@ -11,9 +13,18 @@ export const PRINT_STYLE_SELECTORS = [
11
13
  "[data-space-before]",
12
14
  "[data-space-after]",
13
15
  "table[data-borders]",
16
+ "table[data-cell-padding-mm]",
17
+ "table[data-table-width-mm]",
18
+ "table[data-table-align]",
19
+ "tr[data-line-above]",
20
+ "tr[data-line-below]",
14
21
  "[data-background]",
15
22
  "[data-colwidth]",
16
23
  "img[data-bleed]",
24
+ "img[data-width-mm]",
25
+ "img[data-align]",
26
+ "hr[data-color]",
27
+ "hr[data-weight-pt]",
17
28
  ] as const;
18
29
 
19
30
  export type PrintOnlyFeatures = {
@@ -36,6 +47,19 @@ export function hasNestedFrame(body: ScanElement): boolean {
36
47
  );
37
48
  }
38
49
 
50
+ export function framesOutsidePage(body: ScanElement): string[] {
51
+ return Array.from(body.querySelectorAll("div[data-frame]")).flatMap((element) => {
52
+ const frame = readFrameAttributes(element);
53
+ if (frame === null) return [];
54
+ const overshootsPage =
55
+ frame.xMm + frame.widthMm > PDF_MAX_PAGE_EDGE_MM ||
56
+ frame.yMm + frame.heightMm > PDF_MAX_PAGE_EDGE_MM;
57
+ return overshootsPage
58
+ ? [`${frame.xMm}/${frame.yMm} ${frame.widthMm}x${frame.heightMm} mm`]
59
+ : [];
60
+ });
61
+ }
62
+
39
63
  export function hasFrame(body: ScanElement): boolean {
40
64
  return body.querySelector("div[data-frame]") !== null;
41
65
  }
@@ -5,7 +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
+ import { framesOutsidePage, hasNestedFrame, scanPrintOnlyFeatures } from "./document-print-only.ts";
9
9
  import type { ContentFormat } from "./web/constants.ts";
10
10
  import { DOCUMENT_HTML_KINDS } from "./web/constants.ts";
11
11
  import {
@@ -18,6 +18,7 @@ import {
18
18
  isDocumentResourceKey,
19
19
  } from "./web/document-schema.ts";
20
20
  import { isDocumentStepKey } from "./web/document-steps.ts";
21
+ import { PDF_MAX_PAGE_EDGE_MM } from "./web/pdf-constants.ts";
21
22
 
22
23
  export type DocumentViolationCode =
23
24
  | "script_element"
@@ -32,6 +33,7 @@ export type DocumentViolationCode =
32
33
  | "images_block_pdf_only"
33
34
  | "print_style_pdf_only"
34
35
  | "frame_not_top_level"
36
+ | "frame_outside_page"
35
37
  | "button_href_not_placeholder"
36
38
  | "document_requires_html_format"
37
39
  | "layout_requires_mjml_format"
@@ -274,6 +276,15 @@ function scanDocumentHtml(html: string): DocumentViolation[] {
274
276
  ),
275
277
  );
276
278
  }
279
+ for (const box of framesOutsidePage(body)) {
280
+ violations.push(
281
+ violation(
282
+ "frame_outside_page",
283
+ box,
284
+ `A frame (${box}) must lie within the largest supported paper size (${PDF_MAX_PAGE_EDGE_MM} mm)`,
285
+ ),
286
+ );
287
+ }
277
288
  });
278
289
  return violations;
279
290
  }
@@ -424,6 +435,7 @@ const VIOLATION_I18N_KEYS: Readonly<Record<DocumentViolationCode, string>> = {
424
435
  images_block_pdf_only: "templateResolver.errors.document.imagesBlockPdfOnly",
425
436
  print_style_pdf_only: "templateResolver.errors.document.printStylePdfOnly",
426
437
  frame_not_top_level: "templateResolver.errors.document.frameNotTopLevel",
438
+ frame_outside_page: "templateResolver.errors.document.frameOutsidePage",
427
439
  button_href_not_placeholder: "templateResolver.errors.document.buttonHrefNotPlaceholder",
428
440
  document_requires_html_format: "templateResolver.errors.document.documentRequiresHtmlFormat",
429
441
  layout_requires_mjml_format: "templateResolver.errors.document.layoutRequiresMjmlFormat",
@@ -30,7 +30,7 @@ export function makeCreateLayoutWrite(policy: TemplateEditPolicy) {
30
30
  access: templateEditAccess(policy.tenantEditable),
31
31
  agent: { risk: "low", effect: "proposal" },
32
32
  description:
33
- "Creates a new PDF layout of the caller's tenant as a draft under the slug tenant-layout-<name> (name is kebab-case) with empty header, signature and footer regions and the standard look (font, size, table style); it fails with layout_exists when the tenant already has that layout. A TenantAdmin may create layouts as soon as they may edit any PDF template; every other caller is refused. Returns the full slug, locale, kind and base ({scope, version}) for the next call. Next steps: fill the regions with patch-draft (kind pdf-layout, the returned slug, region header, signature or footer; setMeta changes margins, fontFamily, fontSizePt, textColor, tableStyle, tableHeaderBackground), then let a person publish the layout and point a PDF template at it with patch-draft setMeta {layoutSlug: <returned slug>}.",
33
+ "Creates a new PDF layout of the caller's tenant as a draft under the slug tenant-layout-<name> (name is kebab-case) with empty header, signature and footer regions and the standard look (font, size, table style); it fails with layout_exists when the tenant already has that layout. A TenantAdmin may create layouts as soon as they may edit any PDF template; every other caller is refused. Returns the full slug, locale, kind and base ({scope, version}) for the next call. Next steps: fill the regions with patch-draft (kind pdf-layout, the returned slug, region header, signature or footer; setMeta changes margins {top,right,bottom,left in mm}, fontFamily, fontSizePt, textColor, tableStyle, tableHeaderBackground, tableLineColor (#rrggbb, line color of the table style, default #bbb), foldMarks (none|din-a|din-b: DIN 5008 fold and punch marks at the left paper edge on every page, form A folds at 87 and 192 mm, form B at 105 and 210 mm), cornerMarks (boolean, default false; angles of 5 mm legs, 0.5 pt, 10 mm from the paper edge in all four corners of every page), paperColor (#rrggbb when the whole page has a tinted paper background, margins, header and footer included; default white), headerOnFirstPage and footerOnFirstPage (booleans, default true; false prints the header or footer only from page 2, margins stay the same)), then let a person publish the layout and point a PDF template at it with patch-draft setMeta {layoutSlug: <returned slug>}.",
34
34
  handler: async (event, ctx) => {
35
35
  const { name, title, locale } = event.payload;
36
36
  const slug = `${TENANT_LAYOUT_SLUG_PREFIX}${name}`;
@@ -46,7 +46,7 @@ export function makePatchDraftWrite(policy: TemplateEditPolicy) {
46
46
  access: templateEditAccess(policy.tenantEditable),
47
47
  agent: { risk: "low", effect: "proposal" },
48
48
  description:
49
- 'Changes a mail template, a PDF document template (kind document-pdf) or one region of a PDF layout (kind pdf-layout with region header, signature or footer; a tenant edits its own layouts under the slug tenant-layout-<name>, created with create-layout) with structured operations instead of a full rewrite and saves the result as the caller\'s tenant draft (never published, an active version keeps being served until publish). Never send raw HTML: every block goes through the same checks as the editor. Block forms: paragraph and heading {text} or {runs:[{text,bold,italic,underline,font,sizePt,color}]} with optional align, style {lineHeight,spaceBeforePt,spaceAfterPt} and textStyle {font,sizePt,color}; list {ordered,items:[text or runs]}; table {borders:"none",columnWidthsPx,header:{cells:[{text|runs,background,align}]},rows:[{cells}],repeat:{each:<list variable>,row}} (repeat is the row printed once per list entry; header repeats on every page); frame {xMm,yMm,widthMm,heightMm,preset:address|text,reserveFlow,blocks} only in document-pdf, at the top level (the DIN address window is x20 y45 w85 h45 with preset address); image {resource,alt}; button {text,href} mails only; divider; pageBreak PDF only. Fonts, sizes, colors (#rrggbb), line spacing, borders, backgrounds and frames are print styling: PDF only, a mail refuses them with print_style_not_allowed. Operations: insertBlock after a block id (null = at the start), replaceBody {blocks} (replaces the whole content, at most 300 blocks including the ones inside frames; read ids no longer apply afterwards), formatBlock {blockId,align,style,textStyle} on a paragraph, heading or list, replaceText inside one block (the text must occur exactly once within one formatting run and cannot contain a {{placeholder}}: a find across a formatting change fails with text_spans_formatting, a find with a placeholder with placeholder_not_replaceable, and the formatting of the replaced text is kept), removeBlock, setResource on an image block, setMeta (flat merge, null removes a key) and setVariable (adds, replaces or with null removes a variable definition; refused when a notification declares the variables). Block ids and base come from document-blocks and refer to the state that was read; if the template changed since, the call fails with version_conflict and nothing is written. A patch that removes a required placeholder is refused. A TenantAdmin may patch only templates the app lists in tenantEditable, otherwise SystemAdmin only. Returns the written row.',
49
+ 'Changes a mail template, a PDF document template (kind document-pdf) or one region of a PDF layout (kind pdf-layout with region header, signature or footer; a tenant edits its own layouts under the slug tenant-layout-<name>, created with create-layout) with structured operations instead of a full rewrite and saves the result as the caller\'s tenant draft (never published, an active version keeps being served until publish). Never send raw HTML: every block goes through the same checks as the editor. Block forms: paragraph and heading {text} or {runs:[{text,bold,italic,underline,font,sizePt,color,dateStyle (short prints a date placeholder in that run as 15.01.2026, long is the default 15. January 2026; both follow the document locale)}]} with optional align, style {lineHeight,spaceBeforePt,spaceAfterPt} and textStyle {font,sizePt,color}; list {ordered,items:[text or runs]}; table {borders:"none",cellPaddingMm (0 to 10, padding inside every cell),widthMm (0.1 to 210, table width),align:left|center|right (placement of a table narrower than the text area),columnWidthsPx,header:{cells:[{text|runs,background,align}]},rows:[{cells,lineAbove:{color #rrggbb,weightPt 0.25 to 4},lineBelow:{...}}],repeat:{each:<list variable>,row},rowsAfterRepeat:[{cells,lineAbove,lineBelow}]} (a row line is a rule on the top or bottom edge of that row; it beats tableLineColor there and works on the header, repeat and rowsAfterRepeat rows too) (repeat is the row printed once per list entry; header repeats on every page; rowsAfterRepeat are printed once below the repeated rows, e.g. total lines, and need a repeat); a run is {text,bold,italic,underline,font,sizePt,color} or {hardBreak:true}, which starts a new line inside the paragraph or table cell, e.g. a description followed by a small grey second line; frame {xMm,yMm,widthMm,heightMm,preset:address|text,reserveFlow,blocks} only in document-pdf, at the top level (the DIN address window is x20 y45 w85 h45 with preset address); image {resource,alt,widthMm (0.1 to 210, printed width; without it the image keeps its natural size, in a layout region at most 20 mm high),align:left|center|right,bleed (true runs the image from paper edge to paper edge, flush with the top in a header and with the bottom in a footer; only in the header or footer region of a pdf-layout, refused elsewhere with bleed_not_allowed)}; button {text,href} mails only; divider {color #rrggbb,weightPt 0.25 to 4}; pageBreak PDF only. Fonts, sizes, colors (#rrggbb), line spacing, borders, backgrounds and frames are print styling: PDF only, a mail refuses them with print_style_not_allowed. Operations: insertBlock after a block id (null = at the start), replaceBody {blocks} (replaces the whole content, at most 300 blocks including the ones inside frames; read ids no longer apply afterwards), formatBlock {blockId,align,style,textStyle} on a paragraph, heading or list, replaceText inside one block (the text must occur exactly once within one formatting run and cannot contain a {{placeholder}}: a find across a formatting change fails with text_spans_formatting, a find with a placeholder with placeholder_not_replaceable, and the formatting of the replaced text is kept), removeBlock, setResource on an image block, setMeta (flat merge, null removes a key; layout keys are listed with create-layout) and setVariable (adds, replaces or with null removes a variable definition; refused when a notification declares the variables). Block ids and base come from document-blocks and refer to the state that was read; if the template changed since, the call fails with version_conflict and nothing is written. A patch that removes a required placeholder is refused. A TenantAdmin may patch only templates the app lists in tenantEditable, otherwise SystemAdmin only. Returns the written row.',
50
50
  handler: async (event, ctx) => {
51
51
  const { slug, kind, region, locale, base, ops } = event.payload;
52
52
  const misplacedRegion = regionIssue(kind, region);
@@ -83,6 +83,7 @@ export function makePatchDraftWrite(policy: TemplateEditPolicy) {
83
83
  meta: loaded.meta,
84
84
  variableSchema: loaded.variableSchema,
85
85
  kind,
86
+ region,
86
87
  ops,
87
88
  });
88
89
  if (!applied.ok) return writeFailure(new ValidationError({ fields: applied.issues }));
@@ -1,6 +1,6 @@
1
1
  import type { HandlerContext } from "@cosmicdrift/kumiko-framework/engine";
2
2
  import { toKebab } from "@cosmicdrift/kumiko-types/kebab-case";
3
- import { createTemplateResolverApi, TemplateNotFoundError } from "../api.ts";
3
+ import { createTemplateResolverApi, TemplateNotFoundError, type TemplateResource } from "../api.ts";
4
4
  import { withParsedDocument } from "../document-sanitizer.ts";
5
5
  import { parseTemplateMeta, readPdfTemplateMeta } from "../template-meta.ts";
6
6
  import {
@@ -33,27 +33,57 @@ type DefaultLayoutContext = Pick<HandlerContext, "config" | "registry"> & {
33
33
 
34
34
  // A configured default that no longer resolves (archived or deleted) must not leave documents
35
35
  // without letterhead, so it falls back to the built-in layout.
36
- export async function defaultPdfLayoutSlug(
36
+ export type DefaultPdfLayout = {
37
+ readonly slug: string;
38
+ // Set only when the configured default was resolved to check it; the built-in fallback is not looked up here.
39
+ readonly resolved: TemplateResource | null;
40
+ };
41
+
42
+ export async function resolveDefaultPdfLayout(
37
43
  ctx: DefaultLayoutContext,
38
44
  tenantId: string,
39
45
  locale: string = FALLBACK_LOCALE,
40
- ): Promise<string> {
46
+ working = false,
47
+ ): Promise<DefaultPdfLayout> {
41
48
  const slug = await readTenantConfigText(ctx, DEFAULT_PDF_LAYOUT_SLUG_CONFIG_KEY);
42
- if (slug === "") return DEFAULT_PDF_LAYOUT_SLUG;
49
+ if (slug === "") return { slug: DEFAULT_PDF_LAYOUT_SLUG, resolved: null };
43
50
  try {
44
- await createTemplateResolverApi(ctx.db, ctx.registry).resolveLayout({
51
+ const resolved = await createTemplateResolverApi(ctx.db, ctx.registry).resolveLayout({
45
52
  tenantId,
46
53
  slug,
47
54
  kind: "pdf-layout",
48
55
  locale,
56
+ working,
49
57
  });
50
- return slug;
58
+ return { slug, resolved };
51
59
  } catch (e) {
52
- if (e instanceof TemplateNotFoundError) return DEFAULT_PDF_LAYOUT_SLUG;
60
+ if (e instanceof TemplateNotFoundError) {
61
+ return { slug: DEFAULT_PDF_LAYOUT_SLUG, resolved: null };
62
+ }
53
63
  throw e;
54
64
  }
55
65
  }
56
66
 
67
+ // A layout the document names itself wins; only without one is the tenant default resolved (once, so callers reuse it).
68
+ export async function effectivePdfLayout(
69
+ ctx: DefaultLayoutContext,
70
+ tenantId: string,
71
+ ownSlug: string | undefined,
72
+ locale: string = FALLBACK_LOCALE,
73
+ working = false,
74
+ ): Promise<DefaultPdfLayout> {
75
+ if (ownSlug !== undefined) return { slug: ownSlug, resolved: null };
76
+ return resolveDefaultPdfLayout(ctx, tenantId, locale, working);
77
+ }
78
+
79
+ export async function defaultPdfLayoutSlug(
80
+ ctx: DefaultLayoutContext,
81
+ tenantId: string,
82
+ locale: string = FALLBACK_LOCALE,
83
+ ): Promise<string> {
84
+ return (await resolveDefaultPdfLayout(ctx, tenantId, locale)).slug;
85
+ }
86
+
57
87
  export function isCompanyPlaceholder(name: string): boolean {
58
88
  return COMPANY_PLACEHOLDERS.some((candidate) => candidate === name);
59
89
  }
@@ -77,14 +107,21 @@ async function layoutHtmlOf(
77
107
  const parsedMeta = parseTemplateMeta("document-pdf", meta);
78
108
  const pdfMeta = parsedMeta.ok ? readPdfTemplateMeta(parsedMeta.meta) : null;
79
109
  const effectiveLocale = locale ?? FALLBACK_LOCALE;
80
- const slug = pdfMeta?.layoutSlug ?? (await defaultPdfLayoutSlug(ctx, tenantId, effectiveLocale));
110
+ const { slug, resolved } = await effectivePdfLayout(
111
+ ctx,
112
+ tenantId,
113
+ pdfMeta?.layoutSlug,
114
+ effectiveLocale,
115
+ );
81
116
  try {
82
- const layout = await createTemplateResolverApi(ctx.db, ctx.registry).resolveLayout({
83
- tenantId,
84
- slug,
85
- kind: "pdf-layout",
86
- locale: effectiveLocale,
87
- });
117
+ const layout =
118
+ resolved ??
119
+ (await createTemplateResolverApi(ctx.db, ctx.registry).resolveLayout({
120
+ tenantId,
121
+ slug,
122
+ kind: "pdf-layout",
123
+ locale: effectiveLocale,
124
+ }));
88
125
  return layout.content ?? "";
89
126
  } catch (e) {
90
127
  if (e instanceof TemplateNotFoundError) return "";