@cosmicdrift/kumiko-samples 0.414.0 → 0.416.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.
- package/package.json +1 -1
- package/packages/bundled-features/package.json +21 -1
- package/packages/bundled-features/src/agent-tools/changes.json +6 -0
- package/packages/bundled-features/src/agent-tools/tool-catalog.ts +20 -1
- package/packages/bundled-features/src/agent-tools/tool-dispatch.ts +19 -5
- package/packages/bundled-features/src/auth-email-password/signup-token-store.ts +2 -3
- package/packages/bundled-features/src/auth-email-password/web/session.tsx +2 -1
- package/packages/bundled-features/src/auth-mfa/changes.json +6 -0
- package/packages/bundled-features/src/billing-foundation/changes.json +24 -0
- package/packages/bundled-features/src/billing-foundation/checkout-core.ts +11 -0
- package/packages/bundled-features/src/billing-foundation/checkout-ledger.ts +8 -0
- package/packages/bundled-features/src/billing-foundation/events.ts +7 -5
- package/packages/bundled-features/src/billing-foundation/handlers/create-checkout-session.write.ts +2 -0
- package/packages/bundled-features/src/billing-foundation/handlers/process-event.write.ts +76 -24
- package/packages/bundled-features/src/billing-foundation/handlers/process-payment-event.write.ts +5 -4
- package/packages/bundled-features/src/billing-foundation/handlers/start-plan-checkout.write.ts +2 -0
- package/packages/bundled-features/src/billing-foundation/webhook-handler.ts +2 -2
- package/packages/bundled-features/src/channel-whatsapp/changes.json +30 -0
- package/packages/bundled-features/src/channel-whatsapp/constants.ts +1 -0
- package/packages/bundled-features/src/channel-whatsapp/events.ts +4 -3
- package/packages/bundled-features/src/channel-whatsapp/graph-client.ts +37 -1
- package/packages/bundled-features/src/channel-whatsapp/inbound-handlers.ts +23 -2
- package/packages/bundled-features/src/channel-whatsapp/webhook-normalize.ts +27 -6
- package/packages/bundled-features/src/compliance-profiles/changes.json +5 -0
- package/packages/bundled-features/src/compliance-profiles/handlers/set-profile.write.ts +2 -0
- package/packages/bundled-features/src/data-retention/feature.ts +1 -0
- package/packages/bundled-features/src/delivery/changes.json +6 -0
- package/packages/bundled-features/src/delivery/handlers/opted-in-user-ids.query.ts +12 -3
- package/packages/bundled-features/src/document-ingest-foundation/changes.json +6 -0
- package/packages/bundled-features/src/document-ingest-foundation/feature.ts +1 -0
- package/packages/bundled-features/src/document-ingest-foundation/report-ingest-progress.ts +3 -1
- package/packages/bundled-features/src/documents/changes.json +6 -0
- package/packages/bundled-features/src/documents/feature.ts +10 -5
- package/packages/bundled-features/src/form-draft/feature.ts +1 -0
- package/packages/bundled-features/src/handbook-knowledge/README.md +64 -0
- package/packages/bundled-features/src/handbook-knowledge/changes.json +8 -0
- package/packages/bundled-features/src/handbook-knowledge/constants.ts +8 -0
- package/packages/bundled-features/src/handbook-knowledge/feature.ts +34 -0
- package/packages/bundled-features/src/handbook-knowledge/handbook-index.ts +66 -0
- package/packages/bundled-features/src/handbook-knowledge/handlers.ts +77 -0
- package/packages/bundled-features/src/handbook-knowledge/index.ts +10 -0
- package/packages/bundled-features/src/helpdesk/changes.json +6 -0
- package/packages/bundled-features/src/helpdesk/feature.ts +1 -0
- package/packages/bundled-features/src/helpdesk/handlers/reply.write.ts +3 -3
- package/packages/bundled-features/src/helpdesk/handlers/report.write.ts +3 -2
- package/packages/bundled-features/src/helpdesk/handlers/submit.write.ts +3 -2
- package/packages/bundled-features/src/helpdesk/legacy-contact-streams.ts +3 -1
- package/packages/bundled-features/src/helpdesk/lib.ts +9 -4
- package/packages/bundled-features/src/inbound-mail-foundation/account-poll.ts +4 -1
- package/packages/bundled-features/src/inbound-mail-foundation/changes.json +6 -0
- package/packages/bundled-features/src/inbound-mail-foundation/content-refetch.ts +11 -4
- package/packages/bundled-features/src/inbound-mail-foundation/entities.ts +18 -9
- package/packages/bundled-features/src/inbound-mail-foundation/events.ts +18 -9
- package/packages/bundled-features/src/inbound-mail-foundation/handlers/connect-account.write.ts +2 -1
- package/packages/bundled-features/src/inbound-mail-foundation/handlers/forget-message.write.ts +6 -0
- package/packages/bundled-features/src/inbound-mail-foundation/handlers/ingest-message-schema.ts +18 -5
- package/packages/bundled-features/src/inbound-mail-foundation/normalize-inbound-message.ts +22 -8
- package/packages/bundled-features/src/inbound-mail-foundation/sanitize-inbound-html.ts +2 -5
- package/packages/bundled-features/src/managed-pages/web/page-edit-screen.tsx +11 -5
- package/packages/bundled-features/src/shared/changes.json +6 -0
- package/packages/bundled-features/src/shared/hmac-signature.ts +4 -2
- package/packages/bundled-features/src/shared/index.ts +2 -1
- package/packages/bundled-features/src/shared/normalize-email.ts +3 -0
- package/packages/bundled-features/src/shared/send-best-effort.ts +16 -6
- package/packages/bundled-features/src/signature/README.md +59 -0
- package/packages/bundled-features/src/signature/changes.json +15 -0
- package/packages/bundled-features/src/signature/entity.ts +192 -0
- package/packages/bundled-features/src/signature/feature.ts +125 -0
- package/packages/bundled-features/src/signature/files.ts +107 -0
- package/packages/bundled-features/src/signature/grant.ts +79 -0
- package/packages/bundled-features/src/signature/handlers/anonymous.write.ts +88 -0
- package/packages/bundled-features/src/signature/handlers/cancel.write.ts +40 -0
- package/packages/bundled-features/src/signature/handlers/issue-link.write.ts +72 -0
- package/packages/bundled-features/src/signature/handlers/lifecycle.write.ts +99 -0
- package/packages/bundled-features/src/signature/handlers/link-internal.write.ts +261 -0
- package/packages/bundled-features/src/signature/handlers/request.write.ts +86 -0
- package/packages/bundled-features/src/signature/handlers/revoke-link.write.ts +23 -0
- package/packages/bundled-features/src/signature/handlers/sign-in-person.write.ts +69 -0
- package/packages/bundled-features/src/signature/i18n.ts +52 -0
- package/packages/bundled-features/src/signature/index.ts +33 -0
- package/packages/bundled-features/src/signature/lib.ts +125 -0
- package/packages/bundled-features/src/signature/options.ts +49 -0
- package/packages/bundled-features/src/signature/payloads.ts +71 -0
- package/packages/bundled-features/src/signature/png.ts +169 -0
- package/packages/bundled-features/src/signature/screens.ts +115 -0
- package/packages/bundled-features/src/signature/signature-page.ts +93 -0
- package/packages/bundled-features/src/signature/signing.ts +77 -0
- package/packages/bundled-features/src/signature/static-sign.ts +98 -0
- package/packages/bundled-features/src/signature/sweep.ts +161 -0
- package/packages/bundled-features/src/signature/user-data.ts +159 -0
- package/packages/bundled-features/src/signature/web/constants.ts +92 -0
- package/packages/bundled-features/src/signature/web/index.ts +31 -0
- package/packages/bundled-features/src/signature/web/pad.ts +147 -0
- package/packages/bundled-features/src/signature/web/signature-pad.tsx +82 -0
- package/packages/bundled-features/src/step-dispatcher/changes.json +6 -0
- package/packages/bundled-features/src/step-dispatcher/deliver-dispatch-request.ts +5 -2
- package/packages/bundled-features/src/step-dispatcher/feature.ts +14 -0
- package/packages/bundled-features/src/step-dispatcher/sweep-abandoned.ts +4 -0
- package/packages/bundled-features/src/subscription-paddle/backfill-checkout-ledger.ts +2 -0
- package/packages/bundled-features/src/subscription-paddle/changes.json +6 -0
- package/packages/bundled-features/src/subscription-paddle/redeliver-legacy-checkout.ts +23 -2
- package/packages/bundled-features/src/subscription-stripe/changes.json +12 -0
- package/packages/bundled-features/src/subscription-stripe/feature.ts +9 -0
- package/packages/bundled-features/src/subscription-stripe/plugin-methods.ts +7 -1
- package/packages/bundled-features/src/subscription-stripe/verify-webhook.ts +19 -5
- package/packages/bundled-features/src/template-resolver/changes.json +12 -0
- package/packages/bundled-features/src/template-resolver/seeding.ts +37 -7
- package/packages/bundled-features/src/template-resolver/web/web-preview-renderer.tsx +7 -1
- package/packages/bundled-features/src/tenant-inactivity/changes.json +6 -0
- package/packages/bundled-features/src/tenant-inactivity/check-inactive-tenants.ts +34 -16
- package/packages/bundled-features/src/tenant-inactivity/handlers/keep-account.write.ts +6 -0
- package/packages/bundled-features/src/tenant-inactivity/state-store.ts +12 -1
- package/packages/bundled-features/src/tenant-lifecycle/changes.json +6 -0
- package/packages/bundled-features/src/tenant-lifecycle/feature.ts +1 -0
- package/packages/bundled-features/src/user/resolve-verified-user-email.ts +3 -3
- package/packages/bundled-features/src/user-data-rights/feature.ts +1 -0
- package/packages/bundled-features/src/waitlist/handlers/reject.write.ts +1 -1
- package/packages/bundled-features/src/waitlist/handlers/submit.write.ts +2 -2
- package/packages/bundled-features/src/waitlist/import.ts +2 -1
- package/packages/bundled-features/src/waitlist/lib.ts +1 -5
- package/packages/bundled-features/src/waitlist/link-on-signup.ts +2 -2
- package/packages/bundled-features/src/workflow-runner/changes.json +6 -0
- package/packages/bundled-features/src/workflow-runner/handlers/resume-run.write.ts +4 -2
- package/samples/apps/admin-console/src/app/shell.tsx +1 -0
- package/samples/apps/use-all-bundled/feature-manifest.json +63 -1
- package/samples/apps/use-all-bundled/kumiko/migrations/0068_signature.rebuild.json +4 -0
- package/samples/apps/use-all-bundled/src/run-config.ts +35 -1
- package/samples/recipes/crypto-shredding-hr/README.md +11 -0
- package/samples/recipes/crypto-shredding-hr/src/feature.ts +27 -0
- package/samples/recipes/embedded/README.md +4 -0
- package/samples/recipes/embedded/src/entities/invoice.ts +6 -0
- package/samples/recipes/embedded/src/feature.ts +7 -1
- package/samples/recipes/embedded/src/handlers/invoice-receive.write.ts +1 -0
- package/samples/recipes/embedded/src/screens/invoice-receive.screen.ts +2 -0
- package/samples/recipes/handbook-knowledge/README.md +22 -0
- package/samples/recipes/handbook-knowledge/package.json +12 -0
- package/samples/recipes/handbook-knowledge/src/feature.ts +42 -0
- package/samples/recipes/record-detail-layout/src/feature.ts +36 -5
- package/samples/recipes/record-detail-layout/src/order-board.ts +10 -2
- package/samples/recipes/signature/README.md +21 -0
- package/samples/recipes/signature/package.json +13 -0
- package/samples/recipes/signature/src/feature.ts +26 -0
|
@@ -23,8 +23,9 @@ export const WHATSAPP_THROTTLED_EVENT_QN =
|
|
|
23
23
|
`${CHANNEL_WHATSAPP_FEATURE}:event:${WHATSAPP_THROTTLED_EVENT_SHORT}` as const;
|
|
24
24
|
|
|
25
25
|
const E164_MAX_CHARS = 32;
|
|
26
|
-
const WAMID_MAX_CHARS = 256;
|
|
27
|
-
const PHONE_NUMBER_ID_MAX_CHARS = 64;
|
|
26
|
+
export const WAMID_MAX_CHARS = 256;
|
|
27
|
+
export const PHONE_NUMBER_ID_MAX_CHARS = 64;
|
|
28
|
+
export const MIME_TYPE_MAX_CHARS = 255;
|
|
28
29
|
export const RAW_STATUS_MAX_CHARS = 64;
|
|
29
30
|
|
|
30
31
|
// What the webhook route hands to the write handlers: normalized, still plaintext.
|
|
@@ -38,7 +39,7 @@ export const receiveMessageInputSchema = z.object({
|
|
|
38
39
|
buttonPayload: z.string().max(WHATSAPP_BUTTON_PAYLOAD_MAX_CHARS).nullable(),
|
|
39
40
|
contextWamid: z.string().max(WAMID_MAX_CHARS).nullable(),
|
|
40
41
|
mediaId: z.string().max(WAMID_MAX_CHARS).nullable(),
|
|
41
|
-
mimeType: z.string().max(
|
|
42
|
+
mimeType: z.string().max(MIME_TYPE_MAX_CHARS).nullable(),
|
|
42
43
|
});
|
|
43
44
|
export type ReceiveMessageInput = z.infer<typeof receiveMessageInputSchema>;
|
|
44
45
|
|
|
@@ -8,6 +8,7 @@ import {
|
|
|
8
8
|
WHATSAPP_BUTTON_PAYLOAD_MAX_CHARS,
|
|
9
9
|
WHATSAPP_BUTTON_TITLE_MAX_CHARS,
|
|
10
10
|
WHATSAPP_MAX_REPLY_BUTTONS,
|
|
11
|
+
WHATSAPP_MAX_TEMPLATE_BUTTONS,
|
|
11
12
|
WHATSAPP_SECRET_KEYS,
|
|
12
13
|
WHATSAPP_TEXT_MAX_CHARS,
|
|
13
14
|
} from "./constants.ts";
|
|
@@ -62,6 +63,10 @@ export type WhatsappTemplateInput = SendBase & {
|
|
|
62
63
|
readonly templateName: string;
|
|
63
64
|
readonly languageCode: string;
|
|
64
65
|
readonly bodyParameters?: readonly string[];
|
|
66
|
+
// One payload per quick-reply button, echoed back as `buttonPayload`. Meta's button `index` is the
|
|
67
|
+
// position among all template buttons: quick-reply buttons must be the first ones; payload i goes to button index i.
|
|
68
|
+
readonly quickReplyPayloads?: readonly string[];
|
|
69
|
+
readonly headerImageLink?: string;
|
|
65
70
|
};
|
|
66
71
|
export type WhatsappReplyButton = {
|
|
67
72
|
// Echoed back unchanged in the `buttonPayload` of the answering message.
|
|
@@ -340,13 +345,44 @@ export function buildWhatsappClient(resolved: ResolvedWhatsappOptions): Whatsapp
|
|
|
340
345
|
) {
|
|
341
346
|
return Promise.resolve({ ok: false, code: "invalid_message" });
|
|
342
347
|
}
|
|
348
|
+
const quickReplyPayloads = input.quickReplyPayloads;
|
|
349
|
+
if (
|
|
350
|
+
quickReplyPayloads !== undefined &&
|
|
351
|
+
(quickReplyPayloads.length === 0 ||
|
|
352
|
+
quickReplyPayloads.length > WHATSAPP_MAX_TEMPLATE_BUTTONS ||
|
|
353
|
+
quickReplyPayloads.some(
|
|
354
|
+
(payload) => payload === "" || payload.length > WHATSAPP_BUTTON_PAYLOAD_MAX_CHARS,
|
|
355
|
+
))
|
|
356
|
+
) {
|
|
357
|
+
return Promise.resolve({ ok: false, code: "invalid_message" });
|
|
358
|
+
}
|
|
359
|
+
if (input.headerImageLink !== undefined && !isPublicMediaLink(input.headerImageLink, true)) {
|
|
360
|
+
return Promise.resolve({ ok: false, code: "invalid_message" });
|
|
361
|
+
}
|
|
343
362
|
const parameters = (input.bodyParameters ?? []).map((text) => ({ type: "text", text }));
|
|
363
|
+
const components = [
|
|
364
|
+
...(input.headerImageLink !== undefined
|
|
365
|
+
? [
|
|
366
|
+
{
|
|
367
|
+
type: "header",
|
|
368
|
+
parameters: [{ type: "image", image: { link: input.headerImageLink } }],
|
|
369
|
+
},
|
|
370
|
+
]
|
|
371
|
+
: []),
|
|
372
|
+
...(parameters.length > 0 ? [{ type: "body", parameters }] : []),
|
|
373
|
+
...(quickReplyPayloads ?? []).map((payload, index) => ({
|
|
374
|
+
type: "button",
|
|
375
|
+
sub_type: "quick_reply",
|
|
376
|
+
index: String(index),
|
|
377
|
+
parameters: [{ type: "payload", payload }],
|
|
378
|
+
})),
|
|
379
|
+
];
|
|
344
380
|
return postMessage(ctx, input, {
|
|
345
381
|
type: "template",
|
|
346
382
|
template: {
|
|
347
383
|
name: input.templateName,
|
|
348
384
|
language: { code: input.languageCode },
|
|
349
|
-
...(
|
|
385
|
+
...(components.length > 0 && { components }),
|
|
350
386
|
},
|
|
351
387
|
});
|
|
352
388
|
},
|
|
@@ -17,6 +17,8 @@ import {
|
|
|
17
17
|
import type { ResolvedWhatsappOptions } from "./options.ts";
|
|
18
18
|
import { encryptWhatsappPii, WhatsappPiiFields } from "./pii.ts";
|
|
19
19
|
|
|
20
|
+
const WHATSAPP_STREAM_LOCK_NAMESPACE = 0x77616d73;
|
|
21
|
+
|
|
20
22
|
export type InboundOutcome = "stored" | "duplicate" | "throttled";
|
|
21
23
|
|
|
22
24
|
type InboundResult = {
|
|
@@ -32,11 +34,17 @@ type LimitContext = Pick<HandlerContext, "services" | "rateLimitDigest">;
|
|
|
32
34
|
|
|
33
35
|
// Counts one message against every per-sender window. Only a RateLimitError means "throttled";
|
|
34
36
|
// anything else (Redis down, bad config) propagates so the webhook answers 5xx and Meta redelivers.
|
|
37
|
+
// A one-token marker bucket per wamid makes the charge once-only across failed rounds and
|
|
38
|
+
// concurrent deliveries. The marker is taken before the charge: a crash in between loses one
|
|
39
|
+
// charge, never doubles one. A redelivery after a throttled-then-failed attempt skips the charge.
|
|
40
|
+
// ponytail: that redelivery also skips the throttle decision (RateLimitResolver cannot read without
|
|
41
|
+
// consuming), so at most one message per failed round gets past the limit; upgrade: add a peek.
|
|
35
42
|
async function chargeSender(
|
|
36
43
|
ctx: LimitContext,
|
|
37
44
|
options: ResolvedWhatsappOptions,
|
|
38
45
|
tenantId: TenantId,
|
|
39
46
|
from: string,
|
|
47
|
+
wamid: string,
|
|
40
48
|
): Promise<RateLimitError | null> {
|
|
41
49
|
if (options.senderRateLimits.length === 0) return null;
|
|
42
50
|
const { rateLimit } = ctx.services;
|
|
@@ -46,6 +54,16 @@ async function chargeSender(
|
|
|
46
54
|
message: "channel-whatsapp: the per-sender limit needs a rate limiter and a digest key",
|
|
47
55
|
});
|
|
48
56
|
}
|
|
57
|
+
const markerWindowSeconds = Math.max(...options.senderRateLimits.map((l) => l.windowSeconds));
|
|
58
|
+
try {
|
|
59
|
+
await rateLimit.enforce(`whatsapp-inbound-charged:${tenantId}:${wamid}`, {
|
|
60
|
+
limit: 1,
|
|
61
|
+
windowSeconds: markerWindowSeconds,
|
|
62
|
+
});
|
|
63
|
+
} catch (error) {
|
|
64
|
+
if (error instanceof RateLimitError) return null;
|
|
65
|
+
throw error;
|
|
66
|
+
}
|
|
49
67
|
const senderKey = `whatsapp-inbound:${tenantId}:${digest(from)}`;
|
|
50
68
|
try {
|
|
51
69
|
await rateLimit.enforceAll(
|
|
@@ -74,11 +92,13 @@ export function createReceiveMessageHandler(options: ResolvedWhatsappOptions) {
|
|
|
74
92
|
const input = event.payload;
|
|
75
93
|
const tenantId = event.user.tenantId;
|
|
76
94
|
const aggregateId = whatsappMessageAggregateId(tenantId, input.wamid);
|
|
95
|
+
// tryAppend re-reads the stream version, so a delivery that committed after our load would land as a second event.
|
|
96
|
+
await ctx.db.advisoryXactLock(WHATSAPP_STREAM_LOCK_NAMESPACE, aggregateId);
|
|
77
97
|
|
|
78
98
|
// Dedupe before the limit: Meta's redeliveries must not use up the sender's budget.
|
|
79
99
|
if ((await ctx.events.load(aggregateId)).length > 0) return OUTCOME_DUPLICATE;
|
|
80
100
|
|
|
81
|
-
const throttle = await chargeSender(ctx, options, tenantId, input.from);
|
|
101
|
+
const throttle = await chargeSender(ctx, options, tenantId, input.from, input.wamid);
|
|
82
102
|
const requestId = `channel-whatsapp:receive-message:${aggregateId}`;
|
|
83
103
|
const from = await encryptWhatsappPii(
|
|
84
104
|
tenantId,
|
|
@@ -132,7 +152,6 @@ export function createReceiveMessageHandler(options: ResolvedWhatsappOptions) {
|
|
|
132
152
|
mediaId: input.mediaId,
|
|
133
153
|
mimeType: input.mimeType,
|
|
134
154
|
};
|
|
135
|
-
// A concurrent delivery of the same wamid that won the race counts as a duplicate.
|
|
136
155
|
const appended = await ctx.events.tryAppend({
|
|
137
156
|
aggregateId,
|
|
138
157
|
aggregateType: WHATSAPP_MESSAGE_AGGREGATE_TYPE,
|
|
@@ -162,6 +181,8 @@ export function createRecordStatusHandler(options: ResolvedWhatsappOptions) {
|
|
|
162
181
|
input.status,
|
|
163
182
|
input.rawStatus,
|
|
164
183
|
);
|
|
184
|
+
// tryAppend re-reads the stream version, so a delivery that committed after our load would land as a second event.
|
|
185
|
+
await ctx.db.advisoryXactLock(WHATSAPP_STREAM_LOCK_NAMESPACE, aggregateId);
|
|
165
186
|
if ((await ctx.events.load(aggregateId)).length > 0) return OUTCOME_DUPLICATE;
|
|
166
187
|
|
|
167
188
|
const payload: StatusUpdatedPayload = {
|
|
@@ -7,9 +7,12 @@ import {
|
|
|
7
7
|
type WhatsappStatusKind,
|
|
8
8
|
} from "./constants.ts";
|
|
9
9
|
import {
|
|
10
|
+
MIME_TYPE_MAX_CHARS,
|
|
11
|
+
PHONE_NUMBER_ID_MAX_CHARS,
|
|
10
12
|
RAW_STATUS_MAX_CHARS,
|
|
11
13
|
type ReceiveMessageInput,
|
|
12
14
|
type RecordStatusInput,
|
|
15
|
+
WAMID_MAX_CHARS,
|
|
13
16
|
} from "./events.ts";
|
|
14
17
|
|
|
15
18
|
// Meta adds fields and message types without notice. Every nested object is `.catch(undefined)`,
|
|
@@ -46,7 +49,7 @@ const statusSchema = z.object({
|
|
|
46
49
|
timestamp: z.string().optional(),
|
|
47
50
|
recipient_id: z.string().optional(),
|
|
48
51
|
errors: z
|
|
49
|
-
.array(z.object({ code: z.number().optional() }))
|
|
52
|
+
.array(z.object({ code: z.number().int().optional().catch(undefined) }))
|
|
50
53
|
.optional()
|
|
51
54
|
.catch(undefined),
|
|
52
55
|
});
|
|
@@ -75,10 +78,14 @@ const webhookSchema = z.object({
|
|
|
75
78
|
export type NormalizedWebhook = {
|
|
76
79
|
readonly messages: readonly ReceiveMessageInput[];
|
|
77
80
|
readonly statuses: readonly RecordStatusInput[];
|
|
78
|
-
// Entries that carried no usable id, sender or phone number id
|
|
81
|
+
// Entries that carried no usable id, sender or phone number id, or an id longer than the event
|
|
82
|
+
// schema allows; nothing a redelivery could fix.
|
|
79
83
|
readonly skipped: number;
|
|
80
84
|
};
|
|
81
85
|
|
|
86
|
+
// Temporal.Instant throws beyond 8.64e15 epoch milliseconds.
|
|
87
|
+
const MAX_EPOCH_SECONDS = 8.64e12;
|
|
88
|
+
|
|
82
89
|
const DIGITS_PATTERN = /^\d{5,20}$/;
|
|
83
90
|
|
|
84
91
|
function toE164(raw: string): string | null {
|
|
@@ -88,7 +95,10 @@ function toE164(raw: string): string | null {
|
|
|
88
95
|
|
|
89
96
|
function toIso(unixSeconds: string | undefined, fallbackIso: string): string {
|
|
90
97
|
const seconds = Number(unixSeconds);
|
|
91
|
-
return unixSeconds !== undefined &&
|
|
98
|
+
return unixSeconds !== undefined &&
|
|
99
|
+
Number.isFinite(seconds) &&
|
|
100
|
+
seconds > 0 &&
|
|
101
|
+
seconds <= MAX_EPOCH_SECONDS
|
|
92
102
|
? Temporal.Instant.fromEpochMilliseconds(Math.floor(seconds) * 1000).toString()
|
|
93
103
|
: fallbackIso;
|
|
94
104
|
}
|
|
@@ -108,6 +118,11 @@ function optionalClip(value: string | undefined, maxChars: number): string | nul
|
|
|
108
118
|
return value === undefined ? null : clip(value, maxChars);
|
|
109
119
|
}
|
|
110
120
|
|
|
121
|
+
// A truncated id would point at another object, so an oversized one is dropped, not clipped.
|
|
122
|
+
function optionalId(value: string | undefined): string | null {
|
|
123
|
+
return value === undefined || value.length > WAMID_MAX_CHARS ? null : value;
|
|
124
|
+
}
|
|
125
|
+
|
|
111
126
|
function buttonContentOf(message: MetaMessage): MessageContent | null {
|
|
112
127
|
const reply = message.interactive?.button_reply;
|
|
113
128
|
if (message.type === "interactive" && reply) {
|
|
@@ -137,8 +152,8 @@ function mediaContentOf(message: MetaMessage): MessageContent | null {
|
|
|
137
152
|
return {
|
|
138
153
|
...NO_CONTENT,
|
|
139
154
|
messageType: message.type,
|
|
140
|
-
mediaId: media.id
|
|
141
|
-
mimeType: media.mime_type
|
|
155
|
+
mediaId: optionalId(media.id),
|
|
156
|
+
mimeType: optionalClip(media.mime_type, MIME_TYPE_MAX_CHARS),
|
|
142
157
|
};
|
|
143
158
|
}
|
|
144
159
|
|
|
@@ -163,6 +178,9 @@ function normalizeMessage(
|
|
|
163
178
|
const parsed = messageSchema.safeParse(raw);
|
|
164
179
|
if (!parsed.success) return null;
|
|
165
180
|
const message = parsed.data;
|
|
181
|
+
if (message.id.length > WAMID_MAX_CHARS || phoneNumberId.length > PHONE_NUMBER_ID_MAX_CHARS) {
|
|
182
|
+
return null;
|
|
183
|
+
}
|
|
166
184
|
const from = toE164(message.from);
|
|
167
185
|
if (from === null) return null;
|
|
168
186
|
return {
|
|
@@ -170,7 +188,7 @@ function normalizeMessage(
|
|
|
170
188
|
wamid: message.id,
|
|
171
189
|
from,
|
|
172
190
|
timestampIso: toIso(message.timestamp, nowIso),
|
|
173
|
-
contextWamid: message.context?.id
|
|
191
|
+
contextWamid: optionalId(message.context?.id),
|
|
174
192
|
...contentOf(message),
|
|
175
193
|
};
|
|
176
194
|
}
|
|
@@ -187,6 +205,9 @@ function normalizeStatus(
|
|
|
187
205
|
const parsed = statusSchema.safeParse(raw);
|
|
188
206
|
if (!parsed.success) return null;
|
|
189
207
|
const status: MetaStatus = parsed.data;
|
|
208
|
+
if (status.id.length > WAMID_MAX_CHARS || phoneNumberId.length > PHONE_NUMBER_ID_MAX_CHARS) {
|
|
209
|
+
return null;
|
|
210
|
+
}
|
|
190
211
|
const recipient = toE164(status.recipient_id ?? "");
|
|
191
212
|
if (recipient === null) return null;
|
|
192
213
|
return {
|
|
@@ -46,6 +46,8 @@ export const setProfileWrite = defineWriteHandler({
|
|
|
46
46
|
// SystemAdmin can set profiles for customer setup through the platform-
|
|
47
47
|
// operator path; TenantAdmin can set them only for their own tenant.
|
|
48
48
|
access: { roles: access.admin },
|
|
49
|
+
// The profile picks the retention preset, so a change can shorten how long data is kept before the purge.
|
|
50
|
+
agent: { risk: "high" },
|
|
49
51
|
description:
|
|
50
52
|
"Sets or replaces a tenant's compliance profile key plus an optional JSON override, for onboarding or a later region change; a system admin may target a different tenant through tenantIdOverride.",
|
|
51
53
|
handler: async (event, ctx) => {
|
|
@@ -73,6 +73,7 @@ export function createDataRetentionFeature(): FeatureDefinition {
|
|
|
73
73
|
r.job({
|
|
74
74
|
name: "retention-cleanup",
|
|
75
75
|
trigger: { maintenance: true },
|
|
76
|
+
irreversibleWithoutEntryHandler: "high-risk-or-cron-pipeline",
|
|
76
77
|
perTenant: true,
|
|
77
78
|
includeSystemTenant: true,
|
|
78
79
|
concurrency: "skip",
|
|
@@ -1,4 +1,10 @@
|
|
|
1
1
|
[
|
|
2
|
+
{
|
|
3
|
+
"version": "0.415.0",
|
|
4
|
+
"type": "fix",
|
|
5
|
+
"title": "opted-in-user-ids refuses the wildcard type and resolves former names",
|
|
6
|
+
"detail": "A notificationType of \"*\" is rejected by the schema so wildcard rows never count as opt-in, and a former notification name resolves to the current type instead of returning an empty list."
|
|
7
|
+
},
|
|
2
8
|
{
|
|
3
9
|
"version": "0.414.0",
|
|
4
10
|
"type": "improvement",
|
|
@@ -3,13 +3,21 @@ import { defineQueryHandler, SYSTEM_ROLE } from "@cosmicdrift/kumiko-framework/e
|
|
|
3
3
|
import { InternalError } from "@cosmicdrift/kumiko-framework/errors";
|
|
4
4
|
import * as z from "zod";
|
|
5
5
|
import { tenantMembershipsTable } from "../../tenant/index.ts";
|
|
6
|
-
import { notificationTypeNames } from "../notification-type-aliases.ts";
|
|
6
|
+
import { currentNotificationType, notificationTypeNames } from "../notification-type-aliases.ts";
|
|
7
7
|
import { collapsePreferenceRows } from "../preference-rows.ts";
|
|
8
8
|
import { notificationPreferencesTable } from "../tables.ts";
|
|
9
9
|
|
|
10
10
|
export const optedInUserIdsQuery = defineQueryHandler({
|
|
11
11
|
name: "opted-in-user-ids",
|
|
12
|
-
schema: z
|
|
12
|
+
schema: z
|
|
13
|
+
.object({
|
|
14
|
+
notificationType: z
|
|
15
|
+
.string()
|
|
16
|
+
.min(1)
|
|
17
|
+
.refine((type) => type !== "*", { message: "a wildcard is not a notification type" }),
|
|
18
|
+
channel: z.string().min(1),
|
|
19
|
+
})
|
|
20
|
+
.strict(),
|
|
13
21
|
access: { roles: [SYSTEM_ROLE] },
|
|
14
22
|
agent: { expose: false },
|
|
15
23
|
description:
|
|
@@ -21,7 +29,8 @@ export const optedInUserIdsQuery = defineQueryHandler({
|
|
|
21
29
|
});
|
|
22
30
|
}
|
|
23
31
|
const db = ctx.systemDb.assertTenantMatch(query.user.tenantId);
|
|
24
|
-
const {
|
|
32
|
+
const { channel } = query.payload;
|
|
33
|
+
const notificationType = currentNotificationType(ctx.registry, query.payload.notificationType);
|
|
25
34
|
|
|
26
35
|
const rows = await selectMany(db, notificationPreferencesTable, {
|
|
27
36
|
tenantId: query.user.tenantId,
|
|
@@ -1,4 +1,10 @@
|
|
|
1
1
|
[
|
|
2
|
+
{
|
|
3
|
+
"version": "0.415.0",
|
|
4
|
+
"type": "fix",
|
|
5
|
+
"title": "Parallel ingest progress reports no longer fail after the retry budget",
|
|
6
|
+
"detail": "A version conflict after the last attempt means a newer report already landed, so reportIngestProgress returns instead of throwing into the ingest run."
|
|
7
|
+
},
|
|
2
8
|
{
|
|
3
9
|
"version": "0.409.0",
|
|
4
10
|
"type": "improvement",
|
|
@@ -272,6 +272,7 @@ export function createDocumentIngestFoundationFeature() {
|
|
|
272
272
|
// extracted text has no reason to survive it either.
|
|
273
273
|
r.multiStreamProjection({
|
|
274
274
|
name: "forget-extract-with-file-ref",
|
|
275
|
+
irreversibleWithoutEntryHandler: "rebuildable-derived-data",
|
|
275
276
|
apply: {
|
|
276
277
|
[FILE_REF_DELETED]: forgetExtractOnFileRefDeletedHook,
|
|
277
278
|
[FILE_REF_FORGOTTEN]: forgetExtractOnFileRefForgottenHook,
|
|
@@ -55,7 +55,9 @@ export async function reportIngestProgress(
|
|
|
55
55
|
// skip: event appended, nothing left to retry
|
|
56
56
|
return;
|
|
57
57
|
} catch (e) {
|
|
58
|
-
if (!(e instanceof VersionConflictError)
|
|
58
|
+
if (!(e instanceof VersionConflictError)) throw e;
|
|
59
|
+
// skip: a conflict after the last attempt means a newer report already landed
|
|
60
|
+
if (attempt >= MAX_VERSION_CONFLICT_ATTEMPTS) return;
|
|
59
61
|
}
|
|
60
62
|
}
|
|
61
63
|
}
|
|
@@ -1,4 +1,10 @@
|
|
|
1
1
|
[
|
|
2
|
+
{
|
|
3
|
+
"version": "0.415.0",
|
|
4
|
+
"type": "fix",
|
|
5
|
+
"title": "Split access without write no longer lets members file invisible documents",
|
|
6
|
+
"detail": "With `access: { read, delete }` and no `write`, create fell back to TenantAdmin and TenantMember, so a member could file a document they could never see. Create now stays limited to the admin roles unless a write rule is set."
|
|
7
|
+
},
|
|
2
8
|
{
|
|
3
9
|
"version": "0.414.0",
|
|
4
10
|
"type": "improvement",
|
|
@@ -64,8 +64,8 @@ export type DocumentsFeatureOptions = {
|
|
|
64
64
|
/**
|
|
65
65
|
* Who may use the document handlers. One rule applies to read, write and delete; the split form
|
|
66
66
|
* sets them apart. Default TenantAdmin and TenantMember; a missing delete follows write. Without
|
|
67
|
-
*
|
|
68
|
-
* visible to them only.
|
|
67
|
+
* a write rule (no option, or a split form without `write`), creating a document is limited to
|
|
68
|
+
* the admin roles, since an unlinked document is visible to them only.
|
|
69
69
|
*/
|
|
70
70
|
readonly access?: AccessRule | DocumentsAccess;
|
|
71
71
|
/** Roles that see every document of their tenant whose file owner they can read, without a link. */
|
|
@@ -88,6 +88,10 @@ function isAccessRule(access: AccessRule | DocumentsAccess): access is AccessRul
|
|
|
88
88
|
return "roles" in access || "openToAll" in access;
|
|
89
89
|
}
|
|
90
90
|
|
|
91
|
+
function hasNoExplicitWrite(access: AccessRule | DocumentsAccess | undefined): boolean {
|
|
92
|
+
return access === undefined || (!isAccessRule(access) && access.write === undefined);
|
|
93
|
+
}
|
|
94
|
+
|
|
91
95
|
function resolveAccess(access: AccessRule | DocumentsAccess | undefined): ResolvedDocumentsAccess {
|
|
92
96
|
if (access === undefined) {
|
|
93
97
|
return {
|
|
@@ -128,9 +132,10 @@ function registerDocuments(
|
|
|
128
132
|
});
|
|
129
133
|
const linkEntity = createDocumentLinkEntity(linkTargets);
|
|
130
134
|
// A fresh document is invisible until linked, except to the admin roles; with the default access
|
|
131
|
-
// a member would file a record they can never see again. An explicit
|
|
132
|
-
const createAccess: AccessRule =
|
|
133
|
-
|
|
135
|
+
// a member would file a record they can never see again. An explicit write rule stays in charge.
|
|
136
|
+
const createAccess: AccessRule = hasNoExplicitWrite(opts.access)
|
|
137
|
+
? { roles: opts.adminRoles ?? DEFAULT_ADMIN_ROLES }
|
|
138
|
+
: access.write;
|
|
134
139
|
const executors = createDocumentExecutors(documentEntity, linkEntity);
|
|
135
140
|
|
|
136
141
|
r.requires({ features: ["files"] });
|
|
@@ -44,6 +44,7 @@ function registerFormDraft(r: FeatureRegistrar<typeof FORM_DRAFT_FEATURE_NAME>):
|
|
|
44
44
|
r.job({
|
|
45
45
|
name: "cleanup",
|
|
46
46
|
trigger: { maintenance: true },
|
|
47
|
+
irreversibleWithoutEntryHandler: "high-risk-or-cron-pipeline",
|
|
47
48
|
concurrency: "skip",
|
|
48
49
|
escapeHatch: { reason: CLEANUP_ESCAPE_HATCH_REASON },
|
|
49
50
|
handler: (payload, ctx) =>
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
# handbook-knowledge
|
|
2
|
+
|
|
3
|
+
Gives the AI agent the app's handbook: two read-only query tools, built from the
|
|
4
|
+
JSON that `kumiko handbuch knowledge` writes. No table, no migration, no search
|
|
5
|
+
index. The model picks the page itself from the catalog of titles and questions.
|
|
6
|
+
|
|
7
|
+
## Setup
|
|
8
|
+
|
|
9
|
+
1. Add the process pages to the handbook config (`processTextsDir`, with `{locale}`):
|
|
10
|
+
|
|
11
|
+
```json
|
|
12
|
+
{ "textsDir": "docs/handbuch/{locale}", "processTextsDir": "docs/handbuch/{locale}/prozesse" }
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
A process page is a Markdown file with frontmatter `titel`, `gruppe: aufgaben`,
|
|
16
|
+
`fragen` (the questions it answers), `masken` (screen ids, in order) and optionally
|
|
17
|
+
`start` (the qualified name of the write handler that begins the task, e.g.
|
|
18
|
+
`ai-orchestration:write:start-move-out`). The assistant answers with the page's
|
|
19
|
+
steps, links the page and offers to start the task as a plan through exactly that
|
|
20
|
+
handler, the same one the screen calls; the framework does not validate the name. Without
|
|
21
|
+
`processTextsDir` the handbook build is unchanged.
|
|
22
|
+
|
|
23
|
+
2. Export the knowledge file (deterministic, one list per locale, images removed):
|
|
24
|
+
|
|
25
|
+
```sh
|
|
26
|
+
kumiko handbuch knowledge handbuch.json --out src/handbook-knowledge.json
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
3. Mount the feature:
|
|
30
|
+
|
|
31
|
+
```typescript
|
|
32
|
+
import { createHandbookKnowledgeFeature } from "@cosmicdrift/kumiko-bundled-features/handbook-knowledge";
|
|
33
|
+
import pages from "./handbook-knowledge.json";
|
|
34
|
+
|
|
35
|
+
createHandbookKnowledgeFeature({
|
|
36
|
+
pages,
|
|
37
|
+
access: { roles: ["Member", "Admin"] },
|
|
38
|
+
publicPath: "/handbuch",
|
|
39
|
+
});
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
`pages` is validated once at boot. `access` is the declarative access of both
|
|
43
|
+
handlers; the agent tool catalog only contains the tools for roles it admits.
|
|
44
|
+
`publicPath` is optional; page links are `<publicPath>/<page id>`, with or without a trailing slash.
|
|
45
|
+
|
|
46
|
+
## Handlers
|
|
47
|
+
|
|
48
|
+
| Handler | Payload | Returns |
|
|
49
|
+
| ------------------------------------- | -------- | ----------------------------------------------------------------------------------------------------- |
|
|
50
|
+
| `handbook-knowledge:query:list-pages` | none | `locale`, `pages[]` with `id`, `kind` (`process` or `screen`), `title`, `questions`, `start` when set |
|
|
51
|
+
| `handbook-knowledge:query:read-page` | `{ id }` | the page with `bodyMd`, `start` when set, `locale`, `truncated`, `notice`, `publicPath` |
|
|
52
|
+
|
|
53
|
+
- Language: the caller's `ctx.locale` (`de-AT` serves `de`). A language or page the
|
|
54
|
+
handbook lacks falls back to the default language.
|
|
55
|
+
- `read-page` cuts a body at `HANDBOOK_PAGE_MAX_CHARS` (12000) at a paragraph break
|
|
56
|
+
and says so in `notice`. An unknown `id` is a `not_found` error.
|
|
57
|
+
- Both handlers carry a `description` that tells the model to use them for every
|
|
58
|
+
how-do-I question, which is what puts them into the agent tool catalog. The
|
|
59
|
+
`agent-tools` feature does not have to be mounted.
|
|
60
|
+
|
|
61
|
+
## Content rules
|
|
62
|
+
|
|
63
|
+
The text is returned as tool data, not as instructions, and ships to every caller the
|
|
64
|
+
`access` admits. Put only public handbook content into it, never tenant or customer data.
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
[
|
|
2
|
+
{
|
|
3
|
+
"version": "0.416.0",
|
|
4
|
+
"type": "improvement",
|
|
5
|
+
"title": "Handbook pages for the AI assistant, with a process axis in the handbuch CLI",
|
|
6
|
+
"detail": "`createHandbookKnowledgeFeature({ pages, access })` mounts the query handlers `list-pages` (catalog of id, kind, title and questions) and `read-page` (one page in the caller's language, falling back to the default language, cut at 12000 characters with a notice; with `publicPath` it links the page as `<publicPath>/<id>`). Both appear in the agent tool catalog for the roles in `access`; no entity, no migration. The handbuch config takes an optional `processTextsDir` (with `{locale}`): its pages show as an own group in the HTML, and the new command `kumiko handbuch knowledge <config> --out <file>` writes the pages per locale as deterministic JSON without images. A process page may carry `start` (qualified name of a write handler); `list-pages` and `read-page` return it, and their descriptions tell the assistant to answer with the page's steps, link the page and offer to start the task as a plan through exactly that handler. Without `processTextsDir` the built handbook stays byte-identical."
|
|
7
|
+
}
|
|
8
|
+
]
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export const HANDBOOK_KNOWLEDGE_FEATURE = "handbook-knowledge";
|
|
2
|
+
|
|
3
|
+
export const HandbookKnowledgeQueries = {
|
|
4
|
+
listPages: `${HANDBOOK_KNOWLEDGE_FEATURE}:query:list-pages`,
|
|
5
|
+
readPage: `${HANDBOOK_KNOWLEDGE_FEATURE}:query:read-page`,
|
|
6
|
+
} as const;
|
|
7
|
+
|
|
8
|
+
export const HANDBOOK_PAGE_MAX_CHARS = 12_000;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type AccessRule,
|
|
3
|
+
defineFeature,
|
|
4
|
+
type FeatureDefinition,
|
|
5
|
+
} from "@cosmicdrift/kumiko-framework/engine";
|
|
6
|
+
import { HANDBOOK_KNOWLEDGE_FEATURE } from "./constants.ts";
|
|
7
|
+
import { createHandbookIndex } from "./handbook-index.ts";
|
|
8
|
+
import { createListPagesQuery, createReadPageQuery } from "./handlers.ts";
|
|
9
|
+
|
|
10
|
+
export type HandbookKnowledgeOptions = {
|
|
11
|
+
/** The JSON written by `kumiko handbuch knowledge`; validated once at boot. */
|
|
12
|
+
pages: unknown;
|
|
13
|
+
access: AccessRule;
|
|
14
|
+
/** Where the public handbook lives (e.g. "/handbuch"); page links are `<publicPath>/<id>`, with or without a trailing slash. */
|
|
15
|
+
publicPath?: string;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
export function createHandbookKnowledgeFeature(
|
|
19
|
+
options: HandbookKnowledgeOptions,
|
|
20
|
+
): FeatureDefinition {
|
|
21
|
+
const index = createHandbookIndex(options.pages);
|
|
22
|
+
return defineFeature(HANDBOOK_KNOWLEDGE_FEATURE, (r) => {
|
|
23
|
+
r.describe(
|
|
24
|
+
"Gives the AI agent the app's handbook as two read-only query tools: `list-pages` returns the catalog of task and screen pages with the questions each answers, `read-page` returns one page in the caller's language with a fallback to the default language and a fixed length cap. The pages come from a build-time JSON (`kumiko handbuch knowledge`), so no table, projection or search index is involved and the handbook text stays public content.",
|
|
25
|
+
);
|
|
26
|
+
r.uiHints({
|
|
27
|
+
displayLabel: "Handbook Knowledge",
|
|
28
|
+
category: "ai",
|
|
29
|
+
recommended: false,
|
|
30
|
+
});
|
|
31
|
+
r.queryHandler(createListPagesQuery(index, options.access));
|
|
32
|
+
r.queryHandler(createReadPageQuery(index, options.access, options.publicPath));
|
|
33
|
+
});
|
|
34
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import * as z from "zod";
|
|
2
|
+
|
|
3
|
+
const handbookPageSchema = z.object({
|
|
4
|
+
id: z.string().min(1),
|
|
5
|
+
kind: z.enum(["process", "screen"]),
|
|
6
|
+
title: z.string(),
|
|
7
|
+
questions: z.array(z.string()),
|
|
8
|
+
screens: z.array(z.string()),
|
|
9
|
+
start: z.string().min(1).optional(),
|
|
10
|
+
bodyMd: z.string(),
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
const handbookKnowledgeSchema = z
|
|
14
|
+
.object({
|
|
15
|
+
defaultLocale: z.string().min(1),
|
|
16
|
+
locales: z.record(z.string(), z.array(handbookPageSchema)),
|
|
17
|
+
})
|
|
18
|
+
.refine((knowledge) => knowledge.defaultLocale in knowledge.locales, {
|
|
19
|
+
message: "defaultLocale must be a key of locales",
|
|
20
|
+
path: ["defaultLocale"],
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
export type HandbookPage = z.infer<typeof handbookPageSchema>;
|
|
24
|
+
|
|
25
|
+
export type HandbookIndex = {
|
|
26
|
+
listPages(requestedLocale: string): { locale: string; pages: readonly HandbookPage[] };
|
|
27
|
+
findPage(requestedLocale: string, id: string): { locale: string; page: HandbookPage } | undefined;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
// Validates the JSON that `kumiko handbuch knowledge` writes, once at boot.
|
|
31
|
+
export function createHandbookIndex(rawKnowledge: unknown): HandbookIndex {
|
|
32
|
+
const knowledge = handbookKnowledgeSchema.parse(rawKnowledge);
|
|
33
|
+
const pagesByLocale = new Map(
|
|
34
|
+
Object.entries(knowledge.locales).map(([locale, pages]) => [
|
|
35
|
+
locale,
|
|
36
|
+
new Map(pages.map((page) => [page.id, page])),
|
|
37
|
+
]),
|
|
38
|
+
);
|
|
39
|
+
const defaultPages =
|
|
40
|
+
pagesByLocale.get(knowledge.defaultLocale) ?? new Map<string, HandbookPage>();
|
|
41
|
+
|
|
42
|
+
// "de-AT" serves "de"; anything the handbook has no text for serves the default language.
|
|
43
|
+
const resolveLocale = (requestedLocale: string): string => {
|
|
44
|
+
const baseLanguage = requestedLocale.split("-")[0] ?? requestedLocale;
|
|
45
|
+
return (
|
|
46
|
+
[requestedLocale, baseLanguage].find((candidate) => pagesByLocale.has(candidate)) ??
|
|
47
|
+
knowledge.defaultLocale
|
|
48
|
+
);
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
return {
|
|
52
|
+
listPages(requestedLocale) {
|
|
53
|
+
const locale = resolveLocale(requestedLocale);
|
|
54
|
+
const merged = new Map(defaultPages);
|
|
55
|
+
for (const [id, page] of pagesByLocale.get(locale) ?? []) merged.set(id, page);
|
|
56
|
+
return { locale, pages: [...merged.values()] };
|
|
57
|
+
},
|
|
58
|
+
findPage(requestedLocale, id) {
|
|
59
|
+
const locale = resolveLocale(requestedLocale);
|
|
60
|
+
const page = pagesByLocale.get(locale)?.get(id);
|
|
61
|
+
if (page) return { locale, page };
|
|
62
|
+
const fallback = defaultPages.get(id);
|
|
63
|
+
return fallback ? { locale: knowledge.defaultLocale, page: fallback } : undefined;
|
|
64
|
+
},
|
|
65
|
+
};
|
|
66
|
+
}
|