@pplethai/cli 0.12.0 → 0.13.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/dist/bin.js +109 -109
- package/package.json +1 -1
- package/templates/golden-path/CLAUDE.md +10 -0
- package/templates/golden-path/README.md +6 -0
- package/templates/golden-path/shared/api.ts +94 -0
- package/templates/golden-path/src/index.ts +19 -3
- package/templates/golden-path/src/notification-response.ts +55 -0
- package/templates/golden-path/src/notify.ts +127 -8
- package/templates/golden-path/src/registry.ts +3 -0
- package/templates/golden-path/test/harness.ts +7 -0
- package/templates/golden-path/test/interaction.test.ts +186 -0
- package/templates/golden-path/test/notification-response.test.ts +79 -0
package/package.json
CHANGED
|
@@ -102,6 +102,16 @@ Where the token comes from:
|
|
|
102
102
|
- **Notifications**: the shape that makes the audience required is in
|
|
103
103
|
`shared/api.ts`; read the rules that come with naming recipients before
|
|
104
104
|
changing anything there.
|
|
105
|
+
- **Interactive Notifications**: `sendNotification` takes an optional
|
|
106
|
+
`interaction` and returns `notificationId`; `closeInteraction` closes it
|
|
107
|
+
early. Keep `linkPath` as the fallback. Answers (Notification Responses)
|
|
108
|
+
arrive at `notificationResponse` on the default export (`src/index.ts`,
|
|
109
|
+
type in `src/notification-response.ts`): dedupe on `event.id`, pick a winner
|
|
110
|
+
by `respondedAt` then `id` (answers can come after a close), return `410` to
|
|
111
|
+
stop answers, do slow work in `ctx.waitUntil`. The responder is
|
|
112
|
+
`event.responder.sub` only. Try the question with `pple notify test` (it
|
|
113
|
+
reaches only you; its answers reach no handler). Full guide: the
|
|
114
|
+
`pple-platform` Skill, mini-app reference.
|
|
105
115
|
- **Mobile-first layout** uses the layout classes in `web/app.css`.
|
|
106
116
|
- **Add a DB table** by writing a new migration and running
|
|
107
117
|
`npm run db:migrate:local`.
|
|
@@ -91,5 +91,11 @@ you, so a freshly created app is ready to `npm run dev` straight away.)
|
|
|
91
91
|
audience — everyone this app can reach, or the people it names by PPLE ID
|
|
92
92
|
`sub` or mobile number. Naming only ever narrows that set: someone who has
|
|
93
93
|
never opened this app receives nothing.
|
|
94
|
+
- **Ask a question in a notification:** pass `interaction` to `notify()`, keep
|
|
95
|
+
`linkPath` as the fallback, and add `notificationResponse` to the default
|
|
96
|
+
export to receive the answers (dedupe on `id`; `410` stops them; slow work
|
|
97
|
+
in `ctx.waitUntil`). `closeInteraction()` stops answers early. See a sample
|
|
98
|
+
in `test/notification-response.test.ts`. `pple notify test <file.json | ->`
|
|
99
|
+
shows the question on your own phone; its answers reach no handler.
|
|
94
100
|
|
|
95
101
|
The demo cards (Notes / Files / Notify) are examples — replace them.
|
|
@@ -157,6 +157,93 @@ export const NotificationAudienceSchema = z.discriminatedUnion("kind", [
|
|
|
157
157
|
]);
|
|
158
158
|
export type NotificationAudience = z.infer<typeof NotificationAudienceSchema>;
|
|
159
159
|
|
|
160
|
+
/**
|
|
161
|
+
* The names an Action may take as its `icon`: PPLE Today's fixed allowlist.
|
|
162
|
+
* Anything else is refused by PPLE Today, not here.
|
|
163
|
+
*/
|
|
164
|
+
export type InteractionIconName =
|
|
165
|
+
| "check"
|
|
166
|
+
| "x"
|
|
167
|
+
| "thumbs-up"
|
|
168
|
+
| "thumbs-down"
|
|
169
|
+
| "calendar-check"
|
|
170
|
+
| "calendar-x"
|
|
171
|
+
| "clock"
|
|
172
|
+
| "send"
|
|
173
|
+
| "heart"
|
|
174
|
+
| "star"
|
|
175
|
+
| "flag"
|
|
176
|
+
| "user-check"
|
|
177
|
+
| "user-x"
|
|
178
|
+
| "help";
|
|
179
|
+
|
|
180
|
+
export interface InteractionOption {
|
|
181
|
+
id: string;
|
|
182
|
+
label: string;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** One input an Interactive Notification asks for, above its actions. */
|
|
186
|
+
export type InteractionField =
|
|
187
|
+
| {
|
|
188
|
+
id: string;
|
|
189
|
+
type: "text";
|
|
190
|
+
label: string;
|
|
191
|
+
description?: string;
|
|
192
|
+
required?: boolean;
|
|
193
|
+
placeholder?: string;
|
|
194
|
+
multiline?: boolean;
|
|
195
|
+
maxLength?: number;
|
|
196
|
+
minLength?: number;
|
|
197
|
+
}
|
|
198
|
+
| {
|
|
199
|
+
id: string;
|
|
200
|
+
type: "radio";
|
|
201
|
+
label: string;
|
|
202
|
+
description?: string;
|
|
203
|
+
required?: boolean;
|
|
204
|
+
options: InteractionOption[];
|
|
205
|
+
default?: string;
|
|
206
|
+
}
|
|
207
|
+
| {
|
|
208
|
+
id: string;
|
|
209
|
+
type: "checkbox";
|
|
210
|
+
label: string;
|
|
211
|
+
description?: string;
|
|
212
|
+
required?: boolean;
|
|
213
|
+
options: InteractionOption[];
|
|
214
|
+
min?: number;
|
|
215
|
+
max?: number;
|
|
216
|
+
default?: string[];
|
|
217
|
+
};
|
|
218
|
+
|
|
219
|
+
/** A button that submits the answer. Every interaction has one to three. */
|
|
220
|
+
export interface InteractionAction {
|
|
221
|
+
id: string;
|
|
222
|
+
label: string;
|
|
223
|
+
icon?: InteractionIconName;
|
|
224
|
+
style?: "primary" | "outline" | "destructive";
|
|
225
|
+
/** Field ids this action needs filled, on top of fields marked `required`. */
|
|
226
|
+
requires?: string[];
|
|
227
|
+
confirm?: { title: string; message?: string };
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* What an Interactive Notification asks its recipients. Passed to PPLE Today
|
|
232
|
+
* exactly as written: PPLE Today owns the rules (id format, limits, expiry),
|
|
233
|
+
* and a broken one comes back as `invalid_interaction` naming the failing
|
|
234
|
+
* path. The type is here so an editor can help; it is not a validator.
|
|
235
|
+
*/
|
|
236
|
+
export interface Interaction {
|
|
237
|
+
/** Opaque to the platform; echoed back with the answer. At most 200 chars. */
|
|
238
|
+
ref?: string;
|
|
239
|
+
/** ISO date-time with `Z` or an offset, in the future, at most 30 days out. */
|
|
240
|
+
expiresAt?: string;
|
|
241
|
+
fields?: InteractionField[];
|
|
242
|
+
actions: InteractionAction[];
|
|
243
|
+
/** `false` keeps action buttons off the OS notification. Default `true`. */
|
|
244
|
+
tray?: boolean;
|
|
245
|
+
}
|
|
246
|
+
|
|
160
247
|
/**
|
|
161
248
|
* A notification to send. The privacy model in one line: this app can reach
|
|
162
249
|
* the people who already use it — and now say which of them it means — and no
|
|
@@ -185,6 +272,13 @@ export const NotificationSchema = z.object({
|
|
|
185
272
|
* recipient list of a different length is a conflict, not a replay.
|
|
186
273
|
*/
|
|
187
274
|
idempotencyKey: z.string().trim().min(1).optional(),
|
|
275
|
+
/**
|
|
276
|
+
* Makes this an Interactive Notification. Only checked to be an object here;
|
|
277
|
+
* PPLE Today validates it and names the failing path.
|
|
278
|
+
*/
|
|
279
|
+
interaction: z
|
|
280
|
+
.custom<Interaction>((v) => typeof v === "object" && v !== null && !Array.isArray(v))
|
|
281
|
+
.optional(),
|
|
188
282
|
});
|
|
189
283
|
export type Notification = z.infer<typeof NotificationSchema>;
|
|
190
284
|
|
|
@@ -11,7 +11,7 @@ import { addNote, listNotes } from "./db";
|
|
|
11
11
|
import type { Env } from "./env";
|
|
12
12
|
import { devWorkerFetch } from "./dev-registry";
|
|
13
13
|
import { getFile, listFiles, putFile } from "./files";
|
|
14
|
-
import { sendNotification } from "./notify";
|
|
14
|
+
import { closeInteraction, sendNotification } from "./notify";
|
|
15
15
|
import type { PpleWorker, RegistryFetch, RegistryMap } from "./registry";
|
|
16
16
|
|
|
17
17
|
/** Test seam: real fetch by default, an injected fake in tests. */
|
|
@@ -101,17 +101,33 @@ export function createApp(overrides: AppOverrides = {}) {
|
|
|
101
101
|
const result = await sendNotification(c.env, parsed.data, fetchImpl);
|
|
102
102
|
if (!result.ok) {
|
|
103
103
|
return c.json(
|
|
104
|
-
{
|
|
104
|
+
{
|
|
105
|
+
error: result.error,
|
|
106
|
+
...(result.message ? { message: result.message } : {}),
|
|
107
|
+
...(result.quota ? { quota: result.quota } : {}),
|
|
108
|
+
},
|
|
105
109
|
result.status as ContentfulStatusCode,
|
|
106
110
|
);
|
|
107
111
|
}
|
|
108
112
|
// A Direct send answers for each recipient it named; a Broadcast names no
|
|
109
113
|
// one, so there is nothing to enumerate.
|
|
114
|
+
const notificationId = result.notificationId ? { notificationId: result.notificationId } : {};
|
|
110
115
|
return c.json(
|
|
111
|
-
result.audience === "direct"
|
|
116
|
+
result.audience === "direct"
|
|
117
|
+
? { ok: true, results: result.results, ...notificationId }
|
|
118
|
+
: { ok: true, ...notificationId },
|
|
112
119
|
);
|
|
113
120
|
});
|
|
114
121
|
|
|
122
|
+
// Close an Interactive Notification early, by the id its send returned.
|
|
123
|
+
app.post("/notify/:notificationId/close", async (c) => {
|
|
124
|
+
const result = await closeInteraction(c.env, c.req.param("notificationId"), fetchImpl);
|
|
125
|
+
if (!result.ok) {
|
|
126
|
+
return c.json({ error: result.error }, result.status as ContentfulStatusCode);
|
|
127
|
+
}
|
|
128
|
+
return c.json({ ok: true, ...(result.closedAt ? { closedAt: result.closedAt } : {}) });
|
|
129
|
+
});
|
|
130
|
+
|
|
115
131
|
return app;
|
|
116
132
|
}
|
|
117
133
|
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// A Notification Response: one recipient's answer to an Interactive Notification
|
|
2
|
+
// your app sent (docs/adr/0035). today-v2 delivers it through the platform to
|
|
3
|
+
// `notificationResponse(event, env, ctx)` on the Worker default export, beside
|
|
4
|
+
// `fetch` and `registry`. Define it on `worker` in `src/index.ts`.
|
|
5
|
+
//
|
|
6
|
+
// What your handler does is the status today-v2 retries on:
|
|
7
|
+
//
|
|
8
|
+
// - not defined: the platform answers 404, and answers keep coming for about
|
|
9
|
+
// a day and a half, so there is time to ship one
|
|
10
|
+
// - returns nothing: 204, delivered
|
|
11
|
+
// - returns a `Response`: that status. Return `410` to say "stop sending me
|
|
12
|
+
// these", which ends delivery for good
|
|
13
|
+
// - throws: 500, and today-v2 tries again
|
|
14
|
+
//
|
|
15
|
+
// Delivery is at-least-once and unordered. Dedupe on `event.id`. If only the
|
|
16
|
+
// first answer should count ("first approver wins"), decide it yourself by
|
|
17
|
+
// `respondedAt`, then `id`. An answer can arrive after you closed the
|
|
18
|
+
// interaction.
|
|
19
|
+
//
|
|
20
|
+
// The platform answers when the handler returns. It does not wait for work
|
|
21
|
+
// handed to `ctx.waitUntil`, so do the slow part there, after the answer is
|
|
22
|
+
// acknowledged. today-v2 gives up on a call after about 10 s.
|
|
23
|
+
//
|
|
24
|
+
// The handler gets the parsed event only: no request, no headers. The
|
|
25
|
+
// responder is a PPLE ID `sub` and nothing else. If you need more about that
|
|
26
|
+
// person, call a Service you have been granted.
|
|
27
|
+
|
|
28
|
+
import type { Env } from "./env";
|
|
29
|
+
|
|
30
|
+
export interface NotificationResponseEvent {
|
|
31
|
+
type: "notification.response";
|
|
32
|
+
/** The response's own id. The same on every retry, so dedupe on it. */
|
|
33
|
+
id: string;
|
|
34
|
+
/** The notification that was answered. `notify()` returned it when you sent. */
|
|
35
|
+
notificationId: string;
|
|
36
|
+
/** Your own id for the question, as you sent it. Absent if you sent none. */
|
|
37
|
+
ref?: string;
|
|
38
|
+
app: { slug: string };
|
|
39
|
+
/** Who answered: their PPLE ID `sub`. */
|
|
40
|
+
responder: { sub: string };
|
|
41
|
+
/** The action the recipient chose. */
|
|
42
|
+
action: string;
|
|
43
|
+
/** The form fields they filled in, by field id. A tick-list is an array. */
|
|
44
|
+
values?: Record<string, string | string[]>;
|
|
45
|
+
/** ISO 8601 time they answered. */
|
|
46
|
+
respondedAt: string;
|
|
47
|
+
/** Which delivery attempt this is, from 1. */
|
|
48
|
+
attempt: number;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export type NotificationResponseHandler = (
|
|
52
|
+
event: NotificationResponseEvent,
|
|
53
|
+
env: Env,
|
|
54
|
+
ctx: ExecutionContext,
|
|
55
|
+
) => void | Response | Promise<void | Response>;
|
|
@@ -49,6 +49,14 @@ interface NotifyEnv {
|
|
|
49
49
|
* against the named count, so the call is rejected whole rather than
|
|
50
50
|
* half-sent.
|
|
51
51
|
* - `not_permitted` — this key may not use this route.
|
|
52
|
+
* - `invalid_interaction` — PPLE Today refused the `interaction`; `message`
|
|
53
|
+
* names the first failing path, e.g. `interaction.actions[1].requires[0]`.
|
|
54
|
+
* Nothing was sent.
|
|
55
|
+
* - `interaction_unavailable` — this app cannot send an interaction right now:
|
|
56
|
+
* no callback target yet, or the feature is switched off. Nothing was sent;
|
|
57
|
+
* retrying without `interaction` sends a plain notification.
|
|
58
|
+
* - `notification_not_found` — `closeInteraction` named an id that is not one
|
|
59
|
+
* of this app's notifications (PPLE Today answers the same for all of them).
|
|
52
60
|
* - `send_failed` — anything else.
|
|
53
61
|
*/
|
|
54
62
|
export type NotifyError =
|
|
@@ -58,6 +66,9 @@ export type NotifyError =
|
|
|
58
66
|
| "idempotency_key_conflict"
|
|
59
67
|
| "quota_exceeded"
|
|
60
68
|
| "not_permitted"
|
|
69
|
+
| "invalid_interaction"
|
|
70
|
+
| "interaction_unavailable"
|
|
71
|
+
| "notification_not_found"
|
|
61
72
|
| "send_failed";
|
|
62
73
|
|
|
63
74
|
/**
|
|
@@ -73,10 +84,32 @@ export interface NotifyQuota {
|
|
|
73
84
|
resetAt?: string;
|
|
74
85
|
}
|
|
75
86
|
|
|
87
|
+
/**
|
|
88
|
+
* `notificationId` is PPLE Today's id for the send, the one `closeInteraction`
|
|
89
|
+
* takes. A replay of an `idempotencyKey` returns the original id. It is absent
|
|
90
|
+
* only if PPLE Today did not give one (for instance an audience that reached
|
|
91
|
+
* no one).
|
|
92
|
+
*/
|
|
76
93
|
export type NotifyResult =
|
|
77
|
-
| { ok: true; audience: "all" }
|
|
78
|
-
| {
|
|
79
|
-
|
|
94
|
+
| { ok: true; audience: "all"; notificationId?: string }
|
|
95
|
+
| {
|
|
96
|
+
ok: true;
|
|
97
|
+
audience: "direct";
|
|
98
|
+
results: NotificationDelivery[];
|
|
99
|
+
notificationId?: string;
|
|
100
|
+
}
|
|
101
|
+
| {
|
|
102
|
+
ok: false;
|
|
103
|
+
status: number;
|
|
104
|
+
error: NotifyError;
|
|
105
|
+
/** PPLE Today's own words, kept for `invalid_interaction`. */
|
|
106
|
+
message?: string;
|
|
107
|
+
quota?: NotifyQuota;
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
export type CloseInteractionResult =
|
|
111
|
+
| { ok: true; closedAt?: string }
|
|
112
|
+
| { ok: false; status: number; error: NotifyError };
|
|
80
113
|
|
|
81
114
|
export async function sendNotification(
|
|
82
115
|
env: NotifyEnv,
|
|
@@ -103,23 +136,109 @@ export async function sendNotification(
|
|
|
103
136
|
...(input.idempotencyKey !== undefined
|
|
104
137
|
? { idempotencyKey: input.idempotencyKey }
|
|
105
138
|
: {}),
|
|
139
|
+
// Passed on unchanged: PPLE Today owns its validation.
|
|
140
|
+
...(input.interaction !== undefined ? { interaction: input.interaction } : {}),
|
|
106
141
|
}),
|
|
107
142
|
});
|
|
108
143
|
|
|
109
144
|
if (!res.ok) {
|
|
110
|
-
const
|
|
111
|
-
const
|
|
112
|
-
|
|
145
|
+
const body = await readJson(res);
|
|
146
|
+
const code = codeOf(body);
|
|
147
|
+
const error = interactionErrorFor(code) ?? errorFor(res.status);
|
|
148
|
+
const quota = error === "quota_exceeded" ? quotaOf(body) : undefined;
|
|
149
|
+
const message = error === "invalid_interaction" ? messageOf(body) : undefined;
|
|
150
|
+
return {
|
|
151
|
+
ok: false,
|
|
152
|
+
status: res.status,
|
|
153
|
+
error,
|
|
154
|
+
...(message ? { message } : {}),
|
|
155
|
+
...(quota ? { quota } : {}),
|
|
156
|
+
};
|
|
113
157
|
}
|
|
114
158
|
|
|
115
|
-
|
|
159
|
+
const body = await readJson(res);
|
|
160
|
+
const id = (body as { notificationId?: unknown } | null)?.notificationId;
|
|
161
|
+
const notificationId = typeof id === "string" ? { notificationId: id } : {};
|
|
162
|
+
if (input.audience.kind === "all") return { ok: true, audience: "all", ...notificationId };
|
|
116
163
|
return {
|
|
117
164
|
ok: true,
|
|
118
165
|
audience: "direct",
|
|
119
|
-
results: zipResults(input.audience.recipients,
|
|
166
|
+
results: zipResults(input.audience.recipients, body),
|
|
167
|
+
...notificationId,
|
|
120
168
|
};
|
|
121
169
|
}
|
|
122
170
|
|
|
171
|
+
/**
|
|
172
|
+
* Stop accepting answers to one of this app's Interactive Notifications.
|
|
173
|
+
* Idempotent: closing again succeeds. Answers already in flight can still
|
|
174
|
+
* arrive after this returns, so an app that needs "first wins" settles it on
|
|
175
|
+
* its own side by `respondedAt`.
|
|
176
|
+
*/
|
|
177
|
+
export async function closeInteraction(
|
|
178
|
+
env: NotifyEnv,
|
|
179
|
+
notificationId: string,
|
|
180
|
+
fetchImpl: typeof fetch = globalThis.fetch.bind(globalThis),
|
|
181
|
+
): Promise<CloseInteractionResult> {
|
|
182
|
+
if (!env.NOTIFY_API_BASE || !env.NOTIFY_API_KEY) {
|
|
183
|
+
return { ok: false, status: 503, error: "notifications_not_configured" };
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const res = await fetchImpl(
|
|
187
|
+
`${env.NOTIFY_API_BASE}/notifications/${encodeURIComponent(notificationId)}/interaction/close`,
|
|
188
|
+
{ method: "POST", headers: { authorization: `Bearer ${env.NOTIFY_API_KEY}` } },
|
|
189
|
+
);
|
|
190
|
+
|
|
191
|
+
if (!res.ok) {
|
|
192
|
+
const code = codeOf(await readJson(res));
|
|
193
|
+
const error =
|
|
194
|
+
interactionErrorFor(code) ??
|
|
195
|
+
(res.status === 404
|
|
196
|
+
? "notification_not_found"
|
|
197
|
+
: res.status === 401 || res.status === 403
|
|
198
|
+
? "not_permitted"
|
|
199
|
+
: "send_failed");
|
|
200
|
+
return { ok: false, status: res.status, error };
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const closedAt = (await readJson(res) as { closedAt?: unknown } | null)?.closedAt;
|
|
204
|
+
return { ok: true, ...(typeof closedAt === "string" ? { closedAt } : {}) };
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* PPLE Today's own codes for interaction refusals. These share status 400 with
|
|
209
|
+
* recipient refusals, so the code is read before the status is.
|
|
210
|
+
*/
|
|
211
|
+
function interactionErrorFor(code: string): NotifyError | undefined {
|
|
212
|
+
switch (code) {
|
|
213
|
+
case "NOTIFICATION_INVALID_INTERACTION":
|
|
214
|
+
return "invalid_interaction";
|
|
215
|
+
case "NOTIFICATION_INTERACTION_NO_CALLBACK":
|
|
216
|
+
case "INTERACTIVE_NOTIFICATIONS_DISABLED":
|
|
217
|
+
return "interaction_unavailable";
|
|
218
|
+
default:
|
|
219
|
+
return undefined;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** PPLE Today answers `{ error: { code, message } }`; tolerate a flat body too. */
|
|
224
|
+
function errorObject(body: unknown): Record<string, unknown> {
|
|
225
|
+
if (typeof body !== "object" || body === null) return {};
|
|
226
|
+
const { error } = body as { error?: unknown };
|
|
227
|
+
return typeof error === "object" && error !== null
|
|
228
|
+
? (error as Record<string, unknown>)
|
|
229
|
+
: (body as Record<string, unknown>);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function codeOf(body: unknown): string {
|
|
233
|
+
const { code } = errorObject(body);
|
|
234
|
+
return typeof code === "string" ? code : "";
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function messageOf(body: unknown): string | undefined {
|
|
238
|
+
const { message } = errorObject(body);
|
|
239
|
+
return typeof message === "string" ? message : undefined;
|
|
240
|
+
}
|
|
241
|
+
|
|
123
242
|
/**
|
|
124
243
|
* The platform splits its refusals: schema-level ones answer 422 (its whole
|
|
125
244
|
* API validates uniformly, and this route does not get to be the exception),
|
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
|
|
15
15
|
import { IdentitySchema, type Identity } from "../shared/api";
|
|
16
16
|
import type { Env } from "./env";
|
|
17
|
+
import type { NotificationResponseHandler } from "./notification-response";
|
|
17
18
|
|
|
18
19
|
export const CONSUMER_HEADER = "x-pple-consumer";
|
|
19
20
|
export const ENTRY_HEADER = "x-pple-entry";
|
|
@@ -89,6 +90,8 @@ export type RegistryMap = Record<string, RegistryHandler | DatasetPages>;
|
|
|
89
90
|
export interface PpleWorker {
|
|
90
91
|
fetch(request: Request, env: Env, ctx: ExecutionContext): Response | Promise<Response>;
|
|
91
92
|
registry?: RegistryMap;
|
|
93
|
+
/** Answers to your Interactive Notifications. See `./notification-response`. */
|
|
94
|
+
notificationResponse?: NotificationResponseHandler;
|
|
92
95
|
}
|
|
93
96
|
|
|
94
97
|
function decodeIdentity(value: string): Identity | null {
|
|
@@ -35,6 +35,8 @@ export interface Fakes {
|
|
|
35
35
|
sso?: (req: Request) => Response | Promise<Response>;
|
|
36
36
|
/** Handles POST {NOTIFY_API_BASE}/notifications */
|
|
37
37
|
notify?: (req: Request) => Response | Promise<Response>;
|
|
38
|
+
/** Handles POST {NOTIFY_API_BASE}/notifications/:id/interaction/close */
|
|
39
|
+
close?: (req: Request) => Response | Promise<Response>;
|
|
38
40
|
/**
|
|
39
41
|
* Handles `{PPLE_SERVICES_URL}/<name>/…` for `callService` and
|
|
40
42
|
* `readDataset`. Answer as the platform, or refuse with `serviceRefusal`
|
|
@@ -68,6 +70,7 @@ export function serviceRefusal(code: string, status: number): Response {
|
|
|
68
70
|
export function makeHarness(fakes: Fakes = {}, envOverrides: Partial<Env> = {}) {
|
|
69
71
|
const calls = {
|
|
70
72
|
notify: [] as Request[],
|
|
73
|
+
close: [] as Request[],
|
|
71
74
|
services: [] as RecordedServiceCall[],
|
|
72
75
|
};
|
|
73
76
|
|
|
@@ -96,6 +99,10 @@ export function makeHarness(fakes: Fakes = {}, envOverrides: Partial<Env> = {})
|
|
|
96
99
|
if (url.pathname.endsWith("/oidc/v1/userinfo")) {
|
|
97
100
|
return fakes.sso ? fakes.sso(req) : new Response(null, { status: 502 });
|
|
98
101
|
}
|
|
102
|
+
if (url.pathname.endsWith("/interaction/close")) {
|
|
103
|
+
calls.close.push(req.clone());
|
|
104
|
+
return fakes.close ? fakes.close(req) : new Response(null, { status: 502 });
|
|
105
|
+
}
|
|
99
106
|
if (url.pathname.endsWith("/notifications")) {
|
|
100
107
|
calls.notify.push(req.clone());
|
|
101
108
|
return fakes.notify ? fakes.notify(req) : new Response(null, { status: 502 });
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import type { Interaction } from "../shared/api";
|
|
3
|
+
import { makeHarness } from "./harness";
|
|
4
|
+
|
|
5
|
+
const NOTIFY_ENV = {
|
|
6
|
+
NOTIFY_API_BASE: "https://today.test/external",
|
|
7
|
+
NOTIFY_API_KEY: "app-key",
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
const interaction: Interaction = {
|
|
11
|
+
ref: "leave:123",
|
|
12
|
+
expiresAt: "2026-11-17T00:00:00Z",
|
|
13
|
+
tray: false,
|
|
14
|
+
fields: [{ id: "note", type: "text", label: "เหตุผล", multiline: true, maxLength: 300 }],
|
|
15
|
+
actions: [
|
|
16
|
+
{ id: "approve", label: "อนุมัติ", icon: "check", style: "primary" },
|
|
17
|
+
{
|
|
18
|
+
id: "reject",
|
|
19
|
+
label: "ไม่อนุมัติ",
|
|
20
|
+
style: "destructive",
|
|
21
|
+
requires: ["note"],
|
|
22
|
+
confirm: { title: "ยืนยันการไม่อนุมัติ?" },
|
|
23
|
+
},
|
|
24
|
+
],
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
const direct = { kind: "direct", recipients: [{ sub: "u-1" }] };
|
|
28
|
+
|
|
29
|
+
const sendWith = (h: ReturnType<typeof makeHarness>, extra: Record<string, unknown> = {}) =>
|
|
30
|
+
h.request("/api/notify", {
|
|
31
|
+
method: "POST",
|
|
32
|
+
headers: { "content-type": "application/json" },
|
|
33
|
+
body: JSON.stringify({ audience: direct, title: "Leave", body: "Please answer", ...extra }),
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
const refusal = (status: number, code: string, message = "refused") => ({
|
|
37
|
+
notify: () => Response.json({ error: { code, message } }, { status }),
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
describe("interactive notifications: sending", () => {
|
|
41
|
+
it("passes the interaction to today-v2 exactly as written", async () => {
|
|
42
|
+
const h = makeHarness(
|
|
43
|
+
{
|
|
44
|
+
notify: () =>
|
|
45
|
+
Response.json(
|
|
46
|
+
{ notificationId: "n_1", results: [{ status: "delivered" }] },
|
|
47
|
+
{ status: 201 },
|
|
48
|
+
),
|
|
49
|
+
},
|
|
50
|
+
NOTIFY_ENV,
|
|
51
|
+
);
|
|
52
|
+
const res = await sendWith(h, { interaction });
|
|
53
|
+
expect(res.status).toBe(200);
|
|
54
|
+
const payload = await h.calls.notify[0]!.json<Record<string, unknown>>();
|
|
55
|
+
expect(payload.interaction).toEqual(interaction);
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it("does not add an interaction key to a send without one", async () => {
|
|
59
|
+
const h = makeHarness(
|
|
60
|
+
{ notify: () => Response.json({ notificationId: "n_1", results: [] }) },
|
|
61
|
+
NOTIFY_ENV,
|
|
62
|
+
);
|
|
63
|
+
await sendWith(h);
|
|
64
|
+
const payload = await h.calls.notify[0]!.json<Record<string, unknown>>();
|
|
65
|
+
expect("interaction" in payload).toBe(false);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it("returns the notificationId for a Direct and a Broadcast send", async () => {
|
|
69
|
+
const h = makeHarness(
|
|
70
|
+
{
|
|
71
|
+
notify: () =>
|
|
72
|
+
Response.json({ notificationId: "n_7", results: [{ status: "delivered" }] }),
|
|
73
|
+
},
|
|
74
|
+
NOTIFY_ENV,
|
|
75
|
+
);
|
|
76
|
+
expect(await (await sendWith(h)).json()).toMatchObject({ ok: true, notificationId: "n_7" });
|
|
77
|
+
|
|
78
|
+
const b = makeHarness(
|
|
79
|
+
{ notify: () => Response.json({ notificationId: "n_8" }, { status: 201 }) },
|
|
80
|
+
NOTIFY_ENV,
|
|
81
|
+
);
|
|
82
|
+
expect(await (await sendWith(b, { audience: { kind: "all" } })).json()).toEqual({
|
|
83
|
+
ok: true,
|
|
84
|
+
notificationId: "n_8",
|
|
85
|
+
});
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
it("answers without a notificationId when today-v2 gave none", async () => {
|
|
89
|
+
const h = makeHarness({ notify: () => new Response(null, { status: 202 }) }, NOTIFY_ENV);
|
|
90
|
+
expect(await (await sendWith(h, { audience: { kind: "all" } })).json()).toEqual({ ok: true });
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
it("names the failing path when today-v2 refuses the interaction", async () => {
|
|
94
|
+
const h = makeHarness(
|
|
95
|
+
refusal(
|
|
96
|
+
400,
|
|
97
|
+
"NOTIFICATION_INVALID_INTERACTION",
|
|
98
|
+
"interaction.actions[1].requires[0]: unknown field",
|
|
99
|
+
),
|
|
100
|
+
NOTIFY_ENV,
|
|
101
|
+
);
|
|
102
|
+
const res = await sendWith(h, { interaction });
|
|
103
|
+
expect(res.status).toBe(400);
|
|
104
|
+
expect(await res.json()).toEqual({
|
|
105
|
+
error: "invalid_interaction",
|
|
106
|
+
message: "interaction.actions[1].requires[0]: unknown field",
|
|
107
|
+
});
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
it.each(["NOTIFICATION_INTERACTION_NO_CALLBACK", "INTERACTIVE_NOTIFICATIONS_DISABLED"])(
|
|
111
|
+
"reports %s as interaction_unavailable",
|
|
112
|
+
async (code) => {
|
|
113
|
+
const h = makeHarness(refusal(400, code), NOTIFY_ENV);
|
|
114
|
+
const res = await sendWith(h, { interaction });
|
|
115
|
+
expect(res.status).toBe(400);
|
|
116
|
+
expect(await res.json()).toMatchObject({ error: "interaction_unavailable" });
|
|
117
|
+
},
|
|
118
|
+
);
|
|
119
|
+
|
|
120
|
+
it("still reads a plain 400 as invalid_recipients", async () => {
|
|
121
|
+
const h = makeHarness(refusal(400, "NOTIFICATION_INVALID_RECIPIENTS"), NOTIFY_ENV);
|
|
122
|
+
expect(await (await sendWith(h)).json()).toMatchObject({ error: "invalid_recipients" });
|
|
123
|
+
});
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
describe("interactive notifications: closing early", () => {
|
|
127
|
+
const close = (h: ReturnType<typeof makeHarness>, id = "n_1") =>
|
|
128
|
+
h.request(`/api/notify/${id}/close`, { method: "POST" });
|
|
129
|
+
|
|
130
|
+
it("calls today-v2's close endpoint with the app's key", async () => {
|
|
131
|
+
const h = makeHarness(
|
|
132
|
+
{ close: () => Response.json({ closedAt: "2026-11-10T00:00:00Z" }) },
|
|
133
|
+
NOTIFY_ENV,
|
|
134
|
+
);
|
|
135
|
+
const res = await close(h);
|
|
136
|
+
expect(res.status).toBe(200);
|
|
137
|
+
expect(await res.json()).toEqual({ ok: true, closedAt: "2026-11-10T00:00:00Z" });
|
|
138
|
+
const sent = h.calls.close[0]!;
|
|
139
|
+
expect(sent.method).toBe("POST");
|
|
140
|
+
expect(new URL(sent.url).pathname).toBe("/external/notifications/n_1/interaction/close");
|
|
141
|
+
expect(sent.headers.get("authorization")).toBe("Bearer app-key");
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
it("is idempotent: closing twice is two successes", async () => {
|
|
145
|
+
const h = makeHarness(
|
|
146
|
+
{ close: () => Response.json({ closedAt: "2026-11-10T00:00:00Z" }) },
|
|
147
|
+
NOTIFY_ENV,
|
|
148
|
+
);
|
|
149
|
+
expect((await close(h)).status).toBe(200);
|
|
150
|
+
expect((await close(h)).status).toBe(200);
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
it("reports a 404 as notification_not_found", async () => {
|
|
154
|
+
const h = makeHarness(
|
|
155
|
+
{
|
|
156
|
+
close: () =>
|
|
157
|
+
Response.json({ error: { code: "NOTIFICATION_NOT_FOUND" } }, { status: 404 }),
|
|
158
|
+
},
|
|
159
|
+
NOTIFY_ENV,
|
|
160
|
+
);
|
|
161
|
+
const res = await close(h);
|
|
162
|
+
expect(res.status).toBe(404);
|
|
163
|
+
expect(await res.json()).toMatchObject({ error: "notification_not_found" });
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
it("reports the flag being off as interaction_unavailable", async () => {
|
|
167
|
+
const h = makeHarness(
|
|
168
|
+
{
|
|
169
|
+
close: () =>
|
|
170
|
+
Response.json(
|
|
171
|
+
{ error: { code: "INTERACTIVE_NOTIFICATIONS_DISABLED" } },
|
|
172
|
+
{ status: 400 },
|
|
173
|
+
),
|
|
174
|
+
},
|
|
175
|
+
NOTIFY_ENV,
|
|
176
|
+
);
|
|
177
|
+
expect(await (await close(h)).json()).toMatchObject({ error: "interaction_unavailable" });
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
it("fails loud when no key is bound", async () => {
|
|
181
|
+
const h = makeHarness({}, { NOTIFY_API_BASE: "" });
|
|
182
|
+
const res = await close(h);
|
|
183
|
+
expect(res.status).toBe(503);
|
|
184
|
+
expect(await res.json()).toMatchObject({ error: "notifications_not_configured" });
|
|
185
|
+
});
|
|
186
|
+
});
|