@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
@@ -122,13 +122,34 @@ function unfilterRows(raw: Uint8Array, header: Header): boolean {
122
122
  }
123
123
 
124
124
  function countInkPixels(raw: Uint8Array, header: Header): number {
125
- const stride = header.width * header.bytesPerPixel + 1;
125
+ const bytesPerPixel = header.bytesPerPixel;
126
+ const stride = header.width * bytesPerPixel + 1;
127
+ const pixelStart = (row: number, column: number): number =>
128
+ row * stride + 1 + column * bytesPerPixel;
129
+ const background = pixelStart(0, 0);
130
+ const alphaOf = (start: number): number => raw[start + bytesPerPixel - 1] ?? 0;
131
+ const colorMatchesBackground = (start: number): boolean => {
132
+ for (let i = 0; i < bytesPerPixel; i++) {
133
+ if (raw[start + i] !== raw[background + i]) return false;
134
+ }
135
+ return true;
136
+ };
137
+ // Only four identical, opaque corners mean a solid background; a single opaque pixel could be a stroke.
138
+ const corners = [
139
+ background,
140
+ pixelStart(0, header.width - 1),
141
+ pixelStart(header.height - 1, 0),
142
+ pixelStart(header.height - 1, header.width - 1),
143
+ ];
144
+ const hasSolidBackground = corners.every(
145
+ (corner) => alphaOf(corner) > 0 && colorMatchesBackground(corner),
146
+ );
126
147
  let ink = 0;
127
148
  for (let row = 0; row < header.height; row++) {
128
149
  for (let column = 0; column < header.width; column++) {
129
- const alphaIndex =
130
- row * stride + 1 + column * header.bytesPerPixel + header.bytesPerPixel - 1;
131
- if ((raw[alphaIndex] ?? 0) > 0) ink++;
150
+ const start = pixelStart(row, column);
151
+ const isInk = alphaOf(start) > 0 && (!hasSolidBackground || !colorMatchesBackground(start));
152
+ if (isInk) ink++;
132
153
  }
133
154
  }
134
155
  return ink;
@@ -2,12 +2,14 @@ import {
2
2
  DEFAULT_LIST_LIMIT,
3
3
  entityListSchema,
4
4
  type HandlerContext,
5
+ isUuid,
5
6
  MAX_LIST_LIMIT,
6
7
  type QueryHandlerDef,
7
8
  type SessionUser,
8
9
  } from "@cosmicdrift/kumiko-framework/engine";
9
10
  import { AccessDeniedError } from "@cosmicdrift/kumiko-framework/errors";
10
11
  import { requestExecutor } from "./entity.ts";
12
+ import { openListCursor, sealListCursor } from "./list-cursor-seal.ts";
11
13
  import type { SubjectScope } from "./subject-scope.ts";
12
14
 
13
15
  type ListPayload = ReturnType<typeof entityListSchema.parse>;
@@ -45,7 +47,44 @@ const MAX_BASE_PAGES_PER_ANSWER = 10;
45
47
  // authorizeSubject usually queries the database; a page of 200 subjects must not take the whole pool.
46
48
  const SUBJECT_CHECKS_IN_PARALLEL = 10;
47
49
 
48
- export function scopeRequestList(base: QueryHandlerDef, scope: SubjectScope): QueryHandlerDef {
50
+ type ListQuery = Parameters<QueryHandlerDef["handler"]>[0];
51
+
52
+ async function openFirstQuery(
53
+ query: ListQuery,
54
+ payload: ListPayload,
55
+ user: SessionUser,
56
+ cursorSecret: string,
57
+ ): Promise<ListQuery> {
58
+ const { cursor: sealedCursor, ...payloadWithoutCursor } = payload;
59
+ if (sealedCursor === undefined) return query;
60
+ const openedCursor = await openListCursor(sealedCursor, user, cursorSecret);
61
+ if (openedCursor === null) throw new AccessDeniedError();
62
+ return { ...query, payload: { ...payloadWithoutCursor, cursor: openedCursor } };
63
+ }
64
+
65
+ async function sealedPage(
66
+ page: RowsPage,
67
+ visibleRows: unknown[],
68
+ nextCursor: unknown,
69
+ user: SessionUser,
70
+ cursorSecret: string,
71
+ ) {
72
+ // `total` would count requests of foreign subjects. The base cursor names the last base row,
73
+ // which may belong to a foreign subject, so the user only gets it sealed.
74
+ const { total: _total, rows: _rows, nextCursor: _baseCursor, ...rest } = page;
75
+ return {
76
+ ...rest,
77
+ rows: visibleRows,
78
+ nextCursor:
79
+ typeof nextCursor === "string" ? await sealListCursor(nextCursor, user, cursorSecret) : null,
80
+ };
81
+ }
82
+
83
+ export function scopeRequestList(
84
+ base: QueryHandlerDef,
85
+ scope: SubjectScope,
86
+ cursorSecret: string,
87
+ ): QueryHandlerDef {
49
88
  return {
50
89
  ...base,
51
90
  handler: async (query, ctx) => {
@@ -53,14 +92,16 @@ export function scopeRequestList(base: QueryHandlerDef, scope: SubjectScope): Qu
53
92
  if (!scope.isScoped(user)) return base.handler(query, ctx);
54
93
  const payload = entityListSchema.parse(query.payload);
55
94
  // Group counts would include requests of foreign subjects, and an offset counts base rows,
56
- // not the rows this user sees; the screen pages by cursor.
57
- if (payload.aggregate !== undefined || (payload.offset ?? 0) > 0) {
95
+ // not the rows this user sees; the screen pages by cursor. limit 0 would hand out a cursor
96
+ // without checking a row.
97
+ if (payload.aggregate !== undefined || (payload.offset ?? 0) > 0 || payload.limit === 0) {
58
98
  throw new AccessDeniedError();
59
99
  }
60
100
  const limit = payload.limit ?? DEFAULT_LIST_LIMIT;
61
101
  const verdicts = new Map<string, boolean>();
62
102
  const visibleRows: unknown[] = [];
63
- let page: unknown = await base.handler(query, ctx);
103
+ const firstQuery = await openFirstQuery(query, payload, user, cursorSecret);
104
+ let page: unknown = await base.handler(firstQuery, ctx);
64
105
  for (let fetched = 1; ; fetched++) {
65
106
  if (!isRowsPage(page)) throw new Error("signature request list did not return a rows page");
66
107
  const unknownSubjects = new Map(
@@ -84,9 +125,7 @@ export function scopeRequestList(base: QueryHandlerDef, scope: SubjectScope): Qu
84
125
  fetched >= MAX_BASE_PAGES_PER_ANSWER ||
85
126
  verdicts.size >= MAX_LIST_LIMIT
86
127
  ) {
87
- // `total` would count requests of foreign subjects; the cursor continues after the last base page.
88
- const { total: _total, rows: _rows, ...rest } = page;
89
- return { ...rest, rows: visibleRows };
128
+ return sealedPage(page, visibleRows, nextCursor, user, cursorSecret);
90
129
  }
91
130
  page = await base.handler(
92
131
  {
@@ -134,6 +173,7 @@ export function scopeSignerList(base: QueryHandlerDef, scope: SubjectScope): Que
134
173
  ) {
135
174
  throw new AccessDeniedError();
136
175
  }
176
+ if (!isUuid(requestFilter.value)) return emptyPage(payload);
137
177
  const request = await requestExecutor.detail({ id: requestFilter.value }, user, ctx.db);
138
178
  if (request === null || !(await scope.allowsRequest(ctx, user, request))) {
139
179
  return emptyPage(payload);
@@ -24,8 +24,10 @@ import {
24
24
  type SignaturePageEntry,
25
25
  } from "./signature-page.ts";
26
26
  import {
27
+ SIGNATURE_FAILURE_REASON,
27
28
  SIGNATURE_METHOD,
28
29
  SIGNATURE_REQUEST_STATUS,
30
+ type SignatureFailureReason,
29
31
  SignatureInternalHandlers,
30
32
  } from "./web/constants.ts";
31
33
 
@@ -85,8 +87,34 @@ async function signaturePageEntries(
85
87
  return entries;
86
88
  }
87
89
 
88
- // Appends the signature page to the unchanged original. A renderer outage throws, the request
89
- // stays all-signed and the next run tries again.
90
+ async function failRequest(
91
+ ctx: JobContext,
92
+ request: RequestRow,
93
+ reason: SignatureFailureReason,
94
+ ): Promise<void> {
95
+ const failed = await ctx.dispatch.write(SignatureInternalHandlers.fail, {
96
+ requestId: request.id,
97
+ reason,
98
+ });
99
+ if (!failed.isSuccess) {
100
+ ctx.obs.log.error("[signature:sweep] marking the request failed was rejected", {
101
+ requestId: request.id,
102
+ reason,
103
+ error: failed.error,
104
+ });
105
+ return;
106
+ }
107
+ if (propertyOf(failed.data, "failed") === true) {
108
+ ctx.obs.log.warn("[signature:sweep] request cannot be completed, marked failed", {
109
+ requestId: request.id,
110
+ reason,
111
+ });
112
+ }
113
+ }
114
+
115
+ // Appends the signature page to the unchanged original. A missing or changed original or a
116
+ // missing signature image can never heal and ends the request as failed. A renderer outage
117
+ // throws, the request stays all-signed and the next run tries again.
90
118
  async function finalizeRequest(
91
119
  ctx: JobContext,
92
120
  opts: SignatureOptions,
@@ -94,9 +122,7 @@ async function finalizeRequest(
94
122
  ): Promise<void> {
95
123
  const original = await readTenantFile(ctx, ctx.systemUser.tenantId, request.documentFileId);
96
124
  if (original === null || sha256Hex(original.content) !== request.documentSha256) {
97
- ctx.obs.log.warn("[signature:sweep] original document missing or changed, not completing", {
98
- requestId: request.id,
99
- });
125
+ await failRequest(ctx, request, SIGNATURE_FAILURE_REASON.DocumentChanged);
100
126
  return;
101
127
  }
102
128
  const entries = await signaturePageEntries(
@@ -104,9 +130,7 @@ async function finalizeRequest(
104
130
  await listSigners(ctx, ctx.systemUser, request.id),
105
131
  );
106
132
  if (entries === null) {
107
- ctx.obs.log.warn("[signature:sweep] signature image missing, not completing", {
108
- requestId: request.id,
109
- });
133
+ await failRequest(ctx, request, SIGNATURE_FAILURE_REASON.SignatureImageMissing);
110
134
  return;
111
135
  }
112
136
  const html = buildSignaturePageHtml({
@@ -16,6 +16,7 @@ export const SIGNATURE_REQUEST_STATUS = {
16
16
  Completed: "completed",
17
17
  Declined: "declined",
18
18
  Expired: "expired",
19
+ Failed: "failed",
19
20
  Cancelled: "cancelled",
20
21
  } as const;
21
22
 
@@ -64,12 +65,22 @@ export const SIGNATURE_EVENT_SHORT = {
64
65
  completed: "completed",
65
66
  declined: "declined",
66
67
  expired: "expired",
68
+ failed: "failed",
67
69
  } as const;
68
70
 
71
+ export const SIGNATURE_FAILURE_REASON = {
72
+ DocumentChanged: "document-changed",
73
+ SignatureImageMissing: "signature-image-missing",
74
+ } as const;
75
+
76
+ export type SignatureFailureReason =
77
+ (typeof SIGNATURE_FAILURE_REASON)[keyof typeof SIGNATURE_FAILURE_REASON];
78
+
69
79
  export const SignatureEvents = {
70
80
  completed: `${SIGNATURE_FEATURE}:event:${SIGNATURE_EVENT_SHORT.completed}`,
71
81
  declined: `${SIGNATURE_FEATURE}:event:${SIGNATURE_EVENT_SHORT.declined}`,
72
82
  expired: `${SIGNATURE_FEATURE}:event:${SIGNATURE_EVENT_SHORT.expired}`,
83
+ failed: `${SIGNATURE_FEATURE}:event:${SIGNATURE_EVENT_SHORT.failed}`,
73
84
  } as const;
74
85
 
75
86
  // Every link rejection (forged, expired, revoked, used up, already signed) carries this reason, so
@@ -88,5 +99,6 @@ export const SignatureInternalHandlers = {
88
99
  linkDecline: `${SIGNATURE_FEATURE}:write:link-decline`,
89
100
  finish: `${SIGNATURE_FEATURE}:write:finish`,
90
101
  expire: `${SIGNATURE_FEATURE}:write:expire`,
102
+ fail: `${SIGNATURE_FEATURE}:write:fail`,
91
103
  reconcile: `${SIGNATURE_FEATURE}:write:reconcile`,
92
104
  } as const;
@@ -3,7 +3,7 @@
3
3
  "version": "0.415.0",
4
4
  "type": "fix",
5
5
  "title": "unreadable ledger backfill marker no longer causes endless 503",
6
- "detail": "shouldRedeliverLegacyCheckout answers 200 and logs when the marker dispatch fails, because custom_data.tenantBinding is client-settable."
6
+ "detail": "shouldRedeliverLegacyCheckout answers 200 and logs only when the marker dispatch fails with a configuration error (access_denied, not_found, feature_disabled), because custom_data.tenantBinding is client-settable; other dispatch failures still answer 503 so Paddle redelivers a bounded number of times."
7
7
  },
8
8
  {
9
9
  "version": "0.414.0",
@@ -1,4 +1,10 @@
1
1
  [
2
+ {
3
+ "version": "0.418.0",
4
+ "type": "fix",
5
+ "title": "One-off checkouts with a 100% promo code are booked",
6
+ "detail": "A Stripe checkout session in payment mode that a 100% promo code makes free is now booked like a paid one: the handler reads the session metadata in payment mode. Sessions created before the upgrade carry no session metadata and are still discarded."
7
+ },
2
8
  {
3
9
  "version": "0.416.0",
4
10
  "type": "improvement",
@@ -160,6 +160,8 @@ export function createStripeCheckoutSession(
160
160
  ...(mode === "subscription"
161
161
  ? { subscription_data: { metadata } }
162
162
  : {
163
+ // Session metadata too: a 100% promotion code completes without a PaymentIntent.
164
+ metadata,
163
165
  payment_intent_data: { metadata },
164
166
  invoice_creation: { enabled: paymentInvoiceCreation },
165
167
  // Without a customer, Stripe's default "if_required" makes a guest
@@ -399,9 +399,13 @@ async function parsePaymentEvent(
399
399
  ): Promise<PaymentEvent | null> {
400
400
  const session = event.data.object as Stripe.Checkout.Session; // @cast-boundary engine-bridge
401
401
  // mode !== "payment" excludes subscription-checkout sessions (same event types);
402
- // payment_status !== "paid" excludes an unpaid/expired session. Null here — not an
403
- // error — maps to foundation's 200 "ignored", same as the subscription-path's filters.
404
- if (session.mode !== "payment" || session.payment_status !== "paid") {
402
+ // any status but paid / no_payment_required (a 100% promotion code) excludes an
403
+ // unpaid/expired session. Null here — not an error — maps to foundation's 200 "ignored",
404
+ // same as the subscription-path's filters.
405
+ if (
406
+ session.mode !== "payment" ||
407
+ (session.payment_status !== "paid" && session.payment_status !== "no_payment_required")
408
+ ) {
405
409
  return null;
406
410
  }
407
411
 
@@ -420,21 +424,22 @@ async function parsePaymentEvent(
420
424
  throw transientProviderRejection(error);
421
425
  }
422
426
 
423
- // Tenant-resolution: mode:"payment" checkout sessions carry tenantId on
424
- // the PaymentIntent's OWN metadata (plugin-methods.ts sets it via
425
- // payment_intent_data.metadata), NOT on session-level metadata —
426
- // session.metadata is unset for this mode. Reading it off the expanded,
427
- // Stripe-verified PaymentIntent (not a freely-choosable payload field) is
428
- // what keeps tenant-attribution trustworthy: the webhook signature proves
429
- // this whole object chain came from Stripe, and the metadata itself was
430
- // set by our own backend at checkout-creation time.
427
+ // Tenant-resolution: plugin-methods.ts sets tenantId on the PaymentIntent metadata and on the
428
+ // session metadata. A 100% promotion code creates no PaymentIntent, so the session metadata
429
+ // is only read then. Both are set by our own backend at checkout-creation time and reach us
430
+ // through the signature-verified webhook chain, not as a freely-choosable payload field.
431
431
  const paymentIntent = expanded.payment_intent;
432
- if (!paymentIntent || typeof paymentIntent === "string") {
433
- // Not expanded (Stripe-API-drift) or absent — no verified tenant-claim
432
+ if (
433
+ typeof paymentIntent === "string" ||
434
+ (paymentIntent === null && session.payment_status === "paid")
435
+ ) {
436
+ // Not expanded (Stripe-API-drift) or absent on a paid session — no verified tenant-claim
434
437
  // to trust.
435
438
  return dropPaidSession(event, session, "payment_intent_not_expanded");
436
439
  }
437
- const tenantId = paymentIntent.metadata?.["tenantId"];
440
+ const tenantId = paymentIntent
441
+ ? paymentIntent.metadata?.["tenantId"]
442
+ : expanded.metadata?.["tenantId"];
438
443
  if (!tenantId || tenantId.length === 0) {
439
444
  return dropPaidSession(event, session, "missing_tenant_id");
440
445
  }
@@ -450,9 +455,9 @@ async function parsePaymentEvent(
450
455
  const sessionCustomer = expanded.customer;
451
456
  const providerCustomerId =
452
457
  (typeof sessionCustomer === "string" ? sessionCustomer : sessionCustomer?.id) ??
453
- (typeof paymentIntent.customer === "string"
458
+ (typeof paymentIntent?.customer === "string"
454
459
  ? paymentIntent.customer
455
- : paymentIntent.customer?.id);
460
+ : paymentIntent?.customer?.id);
456
461
  if (!providerCustomerId) {
457
462
  return dropPaidSession(event, session, "missing_customer");
458
463
  }
@@ -1,4 +1,42 @@
1
1
  [
2
+ {
3
+ "version": "0.419.0",
4
+ "type": "improvement",
5
+ "title": "Frames and text styles in PDF templates",
6
+ "detail": "A PDF body can hold positioned frames (address window at DIN 5008 form B or A, free text frame, as `div[data-frame]` with `data-x`, `data-y`, `data-width`, `data-height` in mm) and text styles (`span[data-text-style]` with font, size in pt and colour, plus line height and paragraph spacing on blocks). Both go through the sanitizer and compile to inline CSS. The font catalog is Arial, Times New Roman, Courier New, Calibri and Cambria; the puppeteer-service image needs the metric-compatible fonts (Carlito, Caladea) next to the Liberation ones, so rebuild it."
7
+ },
8
+ {
9
+ "version": "0.419.0",
10
+ "type": "breaking",
11
+ "title": "signature and imprint are no longer placeholders, company* names are reserved",
12
+ "detail": "In `document-pdf` and `pdf-layout` templates, `signature` and `imprint` are no longer placeholders; a template that uses them fails on save and publish. The ten `company*` names (`companyAddress`, `companyPhone`, `companyEmail`, `companyWebsite`, `companyRegister`, `companyVatId`, `companyManagement`, `companyBank`, `companyIban`, `companyBic`) are now reserved, so a notification variable with such a name fails at boot.",
13
+ "migration": "Remove `signature` and `imprint` from PDF templates and layouts. Rename notification variables that collide with a reserved `company*` name."
14
+ },
15
+ {
16
+ "version": "0.419.0",
17
+ "type": "improvement",
18
+ "title": "Header and footer use the layout font size",
19
+ "detail": "PDF header and footer take the layout's `fontSizePt` and fall back to 10.5pt, the size the editor always showed; before they printed at 9px. Paragraphs in header and footer no longer carry margins. Existing PDF layouts therefore change on the next render: a footer taller than the bottom margin minus 4mm reaches into the page body, so check multi-line footers."
20
+ },
21
+ {
22
+ "version": "0.419.0",
23
+ "type": "improvement",
24
+ "title": "Default PDF layout per tenant, apply-layout and publish-templates",
25
+ "detail": "The tenant config key `template-resolver:config:default-pdf-layout-slug` picks the layout of PDF templates that name none. `template-resolver:write:apply-layout` sets it (mode `all`, no copies) or writes the layout into a tenant draft per chosen template (mode `selected`, text unchanged); `template-resolver:write:publish-templates` activates drafts together and reports per template what failed. The usage query lists the templates a layout serves, with `hasOwnLayout` for those that follow the default."
26
+ },
27
+ {
28
+ "version": "0.419.0",
29
+ "type": "breaking",
30
+ "title": "Line grid, flush tables and the address window in PDF bodies",
31
+ "detail": "PDF bodies print at line height 1.2. Paragraphs, lists, headings and tables are spaced by one body line (`--doc-line`, font size times 1.2) instead of 6pt after a paragraph and browser heading margins; the last element in a cell, list item, frame or the document has no bottom margin. Tables are flush with the text margin: the outer cells lose their left and right padding unless the layout table style is `grid` or the header has a background. Address paragraphs start at the text margin, have no spacing between lines, and the sender line prints at 7pt and wraps instead of being cut off. Flow text below a frame that reserves space starts 8mm under it. In the editor, cells are top-aligned, header cells print like body text, and rules appear only where the layout table style prints them; an untouched layout shows the table style \"plain\", as the PDF always printed it; a dashed outline marks cells while editing. Frames snap to page margins and other frames while moving or resizing (hold Alt to move freely).",
32
+ "migration": "Render existing PDF templates once and check the page breaks. A template that relied on the 6pt paragraph gap sets the spacing per paragraph instead."
33
+ },
34
+ {
35
+ "version": "0.419.0",
36
+ "type": "improvement",
37
+ "title": "patch-draft and create-layout let an agent rebuild PDF templates and layouts",
38
+ "detail": "patch-draft and document-blocks accept inline runs (bold, italic, underline, font, size, color), block formatting, lists, tables with a repeat row, address and text frames, a replaceBody op and a formatBlock op, all checked against the editor's print ranges and fonts. They also take kind pdf-layout with a region (header, signature or footer). The new create-layout handler creates an empty PDF layout draft under the slug tenant-layout-<name>; a tenant may edit, publish and use such layouts as soon as it may edit any PDF template, and system layouts may not take that prefix (reserved_layout_slug). patch-draft is now an agent proposal with risk low; its new refusals use the patch error codes print_style_not_allowed, invalid_table, too_many_blocks and others."
39
+ },
2
40
  {
3
41
  "version": "0.415.0",
4
42
  "type": "fix",
@@ -2,6 +2,7 @@ import type { TemplateVariableDef, TemplateVariables } from "@cosmicdrift/kumiko
2
2
  import { isOneOf } from "@cosmicdrift/kumiko-types/type-guards";
3
3
  import type { Element as ScanElement } from "happy-dom";
4
4
  import { isResourceImageContentType } from "../shared/index.ts";
5
+ import { appendStyle, applyDocumentPrintStyles } from "./compile-document-styles.ts";
5
6
  import { rewriteStepsBlock } from "./compile-steps-block.ts";
6
7
  import { conditionScopeElement, withParsedDocument } from "./document-sanitizer.ts";
7
8
  import {
@@ -253,12 +254,6 @@ const MAIL_HEADING_STYLES: Readonly<Record<string, string>> = {
253
254
  h3: "margin:20px 0 8px 0;font-size:17px;line-height:1.3;font-weight:600;color:#0B0D12",
254
255
  };
255
256
 
256
- // Appended after an existing style (data-align) so the alignment survives.
257
- function appendStyle(element: ScanElement, style: string): void {
258
- const existing = element.getAttribute("style");
259
- element.setAttribute("style", existing === null ? style : `${existing};${style}`);
260
- }
261
-
262
257
  function collectUniqueValidAttributes(
263
258
  html: string,
264
259
  selector: string,
@@ -335,8 +330,7 @@ export function toResourceDataUri(contentType: string, bytes: Uint8Array): strin
335
330
  function rewriteAlignment(element: ScanElement): void {
336
331
  const align = element.getAttribute("data-align");
337
332
  element.removeAttribute("data-align");
338
- if (isOneOf(DOCUMENT_TEXT_ALIGNMENTS, align))
339
- element.setAttribute("style", `text-align:${align}`);
333
+ if (isOneOf(DOCUMENT_TEXT_ALIGNMENTS, align)) appendStyle(element, `text-align:${align}`);
340
334
  }
341
335
 
342
336
  function rewriteResourceImage(
@@ -431,6 +425,7 @@ export function compileDocumentBodyToHandlebars(
431
425
  const scrubbed = html.replaceAll(EXPRESSION_OPEN, "").replaceAll(EXPRESSION_CLOSE, "");
432
426
  const compiled = withParsedDocument(scrubbed, (root) => {
433
427
  stripScriptsAndActiveContent(root, options);
428
+ applyDocumentPrintStyles(root);
434
429
  if (options.alignmentAsInlineStyle === true) applyAlignmentInlineStyles(root);
435
430
  if (options.headingAsInlineStyle === true) applyHeadingInlineStyles(root);
436
431
  if (options.tableAsInlineStyle === true) applyTableInlineStyles(root);
@@ -0,0 +1,102 @@
1
+ import type { Element as ScanElement } from "happy-dom";
2
+ import {
3
+ readBlockStyleAttributes,
4
+ readCellBackground,
5
+ readColwidth,
6
+ readFrameAttributes,
7
+ readTextStyleAttributes,
8
+ } from "./web/document-print-style.ts";
9
+ import {
10
+ documentBlockStyleCss,
11
+ documentCellStyleCss,
12
+ documentFrameCss,
13
+ documentTextStyleCss,
14
+ } from "./web/document-style-css.ts";
15
+
16
+ // Appended after an existing style (data-align) so the alignment survives.
17
+ export function appendStyle(element: ScanElement, style: string): void {
18
+ if (style === "") return;
19
+ const existing = element.getAttribute("style");
20
+ element.setAttribute("style", existing === null ? style : `${existing};${style}`);
21
+ }
22
+
23
+ function addClass(element: ScanElement, className: string): void {
24
+ const existing = element.getAttribute("class");
25
+ element.setAttribute("class", existing === null ? className : `${existing} ${className}`);
26
+ }
27
+
28
+ function roundPercent(value: number): number {
29
+ return Math.round(value * 100) / 100;
30
+ }
31
+
32
+ // Percentages sum to exactly 100 so the table keeps the full content width.
33
+ function columnPercentages(widths: readonly number[]): number[] {
34
+ const total = widths.reduce((sum, width) => sum + width, 0);
35
+ const percentages = widths.map((width) => roundPercent((width / total) * 100));
36
+ const last = percentages.length - 1;
37
+ const others = percentages.slice(0, last).reduce((sum, value) => sum + value, 0);
38
+ percentages[last] = roundPercent(100 - others);
39
+ return percentages;
40
+ }
41
+
42
+ function firstRowColumnWidths(table: ScanElement): number[] | null {
43
+ const firstRow = Array.from(table.querySelectorAll("tr")).find(
44
+ (row) => row.closest("table") === table,
45
+ );
46
+ if (firstRow === undefined) return null;
47
+ const widths: number[] = [];
48
+ for (const cell of Array.from(firstRow.children)) {
49
+ const colwidth = readColwidth(cell);
50
+ const span = Number(cell.getAttribute("colspan") ?? 1);
51
+ if (colwidth === null || colwidth.length !== span) return null;
52
+ widths.push(...colwidth);
53
+ }
54
+ return widths.length > 0 ? widths : null;
55
+ }
56
+
57
+ function insertColgroup(table: ScanElement, widths: readonly number[]): void {
58
+ const document = table.ownerDocument;
59
+ const colgroup = document.createElement("colgroup");
60
+ for (const percentage of columnPercentages(widths)) {
61
+ const col = document.createElement("col");
62
+ col.setAttribute("style", `width:${percentage}%`);
63
+ colgroup.append(col);
64
+ }
65
+ table.insertBefore(colgroup, table.firstChild);
66
+ }
67
+
68
+ function applyFrames(root: ScanElement): void {
69
+ for (const frame of Array.from(root.querySelectorAll("div[data-frame]"))) {
70
+ const box = readFrameAttributes(frame);
71
+ if (box === null) {
72
+ frame.replaceWith(...Array.from(frame.childNodes));
73
+ continue;
74
+ }
75
+ addClass(frame, "kumiko-frame");
76
+ appendStyle(frame, documentFrameCss(box));
77
+ }
78
+ }
79
+
80
+ function applyTables(root: ScanElement): void {
81
+ for (const table of Array.from(root.querySelectorAll("table"))) {
82
+ if (table.getAttribute("data-borders") === "none") addClass(table, "kumiko-table-plain");
83
+ const widths = firstRowColumnWidths(table);
84
+ if (widths !== null) insertColgroup(table, widths);
85
+ }
86
+ for (const cell of Array.from(root.querySelectorAll("td, th"))) {
87
+ appendStyle(cell, documentCellStyleCss({ background: readCellBackground(cell) }));
88
+ }
89
+ }
90
+
91
+ // Runs before the placeholder rewrites: a rich text block host copies its paragraph's
92
+ // attributes, so the style has to be on the paragraph by then.
93
+ export function applyDocumentPrintStyles(root: ScanElement): void {
94
+ applyFrames(root);
95
+ applyTables(root);
96
+ for (const span of Array.from(root.querySelectorAll("span[data-text-style]"))) {
97
+ appendStyle(span, documentTextStyleCss(readTextStyleAttributes(span)));
98
+ }
99
+ for (const block of Array.from(root.querySelectorAll("p, h1, h2, h3"))) {
100
+ appendStyle(block, documentBlockStyleCss(readBlockStyleAttributes(block)));
101
+ }
102
+ }
@@ -0,0 +1,25 @@
1
+ // Server-only (happy-dom). Frames are read from the stored body for page planning, and flattened
2
+ // for the editor preview, which shows the body outside a page where absolute coordinates mean nothing.
3
+ import { withParsedDocument } from "./document-sanitizer.ts";
4
+ import { type DocumentFrameAttributes, readFrameAttributes } from "./web/document-print-style.ts";
5
+
6
+ const PREVIEW_FRAME_STYLE =
7
+ "margin:8px 0;padding:6px;border:1px dashed #9ca3af;white-space:pre-line";
8
+
9
+ export function readTopLevelFrames(html: string): readonly DocumentFrameAttributes[] {
10
+ return withParsedDocument(html, (body) =>
11
+ Array.from(body.children).flatMap((child) => {
12
+ const frame = child.matches("div[data-frame]") ? readFrameAttributes(child) : null;
13
+ return frame === null ? [] : [frame];
14
+ }),
15
+ );
16
+ }
17
+
18
+ export function flattenFramesForPreview(compiledHtml: string): string {
19
+ return withParsedDocument(compiledHtml, (body) => {
20
+ for (const frame of Array.from(body.querySelectorAll("div.kumiko-frame"))) {
21
+ frame.setAttribute("style", PREVIEW_FRAME_STYLE);
22
+ }
23
+ return body.innerHTML;
24
+ });
25
+ }