@cosmicdrift/kumiko-samples 0.418.0 → 0.420.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 (90) hide show
  1. package/package.json +1 -1
  2. package/packages/bundled-features/package.json +11 -1
  3. package/packages/bundled-features/src/shared/index.ts +6 -0
  4. package/packages/bundled-features/src/shared/tenant-scoped-subject.ts +28 -0
  5. package/packages/bundled-features/src/signature/changes.json +6 -0
  6. package/packages/bundled-features/src/signature/feature.ts +1 -1
  7. package/packages/bundled-features/src/signature/grant.ts +13 -14
  8. package/packages/bundled-features/src/signature/png.ts +33 -12
  9. package/packages/bundled-features/src/template-resolver/api.ts +17 -7
  10. package/packages/bundled-features/src/template-resolver/changes.json +62 -0
  11. package/packages/bundled-features/src/template-resolver/compile-document-body.ts +10 -9
  12. package/packages/bundled-features/src/template-resolver/compile-document-styles.ts +170 -0
  13. package/packages/bundled-features/src/template-resolver/document-frames.ts +68 -0
  14. package/packages/bundled-features/src/template-resolver/document-op-blocks.ts +682 -0
  15. package/packages/bundled-features/src/template-resolver/document-ops.ts +170 -128
  16. package/packages/bundled-features/src/template-resolver/document-print-only.ts +65 -0
  17. package/packages/bundled-features/src/template-resolver/document-sanitizer.ts +53 -19
  18. package/packages/bundled-features/src/template-resolver/feature.ts +15 -0
  19. package/packages/bundled-features/src/template-resolver/handlers/apply-layout.write.ts +137 -0
  20. package/packages/bundled-features/src/template-resolver/handlers/create-layout.write.ts +87 -0
  21. package/packages/bundled-features/src/template-resolver/handlers/document-base.ts +2 -2
  22. package/packages/bundled-features/src/template-resolver/handlers/document-blocks.query.ts +13 -8
  23. package/packages/bundled-features/src/template-resolver/handlers/document-region.ts +47 -0
  24. package/packages/bundled-features/src/template-resolver/handlers/failure-reason.ts +13 -0
  25. package/packages/bundled-features/src/template-resolver/handlers/import-bundle-system.write.ts +3 -0
  26. package/packages/bundled-features/src/template-resolver/handlers/layout-source.query.ts +17 -5
  27. package/packages/bundled-features/src/template-resolver/handlers/overview.query.ts +16 -4
  28. package/packages/bundled-features/src/template-resolver/handlers/patch-draft.write.ts +20 -6
  29. package/packages/bundled-features/src/template-resolver/handlers/publish-templates.write.ts +69 -0
  30. package/packages/bundled-features/src/template-resolver/handlers/set.write.ts +7 -0
  31. package/packages/bundled-features/src/template-resolver/handlers/template-write.ts +15 -3
  32. package/packages/bundled-features/src/template-resolver/handlers/tenant-settings.ts +159 -0
  33. package/packages/bundled-features/src/template-resolver/handlers/toggle-status.write.ts +25 -10
  34. package/packages/bundled-features/src/template-resolver/handlers/upsert-system.write.ts +7 -3
  35. package/packages/bundled-features/src/template-resolver/handlers/usage.query.ts +131 -18
  36. package/packages/bundled-features/src/template-resolver/handlers/validate.query.ts +10 -0
  37. package/packages/bundled-features/src/template-resolver/i18n.ts +3 -0
  38. package/packages/bundled-features/src/template-resolver/index.ts +39 -0
  39. package/packages/bundled-features/src/template-resolver/layout-regions.ts +54 -16
  40. package/packages/bundled-features/src/template-resolver/print-document.ts +3 -1
  41. package/packages/bundled-features/src/template-resolver/seeding.ts +4 -0
  42. package/packages/bundled-features/src/template-resolver/template-delivery-policy.ts +11 -1
  43. package/packages/bundled-features/src/template-resolver/template-edit-policy.ts +37 -1
  44. package/packages/bundled-features/src/template-resolver/template-meta.ts +31 -6
  45. package/packages/bundled-features/src/template-resolver/template-preview.ts +29 -9
  46. package/packages/bundled-features/src/template-resolver/template-validation.ts +10 -3
  47. package/packages/bundled-features/src/template-resolver/web/constants.ts +33 -0
  48. package/packages/bundled-features/src/template-resolver/web/document-blocks.ts +5 -0
  49. package/packages/bundled-features/src/template-resolver/web/document-editor-extensions.ts +93 -25
  50. package/packages/bundled-features/src/template-resolver/web/document-editor-fonts.ts +13 -0
  51. package/packages/bundled-features/src/template-resolver/web/document-editor.tsx +4 -1
  52. package/packages/bundled-features/src/template-resolver/web/document-fonts.ts +21 -0
  53. package/packages/bundled-features/src/template-resolver/web/document-frame-control.ts +428 -0
  54. package/packages/bundled-features/src/template-resolver/web/document-frame-node-view.tsx +207 -0
  55. package/packages/bundled-features/src/template-resolver/web/document-print-decorations.ts +246 -0
  56. package/packages/bundled-features/src/template-resolver/web/document-print-defaults.ts +59 -0
  57. package/packages/bundled-features/src/template-resolver/web/document-print-style.ts +381 -0
  58. package/packages/bundled-features/src/template-resolver/web/document-repeat-strip.ts +80 -0
  59. package/packages/bundled-features/src/template-resolver/web/document-schema.ts +87 -19
  60. package/packages/bundled-features/src/template-resolver/web/document-style-css.ts +214 -0
  61. package/packages/bundled-features/src/template-resolver/web/document-tiptap-bubble.tsx +185 -16
  62. package/packages/bundled-features/src/template-resolver/web/document-tiptap-content.tsx +70 -7
  63. package/packages/bundled-features/src/template-resolver/web/document-tiptap-context.ts +13 -1
  64. package/packages/bundled-features/src/template-resolver/web/document-tiptap-editor.tsx +25 -4
  65. package/packages/bundled-features/src/template-resolver/web/document-tiptap-helpers.ts +276 -23
  66. package/packages/bundled-features/src/template-resolver/web/document-tiptap-toolbar-groups.tsx +449 -10
  67. package/packages/bundled-features/src/template-resolver/web/document-tiptap-toolbar.tsx +108 -17
  68. package/packages/bundled-features/src/template-resolver/web/document-toolbar-blocks.ts +20 -0
  69. package/packages/bundled-features/src/template-resolver/web/fontsource-css.d.ts +2 -0
  70. package/packages/bundled-features/src/template-resolver/web/i18n.ts +32 -0
  71. package/packages/bundled-features/src/template-resolver/web/index.ts +38 -0
  72. package/packages/bundled-features/src/template-resolver/web/pdf-constants.ts +16 -0
  73. package/packages/bundled-features/src/template-resolver/web/placeholder-text.ts +6 -3
  74. package/packages/bundled-features/src/template-resolver/web/qualified-names.ts +7 -0
  75. package/packages/bundled-features/src/template-resolver/web/use-document-tiptap-model.ts +74 -5
  76. package/packages/bundled-features/src/tenant/company-config.ts +48 -0
  77. package/packages/bundled-features/src/tenant/feature.ts +11 -0
  78. package/packages/bundled-features/src/tenant/i18n.ts +14 -0
  79. package/samples/apps/ui-walkthrough/src/app/auth-constants.ts +51 -0
  80. package/samples/apps/ui-walkthrough/src/app/seed-print-editor-tenants.ts +118 -0
  81. package/samples/apps/ui-walkthrough/src/app/seed-templates.ts +2 -0
  82. package/samples/apps/ui-walkthrough/src/app/server.ts +9 -1
  83. package/samples/apps/ui-walkthrough/src/app/template-seed-data.ts +27 -1
  84. package/samples/apps/ui-walkthrough/src/features/rental/i18n.ts +8 -0
  85. package/samples/apps/ui-walkthrough/src/features/rental/screens.ts +1 -0
  86. package/samples/apps/ui-walkthrough/src/run-config.ts +1 -0
  87. package/samples/apps/use-all-bundled/feature-manifest.json +236 -0
  88. package/samples/recipes/pdf-letterhead/README.md +23 -0
  89. package/samples/recipes/pdf-letterhead/package.json +12 -0
  90. package/samples/recipes/pdf-letterhead/src/letterhead.ts +92 -0
@@ -4,6 +4,7 @@
4
4
  // the renderer did not plan for.
5
5
 
6
6
  import type { Element as ScanElement } from "happy-dom";
7
+ import { hasFrame, IMAGES_BLOCK_SELECTOR, scanPrintOnlyFeatures } from "./document-print-only.ts";
7
8
  import {
8
9
  type DocumentViolation,
9
10
  type SanitizeBodyResult,
@@ -19,11 +20,10 @@ type RegionAttribute = (typeof REGION_ATTRIBUTES)[number];
19
20
 
20
21
  const MAIL_LAYOUT_CONTENT_SLOT = /\{\{\{\s*content\s*\}\}\}/g;
21
22
 
22
- export type LayoutRegions = {
23
- readonly header: string;
24
- readonly signature: string;
25
- readonly footer: string;
26
- };
23
+ export const LAYOUT_REGION_NAMES = ["header", "signature", "footer"] as const;
24
+ export type LayoutRegionName = (typeof LAYOUT_REGION_NAMES)[number];
25
+
26
+ export type LayoutRegions = Readonly<Record<LayoutRegionName, string>>;
27
27
 
28
28
  export type SanitizeLayoutResult =
29
29
  | { readonly ok: true; readonly html: string }
@@ -103,23 +103,28 @@ export function sanitizeLayoutHtml(html: string): SanitizeLayoutResult {
103
103
  for (const name of ["data-header", "data-signature", "data-footer"] as const) {
104
104
  const inner = parsed.innerHtml[name];
105
105
  if (inner === undefined || inner.trim() === "") continue;
106
+ if (withParsedDocument(inner, hasFrame)) {
107
+ violations.push(
108
+ violation(
109
+ "frame_not_top_level",
110
+ name,
111
+ `Frames are not allowed in the ${name} region; they belong in the document body`,
112
+ ),
113
+ );
114
+ continue;
115
+ }
106
116
  const result = sanitizeDocumentHtml(inner);
107
117
  if (result.ok) cleanedHtml[name] = result.html;
108
118
  else violations.push(...result.violations);
109
119
  }
110
120
  if (violations.length > 0) return { ok: false, violations };
111
- const part = (name: RegionAttribute) => {
112
- const regionHtml = cleanedHtml[name];
113
- return regionHtml === undefined ? "" : `<div ${name}>${regionHtml}</div>`;
114
- };
115
121
  return {
116
122
  ok: true,
117
- html: [
118
- part("data-header"),
119
- "<div data-content></div>",
120
- part("data-signature"),
121
- part("data-footer"),
122
- ].join(""),
123
+ html: composeLayoutHtml({
124
+ header: cleanedHtml["data-header"] ?? "",
125
+ signature: cleanedHtml["data-signature"] ?? "",
126
+ footer: cleanedHtml["data-footer"] ?? "",
127
+ }),
123
128
  };
124
129
  }
125
130
 
@@ -132,6 +137,18 @@ export function readLayoutRegions(html: string): LayoutRegions {
132
137
  };
133
138
  }
134
139
 
140
+ // Empty regions are left out, the form the sanitizer stores.
141
+ export function composeLayoutHtml(regions: LayoutRegions): string {
142
+ const part = (name: RegionAttribute, regionHtml: string) =>
143
+ regionHtml.trim() === "" ? "" : `<div ${name}>${regionHtml}</div>`;
144
+ return [
145
+ part("data-header", regions.header),
146
+ "<div data-content></div>",
147
+ part("data-signature", regions.signature),
148
+ part("data-footer", regions.footer),
149
+ ].join("");
150
+ }
151
+
135
152
  export type TemplateWriteScope = "system" | "tenant";
136
153
 
137
154
  function rejected(violationItem: DocumentViolation): SanitizeBodyResult {
@@ -143,7 +160,7 @@ function sanitizeMailLayout(
143
160
  contentFormat: ContentFormat,
144
161
  content: string,
145
162
  ): SanitizeBodyResult {
146
- if (contentFormat === "html") return fromLayoutResult(sanitizeLayoutHtml(content));
163
+ if (contentFormat === "html") return refusePrintOnlyFeatures(sanitizeLayoutHtml(content));
147
164
  if (contentFormat !== "mjml") {
148
165
  return rejected(
149
166
  violation(
@@ -174,6 +191,27 @@ function sanitizeMailLayout(
174
191
  return { ok: true, content };
175
192
  }
176
193
 
194
+ // The shared document model survives the rebuild in a mail layout, but only a PDF applies print styling.
195
+ function refusePrintOnlyFeatures(result: SanitizeLayoutResult): SanitizeBodyResult {
196
+ if (!result.ok) return result;
197
+ const found = withParsedDocument(result.html, scanPrintOnlyFeatures);
198
+ const selectors = [
199
+ ...found.printStyleSelectors,
200
+ ...(found.hasImagesBlock ? [IMAGES_BLOCK_SELECTOR] : []),
201
+ ];
202
+ if (selectors.length === 0) return { ok: true, content: result.html };
203
+ return {
204
+ ok: false,
205
+ violations: selectors.map((selector) =>
206
+ violation(
207
+ "print_style_pdf_only",
208
+ selector,
209
+ `Print styling (${selector}) is only allowed in layouts of kind pdf-layout`,
210
+ ),
211
+ ),
212
+ };
213
+ }
214
+
177
215
  function fromLayoutResult(result: SanitizeLayoutResult): SanitizeBodyResult {
178
216
  return result.ok ? { ok: true, content: result.html } : result;
179
217
  }
@@ -33,7 +33,9 @@ function moveRepeatHeadersIntoThead(table: ScanElement): void {
33
33
  row.removeAttribute(REPEAT_HEADER_ATTRIBUTE);
34
34
  thead.appendChild(row);
35
35
  }
36
- table.insertBefore(thead, table.firstChild);
36
+ // A colgroup has to stay the first child of the table.
37
+ const colgroup = Array.from(table.children).find((child) => child.tagName === "COLGROUP");
38
+ table.insertBefore(thead, colgroup === undefined ? table.firstChild : colgroup.nextSibling);
37
39
  }
38
40
 
39
41
  export function prepareDocumentForPrint(html: string): string {
@@ -39,6 +39,7 @@ import { evaluateTemplateWrite } from "./handlers/template-gates.ts";
39
39
  import { type TemplateResourceRow, templateResourcesTable } from "./table.ts";
40
40
  import type { TemplateBundle } from "./template-bundle.ts";
41
41
  import { activeStampChanges, servedStampChanges } from "./template-draft.ts";
42
+ import { refuseReservedLayoutSlug } from "./template-edit-policy.ts";
42
43
  import { templateSlugSchema } from "./template-meta.ts";
43
44
  import { variablesFromSchema } from "./template-validation.ts";
44
45
  import { type ContentFormat, TEXT_BLOCK_KIND, type UpsertKind } from "./web/constants.ts";
@@ -123,6 +124,9 @@ export async function seedSystemTemplate(
123
124
  const label = `seedSystemTemplate ${opts.slug}/${opts.kind}/${opts.locale}`;
124
125
  const slug = templateSlugSchema.safeParse(opts.slug);
125
126
  if (!slug.success) throw new Error(`${label} rejected: ${slug.error.issues[0]?.message}`);
127
+ if (refuseReservedLayoutSlug({ slug: opts.slug, kind: opts.kind }, "slug") !== null) {
128
+ throw new Error(`${label} rejected: reserved_layout_slug`);
129
+ }
126
130
  const title = seedTitleColumn(opts, label);
127
131
  const evaluated = evaluateTemplateWrite({
128
132
  kind: opts.kind,
@@ -1,6 +1,6 @@
1
1
  import type { Registry } from "@cosmicdrift/kumiko-framework/engine";
2
2
  import { isPlainObject, propertyOf } from "@cosmicdrift/kumiko-types/type-guards";
3
- import { SYSTEM_TENANT_ID } from "./web/constants.ts";
3
+ import { SYSTEM_TENANT_ID, TENANT_LAYOUT_SLUG_PREFIX } from "./web/constants.ts";
4
4
  import { TEMPLATE_RESOLVER_FEATURE } from "./web/qualified-names.ts";
5
5
 
6
6
  type DeliveryTarget = { readonly kind: string; readonly slug: string };
@@ -15,12 +15,22 @@ export type TemplateDeliveryPolicy = {
15
15
 
16
16
  const NOTHING_UNLOCKED: TemplateDeliveryPolicy = { tenantEditable: [], collectionKinds: [] };
17
17
 
18
+ // Tenant-created layouts have no entry of their own: they are served and edited once the app unlocks any PDF template.
19
+ export function isTenantLayout(target: DeliveryTarget): boolean {
20
+ return target.kind === "pdf-layout" && target.slug.startsWith(TENANT_LAYOUT_SLUG_PREFIX);
21
+ }
22
+
23
+ function unlocksTenantLayouts(policy: TemplateDeliveryPolicy): boolean {
24
+ return policy.tenantEditable.some((entry) => entry.kind === "document-pdf");
25
+ }
26
+
18
27
  export function isTenantOverrideServed(
19
28
  policy: TemplateDeliveryPolicy,
20
29
  target: DeliveryTarget,
21
30
  ): boolean {
22
31
  return (
23
32
  policy.collectionKinds.includes(target.kind) ||
33
+ (isTenantLayout(target) && unlocksTenantLayouts(policy)) ||
24
34
  policy.tenantEditable.some((entry) => entry.kind === target.kind && entry.slug === target.slug)
25
35
  );
26
36
  }
@@ -7,12 +7,15 @@ import {
7
7
  } from "@cosmicdrift/kumiko-framework/engine";
8
8
  import {
9
9
  AccessDeniedError,
10
+ ValidationError,
10
11
  type WriteFailure,
11
12
  writeFailure,
12
13
  } from "@cosmicdrift/kumiko-framework/errors";
14
+ import type { TemplateWriteScope } from "./layout-regions.ts";
13
15
  import { type TemplateResourceRow, templateResourcesTable } from "./table.ts";
16
+ import { isTenantLayout } from "./template-delivery-policy.ts";
14
17
  import { isSystemAdmin } from "./template-draft.ts";
15
- import type { TemplateKind } from "./web/constants.ts";
18
+ import { TENANT_LAYOUT_SLUG_PREFIX, type TemplateKind } from "./web/constants.ts";
16
19
  import { TemplateResolverErrors } from "./web/qualified-names.ts";
17
20
 
18
21
  export type TenantEditableTemplate = {
@@ -44,6 +47,7 @@ export function mayEditTemplate(
44
47
  target: EditTarget,
45
48
  ): boolean {
46
49
  if (isSystemAdmin(user)) return true;
50
+ if (isTenantLayout(target)) return mayEditTenantLayouts(policy, user);
47
51
  const entry = policy.tenantEditable.find(
48
52
  (candidate) => candidate.slug === target.slug && candidate.kind === target.kind,
49
53
  );
@@ -89,3 +93,35 @@ export async function refuseTemplateEditById(
89
93
  ? refuseMissingTemplate(policy, user)
90
94
  : refuseTemplateEdit(policy, user, row);
91
95
  }
96
+
97
+ // A tenant layout reaches every template that names it, so building one needs the right on all PDF
98
+ // templates (and at least one must exist: every() on an empty list is true).
99
+ export function mayEditTenantLayouts(policy: TemplateEditPolicy, user: EditUser): boolean {
100
+ const pdfEntries = policy.tenantEditable.filter((entry) => entry.kind === "document-pdf");
101
+ return pdfEntries.length > 0 && pdfEntries.every((entry) => hasAccess(user, entry.access));
102
+ }
103
+
104
+ export function refuseReservedSystemLayoutSlug(
105
+ scope: TemplateWriteScope,
106
+ target: EditTarget,
107
+ path: string,
108
+ ): WriteFailure | null {
109
+ return scope === "system" ? refuseReservedLayoutSlug(target, path) : null;
110
+ }
111
+
112
+ // System layouts must not take a slug from the tenant namespace.
113
+ export function refuseReservedLayoutSlug(target: EditTarget, path: string): WriteFailure | null {
114
+ if (!isTenantLayout(target)) return null;
115
+ return writeFailure(
116
+ new ValidationError({
117
+ fields: [
118
+ {
119
+ path,
120
+ code: "reserved_layout_slug",
121
+ i18nKey: "templateResolver.errors.template.reservedLayoutSlug",
122
+ params: { prefix: TENANT_LAYOUT_SLUG_PREFIX },
123
+ },
124
+ ],
125
+ }),
126
+ );
127
+ }
@@ -5,6 +5,7 @@ import {
5
5
  PDF_PAGE_FORMATS,
6
6
  type TemplateKind,
7
7
  } from "./web/constants.ts";
8
+ import { DOCUMENT_FONTS } from "./web/document-fonts.ts";
8
9
  import { MAIL_TONES, type MailTone } from "./web/mail-constants.ts";
9
10
  import {
10
11
  MAIL_LAYOUT_ACCENT_LINES,
@@ -12,6 +13,7 @@ import {
12
13
  MAIL_LAYOUT_FONTS,
13
14
  MAIL_LAYOUT_WIDTHS,
14
15
  } from "./web/mail-layout-constants.ts";
16
+ import { PDF_FOLD_MARKS, PDF_TABLE_STYLES } from "./web/pdf-constants.ts";
15
17
 
16
18
  // One or more kebab segments joined by ":" — notification templates are seeded
17
19
  // under their qualified name `feature:notify:name`.
@@ -63,6 +65,9 @@ const mailMetaSchema = z.preprocess(
63
65
  );
64
66
 
65
67
  const marginMm = z.number().finite().min(0).max(100).optional();
68
+ const pdfMargins = z
69
+ .object({ top: marginMm, right: marginMm, bottom: marginMm, left: marginMm })
70
+ .strict();
66
71
 
67
72
  // The file name ends up in a Content-Disposition header and on disk.
68
73
  const FORBIDDEN_FILE_NAME = /[/\\";]|\.\./;
@@ -80,10 +85,7 @@ const pdfMetaSchema = z
80
85
  orientation: z.enum(PDF_ORIENTATIONS).optional(),
81
86
  printBackground: z.boolean().optional(),
82
87
  layoutHeaderFooter: z.boolean().optional(),
83
- margins: z
84
- .object({ top: marginMm, right: marginMm, bottom: marginMm, left: marginMm })
85
- .strict()
86
- .optional(),
88
+ margins: pdfMargins.optional(),
87
89
  fileName: singleLine(200)
88
90
  .min(1)
89
91
  .refine((value) => !FORBIDDEN_FILE_NAME.test(value), 'must not contain / \\ " ; or ..')
@@ -111,12 +113,30 @@ const mailLayoutMetaSchema = z
111
113
  })
112
114
  .strict();
113
115
 
114
- const pdfLayoutMetaSchema = z.object({}).strict();
116
+ const hexColor = z.string().regex(HEX_COLOR_PATTERN, "must be a #rrggbb color");
117
+
118
+ const pdfLayoutMetaSchema = z
119
+ .object({
120
+ margins: pdfMargins.optional(),
121
+ fontFamily: z.enum(DOCUMENT_FONTS).optional(),
122
+ fontSizePt: z.number().finite().min(6).max(24).optional(),
123
+ textColor: hexColor.optional(),
124
+ tableStyle: z.enum(PDF_TABLE_STYLES).optional(),
125
+ tableHeaderBackground: hexColor.optional(),
126
+ tableLineColor: hexColor.optional(),
127
+ foldMarks: z.enum(PDF_FOLD_MARKS).optional(),
128
+ cornerMarks: z.boolean().optional(),
129
+ paperColor: hexColor.optional(),
130
+ headerOnFirstPage: z.boolean().optional(),
131
+ footerOnFirstPage: z.boolean().optional(),
132
+ })
133
+ .strict();
115
134
 
116
135
  export type MailTemplateMeta = z.infer<typeof mailMetaSchema>;
117
136
  export type PdfTemplateMeta = z.infer<typeof pdfMetaSchema>;
118
137
  export type MailLayoutMeta = z.infer<typeof mailLayoutMetaSchema>;
119
- export type LayoutTemplateMeta = MailLayoutMeta | z.infer<typeof pdfLayoutMetaSchema>;
138
+ export type PdfLayoutMeta = z.infer<typeof pdfLayoutMetaSchema>;
139
+ export type LayoutTemplateMeta = MailLayoutMeta | PdfLayoutMeta;
120
140
  export type TemplateMeta = MailTemplateMeta | PdfTemplateMeta | LayoutTemplateMeta;
121
141
 
122
142
  export function isMailTemplateMeta(meta: TemplateMeta | null): meta is MailTemplateMeta {
@@ -133,6 +153,11 @@ export function readMailLayoutMeta(meta: unknown): MailLayoutMeta {
133
153
  return parsed.success ? parsed.data : {};
134
154
  }
135
155
 
156
+ export function readPdfLayoutMeta(meta: unknown): PdfLayoutMeta {
157
+ const parsed = pdfLayoutMetaSchema.safeParse(meta ?? {});
158
+ return parsed.success ? parsed.data : {};
159
+ }
160
+
136
161
  export type TemplateMetaIssue = {
137
162
  readonly path: string;
138
163
  /** The setting the issue is about (`subject`), `meta` when it concerns the object as a whole. */
@@ -37,6 +37,7 @@ import {
37
37
  } from "./api.ts";
38
38
  import { collectDocumentResourceKeys } from "./compile-document-body.ts";
39
39
  import { parseStoredJson } from "./handlers/template-gates.ts";
40
+ import { effectivePdfLayout } from "./handlers/tenant-settings.ts";
40
41
  import { validateTemplateDraft } from "./handlers/validate.query.ts";
41
42
  import {
42
43
  type LayoutRegions,
@@ -57,7 +58,6 @@ import {
57
58
  } from "./template-meta.ts";
58
59
  import {
59
60
  DEFAULT_MAIL_LAYOUT_SLUG,
60
- DEFAULT_PDF_LAYOUT_SLUG,
61
61
  MAIL_PREVIEW_MAX_BYTES,
62
62
  SYSTEM_TENANT_ID,
63
63
  type TemplateScope,
@@ -121,11 +121,10 @@ function sampleRow(
121
121
  }
122
122
 
123
123
  function sampleList(def: TemplateListVariableDef, labelText: LabelText): Record<string, unknown>[] {
124
- const rows = (def.example ?? [])
125
- .slice(0, SAMPLE_LIST_ROWS)
126
- .map((given) => sampleRow(def.item, labelText, given));
127
- while (rows.length < SAMPLE_LIST_ROWS) rows.push(sampleRow(def.item, labelText));
128
- return rows;
124
+ const declared = (def.example ?? []).slice(0, SAMPLE_LIST_ROWS);
125
+ // Declared rows are the whole sample: padding them shows rows the data does not have.
126
+ if (declared.length > 0) return declared.map((given) => sampleRow(def.item, labelText, given));
127
+ return Array.from({ length: SAMPLE_LIST_ROWS }, () => sampleRow(def.item, labelText));
129
128
  }
130
129
 
131
130
  function sampleValueFor(name: string, def: TemplateVariableDef, labelText: LabelText): unknown {
@@ -357,11 +356,20 @@ async function resolvePdfLayout(
357
356
  user: SessionUser,
358
357
  slug: string,
359
358
  locale: string,
359
+ resolvedForCaller: TemplateResource | null = null,
360
+ working = false,
360
361
  ): Promise<PreviewLayout | null> {
361
362
  const api = createTemplateResolverApi(ctx.db, ctx.registry);
362
363
  const find = async (tenantId: string): Promise<TemplateResource | null> => {
364
+ if (resolvedForCaller !== null && tenantId === user.tenantId) return resolvedForCaller;
363
365
  try {
364
- return await api.resolveLayout({ tenantId, slug, kind: "pdf-layout", locale });
366
+ return await api.resolveLayout({
367
+ tenantId,
368
+ slug,
369
+ kind: "pdf-layout",
370
+ locale,
371
+ working,
372
+ });
365
373
  } catch (e) {
366
374
  if (e instanceof TemplateNotFoundError) return null;
367
375
  throw e;
@@ -382,6 +390,17 @@ async function resolvePdfLayout(
382
390
  return { slug, scope: layout.scope, html, regions: readLayoutRegions(html) };
383
391
  }
384
392
 
393
+ async function resolvePreviewPdfLayout(
394
+ ctx: HandlerContext,
395
+ user: SessionUser,
396
+ ownSlug: string | undefined,
397
+ locale: string,
398
+ working: boolean,
399
+ ): Promise<PreviewLayout | null> {
400
+ const { slug, resolved } = await effectivePdfLayout(ctx, user.tenantId, ownSlug, locale, working);
401
+ return resolvePdfLayout(ctx, user, slug, locale, resolved, working);
402
+ }
403
+
385
404
  function missingResourceCheck(missing: readonly string[]): PreviewCheck {
386
405
  return {
387
406
  code: "resources_resolved",
@@ -455,11 +474,12 @@ async function renderDocumentPreview(
455
474
  html: content,
456
475
  text: null,
457
476
  attachments: [],
458
- layout: await resolvePdfLayout(
477
+ layout: await resolvePreviewPdfLayout(
459
478
  ctx,
460
479
  user,
461
- pdfMeta?.layoutSlug ?? DEFAULT_PDF_LAYOUT_SLUG,
480
+ pdfMeta?.layoutSlug,
462
481
  input.locale,
482
+ input.content !== undefined,
463
483
  ),
464
484
  sampleValues,
465
485
  checks: [missingResourceCheck(validation.warnings.map((w) => w.detail)), requiredCheck],
@@ -8,6 +8,7 @@ import type { Element as ScanElement } from "happy-dom";
8
8
  import * as z from "zod";
9
9
  import { conditionScopeElement, withParsedDocument } from "./document-sanitizer.ts";
10
10
  import type { TemplateMeta } from "./template-meta.ts";
11
+ import { COMPANY_PLACEHOLDERS } from "./web/constants.ts";
11
12
  import {
12
13
  DOCUMENT_CONDITION_ATTRIBUTE,
13
14
  isDocumentPlaceholderHref,
@@ -24,10 +25,16 @@ export const SYSTEM_PLACEHOLDERS: ReadonlySet<string> = new Set([
24
25
  const PAGE_PLACEHOLDERS = ["page", "pages"] as const;
25
26
  const PAGED_KINDS: ReadonlySet<string> = new Set(["document-pdf", "pdf-layout"]);
26
27
 
28
+ // A PDF has no signature or imprint block, so both stay empty there and are not offered.
29
+ const PDF_EMPTY_PLACEHOLDERS: ReadonlySet<string> = new Set(["signature", "imprint"]);
30
+
27
31
  export function systemPlaceholdersFor(kind: string): ReadonlySet<string> {
28
- return PAGED_KINDS.has(kind)
29
- ? new Set([...SYSTEM_PLACEHOLDERS, ...PAGE_PLACEHOLDERS])
30
- : SYSTEM_PLACEHOLDERS;
32
+ if (!PAGED_KINDS.has(kind)) return SYSTEM_PLACEHOLDERS;
33
+ return new Set([
34
+ ...[...SYSTEM_PLACEHOLDERS].filter((name) => !PDF_EMPTY_PLACEHOLDERS.has(name)),
35
+ ...PAGE_PLACEHOLDERS,
36
+ ...COMPANY_PLACEHOLDERS,
37
+ ]);
31
38
  }
32
39
 
33
40
  const BASE_RESOURCE_KEYS = ["logo"] as const;
@@ -14,6 +14,10 @@ export type RenderKind = (typeof RENDER_KINDS)[number];
14
14
  export const DOCUMENT_HTML_KINDS = ["mail", "document-pdf"] as const;
15
15
  export type DocumentHtmlKind = (typeof DOCUMENT_HTML_KINDS)[number];
16
16
 
17
+ // Kinds structured document ops can edit: the two document kinds plus the regions of a PDF layout.
18
+ export const DOCUMENT_OPS_KINDS = [...DOCUMENT_HTML_KINDS, "pdf-layout"] as const;
19
+ export type DocumentOpsKind = (typeof DOCUMENT_OPS_KINDS)[number];
20
+
17
21
  // Kinds without a renderer plugin: `notification` is the retired sections-JSON
18
22
  // notification kind, kept so rows stored before mails moved to `mail` stay
19
23
  // valid on replay; nothing writes or renders it any more. `text-block` is the Markdown text store
@@ -82,18 +86,44 @@ export const ACTIVE_TEMPLATE_STATUS = "active" satisfies TemplateStatus;
82
86
 
83
87
  export { HEX_COLOR_PATTERN } from "./mail-layout-constants.ts";
84
88
  export {
89
+ PDF_CORNER_MARK_INSET_MM,
90
+ PDF_CORNER_MARK_LEG_MM,
91
+ PDF_DEFAULT_FONT_SIZE_PT,
85
92
  PDF_DEFAULT_MARGIN_MM,
93
+ PDF_FOLD_MARKS,
86
94
  PDF_FOOTER_MARGIN_MM,
87
95
  PDF_HEADER_MARGIN_MM,
88
96
  PDF_ORIENTATIONS,
89
97
  PDF_PAGE_FORMATS,
98
+ PDF_TABLE_STYLES,
99
+ type PdfFoldMarks,
90
100
  type PdfOrientation,
91
101
  type PdfPageFormat,
102
+ type PdfTableStyle,
92
103
  } from "./pdf-constants.ts";
93
104
 
94
105
  export const DEFAULT_MAIL_LAYOUT_SLUG = "default";
95
106
  export const DEFAULT_PDF_LAYOUT_SLUG = "default";
96
107
 
108
+ // Same names as the tenant feature's company config keys: the placeholder is the key name.
109
+ export const COMPANY_PLACEHOLDERS = [
110
+ "companyAddress",
111
+ "companyPhone",
112
+ "companyEmail",
113
+ "companyWebsite",
114
+ "companyRegister",
115
+ "companyVatId",
116
+ "companyManagement",
117
+ "companyBank",
118
+ "companyIban",
119
+ "companyBic",
120
+ ] as const;
121
+ export const MAX_SELECTED_TEMPLATES = 200;
122
+
123
+ // Tenant setting that picks the layout of PDF templates which name none.
124
+ export const DEFAULT_PDF_LAYOUT_SLUG_CONFIG_KEY =
125
+ "template-resolver:config:default-pdf-layout-slug";
126
+
97
127
  // The mail transport enforces no size limit of its own; 10 MiB is a common provider ceiling.
98
128
  export const MAIL_PREVIEW_MAX_BYTES = 10 * 1024 * 1024;
99
129
 
@@ -111,3 +141,6 @@ export const FALLBACK_LOCALE = "de";
111
141
 
112
142
  // A collection mounted without `access` is maintained by the platform only; TenantAdmin access is an explicit mount decision.
113
143
  export const DEFAULT_COLLECTION_ACCESS = { roles: ["SystemAdmin"] } as const;
144
+
145
+ // Tenant-created PDF layouts live under this slug prefix; system layouts may not use it, so the two namespaces never meet.
146
+ export const TENANT_LAYOUT_SLUG_PREFIX = "tenant-layout-";
@@ -29,6 +29,11 @@ export const PDF_DOCUMENT_BLOCKS = [
29
29
  "pageBreak",
30
30
  ] as const satisfies readonly DocumentToolbarBlock[];
31
31
 
32
+ // A layout region has no per-document variables, so a steps block there could never show a stage and an images block no photos.
33
+ export const PDF_LAYOUT_DOCUMENT_BLOCKS = PDF_DOCUMENT_BLOCKS.filter(
34
+ (block) => block !== "steps" && block !== "images",
35
+ );
36
+
32
37
  /** Block set for a template-resource kind; every kind except "document-pdf" gets the mail set. */
33
38
  export function documentBlocksForKind(kind: string | undefined): readonly DocumentToolbarBlock[] {
34
39
  return kind === "document-pdf" ? PDF_DOCUMENT_BLOCKS : MAIL_DOCUMENT_BLOCKS;