@shware/workflow 0.4.0 → 2.0.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/README.md +90 -49
- package/dist/client.d.cts +1 -1
- package/dist/client.d.mts +1 -1
- package/dist/cloudflare/bindings.cjs.map +1 -1
- package/dist/cloudflare/bindings.d.cts +1 -1
- package/dist/cloudflare/bindings.d.mts +1 -1
- package/dist/cloudflare/bindings.mjs.map +1 -1
- package/dist/cloudflare/channels.cjs +13 -18
- package/dist/cloudflare/channels.cjs.map +1 -1
- package/dist/cloudflare/channels.d.cts +3 -3
- package/dist/cloudflare/channels.d.cts.map +1 -1
- package/dist/cloudflare/channels.d.mts +3 -3
- package/dist/cloudflare/channels.d.mts.map +1 -1
- package/dist/cloudflare/channels.mjs +14 -19
- package/dist/cloudflare/channels.mjs.map +1 -1
- package/dist/cloudflare/index.d.cts +4 -4
- package/dist/cloudflare/index.d.mts +4 -4
- package/dist/cloudflare/router.d.cts +1 -1
- package/dist/cloudflare/router.d.mts +1 -1
- package/dist/cloudflare/runner.d.cts +2 -2
- package/dist/cloudflare/runner.d.mts +2 -2
- package/dist/cloudflare/senders.cjs +15 -8
- package/dist/cloudflare/senders.cjs.map +1 -1
- package/dist/cloudflare/senders.d.cts +15 -11
- package/dist/cloudflare/senders.d.cts.map +1 -1
- package/dist/cloudflare/senders.d.mts +15 -11
- package/dist/cloudflare/senders.d.mts.map +1 -1
- package/dist/cloudflare/senders.mjs +15 -8
- package/dist/cloudflare/senders.mjs.map +1 -1
- package/dist/cloudflare/worker.cjs +7 -4
- package/dist/cloudflare/worker.cjs.map +1 -1
- package/dist/cloudflare/worker.d.cts +2 -2
- package/dist/cloudflare/worker.d.cts.map +1 -1
- package/dist/cloudflare/worker.d.mts +2 -2
- package/dist/cloudflare/worker.d.mts.map +1 -1
- package/dist/cloudflare/worker.mjs +8 -5
- package/dist/cloudflare/worker.mjs.map +1 -1
- package/dist/config.cjs +66 -42
- package/dist/config.cjs.map +1 -1
- package/dist/config.d.cts +26 -45
- package/dist/config.d.cts.map +1 -1
- package/dist/config.d.mts +26 -45
- package/dist/config.d.mts.map +1 -1
- package/dist/config.mjs +67 -42
- package/dist/config.mjs.map +1 -1
- package/dist/dsl/action.cjs +1 -1
- package/dist/dsl/action.cjs.map +1 -1
- package/dist/dsl/action.d.cts +1 -1
- package/dist/dsl/action.d.mts +1 -1
- package/dist/dsl/action.mjs +1 -1
- package/dist/dsl/action.mjs.map +1 -1
- package/dist/dsl/bundle.cjs +3 -2
- package/dist/dsl/bundle.cjs.map +1 -1
- package/dist/dsl/bundle.d.cts +3 -2
- package/dist/dsl/bundle.d.cts.map +1 -1
- package/dist/dsl/bundle.d.mts +3 -2
- package/dist/dsl/bundle.d.mts.map +1 -1
- package/dist/dsl/bundle.mjs +3 -2
- package/dist/dsl/bundle.mjs.map +1 -1
- package/dist/dsl/condition.cjs +1 -1
- package/dist/dsl/condition.cjs.map +1 -1
- package/dist/dsl/condition.d.cts +1 -1
- package/dist/dsl/condition.d.mts +1 -1
- package/dist/dsl/condition.mjs +1 -1
- package/dist/dsl/condition.mjs.map +1 -1
- package/dist/dsl/flow.cjs +45 -17
- package/dist/dsl/flow.cjs.map +1 -1
- package/dist/dsl/flow.d.cts +30 -17
- package/dist/dsl/flow.d.cts.map +1 -1
- package/dist/dsl/flow.d.mts +30 -17
- package/dist/dsl/flow.d.mts.map +1 -1
- package/dist/dsl/flow.mjs +45 -18
- package/dist/dsl/flow.mjs.map +1 -1
- package/dist/dsl/index.cjs +0 -1
- package/dist/dsl/index.d.cts +2 -2
- package/dist/dsl/index.d.mts +2 -2
- package/dist/dsl/index.mjs +2 -2
- package/dist/dsl/template.cjs +2 -47
- package/dist/dsl/template.cjs.map +1 -1
- package/dist/dsl/template.d.cts +4 -54
- package/dist/dsl/template.d.cts.map +1 -1
- package/dist/dsl/template.d.mts +4 -54
- package/dist/dsl/template.d.mts.map +1 -1
- package/dist/dsl/template.mjs +3 -47
- package/dist/dsl/template.mjs.map +1 -1
- package/dist/dsl/workflow.cjs +1 -1
- package/dist/dsl/workflow.cjs.map +1 -1
- package/dist/dsl/workflow.d.cts +1 -1
- package/dist/dsl/workflow.d.mts +1 -1
- package/dist/dsl/workflow.mjs +1 -1
- package/dist/dsl/workflow.mjs.map +1 -1
- package/dist/email-context.cjs +29 -0
- package/dist/email-context.cjs.map +1 -0
- package/dist/email-context.d.cts +11 -0
- package/dist/email-context.d.cts.map +1 -0
- package/dist/email-context.d.mts +11 -0
- package/dist/email-context.d.mts.map +1 -0
- package/dist/email-context.mjs +27 -0
- package/dist/email-context.mjs.map +1 -0
- package/dist/email.cjs +72 -0
- package/dist/email.cjs.map +1 -0
- package/dist/email.d.cts +63 -0
- package/dist/email.d.cts.map +1 -0
- package/dist/email.d.mts +63 -0
- package/dist/email.d.mts.map +1 -0
- package/dist/email.mjs +65 -0
- package/dist/email.mjs.map +1 -0
- package/dist/engine/index.d.cts +2 -2
- package/dist/engine/index.d.mts +2 -2
- package/dist/engine/ports.d.cts +7 -2
- package/dist/engine/ports.d.cts.map +1 -1
- package/dist/engine/ports.d.mts +7 -2
- package/dist/engine/ports.d.mts.map +1 -1
- package/dist/index.cjs +13 -3
- package/dist/index.d.cts +5 -4
- package/dist/index.d.mts +5 -4
- package/dist/index.mjs +5 -4
- package/dist/push.cjs +3 -5
- package/dist/push.cjs.map +1 -1
- package/dist/push.d.cts +2 -2
- package/dist/push.d.cts.map +1 -1
- package/dist/push.d.mts +2 -2
- package/dist/push.d.mts.map +1 -1
- package/dist/push.mjs +4 -6
- package/dist/push.mjs.map +1 -1
- package/dist/react-email.cjs +16 -8
- package/dist/react-email.cjs.map +1 -1
- package/dist/react-email.d.cts +2 -1
- package/dist/react-email.d.cts.map +1 -1
- package/dist/react-email.d.mts +2 -1
- package/dist/react-email.d.mts.map +1 -1
- package/dist/react-email.mjs +17 -9
- package/dist/react-email.mjs.map +1 -1
- package/dist/reporting/classify.cjs.map +1 -1
- package/dist/reporting/classify.d.cts +1 -1
- package/dist/reporting/classify.d.mts +1 -1
- package/dist/reporting/classify.mjs.map +1 -1
- package/dist/reporting/observer.cjs +5 -4
- package/dist/reporting/observer.cjs.map +1 -1
- package/dist/reporting/observer.d.cts +3 -2
- package/dist/reporting/observer.d.cts.map +1 -1
- package/dist/reporting/observer.d.mts +3 -2
- package/dist/reporting/observer.d.mts.map +1 -1
- package/dist/reporting/observer.mjs +5 -4
- package/dist/reporting/observer.mjs.map +1 -1
- package/dist/reporting/tracking.cjs +3 -12
- package/dist/reporting/tracking.cjs.map +1 -1
- package/dist/reporting/tracking.d.cts +18 -7
- package/dist/reporting/tracking.d.cts.map +1 -1
- package/dist/reporting/tracking.d.mts +18 -7
- package/dist/reporting/tracking.d.mts.map +1 -1
- package/dist/reporting/tracking.mjs +3 -12
- package/dist/reporting/tracking.mjs.map +1 -1
- package/dist/templates.cjs +90 -30
- package/dist/templates.cjs.map +1 -1
- package/dist/templates.d.cts +70 -13
- package/dist/templates.d.cts.map +1 -1
- package/dist/templates.d.mts +70 -13
- package/dist/templates.d.mts.map +1 -1
- package/dist/templates.mjs +87 -31
- package/dist/templates.mjs.map +1 -1
- package/package.json +11 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tracking.mjs","names":[],"sources":["../../src/reporting/tracking.ts"],"sourcesContent":["import type { JourneyReporting } from '../store';\nimport { BURST_WINDOW_MS, classifyClick, classifyOpen } from './classify';\n\n/**\n * The endpoints a journey email's tracking points at (see ./observer.ts), served by journeyWorker\n * without a bearer — recipients open them:\n *\n * GET /t/o/<message> the open pixel: records the open, answers a 1×1 GIF\n * GET /t/c/<message>/<position> a link: records the click, redirects to the recorded URL\n * POST /t/u/<message> the unsubscribe confirmation\n * POST /t/d/<message> a push the device received (iOS's notification service\n * extension, a browser's service worker)\n * POST /t/p/<message> a push opened, reported by a browser's service worker\n *\n * Every open and click is recorded with its verdict (./classify.ts), and the message keeps its\n * first open and click of each kind. The redirect goes only to the URL recorded for that position,\n * never to one the request carries, so the endpoint cannot bounce visitors anywhere else. The\n * config's unsubscribe link (`emails.unsubscribe`) is a tracked link too: following it shows a\n * confirmation page, and only the confirmation — a POST, which no link scanner sends — counts.\n */\n\nexport interface TrackingOptions {\n /** `emails.unsubscribe` from the config: the footer link that asks for confirmation instead of redirecting. */\n unsubscribe?: string | undefined;\n /** The name the confirmation pages show (the config's `title`). */\n product?: string | undefined;\n /** `emails.tracking.quickClickMs`: how soon after delivery an open or click is a weak machine signal. */\n quickMs?: number | undefined;\n /** A browser reported a push tapped (`/t/p`): the host records it as an event too (`webPush.openedEvent`). */\n pushOpened?:\n | ((open: { messageId: string; userId: string; at: number }) => Promise<void>)\n | undefined;\n}\n\nconst GIF = Uint8Array.from(\n atob('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'),\n (char) => char.charCodeAt(0)\n);\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\ninterface Requester {\n method: string;\n userAgent: string | null;\n asn: number | null;\n organization: string | null;\n country: string | null;\n}\n\nfunction requester(request: Request): Requester {\n const cf = (\n request as Request & { cf?: { asn?: number; asOrganization?: string; country?: string } }\n ).cf;\n return {\n method: request.method,\n userAgent: request.headers.get('user-agent'),\n asn: cf?.asn ?? null,\n organization: cf?.asOrganization ?? null,\n country: cf?.country ?? null,\n };\n}\n\n/** A `/t/...` request's response, or undefined when the path is not a tracking route. */\nexport async function handleTracking(\n request: Request,\n reporting: JourneyReporting,\n options: TrackingOptions = {}\n): Promise<Response | undefined> {\n const url = new URL(request.url);\n const [, root, kind, id, position] = url.pathname.split('/');\n if (root !== 't' || id === undefined || !UUID.test(id)) return undefined;\n const who = requester(request);\n const read = who.method === 'GET' || who.method === 'HEAD';\n if (kind === 'o' && read) {\n await recordOpen(reporting, id, who, options);\n return new Response(who.method === 'HEAD' ? null : GIF, {\n headers: { 'content-type': 'image/gif', 'cache-control': 'no-store, max-age=0' },\n });\n }\n if (kind === 'c' && position !== undefined && read) {\n const target = await recordClick(reporting, id, Number(position), who, options);\n if (target === undefined) return page(options, 'This link has expired.', 404);\n if (options.unsubscribe !== undefined && sameLink(target, options.unsubscribe)) {\n return page(\n options,\n `Unsubscribe from ${escape(options.product ?? 'these')} emails?`,\n 200,\n `<form method=\"post\" action=\"/t/u/${id}\"><button type=\"submit\">Unsubscribe</button></form>`\n );\n }\n return Response.redirect(target, 302);\n }\n if (kind === 'd' && who.method === 'POST') {\n const known = await reporting.recordDeviceDelivered(id, Date.now());\n return new Response(null, { status: known ? 204 : 404 });\n }\n if (kind === 'p' && who.method === 'POST') {\n // A notification tap: a person, as the message id is what proves it is theirs\n const at = Date.now();\n let userId: string | undefined;\n const known = await reporting.recordOpen(id, (message) => {\n userId = message.userId;\n return { at, machine: false, reason: null, ...network(who) };\n });\n if (known && userId !== undefined && options.pushOpened !== undefined) {\n try {\n await options.pushOpened({ messageId: id, userId, at });\n } catch (error) {\n // The open is recorded; the event is the host's extra, never a reason to fail the beacon\n console.error(`[workflow] recording push open ${id} as an event failed`, error);\n }\n }\n return new Response(null, { status: known ? 204 : 404 });\n }\n if (kind === 'u' && who.method === 'POST') {\n const known = await reporting.recordUnsubscribe(id, Date.now());\n if (!known) return page(options, 'This link has expired.', 404);\n return page(\n options,\n options.product === undefined\n ? \"You won't get these emails anymore.\"\n : `You won't get these emails from ${escape(options.product)} anymore.`\n );\n }\n return undefined;\n}\n\n/**\n * A journey push tapped open, as the app reports it (`JourneyClient.messageOpened`): an open on\n * the copy — only the recipient's own, and never a machine, since no proxy or scanner taps a\n * notification. False when the message is unknown or not the user's.\n */\nexport async function recordPushOpen(\n reporting: JourneyReporting,\n userId: string,\n messageId: string,\n at = Date.now()\n): Promise<boolean> {\n if (!UUID.test(messageId)) return false;\n let recorded = false;\n await reporting.recordOpen(messageId, (message) => {\n if (message.userId !== userId) return undefined;\n recorded = true;\n return {\n at,\n machine: false,\n reason: null,\n userAgent: null,\n asn: null,\n organization: null,\n country: null,\n };\n });\n return recorded;\n}\n\nasync function recordOpen(\n reporting: JourneyReporting,\n id: string,\n who: Requester,\n options: TrackingOptions\n) {\n const at = Date.now();\n await reporting.recordOpen(id, (message) => ({\n at,\n ...classifyOpen(\n { ...who, sinceDeliveredMs: at - message.deliveredAt },\n { quickMs: options.quickMs }\n ),\n ...network(who),\n }));\n}\n\nconst network = (who: Requester) => ({\n userAgent: who.userAgent,\n asn: who.asn,\n organization: who.organization,\n country: who.country,\n});\n\n/** Records the click and answers the URL to send the visitor to, or undefined for an unknown link. */\nasync function recordClick(\n reporting: JourneyReporting,\n id: string,\n position: number,\n who: Requester,\n options: TrackingOptions\n): Promise<string | undefined> {\n if (!Number.isInteger(position) || position < 0) return undefined;\n const at = Date.now();\n const recorded = await reporting.recordClick(id, position, at, BURST_WINDOW_MS, (link) => {\n const linksInBurst = new Set([position, ...link.recent.map((click) => click.position)]).size;\n const verdict = classifyClick(\n { ...who, sinceDeliveredMs: at - link.deliveredAt, linksInBurst, linkCount: link.linkCount },\n { quickMs: options.quickMs }\n );\n return {\n engagement: { at, ...verdict, ...network(who) },\n backdate: verdict.reason === 'link_burst' || verdict.reason === 'quick+link_pair',\n };\n });\n return recorded?.url;\n}\n\n/** The unsubscribe link may carry its own query (a token, a list): the path names it. */\nfunction sameLink(target: string, unsubscribe: string): boolean {\n try {\n const a = new URL(target);\n const b = new URL(unsubscribe);\n return a.origin === b.origin && a.pathname === b.pathname;\n } catch {\n return false;\n }\n}\n\nfunction escape(text: string): string {\n return text.replace(/[&<>\"']/g, (c) => `&#${c.charCodeAt(0)};`);\n}\n\nfunction page(options: TrackingOptions, message: string, status = 200, extra = ''): Response {\n const title = escape(options.product ?? 'Email');\n const html = `<!doctype html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>${title}</title><style>body{font:16px system-ui;margin:0;display:grid;place-items:center;min-height:100vh;background:#fafafa;color:#18181b}main{text-align:center;padding:24px}button{font:inherit;padding:10px 20px;border-radius:9999px;border:0;background:#18181b;color:#fff;cursor:pointer}</style></head><body><main><p>${message}</p>${extra}</main></body></html>`;\n return new Response(html, { status, headers: { 'content-type': 'text/html; charset=utf-8' } });\n}\n"],"mappings":";;AAkCA,MAAM,MAAM,WAAW,KACrB,KAAK,0DAA0D,IAC9D,SAAS,KAAK,WAAW,CAAC,CAC7B;AACA,MAAM,OAAO;AAUb,SAAS,UAAU,SAA6B;CAC9C,MAAM,KACJ,QACA;CACF,OAAO;EACL,QAAQ,QAAQ;EAChB,WAAW,QAAQ,QAAQ,IAAI,YAAY;EAC3C,KAAK,IAAI,OAAO;EAChB,cAAc,IAAI,kBAAkB;EACpC,SAAS,IAAI,WAAW;CAC1B;AACF;;AAGA,eAAsB,eACpB,SACA,WACA,UAA2B,CAAC,GACG;CAE/B,MAAM,GAAG,MAAM,MAAM,IAAI,YAAY,IADrB,IAAI,QAAQ,GACW,CAAC,CAAC,SAAS,MAAM,GAAG;CAC3D,IAAI,SAAS,OAAO,OAAO,KAAA,KAAa,CAAC,KAAK,KAAK,EAAE,GAAG,OAAO,KAAA;CAC/D,MAAM,MAAM,UAAU,OAAO;CAC7B,MAAM,OAAO,IAAI,WAAW,SAAS,IAAI,WAAW;CACpD,IAAI,SAAS,OAAO,MAAM;EACxB,MAAM,WAAW,WAAW,IAAI,KAAK,OAAO;EAC5C,OAAO,IAAI,SAAS,IAAI,WAAW,SAAS,OAAO,KAAK,EACtD,SAAS;GAAE,gBAAgB;GAAa,iBAAiB;EAAsB,EACjF,CAAC;CACH;CACA,IAAI,SAAS,OAAO,aAAa,KAAA,KAAa,MAAM;EAClD,MAAM,SAAS,MAAM,YAAY,WAAW,IAAI,OAAO,QAAQ,GAAG,KAAK,OAAO;EAC9E,IAAI,WAAW,KAAA,GAAW,OAAO,KAAK,SAAS,0BAA0B,GAAG;EAC5E,IAAI,QAAQ,gBAAgB,KAAA,KAAa,SAA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I,IAAI,MAAM;EACxB,MAAM,IAAI,IAAI,IAAI,WAAW;EAC7B,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,aAAa,EAAE;CACnD,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAS,OAAO,MAAsB;CACpC,OAAO,KAAK,QAAQ,aAAa,MAAM,KAAK,EAAE,WAAW,CAAC,EAAE,EAAE;AAChE;AAEA,SAAS,KAAK,SAA0B,SAAiB,SAAS,KAAK,QAAQ,IAAc;CAE3F,MAAM,OAAO,8HADC,OAAO,QAAQ,WAAW,OACuG,EAAE,wTAAwT,QAAQ,MAAM,MAAM;CAC7d,OAAO,IAAI,SAAS,MAAM;EAAE;EAAQ,SAAS,EAAE,gBAAgB,2BAA2B;CAAE,CAAC;AAC/F"}
|
|
1
|
+
{"version":3,"file":"tracking.mjs","names":[],"sources":["../../src/reporting/tracking.ts"],"sourcesContent":["import { isUnsubscribeLink } from '../email';\nimport type { JourneyReporting } from '../store';\nimport { BURST_WINDOW_MS, classifyClick, classifyOpen } from './classify';\n\n/**\n * The endpoints a journey email's tracking points at (see ./observer.ts), served by journeyWorker\n * without a bearer — recipients open them:\n *\n * GET /t/o/<message> the open pixel: records the open, answers a 1×1 GIF\n * GET /t/l/<message>/<position> a link: records the click, redirects to the recorded URL\n * GET /t/u/<message>/<position> the unsubscribe link: records the click, asks to confirm\n * POST /t/u/<message> the unsubscribe confirmation\n * GET /t/c/<message>/<position> a link of an email sent before links carried their purpose\n * POST /t/d/<message> a push the device received (iOS's notification service\n * extension, a browser's service worker)\n * POST /t/p/<message> a push opened, reported by a browser's service worker\n *\n * Every open and click is recorded with its verdict (./classify.ts), and the message keeps its\n * first open and click of each kind. The redirect goes only to the URL recorded for that position,\n * never to one the request carries, so the endpoint cannot bounce visitors anywhere else. An\n * email's unsubscribe link is a tracked link too, and which link it is was fixed when the email was\n * sent (its route): following it shows a confirmation page, and only the confirmation — a POST,\n * which no link scanner sends — counts. Changing a template's or the config's unsubscribe URL, or\n * removing the template, changes nothing for emails already sent.\n *\n * Emails sent before that carry `/t/c/` links, which say nothing of their purpose: one is the\n * unsubscribe link when its recorded URL is `legacyUnsubscribeUrl` (the global unsubscribe URL\n * those emails were all sent with), as it was then.\n */\n\nexport interface TrackingOptions {\n /**\n * The unsubscribe URL emails sent with `/t/c/` links carried (the config's `email.unsubscribeUrl`\n * by default): following such a link to it asks for confirmation instead of redirecting.\n */\n legacyUnsubscribeUrl?: string | undefined;\n /** The name the confirmation pages show (the config's `title`). */\n product?: string | undefined;\n /** `email.tracking.quickClickMs`: how soon after delivery an open or click is a weak machine signal. */\n quickMs?: number | undefined;\n /** A browser reported a push tapped (`/t/p`): the host records it as an event too (`webPush.openedEvent`). */\n pushOpened?:\n | ((open: { messageId: string; userId: string; at: number }) => Promise<void>)\n | undefined;\n}\n\nconst GIF = Uint8Array.from(\n atob('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'),\n (char) => char.charCodeAt(0)\n);\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\ninterface Requester {\n method: string;\n userAgent: string | null;\n asn: number | null;\n organization: string | null;\n country: string | null;\n}\n\nfunction requester(request: Request): Requester {\n const cf = (\n request as Request & { cf?: { asn?: number; asOrganization?: string; country?: string } }\n ).cf;\n return {\n method: request.method,\n userAgent: request.headers.get('user-agent'),\n asn: cf?.asn ?? null,\n organization: cf?.asOrganization ?? null,\n country: cf?.country ?? null,\n };\n}\n\n/** A `/t/...` request's response, or undefined when the path is not a tracking route. */\nexport async function handleTracking(\n request: Request,\n reporting: JourneyReporting,\n options: TrackingOptions = {}\n): Promise<Response | undefined> {\n const url = new URL(request.url);\n const [, root, kind, id, position] = url.pathname.split('/');\n if (root !== 't' || id === undefined || !UUID.test(id)) return undefined;\n const who = requester(request);\n const read = who.method === 'GET' || who.method === 'HEAD';\n if (kind === 'o' && read) {\n await recordOpen(reporting, id, who, options);\n return new Response(who.method === 'HEAD' ? null : GIF, {\n headers: { 'content-type': 'image/gif', 'cache-control': 'no-store, max-age=0' },\n });\n }\n if ((kind === 'l' || kind === 'u' || kind === 'c') && position !== undefined && read) {\n const target = await recordClick(reporting, id, Number(position), who, options);\n if (target === undefined) return page(options, 'This link has expired.', 404);\n const unsubscribe =\n kind === 'u' || (kind === 'c' && isUnsubscribeLink(target, options.legacyUnsubscribeUrl));\n if (unsubscribe) {\n return page(\n options,\n `Unsubscribe from ${escape(options.product ?? 'these')} emails?`,\n 200,\n `<form method=\"post\" action=\"/t/u/${id}\"><button type=\"submit\">Unsubscribe</button></form>`\n );\n }\n return Response.redirect(target, 302);\n }\n if (kind === 'd' && who.method === 'POST') {\n const known = await reporting.recordDeviceDelivered(id, Date.now());\n return new Response(null, { status: known ? 204 : 404 });\n }\n if (kind === 'p' && who.method === 'POST') {\n // A notification tap: a person, as the message id is what proves it is theirs\n const at = Date.now();\n let userId: string | undefined;\n const known = await reporting.recordOpen(id, (message) => {\n userId = message.userId;\n return { at, machine: false, reason: null, ...network(who) };\n });\n if (known && userId !== undefined && options.pushOpened !== undefined) {\n try {\n await options.pushOpened({ messageId: id, userId, at });\n } catch (error) {\n // The open is recorded; the event is the host's extra, never a reason to fail the beacon\n console.error(`[workflow] recording push open ${id} as an event failed`, error);\n }\n }\n return new Response(null, { status: known ? 204 : 404 });\n }\n if (kind === 'u' && who.method === 'POST') {\n const known = await reporting.recordUnsubscribe(id, Date.now());\n if (!known) return page(options, 'This link has expired.', 404);\n return page(\n options,\n options.product === undefined\n ? \"You won't get these emails anymore.\"\n : `You won't get these emails from ${escape(options.product)} anymore.`\n );\n }\n return undefined;\n}\n\n/**\n * A journey push tapped open, as the app reports it (`JourneyClient.messageOpened`): an open on\n * the copy — only the recipient's own, and never a machine, since no proxy or scanner taps a\n * notification. False when the message is unknown or not the user's.\n */\nexport async function recordPushOpen(\n reporting: JourneyReporting,\n userId: string,\n messageId: string,\n at = Date.now()\n): Promise<boolean> {\n if (!UUID.test(messageId)) return false;\n let recorded = false;\n await reporting.recordOpen(messageId, (message) => {\n if (message.userId !== userId) return undefined;\n recorded = true;\n return {\n at,\n machine: false,\n reason: null,\n userAgent: null,\n asn: null,\n organization: null,\n country: null,\n };\n });\n return recorded;\n}\n\nasync function recordOpen(\n reporting: JourneyReporting,\n id: string,\n who: Requester,\n options: TrackingOptions\n) {\n const at = Date.now();\n await reporting.recordOpen(id, (message) => ({\n at,\n ...classifyOpen(\n { ...who, sinceDeliveredMs: at - message.deliveredAt },\n { quickMs: options.quickMs }\n ),\n ...network(who),\n }));\n}\n\nconst network = (who: Requester) => ({\n userAgent: who.userAgent,\n asn: who.asn,\n organization: who.organization,\n country: who.country,\n});\n\n/** Records the click and answers the URL to send the visitor to, or undefined for an unknown link. */\nasync function recordClick(\n reporting: JourneyReporting,\n id: string,\n position: number,\n who: Requester,\n options: TrackingOptions\n): Promise<string | undefined> {\n if (!Number.isInteger(position) || position < 0) return undefined;\n const at = Date.now();\n const recorded = await reporting.recordClick(id, position, at, BURST_WINDOW_MS, (link) => {\n const linksInBurst = new Set([position, ...link.recent.map((click) => click.position)]).size;\n const verdict = classifyClick(\n { ...who, sinceDeliveredMs: at - link.deliveredAt, linksInBurst, linkCount: link.linkCount },\n { quickMs: options.quickMs }\n );\n return {\n engagement: { at, ...verdict, ...network(who) },\n backdate: verdict.reason === 'link_burst' || verdict.reason === 'quick+link_pair',\n };\n });\n return recorded?.url;\n}\n\nfunction escape(text: string): string {\n return text.replace(/[&<>\"']/g, (c) => `&#${c.charCodeAt(0)};`);\n}\n\nfunction page(options: TrackingOptions, message: string, status = 200, extra = ''): Response {\n const title = escape(options.product ?? 'Email');\n const html = `<!doctype html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>${title}</title><style>body{font:16px system-ui;margin:0;display:grid;place-items:center;min-height:100vh;background:#fafafa;color:#18181b}main{text-align:center;padding:24px}button{font:inherit;padding:10px 20px;border-radius:9999px;border:0;background:#18181b;color:#fff;cursor:pointer}</style></head><body><main><p>${message}</p>${extra}</main></body></html>`;\n return new Response(html, { status, headers: { 'content-type': 'text/html; charset=utf-8' } });\n}\n"],"mappings":";;;AA8CA,MAAM,MAAM,WAAW,KACrB,KAAK,0DAA0D,IAC9D,SAAS,KAAK,WAAW,CAAC,CAC7B;AACA,MAAM,OAAO;AAUb,SAAS,UAAU,SAA6B;CAC9C,MAAM,KACJ,QACA;CACF,OAAO;EACL,QAAQ,QAAQ;EAChB,WAAW,QAAQ,QAAQ,IAAI,YAAY;EAC3C,KAAK,IAAI,OAAO;EAChB,cAAc,IAAI,kBAAkB;EACpC,SAAS,IAAI,WAAW;CAC1B;AACF;;AAGA,eAAsB,eACpB,SACA,WACA,UAA2B,CAAC,GACG;CAE/B,MAAM,GAAG,MAAM,MAAM,IAAI,YAAY,IADrB,IAAI,QAAQ,GACW,CAAC,CAAC,SAAS,MAAM,GAAG;CAC3D,IAAI,SAAS,OAAO,OAAO,KAAA,KAAa,CAAC,KAAK,KAAK,EAAE,GAAG,OAAO,KAAA;CAC/D,MAAM,MAAM,UAAU,OAAO;CAC7B,MAAM,OAAO,IAAI,WAAW,SAAS,IAAI,WAAW;CACpD,IAAI,SAAS,OAAO,MAAM;EACxB,MAAM,WAAW,WAAW,IAAI,KAAK,OAAO;EAC5C,OAAO,IAAI,SAAS,IAAI,WAAW,SAAS,OAAO,KAAK,EACtD,SAAS;GAAE,gBAAgB;GAAa,iBAAiB;EAAsB,EACjF,CAAC;CACH;CACA,KAAK,SAAS,OAAO,SAAS,OAAO,SAAS,QAAQ,aAAa,KAAA,KAAa,MAAM;EACpF,MAAM,SAAS,MAAM,YAAY,WAAW,IAAI,OAAO,QAAQ,GAAG,KAAK,OAAO;EAC9E,IAAI,WAAW,KAAA,GAAW,OAAO,KAAK,SAAS,0BAA0B,GAAG;EAG5E,IADE,SAAS,OAAQ,SAAS,OAAO,kBAAkB,QAAQ,QAAQ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CAAC,EAAE,EAAE;AAChE;AAEA,SAAS,KAAK,SAA0B,SAAiB,SAAS,KAAK,QAAQ,IAAc;CAE3F,MAAM,OAAO,8HADC,OAAO,QAAQ,WAAW,OACuG,EAAE,wTAAwT,QAAQ,MAAM,MAAM;CAC7d,OAAO,IAAI,SAAS,MAAM;EAAE;EAAQ,SAAS,EAAE,gBAAgB,2BAA2B;CAAE,CAAC;AAC/F"}
|
package/dist/templates.cjs
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
2
|
const require_runtime = require("./_virtual/_rolldown/runtime.cjs");
|
|
3
|
+
const require_email = require("./email.cjs");
|
|
3
4
|
let zod_mini = require("zod/mini");
|
|
4
5
|
zod_mini = require_runtime.__toESM(zod_mini, 1);
|
|
5
6
|
//#region src/templates.ts
|
|
6
7
|
/** Declare a Discord webhook template. Throws when `props` is unsupported or `preview` does not parse. */
|
|
7
8
|
function discordTemplate(definition) {
|
|
9
|
+
assertTemplateId(definition.id, "discordTemplate");
|
|
8
10
|
assertSupportedSchema(definition.props, definition.title);
|
|
9
11
|
parsePreview(definition.props, definition.preview, "discord", definition.title);
|
|
10
12
|
return {
|
|
@@ -15,6 +17,7 @@ function discordTemplate(definition) {
|
|
|
15
17
|
}
|
|
16
18
|
/** Declare a Slack webhook template. Throws when `props` is unsupported or `preview` does not parse. */
|
|
17
19
|
function slackTemplate(definition) {
|
|
20
|
+
assertTemplateId(definition.id, "slackTemplate");
|
|
18
21
|
assertSupportedSchema(definition.props, definition.title);
|
|
19
22
|
parsePreview(definition.props, definition.preview, "slack", definition.title);
|
|
20
23
|
return {
|
|
@@ -23,8 +26,13 @@ function slackTemplate(definition) {
|
|
|
23
26
|
...definition
|
|
24
27
|
};
|
|
25
28
|
}
|
|
26
|
-
/**
|
|
29
|
+
/**
|
|
30
|
+
* Declare an email template. Throws when `from` is missing or invalid, `replyTo` or `unsubscribeUrl`
|
|
31
|
+
* is invalid, `props` uses an unsupported schema or `preview` does not parse.
|
|
32
|
+
*/
|
|
27
33
|
function emailTemplate(definition) {
|
|
34
|
+
assertTemplateId(definition.id, "emailTemplate");
|
|
35
|
+
require_email.assertEmailMetadata(definition, `emailTemplate('${definition.id}')`);
|
|
28
36
|
assertSupportedSchema(definition.props, definition.title);
|
|
29
37
|
parsePreview(definition.props, definition.preview, "email", definition.title);
|
|
30
38
|
return {
|
|
@@ -35,6 +43,7 @@ function emailTemplate(definition) {
|
|
|
35
43
|
}
|
|
36
44
|
/** Declare a push template. Throws when `props` uses an unsupported schema or `preview` does not parse. */
|
|
37
45
|
function pushTemplate(definition) {
|
|
46
|
+
assertTemplateId(definition.id, "pushTemplate");
|
|
38
47
|
assertSupportedSchema(definition.props, definition.title);
|
|
39
48
|
parsePreview(definition.props, definition.preview, "push", definition.title);
|
|
40
49
|
return {
|
|
@@ -43,6 +52,12 @@ function pushTemplate(definition) {
|
|
|
43
52
|
...definition
|
|
44
53
|
};
|
|
45
54
|
}
|
|
55
|
+
function assertTemplateId(id, factory) {
|
|
56
|
+
if (!isTemplateId(id)) throw new TypeError(`${factory}(): 'id' must be a non-empty string`);
|
|
57
|
+
}
|
|
58
|
+
function isTemplateId(id) {
|
|
59
|
+
return typeof id === "string" && id.trim() !== "";
|
|
60
|
+
}
|
|
46
61
|
function isEmailTemplate(value) {
|
|
47
62
|
return isMarked(value, "email-template");
|
|
48
63
|
}
|
|
@@ -64,6 +79,44 @@ const CHANNEL_OF = {
|
|
|
64
79
|
function isMarked(value, kind) {
|
|
65
80
|
return typeof value === "object" && value !== null && value.kind === kind && value.version === 1;
|
|
66
81
|
}
|
|
82
|
+
/** Any template definition, whatever its channel. */
|
|
83
|
+
function isTemplate(value) {
|
|
84
|
+
return typeof value === "object" && value !== null && Object.hasOwn(CHANNEL_OF, value.kind) && value.version === 1;
|
|
85
|
+
}
|
|
86
|
+
const IS_TEMPLATE = {
|
|
87
|
+
email: isEmailTemplate,
|
|
88
|
+
push: isPushTemplate,
|
|
89
|
+
discord: isDiscordTemplate,
|
|
90
|
+
slack: isSlackTemplate
|
|
91
|
+
};
|
|
92
|
+
/**
|
|
93
|
+
* A channel's registry by template id — how everything that turns an id back into a definition
|
|
94
|
+
* (the compiler, the validator, the renderers, the senders, the studio) looks it up. Throws when
|
|
95
|
+
* an entry is not a template of the channel, has no id, or shares its id with another entry: an id
|
|
96
|
+
* is registered once per channel, so two registrations (even of the same object) are an error,
|
|
97
|
+
* not a silent last-wins. Insertion order is the registry's.
|
|
98
|
+
*/
|
|
99
|
+
function indexTemplates(channel, registry) {
|
|
100
|
+
const index = /* @__PURE__ */ new Map();
|
|
101
|
+
const paths = /* @__PURE__ */ new Map();
|
|
102
|
+
for (const [name, entry] of Object.entries(registry ?? {})) {
|
|
103
|
+
const path = `templates.${channel}.${name}`;
|
|
104
|
+
if (!IS_TEMPLATE[channel](entry)) throw new TypeError(`${path} is not a ${channel} template`);
|
|
105
|
+
const id = entry.id;
|
|
106
|
+
if (!isTemplateId(id)) throw new TypeError(`${path} has no id`);
|
|
107
|
+
const previous = paths.get(id);
|
|
108
|
+
if (previous !== void 0) throw new TypeError(`${channel} template id '${id}' is registered twice: ${previous} and ${path}`);
|
|
109
|
+
paths.set(id, path);
|
|
110
|
+
index.set(id, entry);
|
|
111
|
+
}
|
|
112
|
+
return index;
|
|
113
|
+
}
|
|
114
|
+
/** A registered template by id; throws naming the channel and id when there is none. */
|
|
115
|
+
function lookupTemplate(index, channel, id) {
|
|
116
|
+
const template = index.get(id);
|
|
117
|
+
if (template === void 0) throw new Error(`${channel} template '${id}' is not registered`);
|
|
118
|
+
return template;
|
|
119
|
+
}
|
|
67
120
|
/**
|
|
68
121
|
* A template refused its input (`phase: 'props'` — the component/content was
|
|
69
122
|
* never called) or its content function returned something that is not a
|
|
@@ -94,10 +147,10 @@ function issuesOf(error) {
|
|
|
94
147
|
* Parse message props against a template's schema and return the parsed value
|
|
95
148
|
* — the only value anything downstream may use. Throws TemplateValidationError.
|
|
96
149
|
*/
|
|
97
|
-
function parseTemplateProps(template,
|
|
150
|
+
function parseTemplateProps(template, props) {
|
|
98
151
|
const channel = CHANNEL_OF[template.kind];
|
|
99
152
|
const result = zod_mini.safeParse(template.props, props);
|
|
100
|
-
if (!result.success) throw new TemplateValidationError(channel,
|
|
153
|
+
if (!result.success) throw new TemplateValidationError(channel, template.id, "props", issuesOf(result.error));
|
|
101
154
|
return result.data;
|
|
102
155
|
}
|
|
103
156
|
const pushContentSchema = zod_mini.strictObject({
|
|
@@ -107,11 +160,11 @@ const pushContentSchema = zod_mini.strictObject({
|
|
|
107
160
|
url: zod_mini.optional(zod_mini.string())
|
|
108
161
|
});
|
|
109
162
|
/** Run a push template's content over parsed props and check the notification it returns. */
|
|
110
|
-
function renderPushContent(template,
|
|
111
|
-
const parsed = parseTemplateProps(template,
|
|
163
|
+
function renderPushContent(template, props) {
|
|
164
|
+
const parsed = parseTemplateProps(template, props);
|
|
112
165
|
const output = template.content(parsed);
|
|
113
166
|
const result = zod_mini.safeParse(pushContentSchema, output);
|
|
114
|
-
if (!result.success) throw new TemplateValidationError("push",
|
|
167
|
+
if (!result.success) throw new TemplateValidationError("push", template.id, "content", issuesOf(result.error));
|
|
115
168
|
return result.data;
|
|
116
169
|
}
|
|
117
170
|
/**
|
|
@@ -128,21 +181,24 @@ const slackContentSchema = zod_mini.looseObject({
|
|
|
128
181
|
blocks: zod_mini.optional(zod_mini.array(zod_mini.looseObject({ type: zod_mini.string() })))
|
|
129
182
|
});
|
|
130
183
|
/** Run a Discord template's content over parsed props and check the message it returns. */
|
|
131
|
-
function renderDiscordContent(template,
|
|
132
|
-
const output = template.content(parseTemplateProps(template,
|
|
184
|
+
function renderDiscordContent(template, props) {
|
|
185
|
+
const output = template.content(parseTemplateProps(template, props));
|
|
133
186
|
const result = zod_mini.safeParse(discordContentSchema, output);
|
|
134
187
|
const empty = result.success && !result.data.content && (result.data.embeds?.length ?? 0) === 0 && output.poll === void 0 && (output.components?.length ?? 0) === 0;
|
|
135
|
-
if (!result.success || empty)
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
188
|
+
if (!result.success || empty) {
|
|
189
|
+
const issues = result.success ? [{
|
|
190
|
+
path: "",
|
|
191
|
+
message: "a Discord message needs content, an embed, a poll or components"
|
|
192
|
+
}] : issuesOf(result.error);
|
|
193
|
+
throw new TemplateValidationError("discord", template.id, "content", issues);
|
|
194
|
+
}
|
|
139
195
|
return output;
|
|
140
196
|
}
|
|
141
197
|
/** Run a Slack template's content over parsed props and check the message it returns. */
|
|
142
|
-
function renderSlackContent(template,
|
|
143
|
-
const output = template.content(parseTemplateProps(template,
|
|
198
|
+
function renderSlackContent(template, props) {
|
|
199
|
+
const output = template.content(parseTemplateProps(template, props));
|
|
144
200
|
const result = zod_mini.safeParse(slackContentSchema, output);
|
|
145
|
-
if (!result.success) throw new TemplateValidationError("slack",
|
|
201
|
+
if (!result.success) throw new TemplateValidationError("slack", template.id, "content", issuesOf(result.error));
|
|
146
202
|
return output;
|
|
147
203
|
}
|
|
148
204
|
function parsePreview(schema, preview, channel, title) {
|
|
@@ -202,40 +258,44 @@ function rejectCustomChecks(def, where, fail) {
|
|
|
202
258
|
* stops the send before any device; Discord and Slack content likewise. Channels without a
|
|
203
259
|
* registry here (sms, …) pass through to their app-supplied senders.
|
|
204
260
|
*/
|
|
205
|
-
function registryValidator(
|
|
261
|
+
function registryValidator(registry) {
|
|
262
|
+
const email = indexTemplates("email", registry.email);
|
|
263
|
+
const push = indexTemplates("push", registry.push);
|
|
264
|
+
const discord = indexTemplates("discord", registry.discord);
|
|
265
|
+
const slack = indexTemplates("slack", registry.slack);
|
|
206
266
|
return { validate({ channel, template, props }) {
|
|
207
|
-
if (channel === "email") return parseTemplateProps(
|
|
267
|
+
if (channel === "email") return parseTemplateProps(lookupTemplate(email, "email", template), props);
|
|
208
268
|
if (channel === "push") {
|
|
209
|
-
const entry =
|
|
210
|
-
renderPushContent(entry,
|
|
211
|
-
return parseTemplateProps(entry,
|
|
269
|
+
const entry = lookupTemplate(push, "push", template);
|
|
270
|
+
renderPushContent(entry, props);
|
|
271
|
+
return parseTemplateProps(entry, props);
|
|
212
272
|
}
|
|
213
273
|
if (channel === "discord") {
|
|
214
|
-
const entry =
|
|
215
|
-
renderDiscordContent(entry,
|
|
216
|
-
return parseTemplateProps(entry,
|
|
274
|
+
const entry = lookupTemplate(discord, "discord", template);
|
|
275
|
+
renderDiscordContent(entry, props);
|
|
276
|
+
return parseTemplateProps(entry, props);
|
|
217
277
|
}
|
|
218
278
|
if (channel === "slack") {
|
|
219
|
-
const entry =
|
|
220
|
-
renderSlackContent(entry,
|
|
221
|
-
return parseTemplateProps(entry,
|
|
279
|
+
const entry = lookupTemplate(slack, "slack", template);
|
|
280
|
+
renderSlackContent(entry, props);
|
|
281
|
+
return parseTemplateProps(entry, props);
|
|
222
282
|
}
|
|
223
283
|
return props;
|
|
224
284
|
} };
|
|
225
285
|
}
|
|
226
|
-
function lookup(registry, channel, key) {
|
|
227
|
-
if (registry === void 0 || !Object.hasOwn(registry, key)) throw new Error(`${channel} template '${key}' is not registered`);
|
|
228
|
-
return registry[key];
|
|
229
|
-
}
|
|
230
286
|
//#endregion
|
|
287
|
+
exports.CHANNEL_OF = CHANNEL_OF;
|
|
231
288
|
exports.TemplateValidationError = TemplateValidationError;
|
|
232
289
|
exports.assertSupportedSchema = assertSupportedSchema;
|
|
233
290
|
exports.discordTemplate = discordTemplate;
|
|
234
291
|
exports.emailTemplate = emailTemplate;
|
|
292
|
+
exports.indexTemplates = indexTemplates;
|
|
235
293
|
exports.isDiscordTemplate = isDiscordTemplate;
|
|
236
294
|
exports.isEmailTemplate = isEmailTemplate;
|
|
237
295
|
exports.isPushTemplate = isPushTemplate;
|
|
238
296
|
exports.isSlackTemplate = isSlackTemplate;
|
|
297
|
+
exports.isTemplate = isTemplate;
|
|
298
|
+
exports.lookupTemplate = lookupTemplate;
|
|
239
299
|
exports.parseTemplateProps = parseTemplateProps;
|
|
240
300
|
exports.pushTemplate = pushTemplate;
|
|
241
301
|
exports.registryValidator = registryValidator;
|
package/dist/templates.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"templates.cjs","names":["z"],"sources":["../src/templates.ts"],"sourcesContent":["import type { Block, KnownBlock } from '@slack/types';\nimport type { RESTPostAPIWebhookWithTokenJSONBody } from 'discord-api-types/v10';\nimport * as z from 'zod/mini';\nimport type * as core from 'zod/v4/core';\nimport type { ScalarIR } from './ir';\n\n/**\n * Template definitions — `emailTemplate`, `pushTemplate`, `discordTemplate` and `slackTemplate`. One\n * object per template, and its Zod `props` schema is the only source of the\n * props type: the DSL's `.email()/.push()` arguments, the `preview`, and the\n * `component`/`content` parameter are all derived from it, and every render\n * parses the props against it first (types alone check nothing at run time).\n *\n * Kept free of React and of any renderer: the definitions are plain data plus\n * a function, so the DSL, the Worker and the studio can all import them; the\n * React rendering lives in `@shware/workflow/react-email`.\n *\n * Supported schemas (v1): a strict object (`z.strictObject`) whose fields are\n * string / number / boolean — optionally as enums or literals, optionally\n * `.optional()`, with the built-in checks (min, email, …). That is exactly\n * what IR message props can carry, and it keeps input and output identical, so\n * producer, studio and sender never disagree about a transformed value.\n * Anything else (nested objects, arrays, null, default/transform/coerce,\n * custom refinements) is rejected when the template is declared.\n */\n\n/** A strict Zod object schema of scalar fields — the accepted shape of `props`. */\nexport type PropsSchema = core.$ZodObject;\n\n/** What a push template's `content` returns: the notification itself. */\nexport interface PushContent {\n title: string;\n body: string;\n /** Rich image URL (iOS attachment / Android BigPicture). */\n image?: string;\n /** Where a tap leads: the page a browser push opens (the site's root when absent). */\n url?: string;\n}\n\n/** A Discord webhook message (`discord-api-types`): content, embeds, username, allowed mentions… */\nexport type DiscordContent = RESTPostAPIWebhookWithTokenJSONBody;\n\n/** A Slack incoming-webhook message: the fallback `text` and, usually, Block Kit `blocks`. */\nexport interface SlackContent {\n /** Shown in notifications and wherever blocks cannot be; required even with blocks. */\n text: string;\n blocks?: (KnownBlock | Block)[];\n username?: string;\n icon_emoji?: string;\n icon_url?: string;\n mrkdwn?: boolean;\n unfurl_links?: boolean;\n unfurl_media?: boolean;\n}\n\n/** The channels a template can be declared for. */\nexport type TemplateChannel = 'email' | 'push' | 'discord' | 'slack';\n\ninterface TemplateBase<S extends PropsSchema> {\n /** Display name in the studio (not the email subject, not the notification title). */\n readonly title: string;\n readonly description?: string | undefined;\n readonly props: S;\n /** Sample props for the studio; parsed against `props` when the template is declared. */\n readonly preview: core.input<S>;\n}\n\nexport interface EmailTemplate<S extends PropsSchema = PropsSchema> extends TemplateBase<S> {\n readonly kind: 'email-template';\n readonly version: 1;\n readonly subject: string;\n /** The email body: a component over the parsed props (rendered by `@shware/workflow/react-email`). */\n readonly component: (props: Readonly<core.output<S>>) => unknown;\n}\n\nexport interface PushTemplate<S extends PropsSchema = PropsSchema> extends TemplateBase<S> {\n readonly kind: 'push-template';\n readonly version: 1;\n /** The notification, from the parsed props. Synchronous and pure; its result is checked before sending. */\n readonly content: (props: Readonly<core.output<S>>) => PushContent;\n}\n\n/**\n * A message posted to a team channel through an incoming webhook (Discord, Slack). The webhook\n * URL is a secret, so it lives in the Worker's environment and the template reads it from there\n * at send time: `webhook: (env: Env) => env.WEBHOOK_DISCORD_ALERTS`, with `Env` the host's\n * zod-validated environment (`journeyWorker({ env: schema })`). The studio never calls it.\n */\ninterface WebhookTemplateBase<S extends PropsSchema, Env> extends TemplateBase<S> {\n readonly version: 1;\n // A method, so a template typed by the host's Env still fits a registry of any Env\n webhook(env: Env): string | undefined;\n}\n\nexport interface DiscordTemplate<\n S extends PropsSchema = PropsSchema,\n Env = Record<string, unknown>,\n> extends WebhookTemplateBase<S, Env> {\n readonly kind: 'discord-template';\n /** The message, from the parsed props. Synchronous and pure; checked before sending. */\n readonly content: (props: Readonly<core.output<S>>) => DiscordContent;\n}\n\nexport interface SlackTemplate<\n S extends PropsSchema = PropsSchema,\n Env = Record<string, unknown>,\n> extends WebhookTemplateBase<S, Env> {\n readonly kind: 'slack-template';\n /** The message, from the parsed props. Synchronous and pure; checked before sending. */\n readonly content: (props: Readonly<core.output<S>>) => SlackContent;\n}\n\n/** Strips a Promise return out of the accepted callback types: async content is rejected at the type level. */\ntype Sync<T> = T extends Promise<unknown> ? never : T;\n\nexport interface EmailTemplateDefinition<S extends PropsSchema> {\n title: string;\n description?: string;\n props: S;\n subject: string;\n preview: NoInfer<core.input<S>>;\n component: (props: NoInfer<Readonly<core.output<S>>>) => unknown;\n}\n\nexport interface PushTemplateDefinition<S extends PropsSchema, R> {\n title: string;\n description?: string;\n props: S;\n preview: NoInfer<core.input<S>>;\n content: (props: NoInfer<Readonly<core.output<S>>>) => Sync<R> & PushContent;\n}\n\nexport interface WebhookTemplateDefinition<S extends PropsSchema, Env, C> {\n title: string;\n description?: string;\n props: S;\n preview: NoInfer<core.input<S>>;\n /** The webhook URL, read from the Worker's environment when a message is sent. */\n webhook: (env: Env) => string | undefined;\n content: (props: NoInfer<Readonly<core.output<S>>>) => Sync<C>;\n}\n\n/** Declare a Discord webhook template. Throws when `props` is unsupported or `preview` does not parse. */\nexport function discordTemplate<S extends PropsSchema, Env = Record<string, unknown>>(\n definition: WebhookTemplateDefinition<S, Env, DiscordContent>\n): DiscordTemplate<S, Env> {\n assertSupportedSchema(definition.props, definition.title);\n parsePreview(definition.props, definition.preview, 'discord', definition.title);\n return { kind: 'discord-template', version: 1, ...definition };\n}\n\n/** Declare a Slack webhook template. Throws when `props` is unsupported or `preview` does not parse. */\nexport function slackTemplate<S extends PropsSchema, Env = Record<string, unknown>>(\n definition: WebhookTemplateDefinition<S, Env, SlackContent>\n): SlackTemplate<S, Env> {\n assertSupportedSchema(definition.props, definition.title);\n parsePreview(definition.props, definition.preview, 'slack', definition.title);\n return { kind: 'slack-template', version: 1, ...definition };\n}\n\n/** Declare an email template. Throws when `props` uses an unsupported schema or `preview` does not parse. */\nexport function emailTemplate<S extends PropsSchema>(\n definition: EmailTemplateDefinition<S>\n): EmailTemplate<S> {\n assertSupportedSchema(definition.props, definition.title);\n parsePreview(definition.props, definition.preview, 'email', definition.title);\n return { kind: 'email-template', version: 1, ...definition };\n}\n\n/** Declare a push template. Throws when `props` uses an unsupported schema or `preview` does not parse. */\nexport function pushTemplate<S extends PropsSchema, R extends PushContent>(\n definition: PushTemplateDefinition<S, R>\n): PushTemplate<S> {\n assertSupportedSchema(definition.props, definition.title);\n parsePreview(definition.props, definition.preview, 'push', definition.title);\n return { kind: 'push-template', version: 1, ...definition } as unknown as PushTemplate<S>;\n}\n\nexport function isEmailTemplate(value: unknown): value is EmailTemplate {\n return isMarked(value, 'email-template');\n}\n\nexport function isPushTemplate(value: unknown): value is PushTemplate {\n return isMarked(value, 'push-template');\n}\n\nexport function isDiscordTemplate(value: unknown): value is DiscordTemplate {\n return isMarked(value, 'discord-template');\n}\n\nexport function isSlackTemplate(value: unknown): value is SlackTemplate {\n return isMarked(value, 'slack-template');\n}\n\n/** Any declared template. */\nexport type AnyTemplate = EmailTemplate | PushTemplate | DiscordTemplate | SlackTemplate;\n\nconst CHANNEL_OF: Record<AnyTemplate['kind'], TemplateChannel> = {\n 'email-template': 'email',\n 'push-template': 'push',\n 'discord-template': 'discord',\n 'slack-template': 'slack',\n};\n\nfunction isMarked(value: unknown, kind: string): boolean {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { kind?: unknown }).kind === kind &&\n (value as { version?: unknown }).version === 1\n );\n}\n\n/* ------------------------------- validation -------------------------------- */\n\n/** One failed field, with the dotted path the studio and the logs show. */\nexport interface TemplateIssue {\n path: string;\n message: string;\n}\n\n/**\n * A template refused its input (`phase: 'props'` — the component/content was\n * never called) or its content function returned something that is not a\n * notification (`phase: 'content'` — called, but nothing is sent). Never a\n * provider failure: a sender must not read it as a dead device token.\n */\nexport class TemplateValidationError extends Error {\n override readonly name = 'TemplateValidationError';\n constructor(\n readonly channel: TemplateChannel,\n readonly template: string,\n readonly phase: 'props' | 'content',\n readonly issues: TemplateIssue[]\n ) {\n super(\n `${channel} template '${template}' ${phase === 'props' ? 'rejected its props' : 'returned invalid content'}: ${issues\n .map((i) => `${i.path || '(root)'} ${i.message}`)\n .join('; ')}`\n );\n }\n}\n\nfunction issuesOf(error: core.$ZodError): TemplateIssue[] {\n return error.issues.map((issue) => ({\n path: issue.path.map(String).join('.'),\n message: issue.message,\n }));\n}\n\n/**\n * Parse message props against a template's schema and return the parsed value\n * — the only value anything downstream may use. Throws TemplateValidationError.\n */\nexport function parseTemplateProps<S extends PropsSchema>(\n template: EmailTemplate<S> | PushTemplate<S> | DiscordTemplate<S> | SlackTemplate<S>,\n key: string,\n props: Record<string, unknown>\n): core.output<S> {\n const channel = CHANNEL_OF[template.kind];\n const result = z.safeParse(template.props, props);\n if (!result.success) {\n throw new TemplateValidationError(channel, key, 'props', issuesOf(result.error));\n }\n return result.data;\n}\n\nconst pushContentSchema = z.strictObject({\n title: z.string(),\n body: z.string(),\n image: z.optional(z.string()),\n url: z.optional(z.string()),\n});\n\n/** Run a push template's content over parsed props and check the notification it returns. */\nexport function renderPushContent(\n template: PushTemplate,\n key: string,\n props: Record<string, unknown>\n): PushContent {\n const parsed = parseTemplateProps(template, key, props);\n const output: unknown = template.content(parsed);\n // A Promise (async content smuggled past the types) is an object without title/body: refused here\n const result = z.safeParse(pushContentSchema, output);\n if (!result.success) {\n throw new TemplateValidationError('push', key, 'content', issuesOf(result.error));\n }\n return result.data;\n}\n\n/**\n * What a Discord webhook accepts at all: something to show (content, an embed, a poll or\n * components) and content within Discord's 2000 characters. The rest of the body is Discord's to\n * judge; its types come from `discord-api-types`.\n */\nconst discordContentSchema = z.looseObject({\n content: z.optional(z.string().check(z.maxLength(2000))),\n embeds: z.optional(z.array(z.looseObject({}))),\n});\n\nconst slackContentSchema = z.looseObject({\n text: z.string().check(z.minLength(1)),\n blocks: z.optional(z.array(z.looseObject({ type: z.string() }))),\n});\n\n/** Run a Discord template's content over parsed props and check the message it returns. */\nexport function renderDiscordContent(\n template: DiscordTemplate,\n key: string,\n props: Record<string, unknown>\n): DiscordContent {\n const output: unknown = template.content(parseTemplateProps(template, key, props));\n const result = z.safeParse(discordContentSchema, output);\n const empty =\n result.success &&\n !result.data.content &&\n (result.data.embeds?.length ?? 0) === 0 &&\n (output as { poll?: unknown; components?: unknown[] }).poll === undefined &&\n ((output as { components?: unknown[] }).components?.length ?? 0) === 0;\n if (!result.success || empty) {\n const issues = result.success\n ? [{ path: '', message: 'a Discord message needs content, an embed, a poll or components' }]\n : issuesOf(result.error);\n throw new TemplateValidationError('discord', key, 'content', issues);\n }\n return output as DiscordContent;\n}\n\n/** Run a Slack template's content over parsed props and check the message it returns. */\nexport function renderSlackContent(\n template: SlackTemplate,\n key: string,\n props: Record<string, unknown>\n): SlackContent {\n const output: unknown = template.content(parseTemplateProps(template, key, props));\n const result = z.safeParse(slackContentSchema, output);\n if (!result.success) {\n throw new TemplateValidationError('slack', key, 'content', issuesOf(result.error));\n }\n return output as SlackContent;\n}\n\nfunction parsePreview(\n schema: PropsSchema,\n preview: unknown,\n channel: TemplateChannel,\n title: string\n) {\n const result = z.safeParse(schema, preview);\n if (!result.success) {\n throw new TemplateValidationError(\n channel,\n title,\n 'props',\n issuesOf(result.error).map((i) => Object.assign(i, { message: `preview: ${i.message}` }))\n );\n }\n}\n\n/* ---------------------------- supported schemas ---------------------------- */\n\nconst SCALAR_TYPES = new Set(['string', 'number', 'boolean', 'enum']);\n\n/** Throws when `schema` is outside the v1 subset (see the header). */\nexport function assertSupportedSchema(schema: unknown, where: string): void {\n const fail = (reason: string): never => {\n throw new TypeError(`template '${where}': unsupported props schema — ${reason}`);\n };\n const def = (schema as core.$ZodType | undefined)?._zod?.def;\n if (def?.type !== 'object') fail('props must be a z.strictObject({...})');\n const object = def as core.$ZodObjectDef;\n if (object.catchall?._zod.def.type !== 'never') {\n fail(\n 'props must be strict (z.strictObject): unknown fields would be dropped or passed through'\n );\n }\n rejectCustomChecks(object, where, fail);\n for (const [field, value] of Object.entries(object.shape)) {\n let fieldDef = value._zod.def;\n if (fieldDef.type === 'optional') {\n // The wrapper carries checks of its own (`.optional().overwrite(...)`): refuse them too\n rejectCustomChecks(fieldDef, `${where}.${field}`, fail);\n fieldDef = (fieldDef as core.$ZodOptionalDef).innerType._zod.def;\n }\n if (fieldDef.type === 'literal') {\n const values = (fieldDef as core.$ZodLiteralDef<core.util.Literal>).values;\n if (!values.every((v) => ['string', 'number', 'boolean'].includes(typeof v))) {\n fail(`field '${field}' is a literal of a non-scalar value`);\n }\n } else if (!SCALAR_TYPES.has(fieldDef.type)) {\n fail(\n `field '${field}' is ${fieldDef.type}; only string, number, boolean, enum and literal fields (optionally .optional()) are supported`\n );\n }\n if ((fieldDef as { coerce?: boolean }).coerce === true) {\n fail(`field '${field}' coerces its input (z.coerce), which would change what the props mean`);\n }\n rejectCustomChecks(fieldDef, `${where}.${field}`, fail);\n }\n}\n\n/**\n * Checks the subset refuses: `custom` runs arbitrary code (`.refine()`), and\n * `overwrite` changes the value (`.overwrite()`, `.trim()`, `.toLowerCase()`…)\n * — the props are parsed more than once on the way to a send (the validator,\n * then the renderer), so a value-changing check would apply twice and the\n * email would differ from the preview.\n */\nfunction rejectCustomChecks(def: core.$ZodTypeDef, where: string, fail: (reason: string) => never) {\n for (const check of def.checks ?? []) {\n if (check._zod.def.check === 'custom') {\n fail(`'${where}' uses a custom refinement, which the template subset does not support`);\n }\n if (check._zod.def.check === 'overwrite') {\n fail(\n `'${where}' changes the value (.overwrite, .trim, .toLowerCase, …), which the template subset does not support`\n );\n }\n }\n}\n\n/** The scalar props a template accepts, as the IR resolves them before parsing. */\nexport type ResolvedProps = Record<string, ScalarIR | undefined>;\n\n/**\n * The engine's MessageValidator over the template registries: the message's\n * props are parsed by its template (the parsed value is what gets sent); a\n * push's content is also run once and checked, so an invalid notification\n * stops the send before any device; Discord and Slack content likewise. Channels without a\n * registry here (sms, …) pass through to their app-supplied senders.\n */\nexport function registryValidator(registries: {\n email?: Record<string, EmailTemplate> | undefined;\n push?: Record<string, PushTemplate> | undefined;\n discord?: Readonly<Record<string, DiscordTemplate<PropsSchema, never>>> | undefined;\n slack?: Readonly<Record<string, SlackTemplate<PropsSchema, never>>> | undefined;\n}): {\n validate(message: { channel: string; template: string; props: ResolvedProps }): ResolvedProps;\n} {\n return {\n validate({ channel, template, props }) {\n if (channel === 'email') {\n return parseTemplateProps(\n lookup(registries.email, 'email', template),\n template,\n props\n ) as ResolvedProps;\n }\n if (channel === 'push') {\n const entry = lookup(registries.push, 'push', template);\n renderPushContent(entry, template, props);\n return parseTemplateProps(entry, template, props) as ResolvedProps;\n }\n if (channel === 'discord') {\n const entry = lookup(registries.discord, 'discord', template) as DiscordTemplate;\n renderDiscordContent(entry, template, props);\n return parseTemplateProps(entry, template, props) as ResolvedProps;\n }\n if (channel === 'slack') {\n const entry = lookup(registries.slack, 'slack', template) as SlackTemplate;\n renderSlackContent(entry, template, props);\n return parseTemplateProps(entry, template, props) as ResolvedProps;\n }\n return props;\n },\n };\n}\n\nfunction lookup<T>(registry: Record<string, T> | undefined, channel: string, key: string): T {\n if (registry === undefined || !Object.hasOwn(registry, key)) {\n throw new Error(`${channel} template '${key}' is not registered`);\n }\n return registry[key];\n}\n"],"mappings":";;;;;;AA+IA,SAAgB,gBACd,YACyB;CACzB,sBAAsB,WAAW,OAAO,WAAW,KAAK;CACxD,aAAa,WAAW,OAAO,WAAW,SAAS,WAAW,WAAW,KAAK;CAC9E,OAAO;EAAE,MAAM;EAAoB,SAAS;EAAG,GAAG;CAAW;AAC/D;;AAGA,SAAgB,cACd,YACuB;CACvB,sBAAsB,WAAW,OAAO,WAAW,KAAK;CACxD,aAAa,WAAW,OAAO,WAAW,SAAS,SAAS,WAAW,KAAK;CAC5E,OAAO;EAAE,MAAM;EAAkB,SAAS;EAAG,GAAG;CAAW;AAC7D;;AAGA,SAAgB,cACd,YACkB;CAClB,sBAAsB,WAAW,OAAO,WAAW,KAAK;CACxD,aAAa,WAAW,OAAO,WAAW,SAAS,SAAS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,WAAW,QAAQ;GAC5D,qBAAqB,OAAO,UAAU,KAAK;GAC3C,OAAO,mBAAmB,OAAO,UAAU,KAAK;EAClD;EACA,IAAI,YAAY,SAAS;GACvB,MAAM,QAAQ,OAAO,WAAW,OAAO,SAAS,QAAQ;GACxD,mBAAmB,OAAO,UAAU,KAAK;GACzC,OAAO,mBAAmB,OAAO,UAAU,KAAK;EAClD;EACA,OAAO;CACT,EACF;AACF;AAEA,SAAS,OAAU,UAAyC,SAAiB,KAAgB;CAC3F,IAAI,aAAa,KAAA,KAAa,CAAC,OAAO,OAAO,UAAU,GAAG,GACxD,MAAM,IAAI,MAAM,GAAG,QAAQ,aAAa,IAAI,oBAAoB;CAElE,OAAO,SAAS;AAClB"}
|
|
1
|
+
{"version":3,"file":"templates.cjs","names":["z"],"sources":["../src/templates.ts"],"sourcesContent":["import type { Block, KnownBlock } from '@slack/types';\nimport type { RESTPostAPIWebhookWithTokenJSONBody } from 'discord-api-types/v10';\nimport * as z from 'zod/mini';\nimport type * as core from 'zod/v4/core';\nimport { type EmailAddress, assertEmailMetadata } from './email';\nimport type { ScalarIR } from './ir';\n\n/**\n * Template definitions — `emailTemplate`, `pushTemplate`, `discordTemplate` and `slackTemplate`. One\n * object per template, identified by its own `id` (unique per channel): workflows take the\n * definition itself (`.email(welcome, props)`), the config registers it, and the IR, the manifest,\n * the senders and the studio all find it by that id. Its Zod `props` schema is the only source of the\n * props type: the DSL's `.email()/.push()` arguments, the `preview`, and the\n * `component`/`content` parameter are all derived from it, and every render\n * parses the props against it first (types alone check nothing at run time).\n *\n * Kept free of React and of any renderer: the definitions are plain data plus\n * a function, so the DSL, the Worker and the studio can all import them; the\n * React rendering lives in `@shware/workflow/react-email`.\n *\n * Supported schemas (v1): a strict object (`z.strictObject`) whose fields are\n * string / number / boolean — optionally as enums or literals, optionally\n * `.optional()`, with the built-in checks (min, email, …). That is exactly\n * what IR message props can carry, and it keeps input and output identical, so\n * producer, studio and sender never disagree about a transformed value.\n * Anything else (nested objects, arrays, null, default/transform/coerce,\n * custom refinements) is rejected when the template is declared.\n */\n\n/** A strict Zod object schema of scalar fields — the accepted shape of `props`. */\nexport type PropsSchema = core.$ZodObject;\n\n/** What a push template's `content` returns: the notification itself. */\nexport interface PushContent {\n title: string;\n body: string;\n /** Rich image URL (iOS attachment / Android BigPicture). */\n image?: string;\n /** Where a tap leads: the page a browser push opens (the site's root when absent). */\n url?: string;\n}\n\n/** A Discord webhook message (`discord-api-types`): content, embeds, username, allowed mentions… */\nexport type DiscordContent = RESTPostAPIWebhookWithTokenJSONBody;\n\n/** A Slack incoming-webhook message: the fallback `text` and, usually, Block Kit `blocks`. */\nexport interface SlackContent {\n /** Shown in notifications and wherever blocks cannot be; required even with blocks. */\n text: string;\n blocks?: (KnownBlock | Block)[];\n username?: string;\n icon_emoji?: string;\n icon_url?: string;\n mrkdwn?: boolean;\n unfurl_links?: boolean;\n unfurl_media?: boolean;\n}\n\n/** The channels a template can be declared for. */\nexport type TemplateChannel = 'email' | 'push' | 'discord' | 'slack';\n\ninterface TemplateBase<S extends PropsSchema> {\n /**\n * Wire identity, unique per channel: message nodes, the template manifest, every send and the\n * studio's preview links name the template by it. Not something to rename for readability —\n * `title` is; the property a registry holds it under is only a JavaScript name.\n */\n readonly id: string;\n /** Display name in the studio (not the email subject, not the notification title). */\n readonly title: string;\n readonly description?: string | undefined;\n readonly props: S;\n /** Sample props for the studio; parsed against `props` when the template is declared. */\n readonly preview: core.input<S>;\n}\n\n/**\n * Who an email comes from and where it leads: declared on each template, never inherited from a\n * global sender. Metadata, not props — the component never receives it; its layout reads the\n * resolved unsubscribe link with `useEmailContext()` (`@shware/workflow/email-context`).\n */\nexport interface EmailMetadata {\n readonly from: EmailAddress;\n /** Where replies go; left out, the email has no Reply-To (it is not `from`, and not inherited). */\n readonly replyTo?: EmailAddress | undefined;\n /** This template's unsubscribe link; left out, the config's `email.unsubscribeUrl` (if any). */\n readonly unsubscribeUrl?: string | undefined;\n}\n\nexport interface EmailTemplate<S extends PropsSchema = PropsSchema>\n extends TemplateBase<S>, EmailMetadata {\n readonly kind: 'email-template';\n readonly version: 1;\n readonly subject: string;\n /** The email body: a component over the parsed props (rendered by `@shware/workflow/react-email`). */\n readonly component: (props: Readonly<core.output<S>>) => unknown;\n}\n\nexport interface PushTemplate<S extends PropsSchema = PropsSchema> extends TemplateBase<S> {\n readonly kind: 'push-template';\n readonly version: 1;\n /** The notification, from the parsed props. Synchronous and pure; its result is checked before sending. */\n readonly content: (props: Readonly<core.output<S>>) => PushContent;\n}\n\n/**\n * A message posted to a team channel through an incoming webhook (Discord, Slack). The webhook\n * URL is a secret, so it lives in the Worker's environment and the template reads it from there\n * at send time: `webhook: (env: Env) => env.WEBHOOK_DISCORD_ALERTS`, with `Env` the host's\n * zod-validated environment (`journeyWorker({ env: schema })`). The studio never calls it.\n */\ninterface WebhookTemplateBase<S extends PropsSchema, Env> extends TemplateBase<S> {\n readonly version: 1;\n // A method, so a template typed by the host's Env still fits a registry of any Env\n webhook(env: Env): string | undefined;\n}\n\nexport interface DiscordTemplate<\n S extends PropsSchema = PropsSchema,\n Env = Record<string, unknown>,\n> extends WebhookTemplateBase<S, Env> {\n readonly kind: 'discord-template';\n /** The message, from the parsed props. Synchronous and pure; checked before sending. */\n readonly content: (props: Readonly<core.output<S>>) => DiscordContent;\n}\n\nexport interface SlackTemplate<\n S extends PropsSchema = PropsSchema,\n Env = Record<string, unknown>,\n> extends WebhookTemplateBase<S, Env> {\n readonly kind: 'slack-template';\n /** The message, from the parsed props. Synchronous and pure; checked before sending. */\n readonly content: (props: Readonly<core.output<S>>) => SlackContent;\n}\n\n/** Strips a Promise return out of the accepted callback types: async content is rejected at the type level. */\ntype Sync<T> = T extends Promise<unknown> ? never : T;\n\nexport interface EmailTemplateDefinition<S extends PropsSchema> {\n id: string;\n title: string;\n description?: string;\n from: EmailAddress;\n replyTo?: EmailAddress;\n unsubscribeUrl?: string;\n props: S;\n subject: string;\n preview: NoInfer<core.input<S>>;\n component: (props: NoInfer<Readonly<core.output<S>>>) => unknown;\n}\n\nexport interface PushTemplateDefinition<S extends PropsSchema, R> {\n id: string;\n title: string;\n description?: string;\n props: S;\n preview: NoInfer<core.input<S>>;\n content: (props: NoInfer<Readonly<core.output<S>>>) => Sync<R> & PushContent;\n}\n\nexport interface WebhookTemplateDefinition<S extends PropsSchema, Env, C> {\n id: string;\n title: string;\n description?: string;\n props: S;\n preview: NoInfer<core.input<S>>;\n /** The webhook URL, read from the Worker's environment when a message is sent. */\n webhook: (env: Env) => string | undefined;\n content: (props: NoInfer<Readonly<core.output<S>>>) => Sync<C>;\n}\n\n/** Declare a Discord webhook template. Throws when `props` is unsupported or `preview` does not parse. */\nexport function discordTemplate<S extends PropsSchema, Env = Record<string, unknown>>(\n definition: WebhookTemplateDefinition<S, Env, DiscordContent>\n): DiscordTemplate<S, Env> {\n assertTemplateId(definition.id, 'discordTemplate');\n assertSupportedSchema(definition.props, definition.title);\n parsePreview(definition.props, definition.preview, 'discord', definition.title);\n return { kind: 'discord-template', version: 1, ...definition };\n}\n\n/** Declare a Slack webhook template. Throws when `props` is unsupported or `preview` does not parse. */\nexport function slackTemplate<S extends PropsSchema, Env = Record<string, unknown>>(\n definition: WebhookTemplateDefinition<S, Env, SlackContent>\n): SlackTemplate<S, Env> {\n assertTemplateId(definition.id, 'slackTemplate');\n assertSupportedSchema(definition.props, definition.title);\n parsePreview(definition.props, definition.preview, 'slack', definition.title);\n return { kind: 'slack-template', version: 1, ...definition };\n}\n\n/**\n * Declare an email template. Throws when `from` is missing or invalid, `replyTo` or `unsubscribeUrl`\n * is invalid, `props` uses an unsupported schema or `preview` does not parse.\n */\nexport function emailTemplate<S extends PropsSchema>(\n definition: EmailTemplateDefinition<S>\n): EmailTemplate<S> {\n assertTemplateId(definition.id, 'emailTemplate');\n assertEmailMetadata(definition, `emailTemplate('${definition.id}')`);\n assertSupportedSchema(definition.props, definition.title);\n parsePreview(definition.props, definition.preview, 'email', definition.title);\n return { kind: 'email-template', version: 1, ...definition };\n}\n\n/** Declare a push template. Throws when `props` uses an unsupported schema or `preview` does not parse. */\nexport function pushTemplate<S extends PropsSchema, R extends PushContent>(\n definition: PushTemplateDefinition<S, R>\n): PushTemplate<S> {\n assertTemplateId(definition.id, 'pushTemplate');\n assertSupportedSchema(definition.props, definition.title);\n parsePreview(definition.props, definition.preview, 'push', definition.title);\n return { kind: 'push-template', version: 1, ...definition } as unknown as PushTemplate<S>;\n}\n\nfunction assertTemplateId(id: unknown, factory: string): void {\n if (!isTemplateId(id)) {\n throw new TypeError(`${factory}(): 'id' must be a non-empty string`);\n }\n}\n\nfunction isTemplateId(id: unknown): id is string {\n return typeof id === 'string' && id.trim() !== '';\n}\n\nexport function isEmailTemplate(value: unknown): value is EmailTemplate {\n return isMarked(value, 'email-template');\n}\n\nexport function isPushTemplate(value: unknown): value is PushTemplate {\n return isMarked(value, 'push-template');\n}\n\nexport function isDiscordTemplate(value: unknown): value is DiscordTemplate {\n return isMarked(value, 'discord-template');\n}\n\nexport function isSlackTemplate(value: unknown): value is SlackTemplate {\n return isMarked(value, 'slack-template');\n}\n\n/** Any declared template. */\nexport type AnyTemplate = EmailTemplate | PushTemplate | DiscordTemplate | SlackTemplate;\n\nexport const CHANNEL_OF: Record<AnyTemplate['kind'], TemplateChannel> = {\n 'email-template': 'email',\n 'push-template': 'push',\n 'discord-template': 'discord',\n 'slack-template': 'slack',\n};\n\nfunction isMarked(value: unknown, kind: string): boolean {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { kind?: unknown }).kind === kind &&\n (value as { version?: unknown }).version === 1\n );\n}\n\n/** Any template definition, whatever its channel. */\nexport function isTemplate(value: unknown): value is AnyTemplate {\n return (\n typeof value === 'object' &&\n value !== null &&\n Object.hasOwn(CHANNEL_OF, (value as { kind?: unknown }).kind as string) &&\n (value as { version?: unknown }).version === 1\n );\n}\n\n/* --------------------------------- registry -------------------------------- */\n\n/**\n * The template registry: per channel, the definitions the project registers. Each channel is a\n * plain object whose property names are JavaScript names only — a template is identified by its\n * own `id` (`indexTemplates`).\n */\nexport interface TemplateRegistry {\n readonly email?: Readonly<Record<string, EmailTemplate>>;\n readonly push?: Readonly<Record<string, PushTemplate>>;\n /** Discord webhook templates, each typed by the host's Env its `webhook` reads. */\n readonly discord?: Readonly<Record<string, DiscordTemplate<PropsSchema, never>>>;\n readonly slack?: Readonly<Record<string, SlackTemplate<PropsSchema, never>>>;\n}\n\n/** The template a channel's registry holds. */\nexport interface ChannelTemplate {\n email: EmailTemplate;\n push: PushTemplate;\n discord: DiscordTemplate;\n slack: SlackTemplate;\n}\n\nconst IS_TEMPLATE: Record<TemplateChannel, (value: unknown) => boolean> = {\n email: isEmailTemplate,\n push: isPushTemplate,\n discord: isDiscordTemplate,\n slack: isSlackTemplate,\n};\n\n/**\n * A channel's registry by template id — how everything that turns an id back into a definition\n * (the compiler, the validator, the renderers, the senders, the studio) looks it up. Throws when\n * an entry is not a template of the channel, has no id, or shares its id with another entry: an id\n * is registered once per channel, so two registrations (even of the same object) are an error,\n * not a silent last-wins. Insertion order is the registry's.\n */\nexport function indexTemplates<C extends TemplateChannel>(\n channel: C,\n registry: Readonly<Record<string, unknown>> | undefined\n): ReadonlyMap<string, ChannelTemplate[C]> {\n const index = new Map<string, ChannelTemplate[C]>();\n const paths = new Map<string, string>();\n for (const [name, entry] of Object.entries(registry ?? {})) {\n const path = `templates.${channel}.${name}`;\n if (!IS_TEMPLATE[channel](entry)) {\n throw new TypeError(`${path} is not a ${channel} template`);\n }\n const id = (entry as AnyTemplate).id;\n if (!isTemplateId(id)) throw new TypeError(`${path} has no id`);\n const previous = paths.get(id);\n if (previous !== undefined) {\n throw new TypeError(\n `${channel} template id '${id}' is registered twice: ${previous} and ${path}`\n );\n }\n paths.set(id, path);\n index.set(id, entry as ChannelTemplate[C]);\n }\n return index;\n}\n\n/** A registered template by id; throws naming the channel and id when there is none. */\nexport function lookupTemplate<T>(index: ReadonlyMap<string, T>, channel: string, id: string): T {\n const template = index.get(id);\n if (template === undefined) throw new Error(`${channel} template '${id}' is not registered`);\n return template;\n}\n\n/* ------------------------------- validation -------------------------------- */\n\n/** One failed field, with the dotted path the studio and the logs show. */\nexport interface TemplateIssue {\n path: string;\n message: string;\n}\n\n/**\n * A template refused its input (`phase: 'props'` — the component/content was\n * never called) or its content function returned something that is not a\n * notification (`phase: 'content'` — called, but nothing is sent). Never a\n * provider failure: a sender must not read it as a dead device token.\n */\nexport class TemplateValidationError extends Error {\n override readonly name = 'TemplateValidationError';\n constructor(\n readonly channel: TemplateChannel,\n readonly template: string,\n readonly phase: 'props' | 'content',\n readonly issues: TemplateIssue[]\n ) {\n super(\n `${channel} template '${template}' ${phase === 'props' ? 'rejected its props' : 'returned invalid content'}: ${issues\n .map((i) => `${i.path || '(root)'} ${i.message}`)\n .join('; ')}`\n );\n }\n}\n\nfunction issuesOf(error: core.$ZodError): TemplateIssue[] {\n return error.issues.map((issue) => ({\n path: issue.path.map(String).join('.'),\n message: issue.message,\n }));\n}\n\n/**\n * Parse message props against a template's schema and return the parsed value\n * — the only value anything downstream may use. Throws TemplateValidationError.\n */\nexport function parseTemplateProps<S extends PropsSchema>(\n template: EmailTemplate<S> | PushTemplate<S> | DiscordTemplate<S> | SlackTemplate<S>,\n props: Record<string, unknown>\n): core.output<S> {\n const channel = CHANNEL_OF[template.kind];\n const result = z.safeParse(template.props, props);\n if (!result.success) {\n throw new TemplateValidationError(channel, template.id, 'props', issuesOf(result.error));\n }\n return result.data;\n}\n\nconst pushContentSchema = z.strictObject({\n title: z.string(),\n body: z.string(),\n image: z.optional(z.string()),\n url: z.optional(z.string()),\n});\n\n/** Run a push template's content over parsed props and check the notification it returns. */\nexport function renderPushContent(\n template: PushTemplate,\n props: Record<string, unknown>\n): PushContent {\n const parsed = parseTemplateProps(template, props);\n const output: unknown = template.content(parsed);\n // A Promise (async content smuggled past the types) is an object without title/body: refused here\n const result = z.safeParse(pushContentSchema, output);\n if (!result.success) {\n throw new TemplateValidationError('push', template.id, 'content', issuesOf(result.error));\n }\n return result.data;\n}\n\n/**\n * What a Discord webhook accepts at all: something to show (content, an embed, a poll or\n * components) and content within Discord's 2000 characters. The rest of the body is Discord's to\n * judge; its types come from `discord-api-types`.\n */\nconst discordContentSchema = z.looseObject({\n content: z.optional(z.string().check(z.maxLength(2000))),\n embeds: z.optional(z.array(z.looseObject({}))),\n});\n\nconst slackContentSchema = z.looseObject({\n text: z.string().check(z.minLength(1)),\n blocks: z.optional(z.array(z.looseObject({ type: z.string() }))),\n});\n\n/** Run a Discord template's content over parsed props and check the message it returns. */\nexport function renderDiscordContent(\n template: DiscordTemplate,\n props: Record<string, unknown>\n): DiscordContent {\n const output: unknown = template.content(parseTemplateProps(template, props));\n const result = z.safeParse(discordContentSchema, output);\n const empty =\n result.success &&\n !result.data.content &&\n (result.data.embeds?.length ?? 0) === 0 &&\n (output as { poll?: unknown; components?: unknown[] }).poll === undefined &&\n ((output as { components?: unknown[] }).components?.length ?? 0) === 0;\n if (!result.success || empty) {\n const issues = result.success\n ? [{ path: '', message: 'a Discord message needs content, an embed, a poll or components' }]\n : issuesOf(result.error);\n throw new TemplateValidationError('discord', template.id, 'content', issues);\n }\n return output as DiscordContent;\n}\n\n/** Run a Slack template's content over parsed props and check the message it returns. */\nexport function renderSlackContent(\n template: SlackTemplate,\n props: Record<string, unknown>\n): SlackContent {\n const output: unknown = template.content(parseTemplateProps(template, props));\n const result = z.safeParse(slackContentSchema, output);\n if (!result.success) {\n throw new TemplateValidationError('slack', template.id, 'content', issuesOf(result.error));\n }\n return output as SlackContent;\n}\n\nfunction parsePreview(\n schema: PropsSchema,\n preview: unknown,\n channel: TemplateChannel,\n title: string\n) {\n const result = z.safeParse(schema, preview);\n if (!result.success) {\n throw new TemplateValidationError(\n channel,\n title,\n 'props',\n issuesOf(result.error).map((i) => Object.assign(i, { message: `preview: ${i.message}` }))\n );\n }\n}\n\n/* ---------------------------- supported schemas ---------------------------- */\n\nconst SCALAR_TYPES = new Set(['string', 'number', 'boolean', 'enum']);\n\n/** Throws when `schema` is outside the v1 subset (see the header). */\nexport function assertSupportedSchema(schema: unknown, where: string): void {\n const fail = (reason: string): never => {\n throw new TypeError(`template '${where}': unsupported props schema — ${reason}`);\n };\n const def = (schema as core.$ZodType | undefined)?._zod?.def;\n if (def?.type !== 'object') fail('props must be a z.strictObject({...})');\n const object = def as core.$ZodObjectDef;\n if (object.catchall?._zod.def.type !== 'never') {\n fail(\n 'props must be strict (z.strictObject): unknown fields would be dropped or passed through'\n );\n }\n rejectCustomChecks(object, where, fail);\n for (const [field, value] of Object.entries(object.shape)) {\n let fieldDef = value._zod.def;\n if (fieldDef.type === 'optional') {\n // The wrapper carries checks of its own (`.optional().overwrite(...)`): refuse them too\n rejectCustomChecks(fieldDef, `${where}.${field}`, fail);\n fieldDef = (fieldDef as core.$ZodOptionalDef).innerType._zod.def;\n }\n if (fieldDef.type === 'literal') {\n const values = (fieldDef as core.$ZodLiteralDef<core.util.Literal>).values;\n if (!values.every((v) => ['string', 'number', 'boolean'].includes(typeof v))) {\n fail(`field '${field}' is a literal of a non-scalar value`);\n }\n } else if (!SCALAR_TYPES.has(fieldDef.type)) {\n fail(\n `field '${field}' is ${fieldDef.type}; only string, number, boolean, enum and literal fields (optionally .optional()) are supported`\n );\n }\n if ((fieldDef as { coerce?: boolean }).coerce === true) {\n fail(`field '${field}' coerces its input (z.coerce), which would change what the props mean`);\n }\n rejectCustomChecks(fieldDef, `${where}.${field}`, fail);\n }\n}\n\n/**\n * Checks the subset refuses: `custom` runs arbitrary code (`.refine()`), and\n * `overwrite` changes the value (`.overwrite()`, `.trim()`, `.toLowerCase()`…)\n * — the props are parsed more than once on the way to a send (the validator,\n * then the renderer), so a value-changing check would apply twice and the\n * email would differ from the preview.\n */\nfunction rejectCustomChecks(def: core.$ZodTypeDef, where: string, fail: (reason: string) => never) {\n for (const check of def.checks ?? []) {\n if (check._zod.def.check === 'custom') {\n fail(`'${where}' uses a custom refinement, which the template subset does not support`);\n }\n if (check._zod.def.check === 'overwrite') {\n fail(\n `'${where}' changes the value (.overwrite, .trim, .toLowerCase, …), which the template subset does not support`\n );\n }\n }\n}\n\n/** The scalar props a template accepts, as the IR resolves them before parsing. */\nexport type ResolvedProps = Record<string, ScalarIR | undefined>;\n\n/**\n * The engine's MessageValidator over the template registries: the message's\n * props are parsed by its template (the parsed value is what gets sent); a\n * push's content is also run once and checked, so an invalid notification\n * stops the send before any device; Discord and Slack content likewise. Channels without a\n * registry here (sms, …) pass through to their app-supplied senders.\n */\nexport function registryValidator(registry: TemplateRegistry): {\n validate(message: { channel: string; template: string; props: ResolvedProps }): ResolvedProps;\n} {\n const email = indexTemplates('email', registry.email);\n const push = indexTemplates('push', registry.push);\n const discord = indexTemplates('discord', registry.discord);\n const slack = indexTemplates('slack', registry.slack);\n return {\n validate({ channel, template, props }) {\n if (channel === 'email') {\n const entry = lookupTemplate(email, 'email', template);\n return parseTemplateProps(entry, props) as ResolvedProps;\n }\n if (channel === 'push') {\n const entry = lookupTemplate(push, 'push', template);\n renderPushContent(entry, props);\n return parseTemplateProps(entry, props) as ResolvedProps;\n }\n if (channel === 'discord') {\n const entry = lookupTemplate(discord, 'discord', template);\n renderDiscordContent(entry, props);\n return parseTemplateProps(entry, props) as ResolvedProps;\n }\n if (channel === 'slack') {\n const entry = lookupTemplate(slack, 'slack', template);\n renderSlackContent(entry, props);\n return parseTemplateProps(entry, props) as ResolvedProps;\n }\n return props;\n },\n };\n}\n"],"mappings":";;;;;;;AA4KA,SAAgB,gBACd,YACyB;CACzB,iBAAiB,WAAW,IAAI,iBAAiB;CACjD,sBAAsB,WAAW,OAAO,WAAW,KAAK;CACxD,aAAa,WAAW,OAAO,WAAW,SAAS,WAAW,WAAW,KAAK;CAC9E,OAAO;EAAE,MAAM;EAAoB,SAAS;EAAG,GAAG;CAAW;AAC/D;;AAGA,SAAgB,cACd,YACuB;CACvB,iBAAiB,WAAW,IAAI,eAAe;CAC/C,sBAAsB,WAAW,OAAO,WAAW,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UAEhC;CACA,MAAM,QAAQ,eAAe,SAAS,SAAS,KAAK;CACpD,MAAM,OAAO,eAAe,QAAQ,SAAS,IAAI;CACjD,MAAM,UAAU,eAAe,WAAW,SAAS,OAAO;CAC1D,MAAM,QAAQ,eAAe,SAAS,SAAS,KAAK;CACpD,OAAO,EACL,SAAS,EAAE,SAAS,UAAU,SAAS;EACrC,IAAI,YAAY,SAEd,OAAO,mBADO,eAAe,OAAO,SAAS,QACf,GAAG,KAAK;EAExC,IAAI,YAAY,QAAQ;GACtB,MAAM,QAAQ,eAAe,MAAM,QAAQ,QAAQ;GACnD,kBAAkB,OAAO,KAAK;GAC9B,OAAO,mBAAmB,OAAO,KAAK;EACxC;EACA,IAAI,YAAY,WAAW;GACzB,MAAM,QAAQ,eAAe,SAAS,WAAW,QAAQ;GACzD,qBAAqB,OAAO,KAAK;GACjC,OAAO,mBAAmB,OAAO,KAAK;EACxC;EACA,IAAI,YAAY,SAAS;GACvB,MAAM,QAAQ,eAAe,OAAO,SAAS,QAAQ;GACrD,mBAAmB,OAAO,KAAK;GAC/B,OAAO,mBAAmB,OAAO,KAAK;EACxC;EACA,OAAO;CACT,EACF;AACF"}
|
package/dist/templates.d.cts
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
import { ScalarIR } from "./ir.cjs";
|
|
2
|
+
import { EmailAddress } from "./email.cjs";
|
|
2
3
|
import { Block, KnownBlock } from "@slack/types";
|
|
3
4
|
import { RESTPostAPIWebhookWithTokenJSONBody } from "discord-api-types/v10";
|
|
4
5
|
import * as core from "zod/v4/core";
|
|
5
6
|
//#region src/templates.d.ts
|
|
6
7
|
/**
|
|
7
8
|
* Template definitions — `emailTemplate`, `pushTemplate`, `discordTemplate` and `slackTemplate`. One
|
|
8
|
-
* object per template,
|
|
9
|
+
* object per template, identified by its own `id` (unique per channel): workflows take the
|
|
10
|
+
* definition itself (`.email(welcome, props)`), the config registers it, and the IR, the manifest,
|
|
11
|
+
* the senders and the studio all find it by that id. Its Zod `props` schema is the only source of the
|
|
9
12
|
* props type: the DSL's `.email()/.push()` arguments, the `preview`, and the
|
|
10
13
|
* `component`/`content` parameter are all derived from it, and every render
|
|
11
14
|
* parses the props against it first (types alone check nothing at run time).
|
|
@@ -50,6 +53,12 @@ export interface SlackContent {
|
|
|
50
53
|
/** The channels a template can be declared for. */
|
|
51
54
|
export type TemplateChannel = 'email' | 'push' | 'discord' | 'slack';
|
|
52
55
|
interface TemplateBase<S extends PropsSchema> {
|
|
56
|
+
/**
|
|
57
|
+
* Wire identity, unique per channel: message nodes, the template manifest, every send and the
|
|
58
|
+
* studio's preview links name the template by it. Not something to rename for readability —
|
|
59
|
+
* `title` is; the property a registry holds it under is only a JavaScript name.
|
|
60
|
+
*/
|
|
61
|
+
readonly id: string;
|
|
53
62
|
/** Display name in the studio (not the email subject, not the notification title). */
|
|
54
63
|
readonly title: string;
|
|
55
64
|
readonly description?: string | undefined;
|
|
@@ -57,7 +66,19 @@ interface TemplateBase<S extends PropsSchema> {
|
|
|
57
66
|
/** Sample props for the studio; parsed against `props` when the template is declared. */
|
|
58
67
|
readonly preview: core.input<S>;
|
|
59
68
|
}
|
|
60
|
-
|
|
69
|
+
/**
|
|
70
|
+
* Who an email comes from and where it leads: declared on each template, never inherited from a
|
|
71
|
+
* global sender. Metadata, not props — the component never receives it; its layout reads the
|
|
72
|
+
* resolved unsubscribe link with `useEmailContext()` (`@shware/workflow/email-context`).
|
|
73
|
+
*/
|
|
74
|
+
export interface EmailMetadata {
|
|
75
|
+
readonly from: EmailAddress;
|
|
76
|
+
/** Where replies go; left out, the email has no Reply-To (it is not `from`, and not inherited). */
|
|
77
|
+
readonly replyTo?: EmailAddress | undefined;
|
|
78
|
+
/** This template's unsubscribe link; left out, the config's `email.unsubscribeUrl` (if any). */
|
|
79
|
+
readonly unsubscribeUrl?: string | undefined;
|
|
80
|
+
}
|
|
81
|
+
export interface EmailTemplate<S extends PropsSchema = PropsSchema> extends TemplateBase<S>, EmailMetadata {
|
|
61
82
|
readonly kind: 'email-template';
|
|
62
83
|
readonly version: 1;
|
|
63
84
|
readonly subject: string;
|
|
@@ -93,14 +114,19 @@ export interface SlackTemplate<S extends PropsSchema = PropsSchema, Env = Record
|
|
|
93
114
|
/** Strips a Promise return out of the accepted callback types: async content is rejected at the type level. */
|
|
94
115
|
type Sync<T> = T extends Promise<unknown> ? never : T;
|
|
95
116
|
export interface EmailTemplateDefinition<S extends PropsSchema> {
|
|
117
|
+
id: string;
|
|
96
118
|
title: string;
|
|
97
119
|
description?: string;
|
|
120
|
+
from: EmailAddress;
|
|
121
|
+
replyTo?: EmailAddress;
|
|
122
|
+
unsubscribeUrl?: string;
|
|
98
123
|
props: S;
|
|
99
124
|
subject: string;
|
|
100
125
|
preview: NoInfer<core.input<S>>;
|
|
101
126
|
component: (props: NoInfer<Readonly<core.output<S>>>) => unknown;
|
|
102
127
|
}
|
|
103
128
|
export interface PushTemplateDefinition<S extends PropsSchema, R> {
|
|
129
|
+
id: string;
|
|
104
130
|
title: string;
|
|
105
131
|
description?: string;
|
|
106
132
|
props: S;
|
|
@@ -108,6 +134,7 @@ export interface PushTemplateDefinition<S extends PropsSchema, R> {
|
|
|
108
134
|
content: (props: NoInfer<Readonly<core.output<S>>>) => Sync<R> & PushContent;
|
|
109
135
|
}
|
|
110
136
|
export interface WebhookTemplateDefinition<S extends PropsSchema, Env, C> {
|
|
137
|
+
id: string;
|
|
111
138
|
title: string;
|
|
112
139
|
description?: string;
|
|
113
140
|
props: S;
|
|
@@ -120,7 +147,10 @@ export interface WebhookTemplateDefinition<S extends PropsSchema, Env, C> {
|
|
|
120
147
|
export declare function discordTemplate<S extends PropsSchema, Env = Record<string, unknown>>(definition: WebhookTemplateDefinition<S, Env, DiscordContent>): DiscordTemplate<S, Env>;
|
|
121
148
|
/** Declare a Slack webhook template. Throws when `props` is unsupported or `preview` does not parse. */
|
|
122
149
|
export declare function slackTemplate<S extends PropsSchema, Env = Record<string, unknown>>(definition: WebhookTemplateDefinition<S, Env, SlackContent>): SlackTemplate<S, Env>;
|
|
123
|
-
/**
|
|
150
|
+
/**
|
|
151
|
+
* Declare an email template. Throws when `from` is missing or invalid, `replyTo` or `unsubscribeUrl`
|
|
152
|
+
* is invalid, `props` uses an unsupported schema or `preview` does not parse.
|
|
153
|
+
*/
|
|
124
154
|
export declare function emailTemplate<S extends PropsSchema>(definition: EmailTemplateDefinition<S>): EmailTemplate<S>;
|
|
125
155
|
/** Declare a push template. Throws when `props` uses an unsupported schema or `preview` does not parse. */
|
|
126
156
|
export declare function pushTemplate<S extends PropsSchema, R extends PushContent>(definition: PushTemplateDefinition<S, R>): PushTemplate<S>;
|
|
@@ -130,6 +160,38 @@ export declare function isDiscordTemplate(value: unknown): value is DiscordTempl
|
|
|
130
160
|
export declare function isSlackTemplate(value: unknown): value is SlackTemplate;
|
|
131
161
|
/** Any declared template. */
|
|
132
162
|
export type AnyTemplate = EmailTemplate | PushTemplate | DiscordTemplate | SlackTemplate;
|
|
163
|
+
export declare const CHANNEL_OF: Record<AnyTemplate['kind'], TemplateChannel>;
|
|
164
|
+
/** Any template definition, whatever its channel. */
|
|
165
|
+
export declare function isTemplate(value: unknown): value is AnyTemplate;
|
|
166
|
+
/**
|
|
167
|
+
* The template registry: per channel, the definitions the project registers. Each channel is a
|
|
168
|
+
* plain object whose property names are JavaScript names only — a template is identified by its
|
|
169
|
+
* own `id` (`indexTemplates`).
|
|
170
|
+
*/
|
|
171
|
+
export interface TemplateRegistry {
|
|
172
|
+
readonly email?: Readonly<Record<string, EmailTemplate>>;
|
|
173
|
+
readonly push?: Readonly<Record<string, PushTemplate>>;
|
|
174
|
+
/** Discord webhook templates, each typed by the host's Env its `webhook` reads. */
|
|
175
|
+
readonly discord?: Readonly<Record<string, DiscordTemplate<PropsSchema, never>>>;
|
|
176
|
+
readonly slack?: Readonly<Record<string, SlackTemplate<PropsSchema, never>>>;
|
|
177
|
+
}
|
|
178
|
+
/** The template a channel's registry holds. */
|
|
179
|
+
export interface ChannelTemplate {
|
|
180
|
+
email: EmailTemplate;
|
|
181
|
+
push: PushTemplate;
|
|
182
|
+
discord: DiscordTemplate;
|
|
183
|
+
slack: SlackTemplate;
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* A channel's registry by template id — how everything that turns an id back into a definition
|
|
187
|
+
* (the compiler, the validator, the renderers, the senders, the studio) looks it up. Throws when
|
|
188
|
+
* an entry is not a template of the channel, has no id, or shares its id with another entry: an id
|
|
189
|
+
* is registered once per channel, so two registrations (even of the same object) are an error,
|
|
190
|
+
* not a silent last-wins. Insertion order is the registry's.
|
|
191
|
+
*/
|
|
192
|
+
export declare function indexTemplates<C extends TemplateChannel>(channel: C, registry: Readonly<Record<string, unknown>> | undefined): ReadonlyMap<string, ChannelTemplate[C]>;
|
|
193
|
+
/** A registered template by id; throws naming the channel and id when there is none. */
|
|
194
|
+
export declare function lookupTemplate<T>(index: ReadonlyMap<string, T>, channel: string, id: string): T;
|
|
133
195
|
/** One failed field, with the dotted path the studio and the logs show. */
|
|
134
196
|
export interface TemplateIssue {
|
|
135
197
|
path: string;
|
|
@@ -153,13 +215,13 @@ export declare class TemplateValidationError extends Error {
|
|
|
153
215
|
* Parse message props against a template's schema and return the parsed value
|
|
154
216
|
* — the only value anything downstream may use. Throws TemplateValidationError.
|
|
155
217
|
*/
|
|
156
|
-
export declare function parseTemplateProps<S extends PropsSchema>(template: EmailTemplate<S> | PushTemplate<S> | DiscordTemplate<S> | SlackTemplate<S>,
|
|
218
|
+
export declare function parseTemplateProps<S extends PropsSchema>(template: EmailTemplate<S> | PushTemplate<S> | DiscordTemplate<S> | SlackTemplate<S>, props: Record<string, unknown>): core.output<S>;
|
|
157
219
|
/** Run a push template's content over parsed props and check the notification it returns. */
|
|
158
|
-
export declare function renderPushContent(template: PushTemplate,
|
|
220
|
+
export declare function renderPushContent(template: PushTemplate, props: Record<string, unknown>): PushContent;
|
|
159
221
|
/** Run a Discord template's content over parsed props and check the message it returns. */
|
|
160
|
-
export declare function renderDiscordContent(template: DiscordTemplate,
|
|
222
|
+
export declare function renderDiscordContent(template: DiscordTemplate, props: Record<string, unknown>): DiscordContent;
|
|
161
223
|
/** Run a Slack template's content over parsed props and check the message it returns. */
|
|
162
|
-
export declare function renderSlackContent(template: SlackTemplate,
|
|
224
|
+
export declare function renderSlackContent(template: SlackTemplate, props: Record<string, unknown>): SlackContent;
|
|
163
225
|
/** Throws when `schema` is outside the v1 subset (see the header). */
|
|
164
226
|
export declare function assertSupportedSchema(schema: unknown, where: string): void;
|
|
165
227
|
/** The scalar props a template accepts, as the IR resolves them before parsing. */
|
|
@@ -171,12 +233,7 @@ export type ResolvedProps = Record<string, ScalarIR | undefined>;
|
|
|
171
233
|
* stops the send before any device; Discord and Slack content likewise. Channels without a
|
|
172
234
|
* registry here (sms, …) pass through to their app-supplied senders.
|
|
173
235
|
*/
|
|
174
|
-
export declare function registryValidator(
|
|
175
|
-
email?: Record<string, EmailTemplate> | undefined;
|
|
176
|
-
push?: Record<string, PushTemplate> | undefined;
|
|
177
|
-
discord?: Readonly<Record<string, DiscordTemplate<PropsSchema, never>>> | undefined;
|
|
178
|
-
slack?: Readonly<Record<string, SlackTemplate<PropsSchema, never>>> | undefined;
|
|
179
|
-
}): {
|
|
236
|
+
export declare function registryValidator(registry: TemplateRegistry): {
|
|
180
237
|
validate(message: {
|
|
181
238
|
channel: string;
|
|
182
239
|
template: string;
|
package/dist/templates.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"templates.d.cts","names":[],"sources":["../src/templates.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"templates.d.cts","names":[],"sources":["../src/templates.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;YA8BY,cAAc,KAAK;;iBAGd;EACf;EACA;;EAEA;;EAEA;;;YAIU,iBAAiB;;iBAGZ;;EAEf;EACA,UAAU,aAAa;EACvB;EACA;EACA;EACA;EACA;EACA;;;YAIU;UAEF,aAAa,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