@pplethai/cli 0.21.0 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/README.md +12 -14
  2. package/dist/bin.js +102 -102
  3. package/package.json +3 -6
  4. package/templates/golden-path/.dev.vars.example +0 -33
  5. package/templates/golden-path/.env.example +0 -10
  6. package/templates/golden-path/.github/workflows/ci.yml +0 -22
  7. package/templates/golden-path/AGENTS.md +0 -1
  8. package/templates/golden-path/CLAUDE.md +0 -187
  9. package/templates/golden-path/README.md +0 -118
  10. package/templates/golden-path/gitignore +0 -17
  11. package/templates/golden-path/index.html +0 -16
  12. package/templates/golden-path/migrations/0001_init.sql +0 -10
  13. package/templates/golden-path/overlay-mtime.mjs +0 -30
  14. package/templates/golden-path/package-lock.json +0 -4318
  15. package/templates/golden-path/package.json +0 -41
  16. package/templates/golden-path/scripts/assert-dev-compiled-out.mjs +0 -45
  17. package/templates/golden-path/shared/api.ts +0 -325
  18. package/templates/golden-path/src/auth.ts +0 -230
  19. package/templates/golden-path/src/call-service.ts +0 -147
  20. package/templates/golden-path/src/dataset-query.ts +0 -470
  21. package/templates/golden-path/src/dataset-schema.ts +0 -398
  22. package/templates/golden-path/src/db.ts +0 -32
  23. package/templates/golden-path/src/dev-call-service.ts +0 -392
  24. package/templates/golden-path/src/dev-personas.ts +0 -186
  25. package/templates/golden-path/src/dev-read-dataset.ts +0 -444
  26. package/templates/golden-path/src/dev-registry.ts +0 -294
  27. package/templates/golden-path/src/email.ts +0 -224
  28. package/templates/golden-path/src/entry-name.ts +0 -114
  29. package/templates/golden-path/src/env.ts +0 -38
  30. package/templates/golden-path/src/files.ts +0 -38
  31. package/templates/golden-path/src/identity-header.ts +0 -17
  32. package/templates/golden-path/src/index.ts +0 -276
  33. package/templates/golden-path/src/legal-identity.ts +0 -180
  34. package/templates/golden-path/src/levels.ts +0 -132
  35. package/templates/golden-path/src/notification-response.ts +0 -55
  36. package/templates/golden-path/src/notify.ts +0 -311
  37. package/templates/golden-path/src/payment.ts +0 -554
  38. package/templates/golden-path/src/read-dataset.ts +0 -490
  39. package/templates/golden-path/src/registry.ts +0 -128
  40. package/templates/golden-path/src/vite-env.d.ts +0 -27
  41. package/templates/golden-path/test/apply-migrations.ts +0 -4
  42. package/templates/golden-path/test/call-service.test.ts +0 -288
  43. package/templates/golden-path/test/dev-call-service.test.ts +0 -455
  44. package/templates/golden-path/test/dev-read-dataset.test.ts +0 -379
  45. package/templates/golden-path/test/dev-registry.test.ts +0 -404
  46. package/templates/golden-path/test/effective-sub.test.ts +0 -101
  47. package/templates/golden-path/test/email-offline.test.ts +0 -51
  48. package/templates/golden-path/test/email.test.ts +0 -117
  49. package/templates/golden-path/test/env.d.ts +0 -17
  50. package/templates/golden-path/test/fixtures/overlay/branch-list/entry.md +0 -85
  51. package/templates/golden-path/test/fixtures/overlay/branch-list/mocks/audience.json +0 -3
  52. package/templates/golden-path/test/fixtures/overlay/branch-list/mocks/named.json +0 -3
  53. package/templates/golden-path/test/fixtures/overlay/branch-list/mocks/offices.json +0 -6
  54. package/templates/golden-path/test/fixtures/overlay/branch-list/mocks/roster.json +0 -3
  55. package/templates/golden-path/test/fixtures/overlay/branch-list/mocks/summary.json +0 -1
  56. package/templates/golden-path/test/fixtures/overlay/catalog/entry.md +0 -8
  57. package/templates/golden-path/test/fixtures/overlay/catalog/mocks/responses.json +0 -7
  58. package/templates/golden-path/test/fixtures/overlay/election/2027/score/entry.md +0 -11
  59. package/templates/golden-path/test/fixtures/overlay/election/2027/score/mocks/responses.json +0 -7
  60. package/templates/golden-path/test/fixtures/overlay/election/results/entry.md +0 -24
  61. package/templates/golden-path/test/fixtures/overlay/election/results/mocks/turnout.json +0 -1
  62. package/templates/golden-path/test/fixtures/overlay/orders/entry.md +0 -12
  63. package/templates/golden-path/test/fixtures/overlay/orders/mocks/responses.json +0 -36
  64. package/templates/golden-path/test/fixtures/overlay/platform/email/entry.md +0 -12
  65. package/templates/golden-path/test/fixtures/overlay/platform/email/mocks/responses.json +0 -11
  66. package/templates/golden-path/test/fixtures/overlay/platform/legal-identity/entry.md +0 -8
  67. package/templates/golden-path/test/fixtures/overlay/platform/legal-identity/mocks/responses.json +0 -13
  68. package/templates/golden-path/test/fixtures/overlay/platform/payments/entry.md +0 -12
  69. package/templates/golden-path/test/fixtures/overlay/platform/payments/mocks/responses.json +0 -71
  70. package/templates/golden-path/test/fixtures/overlay/platform/sms/entry.md +0 -10
  71. package/templates/golden-path/test/fixtures/overlay/platform/sms/mocks/responses.json +0 -7
  72. package/templates/golden-path/test/fixtures/overlay/score/entry.md +0 -10
  73. package/templates/golden-path/test/fixtures/overlay/score/mocks/responses.json +0 -7
  74. package/templates/golden-path/test/harness.ts +0 -153
  75. package/templates/golden-path/test/interaction.test.ts +0 -230
  76. package/templates/golden-path/test/legal-identity.test.ts +0 -323
  77. package/templates/golden-path/test/membership.test.ts +0 -105
  78. package/templates/golden-path/test/notification-response.test.ts +0 -79
  79. package/templates/golden-path/test/payment-app.test.ts +0 -210
  80. package/templates/golden-path/test/payment-offline.test.ts +0 -91
  81. package/templates/golden-path/test/payment.test.ts +0 -427
  82. package/templates/golden-path/test/payments-offline.ts +0 -33
  83. package/templates/golden-path/test/read-dataset.test.ts +0 -387
  84. package/templates/golden-path/test/service-call.test.ts +0 -166
  85. package/templates/golden-path/test/smoke.test.ts +0 -464
  86. package/templates/golden-path/tsconfig.json +0 -20
  87. package/templates/golden-path/tsconfig.worker.json +0 -21
  88. package/templates/golden-path/vite.config.ts +0 -12
  89. package/templates/golden-path/vitest.config.ts +0 -28
  90. package/templates/golden-path/web/App.tsx +0 -478
  91. package/templates/golden-path/web/app.css +0 -83
  92. package/templates/golden-path/web/main.tsx +0 -51
  93. package/templates/golden-path/web/pple.ts +0 -124
  94. package/templates/golden-path/web/vite-env.d.ts +0 -10
  95. package/templates/golden-path/wrangler.jsonc +0 -89
  96. package/templates/payment-bridge/.github/workflows/ci.yml +0 -21
  97. package/templates/payment-bridge/CLAUDE.md +0 -9
  98. package/templates/payment-bridge/README.md +0 -57
  99. package/templates/payment-bridge/docs/verify-webhook.md +0 -80
  100. package/templates/payment-bridge/docs/verify-webhook.ts +0 -29
  101. package/templates/payment-bridge/gitignore +0 -5
  102. package/templates/payment-bridge/package-lock.json +0 -4198
  103. package/templates/payment-bridge/package.json +0 -21
  104. package/templates/payment-bridge/src/bridge-key.ts +0 -18
  105. package/templates/payment-bridge/src/env.ts +0 -14
  106. package/templates/payment-bridge/src/index.ts +0 -39
  107. package/templates/payment-bridge/src/platform.ts +0 -49
  108. package/templates/payment-bridge/src/webhook.ts +0 -86
  109. package/templates/payment-bridge/test/docs.test.ts +0 -9
  110. package/templates/payment-bridge/test/fixtures/payments-responses.json +0 -71
  111. package/templates/payment-bridge/test/harness.ts +0 -78
  112. package/templates/payment-bridge/test/inbound.test.ts +0 -138
  113. package/templates/payment-bridge/test/webhook.test.ts +0 -174
  114. package/templates/payment-bridge/tsconfig.json +0 -22
  115. package/templates/payment-bridge/vitest.config.ts +0 -8
  116. package/templates/payment-bridge/wrangler.jsonc +0 -15
  117. package/templates/payment-bridge.version +0 -1
@@ -1,294 +0,0 @@
1
- // Offline Provider development (ADR-0026). Active only where
2
- // `import.meta.env.DEV` is true — `vite dev` and the template tests. The
3
- // production build drops this module the same way it drops the Persona
4
- // bypass (ADR-0011).
5
- //
6
- // `npm run dev` has no platform wrapper and no platform-call secret, so a
7
- // Builder can curl `/.pple/registry/<name>/…` directly. This delivers that
8
- // request to `registry[name]` the way the platform wrapper does: the tail
9
- // path, the method and body, and the `x-pple-*` facts. Incoming `x-pple-*`
10
- // headers are never trusted. Public traffic has them stripped before app
11
- // code, so dev and production agree that a Builder cannot invent platform
12
- // facts.
13
- //
14
- // Identity choice. An unset `DEV_PERSONA` uses the default Persona, as the
15
- // rest of local dev does. `DEV_PERSONA=none` sends no `x-pple-identity`,
16
- // which is what the platform does for an entry that declares
17
- // `userToken: none`. A name that is not a Persona does the same, and does
18
- // not fall back to the default: a registry call must not invent a caller.
19
- // `/api` still falls back, so a typo does not lock the Builder out of the
20
- // app. The Consumer is `DEV_CONSUMER`, or `dev-consumer`. `x-pple-entry` is
21
- // the `registry` key. For a bare entry that is the name the platform sends
22
- // (ADR-0031). For a namespaced entry the key is its local path (`2027/score`),
23
- // because the Provider never sees the Namespace (ADR-0032), so the platform's
24
- // header carries the full name while this one carries the path. The Provider is
25
- // not part of it: the local app is the dev Provider, `dev-provider`, because it
26
- // has no App Slug until the platform creates it.
27
- //
28
- // The registry path names an entry by its local path, which may run several
29
- // folders (`/.pple/registry/2027/score/<tail>`). No key is a segment-prefix of
30
- // another in one app (ADR-0032), so the key that leads the path is the entry.
31
- //
32
- // A Dataset value is an object of page functions. `/.pple/registry/<name>/<objectType>`
33
- // calls that function with `{ cursor }` and answers with its page. A value with
34
- // no fetch-shaped handler, and a page map with no function for the segment,
35
- // throws `registry handler missing`, the error the platform wrapper throws.
36
- // `pple-services` turns that throw
37
- // into `provider_unavailable` (502). Nothing here invents that response:
38
- // locally there is no gateway in front of the handler, and the 502 is a
39
- // Consumer-facing answer the Provider's code never sees. Other `/.pple/`
40
- // paths (cron, the deploy probe) are not emulated; they reach app code with
41
- // platform headers stripped.
42
-
43
- import type { Identity } from "../shared/api";
44
- import { DEV_PERSONAS, DEFAULT_DEV_PERSONA } from "./dev-personas";
45
- import type { Env } from "./env";
46
- import { encodeIdentityHeader } from "./identity-header";
47
- import {
48
- CONSUMER_HEADER,
49
- ENTRY_HEADER,
50
- IDENTITY_HEADER,
51
- type DatasetPages,
52
- type RegistryFetch,
53
- type RegistryMap,
54
- } from "./registry";
55
-
56
- export const DEFAULT_DEV_CONSUMER = "dev-consumer";
57
-
58
- /** Local stand-in for the Provider's App Slug. It is never joined into the entry name. */
59
- export const DEV_PROVIDER_SLUG = "dev-provider";
60
-
61
- const REGISTRY_PATH_PREFIX = "/.pple/registry/";
62
-
63
- const HOP_BY_HOP = new Set([
64
- "host",
65
- "connection",
66
- "keep-alive",
67
- "transfer-encoding",
68
- "te",
69
- "trailer",
70
- "upgrade",
71
- ]);
72
-
73
- export interface DevWorker {
74
- fetch: RegistryFetch;
75
- registry?: RegistryMap;
76
- }
77
-
78
- export interface CallRegistryOptions {
79
- /**
80
- * Persona for `x-pple-identity`. `"none"` or an unknown name sends none.
81
- * Omit to use the env's `DEV_PERSONA`.
82
- */
83
- persona?: string;
84
- /** Consumer slug. Omit to use `DEV_CONSUMER`, then `dev-consumer`. */
85
- consumer?: string;
86
- /**
87
- * Method and body, which the platform preserves. `x-pple-*`, Authorization
88
- * and Cookie here are dropped: the call sets the platform facts itself.
89
- */
90
- init?: RequestInit;
91
- }
92
-
93
- /** The Identity a dev registry call carries, or null for `userToken: none`. */
94
- export function devRegistryIdentity(name: string | undefined): Identity | null {
95
- const key = name?.trim() || DEFAULT_DEV_PERSONA;
96
- if (key === "none") return null;
97
- const persona = DEV_PERSONAS[key];
98
- if (persona) return persona;
99
- console.warn(
100
- `Unknown DEV_PERSONA "${key}" on the emulated registry path; sending no Identity ` +
101
- `(userToken: none). Valid personas: ${Object.keys(DEV_PERSONAS).join(", ")}.`,
102
- );
103
- return null;
104
- }
105
-
106
- export function devConsumerSlug(value: string | undefined): string {
107
- const slug = value?.trim();
108
- return slug ? slug : DEFAULT_DEV_CONSUMER;
109
- }
110
-
111
- /**
112
- * Dev entry. Registry calls go to `user.registry`. Everything else is public
113
- * traffic: `x-pple-*` is removed, then `user.fetch` runs.
114
- */
115
- export async function devWorkerFetch(
116
- user: DevWorker,
117
- request: Request,
118
- env: Env,
119
- ctx: ExecutionContext,
120
- ): Promise<Response> {
121
- const url = new URL(request.url);
122
- const parsed = parseRegistryPath(url.pathname, user.registry);
123
- if (!parsed) return user.fetch(stripPlatformHeaders(request), env, ctx);
124
- if (!parsed.name) return emptyRegistryResponse();
125
-
126
- const pages = datasetPages(user.registry, parsed.name);
127
- if (pages) return runDatasetPage(pages, parsed.tail, request, env, ctx);
128
-
129
- const headers = handlerHeaders(
130
- request.headers,
131
- registryFacts(parsed.name, devConsumerSlug(env.DEV_CONSUMER), devRegistryIdentity(env.DEV_PERSONA)),
132
- );
133
- const target = new URL(request.url);
134
- target.pathname = parsed.tail;
135
- return handlerFor(user.registry, parsed.name)(
136
- forwardedRequest(target, request.method, headers, request.body),
137
- env,
138
- ctx,
139
- );
140
- }
141
-
142
- /**
143
- * Call `registry[name]` the way the platform wrapper does. See the file
144
- * comment for a missing handler: this throws `registry handler missing`.
145
- */
146
- export async function callRegistry(
147
- user: DevWorker,
148
- env: Env,
149
- ctx: ExecutionContext,
150
- name: string,
151
- path: string,
152
- options: CallRegistryOptions = {},
153
- ): Promise<Response> {
154
- if (!name) return emptyRegistryResponse();
155
- const personaName = options.persona !== undefined ? options.persona : env.DEV_PERSONA;
156
- const consumerName = options.consumer !== undefined ? options.consumer : env.DEV_CONSUMER;
157
- const headers = handlerHeaders(
158
- new Headers(options.init?.headers),
159
- registryFacts(name, devConsumerSlug(consumerName), devRegistryIdentity(personaName)),
160
- );
161
- const method = options.init?.method ?? "GET";
162
- const body = options.init?.body ?? null;
163
- // No incoming Host: the pathname and query are the tail the platform sets.
164
- const request = forwardedRequest(tailUrl(path), method, headers, body);
165
- const pages = datasetPages(user.registry, name);
166
- if (pages) return runDatasetPage(pages, new URL(request.url).pathname, request, env, ctx);
167
- return handlerFor(user.registry, name)(request, env, ctx);
168
- }
169
-
170
- function registryFacts(
171
- name: string,
172
- consumer: string,
173
- identity: Identity | null,
174
- ): { consumer: string; entry: string; identity: Identity | null } {
175
- return { consumer, entry: name, identity };
176
- }
177
-
178
- /** What the handler sees. Matches pple-services' header filter, minus the secret. */
179
- function handlerHeaders(
180
- incoming: Headers,
181
- facts: { consumer: string; entry: string; identity: Identity | null },
182
- ): Headers {
183
- const headers = new Headers();
184
- for (const [key, value] of incoming) {
185
- const lower = key.toLowerCase();
186
- if (
187
- lower === "authorization" ||
188
- lower === "cookie" ||
189
- lower.startsWith("x-pple-") ||
190
- HOP_BY_HOP.has(lower)
191
- ) {
192
- continue;
193
- }
194
- headers.set(key, value);
195
- }
196
- headers.set(CONSUMER_HEADER, facts.consumer);
197
- headers.set(ENTRY_HEADER, facts.entry);
198
- if (facts.identity) headers.set(IDENTITY_HEADER, encodeIdentityHeader(facts.identity));
199
- return headers;
200
- }
201
-
202
- function datasetPages(registry: RegistryMap | undefined, name: string): DatasetPages | null {
203
- const value = registry?.[name];
204
- if (typeof value !== "object" || value === null || typeof value.fetch === "function") return null;
205
- return value as DatasetPages;
206
- }
207
-
208
- /**
209
- * A Dataset page function is `{ cursor }` in, a page out. The path's single
210
- * segment is the Object Type. No segment, or no function by that name, is
211
- * the same missing-handler failure as a Service with nothing fetch-shaped.
212
- */
213
- async function runDatasetPage(
214
- pages: DatasetPages,
215
- tail: string,
216
- request: Request,
217
- env: Env,
218
- ctx: ExecutionContext,
219
- ): Promise<Response> {
220
- const objectType = tail.startsWith("/") ? tail.slice(1) : tail;
221
- const fn = objectType.includes("/") || objectType === "" ? undefined : pages[objectType];
222
- if (typeof fn !== "function") throw new Error("registry handler missing");
223
- let cursor: string | null = null;
224
- if (request.method !== "GET" && request.method !== "HEAD" && request.body) {
225
- try {
226
- const body = (await request.json()) as { cursor?: unknown };
227
- if (body && typeof body.cursor === "string") cursor = body.cursor;
228
- } catch {
229
- cursor = null;
230
- }
231
- }
232
- return Response.json(await fn({ cursor }, env, ctx));
233
- }
234
-
235
- function handlerFor(registry: RegistryMap | undefined, name: string): RegistryFetch {
236
- const value = registry?.[name];
237
- if (typeof value === "function") return value;
238
- if (value && typeof value === "object" && typeof value.fetch === "function") {
239
- const app = value as { fetch: RegistryFetch };
240
- return (request, env, ctx) => app.fetch(request, env, ctx);
241
- }
242
- throw new Error("registry handler missing");
243
- }
244
-
245
- function parseRegistryPath(
246
- pathname: string,
247
- registry: RegistryMap | undefined,
248
- ): { name: string; tail: string } | null {
249
- if (pathname !== "/.pple/registry" && !pathname.startsWith(REGISTRY_PATH_PREFIX)) return null;
250
- const restPath = pathname.startsWith(REGISTRY_PATH_PREFIX)
251
- ? pathname.slice(REGISTRY_PATH_PREFIX.length)
252
- : "";
253
- // A nested local path (`2027/score`) is a key that leads the path at a
254
- // segment boundary. Otherwise the first segment, so a missing handler
255
- // throws as before.
256
- const key = Object.keys(registry ?? {}).find(
257
- (candidate) => candidate.includes("/") && (restPath === candidate || restPath.startsWith(`${candidate}/`)),
258
- );
259
- if (key) return { name: key, tail: restPath.slice(key.length) || "/" };
260
- const slash = restPath.indexOf("/");
261
- const name = slash === -1 ? restPath : restPath.slice(0, slash);
262
- const tail = slash === -1 ? "/" : restPath.slice(slash) || "/";
263
- return { name, tail };
264
- }
265
-
266
- function tailUrl(path: string): URL {
267
- const raw = path.startsWith("/") ? path : `/${path}`;
268
- return new URL(raw, "https://provider.invalid");
269
- }
270
-
271
- function forwardedRequest(url: URL, method: string, headers: Headers, body: BodyInit | null): Request {
272
- const init: RequestInit & { duplex?: "half" } = { method, headers };
273
- if (method !== "GET" && method !== "HEAD" && body != null) {
274
- init.body = body;
275
- init.duplex = "half";
276
- }
277
- return new Request(url, init);
278
- }
279
-
280
- function stripPlatformHeaders(request: Request): Request {
281
- const headers = new Headers(request.headers);
282
- let changed = false;
283
- for (const key of [...headers.keys()]) {
284
- if (key.toLowerCase().startsWith("x-pple-")) {
285
- headers.delete(key);
286
- changed = true;
287
- }
288
- }
289
- return changed ? new Request(request, { headers }) : request;
290
- }
291
-
292
- function emptyRegistryResponse(): Response {
293
- return new Response(null, { status: 404, headers: { "cache-control": "no-store" } });
294
- }
@@ -1,224 +0,0 @@
1
- // Email: the party's layout, safe HTML building, and sending through
2
- // `platform/email` (needs its Use Grant and at least Beta).
3
- //
4
- // import { html, partyEmail, sendEmail } from "./email";
5
- //
6
- // const email = partyEmail({
7
- // heading: "ยืนยันการลงทะเบียน",
8
- // content: html`<p>สวัสดีคุณ ${name}</p><p>คุณลงทะเบียนงาน ${event} แล้ว</p>`,
9
- // text: `สวัสดีคุณ ${name}\nคุณลงทะเบียนงาน ${event} แล้ว`,
10
- // button: { label: "ดูรายละเอียด", url: "https://my-app.ppleth.ai/events/1" },
11
- // });
12
- // await sendEmail(env, { to: address, subject: "ยืนยันการลงทะเบียน", ...email });
13
- //
14
- // ESCAPE WHAT PEOPLE TYPED. A value put into HTML with a plain template string
15
- // (`<p>${name}</p>`) becomes HTML: a name containing `<a href=…>` puts a link
16
- // in an email sent under the party's name. The platform removes scripts and
17
- // the like, but not links or images: only your code can tell your markup from
18
- // your users' text. Build HTML with the `html` tag below, which escapes every
19
- // value it is given; `raw()` is the deliberate way to insert markup you wrote.
20
- //
21
- // The layout is hand-written table HTML with inline styles, which is what mail
22
- // apps (Gmail, Outlook, Apple Mail) render alike. Keep `content` simple:
23
- // paragraphs, links, lists, `<b>`. The logo is a PNG the platform serves.
24
-
25
- import { callService, type CallServiceEnv } from "./call-service";
26
-
27
- /** HTML that is safe to put in an email as it is: built by `html`, or vouched for with `raw`. */
28
- export class SafeHtml {
29
- constructor(readonly value: string) {}
30
- toString(): string {
31
- return this.value;
32
- }
33
- }
34
-
35
- /** Text in, the same text as HTML out: `&`, `<`, `>`, `"` and `'` become entities. */
36
- export function escapeHtml(text: string): string {
37
- return text.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
38
- }
39
-
40
- /** Markup you wrote yourself, inserted as it is. Never pass it anything a user typed. */
41
- export function raw(trusted: string): SafeHtml {
42
- return new SafeHtml(trusted);
43
- }
44
-
45
- type HtmlValue = SafeHtml | string | number | boolean | null | undefined | readonly HtmlValue[];
46
-
47
- function render(value: HtmlValue): string {
48
- if (value instanceof SafeHtml) return value.value;
49
- if (Array.isArray(value)) return value.map(render).join("");
50
- if (value === null || value === undefined || value === false) return "";
51
- return escapeHtml(String(value));
52
- }
53
-
54
- /**
55
- * A tagged template that escapes every inserted value. Nest it freely: an
56
- * inserted `html` result (or a list of them) goes in as markup, not escaped twice.
57
- *
58
- * html`<p>สวัสดี ${user.name}</p>` // name is escaped
59
- * html`<ul>${items.map((i) => html`<li>${i}</li>`)}</ul>`
60
- */
61
- export function html(strings: TemplateStringsArray, ...values: HtmlValue[]): SafeHtml {
62
- let out = strings[0] ?? "";
63
- values.forEach((value, i) => {
64
- out += render(value) + (strings[i + 1] ?? "");
65
- });
66
- return new SafeHtml(out);
67
- }
68
-
69
- /** A link a reader may follow: `https:` or `mailto:` only, or this throws. */
70
- export function safeUrl(url: string): string {
71
- let parsed: URL;
72
- try {
73
- parsed = new URL(url);
74
- } catch {
75
- throw new Error(`not a URL: ${url}`);
76
- }
77
- if (parsed.protocol !== "https:" && parsed.protocol !== "mailto:") {
78
- throw new Error(`email links must be https: or mailto:, not ${parsed.protocol}`);
79
- }
80
- return parsed.toString();
81
- }
82
-
83
- /** The party's contact details, printed in every email's footer. */
84
- export const PARTY = {
85
- name: "พรรคประชาชน",
86
- logoUrl: "https://services.ppleth.ai/email-assets/logo.png",
87
- logoAlt: "ภาพโลโก้พรรคประชาชน",
88
- phone: "02-038-5100",
89
- phoneHref: "tel:+6620385100",
90
- hours: "จันทร์-ศุกร์ 10:00-18:00 น.",
91
- email: "office@peoplespartythailand.org",
92
- line: "@peoplesth",
93
- lineUrl: "https://line.me/R/ti/p/@peoplesth",
94
- address: ["พรรคประชาชน สำนักงานใหญ่", "เลขที่ 167 ชั้น 4 ซอย รามคำแหง 42", "แขวงหัวหมาก เขตบางกะปิ", "กรุงเทพมหานคร 10240"],
95
- } as const;
96
-
97
- const NAVY = "#0b3a66";
98
- const ORANGE = "#ff6413";
99
- const INK = "#1f2937";
100
- const FONT = "'IBM Plex Sans Thai Looped','Noto Sans Thai','Leelawadee UI',Tahoma,sans-serif";
101
-
102
- export interface PartyEmailInput {
103
- /** The big line at the top of the message. */
104
- heading: string;
105
- /** The message, built with `html`. */
106
- content: SafeHtml;
107
- /** The same message as plain text, for mail apps that show no HTML. */
108
- text: string;
109
- /** One call to action. Its URL must be `https:` or `mailto:`. */
110
- button?: { label: string; url: string };
111
- /** The grey line mail apps show beside the subject. Defaults to none. */
112
- preheader?: string;
113
- }
114
-
115
- // Dark mode. Mail apps treat it three ways, and the layout is built for all:
116
- // - Apple Mail, iOS Mail, Outlook for Mac honour `prefers-color-scheme`: the
117
- // <style> block below swaps the light card for a dark one.
118
- // - Gmail's apps ignore it and invert colours themselves: a navy block turns
119
- // light blue and white text turns dark. They leave a `background-image`
120
- // alone, so the navy header and the orange button are painted twice
121
- // (`bg()`). Text colours are still inverted, so nothing relies on white text
122
- // on a dark block: the header carries only the logo (an image, never
123
- // inverted), and the footer is light with dark text, which Gmail inverts
124
- // the way it inverts the body.
125
- // - Clients that do neither show the light layout as it is.
126
- const DARK_CSS = `
127
- :root { color-scheme: light dark; supported-color-schemes: light dark; }
128
- a[x-apple-data-detectors] { color: inherit !important; text-decoration: none !important; }
129
- @media (prefers-color-scheme: dark) {
130
- .pe-page { background: #0f141a !important; }
131
- .pe-card { background: #1a2129 !important; }
132
- .pe-ink, .pe-ink p, .pe-ink td, .pe-ink li { color: #e6e9ee !important; }
133
- .pe-heading { color: #ffb48a !important; }
134
- .pe-ink td { border-color: #2c3540 !important; }
135
- .pe-foot { background: #11171e !important; border-color: #2c3540 !important; }
136
- .pe-foot-title { color: #ffb48a !important; }
137
- .pe-foot-label { color: #8b96a5 !important; }
138
- .pe-foot-text, .pe-foot-text a { color: #d5dbe3 !important; }
139
- }`;
140
-
141
- /** A solid block Gmail's dark mode leaves alone: the colour twice, once as an image. */
142
- const bg = (color: string) => raw(`background-color:${color};background-image:linear-gradient(${color},${color})`);
143
-
144
- /** The party layout around your message: `{ html, body }` for `sendEmail`. */
145
- export function partyEmail(input: PartyEmailInput): { html: string; body: string } {
146
- const button = input.button
147
- ? html`<table role="presentation" cellpadding="0" cellspacing="0" style="margin:24px 0 8px"><tr><td style="border-radius:8px;${bg(ORANGE)}">
148
- <a href="${safeUrl(input.button.url)}" style="display:inline-block;padding:12px 24px;font-family:${raw(FONT)};font-size:16px;font-weight:bold;color:#ffffff;text-decoration:none;border-radius:8px">${input.button.label}</a>
149
- </td></tr></table>`
150
- : "";
151
-
152
- const contactRow = (label: string, value: SafeHtml) =>
153
- html`<tr><td class="pe-foot-label" style="padding:4px 12px 4px 0;font-size:14px;color:#6b7280;white-space:nowrap;vertical-align:top">${label}</td><td class="pe-foot-text" style="padding:4px 0;font-size:15px;color:${INK}">${value}</td></tr>`;
154
- const link = (href: string, text: string) => html`<a href="${href}" style="color:${INK};text-decoration:none">${text}</a>`;
155
- // A deliberate, styled link: left bare, Gmail and iOS underline the address in blue themselves.
156
- const mapsUrl = `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(PARTY.address.join(" "))}`;
157
-
158
- const page = html`<!doctype html>
159
- <html lang="th"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
160
- <meta name="color-scheme" content="light dark"><meta name="supported-color-schemes" content="light dark">
161
- <meta name="format-detection" content="telephone=no,address=no,email=no,date=no">
162
- <title>${input.heading}</title><style>${raw(DARK_CSS)}</style></head>
163
- <body class="body pe-page" style="margin:0;padding:0;background:#eef1f5">
164
- ${input.preheader ? html`<div style="display:none;max-height:0;overflow:hidden;opacity:0">${input.preheader}</div>` : ""}
165
- <table role="presentation" class="pe-page" width="100%" cellpadding="0" cellspacing="0" style="background:#eef1f5"><tr><td align="center" style="padding:24px 12px">
166
- <table role="presentation" class="pe-card" width="100%" cellpadding="0" cellspacing="0" style="max-width:600px;background:#ffffff;border-radius:12px;overflow:hidden;font-family:${raw(FONT)}">
167
- <tr><td style="${bg(NAVY)};padding:24px 32px"><img src="${PARTY.logoUrl}" width="176" height="50" alt="${PARTY.logoAlt}" style="display:block;border:0;color:#ffffff;font-size:20px;font-weight:bold"></td></tr>
168
- <tr><td class="pe-ink" style="padding:32px 32px 24px;color:${INK};font-size:16px;line-height:1.7">
169
- <h1 class="pe-heading" style="margin:0 0 16px;font-size:24px;line-height:1.4;color:${NAVY}">${input.heading}</h1>
170
- ${input.content}
171
- ${button}
172
- </td></tr>
173
- <tr><td class="pe-foot" style="background:#f3f5f8;border-top:1px solid #e3e7ed;padding:28px 32px">
174
- <div class="pe-foot-title" style="margin:0 0 12px;font-size:20px;font-weight:bold;color:${NAVY}">ติดต่อเรา</div>
175
- <table role="presentation" cellpadding="0" cellspacing="0">
176
- ${contactRow("โทร", html`${link(PARTY.phoneHref, PARTY.phone)} (${PARTY.hours})`)}
177
- ${contactRow("อีเมล", link(`mailto:${PARTY.email}`, PARTY.email))}
178
- ${contactRow("LINE", link(PARTY.lineUrl, PARTY.line))}
179
- </table>
180
- <div class="pe-foot-text" style="margin:16px 0 0;font-size:14px;line-height:1.6;color:#4b5563"><a href="${mapsUrl}" style="color:#4b5563;text-decoration:none">${PARTY.address.map((line, i) => html`${i ? raw("<br>") : ""}${line}`)}</a></div>
181
- </td></tr>
182
- </table>
183
- </td></tr></table>
184
- </body></html>`;
185
-
186
- const body = [
187
- input.heading,
188
- "",
189
- input.text,
190
- ...(input.button ? ["", `${input.button.label}: ${safeUrl(input.button.url)}`] : []),
191
- "",
192
- "—",
193
- `ติดต่อ${PARTY.name}`,
194
- `โทร ${PARTY.phone} (${PARTY.hours})`,
195
- `อีเมล ${PARTY.email}`,
196
- `LINE ${PARTY.line}`,
197
- ...PARTY.address,
198
- ].join("\n");
199
-
200
- return { html: page.value, body };
201
- }
202
-
203
- export interface SendEmailResult {
204
- status: number;
205
- /** Set when the platform refused before the Service ran (`not_granted`, `needs_beta`, …). */
206
- platformError: string | null;
207
- body: unknown;
208
- }
209
-
210
- /** POST /platform/email. Pass `html`, `body` (plain text), or both. See `pple registry show platform/email`. */
211
- export async function sendEmail(
212
- env: CallServiceEnv,
213
- message: { to: string | string[]; subject: string; html?: string; body?: string },
214
- fetchImpl?: typeof fetch,
215
- ): Promise<SendEmailResult> {
216
- const res = await callService(
217
- env,
218
- "platform/email",
219
- "",
220
- { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(message) },
221
- fetchImpl ? { fetchImpl } : {},
222
- );
223
- return { status: res.status, platformError: res.headers.get("x-pple-error"), body: await res.json().catch(() => null) };
224
- }
@@ -1,114 +0,0 @@
1
- // A Registry Entry is named by its full name: one bare segment (`branch-list`),
2
- // or a Namespace (กลุ่มชื่อ) plus one to three more segments (`election/score`,
3
- // `election/2027/score`). The Provider is not part of the name (ADR-0031,
4
- // ADR-0032). The platform's own entries all sit under the Namespace `platform`:
5
- // `platform/sms`, `platform/legal-identity`.
6
- //
7
- // A copy of the name rules in workers/src/shared/registry/validate.ts. This
8
- // file is copied into a Builder App, which cannot import the platform
9
- // package. cli/test/registry-entry-name.test.ts keeps the two in step.
10
- //
11
- // `platform` is reserved for apps: no app may use it as a bare name or a
12
- // Namespace. That is why `platform/<x>` is the platform's name and never an
13
- // app's. A Consumer calls it by that name, so it passes here; the bare
14
- // `platform` does not.
15
-
16
- /** The slug shape of one segment: lowercase words joined by single hyphens. */
17
- const SEGMENT = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
18
- /** The longest one segment may be. */
19
- const SEGMENT_MAX = 63;
20
- /** The longest a full name may be, slashes included. */
21
- export const ENTRY_FULL_NAME_MAX = 128;
22
- /** A Namespace plus at most three path segments. */
23
- export const ENTRY_NAME_MAX_SEGMENTS = 4;
24
- /** The Namespace of every platform entry (`platform/sms`). The platform holds it; no app may. */
25
- export const PLATFORM_NAMESPACE = "platform";
26
- /** Names the platform keeps for itself. Rejected as a bare name and as an app's Namespace. */
27
- export const RESERVED_ENTRY_NAMES: ReadonlySet<string> = new Set(["health", "overlay", "platform"]);
28
-
29
- /**
30
- * Why `name` is not an entry name, or null when it is one. Reserved first
31
- * segments are reported apart from other shape problems so a caller can say
32
- * more about them. `platform/<path>` is an entry name: the platform's own
33
- * Namespace, which only the platform publish holds. The bare `platform` is not.
34
- */
35
- export function entryNameProblem(name: string): "shape" | "reserved" | null {
36
- if (name.length > ENTRY_FULL_NAME_MAX) return "shape";
37
- const segments = name.split("/");
38
- if (segments.length > ENTRY_NAME_MAX_SEGMENTS) return "shape";
39
- if (!segments.every((segment) => segment.length <= SEGMENT_MAX && SEGMENT.test(segment))) return "shape";
40
- const top = segments[0] ?? "";
41
- if (top === PLATFORM_NAMESPACE && segments.length > 1) return null;
42
- return RESERVED_ENTRY_NAMES.has(top) ? "reserved" : null;
43
- }
44
-
45
- /** True when `name` is one an entry may have. */
46
- export function isEntryName(name: string): boolean {
47
- return entryNameProblem(name) === null;
48
- }
49
-
50
- /** Why `name` is refused, in a sentence. Null when it is fine. */
51
- export function entryNameError(name: string): string | null {
52
- const problem = entryNameProblem(name);
53
- if (problem === null) return null;
54
- if (problem === "reserved") {
55
- const top = name.split("/")[0] ?? name;
56
- if (top === PLATFORM_NAMESPACE) {
57
- return `"${name}" is not an entry name: "platform" belongs to the platform, and its entries are named under it, such as "platform/sms"`;
58
- }
59
- return `"${top}" is reserved by the platform and cannot start an entry name`;
60
- }
61
- return (
62
- `"${name}" is not an entry name: use one bare name such as "branch-list", or a Namespace and up to ` +
63
- `${ENTRY_NAME_MAX_SEGMENTS - 1} more names such as "election/2027/score" ` +
64
- `(lowercase letters, digits and hyphens; at most ${ENTRY_FULL_NAME_MAX} characters)`
65
- );
66
- }
67
-
68
- /**
69
- * Throws unless `entry` is an entry name. `fn` is the public function that
70
- * received it, so the message names the call the Builder wrote.
71
- */
72
- export function assertEntryName(fn: string, entry: string): void {
73
- const error = entryNameError(entry);
74
- if (error) throw new Error(`${fn} entry ${error}`);
75
- }
76
-
77
- /** Where the workspace overlay lives. The CLI writes one folder per entry under it. */
78
- export const OVERLAY_ROOT = ".pple/registry/";
79
-
80
- /**
81
- * `file` (a glob key or a path) relative to the overlay root, posix, or null
82
- * when it is not under `root`. The root must start at a path boundary, so
83
- * `x.pple/registry/` is not a root. Tests pass their own `root` for a fixture
84
- * folder, because CI has no `.pple/`.
85
- */
86
- export function overlayRelative(file: string, root: string = OVERLAY_ROOT): string | null {
87
- const path = file.split("?")[0]?.replaceAll("\\", "/") ?? file;
88
- let from = 0;
89
- for (;;) {
90
- const at = path.indexOf(root, from);
91
- if (at === -1) return null;
92
- if (at === 0 || path[at - 1] === "/") return path.slice(at + root.length);
93
- from = at + 1;
94
- }
95
- }
96
-
97
- /**
98
- * The entry full name a file under the overlay belongs to, with the file's
99
- * place inside that entry's folder (`entry.md`, `mocks/orders.json`). An entry
100
- * folder is nested for a namespaced entry, so the name is every folder above
101
- * `entry.md` or `mocks/`. Null for a file that is neither.
102
- */
103
- export function overlayEntryFile(
104
- file: string,
105
- root: string = OVERLAY_ROOT,
106
- ): { name: string; inside: string } | null {
107
- const relative = overlayRelative(file, root);
108
- if (relative === null) return null;
109
- const entryMd = /^(.+)\/(entry\.md)$/.exec(relative);
110
- if (entryMd?.[1] && entryMd[2]) return { name: entryMd[1], inside: entryMd[2] };
111
- const mock = /^(.+)\/(mocks\/[^/]+\.json)$/.exec(relative);
112
- if (mock?.[1] && mock[2]) return { name: mock[1], inside: mock[2] };
113
- return null;
114
- }
@@ -1,38 +0,0 @@
1
- // Everything the Worker needs from its environment. The platform injects the
2
- // real bindings and secrets at deploy time; local defaults live in
3
- // wrangler.jsonc and .dev.vars.
4
- export interface Env {
5
- // Your app's private database and file storage.
6
- DB: D1Database;
7
- FILES: R2Bucket;
8
-
9
- // PPLE ID — the Worker validates bearer tokens against this base URL.
10
- SSO_BASE_URL: string;
11
-
12
- // Audience-bound notifications (see src/notify.ts). Base is a var; the key
13
- // is a platform-provisioned secret. Both may be empty locally.
14
- NOTIFY_API_BASE: string;
15
- NOTIFY_API_KEY?: string;
16
-
17
- // Platform Services (ADR-0022). The App Key is a secret; the URL is plain.
18
- // Both are empty until the platform binds them. `callService` reads them
19
- // (src/call-service.ts); the Builder does not put the App Key on a request.
20
- PPLE_SERVICES_URL?: string;
21
- PPLE_APP_KEY?: string;
22
-
23
- // Local development only: which mock persona to sign in as (src/dev-personas.ts).
24
- // Unset means the default persona; "none" turns the bypass off. Never set in
25
- // production — the dev bypass is compiled out of the deployed Worker anyway.
26
- DEV_PERSONA?: string;
27
-
28
- // Local development only: make offline `callService` and `readDataset`
29
- // return a platform refusal instead of a mock (`not_granted`,
30
- // `level_not_met`, `renamed`, …). A bare code applies to every entry;
31
- // `<name>=<code>` wins for that entry. Comma-separated.
32
- // Compiled out with the offline path.
33
- DEV_REGISTRY_ERROR?: string;
34
-
35
- // Local development only: the Consumer slug on the emulated registry path.
36
- // Unset means `dev-consumer`. Compiled out with the dev wrapper.
37
- DEV_CONSUMER?: string;
38
- }