@cloudlet/toast 1.3.0 → 1.4.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 (54) hide show
  1. package/CHANGELOG.md +128 -0
  2. package/README.md +27 -1
  3. package/dist/agent.d.ts +334 -0
  4. package/dist/agent.d.ts.map +1 -0
  5. package/dist/agent.js +494 -0
  6. package/dist/agent.js.map +1 -0
  7. package/dist/contracts/events.d.ts +14 -0
  8. package/dist/contracts/events.d.ts.map +1 -1
  9. package/dist/contracts/internal.d.ts +16 -2
  10. package/dist/contracts/internal.d.ts.map +1 -1
  11. package/dist/contracts/notifications.d.ts +16 -0
  12. package/dist/contracts/notifications.d.ts.map +1 -1
  13. package/dist/contracts/snapshots.d.ts +8 -0
  14. package/dist/contracts/snapshots.d.ts.map +1 -1
  15. package/dist/core/actions.d.ts +69 -0
  16. package/dist/core/actions.d.ts.map +1 -0
  17. package/dist/core/actions.js +160 -0
  18. package/dist/core/actions.js.map +1 -0
  19. package/dist/core/agent-port.d.ts +116 -0
  20. package/dist/core/agent-port.d.ts.map +1 -0
  21. package/dist/core/agent-port.js +138 -0
  22. package/dist/core/agent-port.js.map +1 -0
  23. package/dist/core/bridge.d.ts.map +1 -1
  24. package/dist/core/bridge.js +120 -231
  25. package/dist/core/bridge.js.map +1 -1
  26. package/dist/core/controller.d.ts +44 -9
  27. package/dist/core/controller.d.ts.map +1 -1
  28. package/dist/core/controller.js +367 -292
  29. package/dist/core/controller.js.map +1 -1
  30. package/dist/core/validation.d.ts.map +1 -1
  31. package/dist/core/validation.js +103 -94
  32. package/dist/core/validation.js.map +1 -1
  33. package/dist/react/card.d.ts.map +1 -1
  34. package/dist/react/card.js +3 -3
  35. package/dist/react/card.js.map +1 -1
  36. package/dist/react/host.d.ts.map +1 -1
  37. package/dist/react/host.js +257 -246
  38. package/dist/react/host.js.map +1 -1
  39. package/dist/react.d.ts +7 -0
  40. package/dist/react.d.ts.map +1 -1
  41. package/package.json +2 -1
  42. package/src/agent.ts +879 -0
  43. package/src/contracts/events.ts +15 -0
  44. package/src/contracts/internal.ts +14 -1
  45. package/src/contracts/notifications.ts +16 -0
  46. package/src/contracts/snapshots.ts +8 -0
  47. package/src/core/actions.ts +149 -0
  48. package/src/core/agent-port.ts +237 -0
  49. package/src/core/bridge.ts +19 -105
  50. package/src/core/controller.ts +183 -56
  51. package/src/core/validation.ts +6 -3
  52. package/src/react/card.tsx +4 -3
  53. package/src/react/host.tsx +26 -3
  54. package/src/react.ts +7 -0
package/dist/agent.js ADDED
@@ -0,0 +1,494 @@
1
+ import { createToasterPort as e } from "./core/agent-port.js";
2
+ //#region src/agent.ts
3
+ var t = Object.freeze, n = t([]), r = JSON.stringify, i = /* @__PURE__ */ new Set([
4
+ "open",
5
+ "close",
6
+ "clear",
7
+ "acknowledge"
8
+ ]), a = /* @__PURE__ */ new Set([
9
+ "dismiss",
10
+ "show",
11
+ "press",
12
+ "fill",
13
+ "submit",
14
+ "cancel",
15
+ "retry"
16
+ ]), o = t({
17
+ toaster: t({
18
+ open: "No arguments. Opens the Island on the notification it shows first. Needs a mounted Toaster; refused while the person is using it.",
19
+ close: "No arguments. Closes the open Island; refused while it holds a form the person or an agent started filling.",
20
+ clear: "No arguments. Closes every notification at once.",
21
+ acknowledge: "No arguments. Marks the notifications that did not fit as seen: overflow.pending turns false."
22
+ }),
23
+ notification: t({
24
+ dismiss: "No arguments. Closes this notification; its record leaves the snapshot.",
25
+ show: "No arguments. Opens the Island on this notification. Needs a mounted Toaster; refused while the person is using it.",
26
+ press: "No arguments. Runs the command action (action.kind \"command\") and waits for it: success closes the notification, result \"pending\" means it is still working. Under action.agent \"confirm\" it may need a person to approve. A link action has no verb: the bridge never opens it; its address is action.href.",
27
+ fill: "args [field name, text]: the field's name from action.fields[].name, not its label, and a string. Writes the field as the agent; never over text the person typed.",
28
+ submit: "No arguments. Sends the form action (action.kind \"form\") and waits for it: success closes the notification, result \"pending\" means it is still working. Under action.agent \"confirm\" it may need a person to approve. A refusal names the fields that were not accepted.",
29
+ cancel: "No arguments. Asks the running operation to stop; result \"requested\".",
30
+ retry: "No arguments. Starts the failed operation again; result \"started\"."
31
+ })
32
+ }), s = {
33
+ allow: 0,
34
+ confirm: 1,
35
+ deny: 2
36
+ }, c = t({ status: "done" }), l = t({
37
+ status: "done",
38
+ gone: !0
39
+ }), u = t({ status: "stale" }), d = t({ status: "unavailable" }), f = "Not accepted by the form's own check", p = "Action failed", m = {
40
+ noScreen: (e) => `No Toaster is on screen: ${r(e)} needs one.`,
41
+ noArguments: (e) => `${r(e.action)} on ${r(e.ref)} takes no arguments.`,
42
+ fillArguments: (e) => `${r(e.action)} on ${r(e.ref)} takes a field name and a value.`,
43
+ noField: (e, t, n) => `No field ${r(t)} on ${r(e.ref)}. Fields: ${n.map((e) => r(e)).join(", ")}.`,
44
+ notText: (e) => `The value for ${r(e)} must be a string.`,
45
+ tooLong: (e, t) => `${r(e)} takes at most ${t} characters.`,
46
+ personTyped: (e) => `The person typed in ${r(e)}. An agent can't overwrite it.`,
47
+ notSent: (e, t) => `${r(e)} was not sent. ${t}`,
48
+ running: (e) => `${r(e)} is already running.`,
49
+ failed: (e, t) => `${r(e)} failed: ${t}`,
50
+ finished: "This operation has already finished.",
51
+ cancelRequested: "Cancelling this operation was already requested.",
52
+ notCancellable: "This operation can't be cancelled.",
53
+ stillRunning: "This operation is still running, so it can't be retried yet.",
54
+ notRetryable: "This operation can't be retried.",
55
+ busy: "The person is using the Island. Try again later.",
56
+ islandOpen: "The Island is open on it.",
57
+ islandLater: "The Island will open on it once they stop using it.",
58
+ noToaster: "No Toaster is on screen, so tell them what it does."
59
+ }, h = /* @__PURE__ */ new Map(), g = t({ available: !1 }), _ = (e) => t({
60
+ available: !1,
61
+ message: e
62
+ }), v = (e) => t({
63
+ available: !0,
64
+ permission: "allow",
65
+ perform: e
66
+ }), y = (e, n, r = {}) => {
67
+ if (e.status !== "rejected") return n;
68
+ let i = e.reason === void 0 ? void 0 : r[e.reason];
69
+ return i === void 0 ? d : t({
70
+ status: "unavailable",
71
+ message: i
72
+ });
73
+ };
74
+ function b(r, f) {
75
+ let b = f?.name ?? "toaster", C = e(r), w = /* @__PURE__ */ new WeakMap(), T = 0, E = (e) => {
76
+ let t = w.get(e);
77
+ return t === void 0 && w.set(e, t = `${b}:${++T}`), t;
78
+ }, D = /* @__PURE__ */ new Map(), O = null, k = 0, A = /* @__PURE__ */ new Set(), j, M, N = n, P = /* @__PURE__ */ new Map(), F = () => {
79
+ let e = C.read();
80
+ if (e === M) return N;
81
+ M = e;
82
+ let r = e.controller;
83
+ if (r.disposed) return P = /* @__PURE__ */ new Map(), N = n;
84
+ let i = new Map(r.notifications.map((e) => [e.handle, e])), a = r.island, o = r.stack.length, s = /* @__PURE__ */ new Map(), c = r.stack.map((t) => {
85
+ let n = i.get(t), r = S(n, E(t), a.open && a.current === t, e.mounted, e.forms.get(t));
86
+ return s.set(r.ref, {
87
+ item: n,
88
+ entry: r
89
+ }), r;
90
+ });
91
+ return P = s, N = t([t({
92
+ ref: b,
93
+ component: "toaster",
94
+ actions: t([
95
+ ...!a.open && o > 0 && e.mounted ? ["open"] : [],
96
+ ...a.open ? ["close"] : [],
97
+ ...o > 0 ? ["clear"] : [],
98
+ ...r.overflow.pending ? ["acknowledge"] : []
99
+ ]),
100
+ island: t({
101
+ open: a.open,
102
+ current: a.current ? E(a.current) : null
103
+ }),
104
+ count: o,
105
+ overflow: t({
106
+ count: r.overflow.count,
107
+ pending: r.overflow.pending
108
+ }),
109
+ mounted: e.mounted
110
+ }), ...c]);
111
+ }, I = (e) => {
112
+ let n = F(), r = M?.mounted ?? !1, { action: o } = e;
113
+ if (e.ref === b && n.length) {
114
+ if (!i.has(o)) return g;
115
+ if (e.args.length) return _(m.noArguments(e));
116
+ if (o === "open" && !r) return _(m.noScreen(o));
117
+ if (!n[0].actions.includes(o)) return g;
118
+ if (o === "open" && M.busy || o === "close" && L()) return _(m.busy);
119
+ switch (o) {
120
+ case "open": return v(() => y(C.open(), c, {
121
+ "no-host": m.noScreen(o),
122
+ busy: m.busy
123
+ }));
124
+ case "close": return v(() => y(C.close(), c, { busy: m.busy }));
125
+ case "clear": return v(() => y(C.clear(), c));
126
+ default: return v(() => y(C.acknowledge(), c));
127
+ }
128
+ }
129
+ let s = P.get(e.ref);
130
+ if (!s || !a.has(o)) return g;
131
+ let { item: u, entry: d } = s;
132
+ if (o === "fill") return R(e, u);
133
+ if (e.args.length) return _(m.noArguments(e));
134
+ let { handle: f } = u;
135
+ switch (o) {
136
+ case "show":
137
+ if (!r) return _(m.noScreen(o));
138
+ break;
139
+ case "press": {
140
+ let e = u.content.action;
141
+ return e?.kind === "command" ? z(u, e) : g;
142
+ }
143
+ case "submit": {
144
+ let e = u.content.action;
145
+ return e?.kind === "form" ? z(u, e) : g;
146
+ }
147
+ case "cancel": {
148
+ let e = u.operation;
149
+ if (!e) return g;
150
+ if (e.status !== "pending") return _(m.finished);
151
+ if (e.cancelRequested) return _(m.cancelRequested);
152
+ if (!e.canCancel) return _(m.notCancellable);
153
+ break;
154
+ }
155
+ case "retry": {
156
+ let e = u.operation;
157
+ if (!e) return g;
158
+ if (e.status === "pending") return _(m.stillRunning);
159
+ if (!e.canRetry) return _(m.notRetryable);
160
+ break;
161
+ }
162
+ }
163
+ if (!d.actions.includes(o)) return g;
164
+ if (o === "show" && M.busy) return _(m.busy);
165
+ switch (o) {
166
+ case "show": return v(() => y(C.show(f), c, {
167
+ "no-host": m.noScreen(o),
168
+ busy: m.busy
169
+ }));
170
+ case "dismiss": return v(() => y(C.dismiss(f), l));
171
+ case "cancel": return v(() => {
172
+ let e = C.cancel(f);
173
+ return e.status === "requested" ? t({
174
+ status: "done",
175
+ result: "requested"
176
+ }) : y(e.status === "unchanged" ? {
177
+ status: "rejected",
178
+ reason: e.reason
179
+ } : e, c, {
180
+ settled: m.finished,
181
+ "already-requested": m.cancelRequested,
182
+ "not-cancellable": m.notCancellable
183
+ });
184
+ });
185
+ default: return v(() => y(C.retry(f), t({
186
+ status: "done",
187
+ result: "started"
188
+ }), {
189
+ "already-pending": m.stillRunning,
190
+ "not-retryable": m.notRetryable
191
+ }));
192
+ }
193
+ }, L = () => {
194
+ let e = M.controller, t = e.island.current;
195
+ return t !== null && e.notifications.some((e) => e.handle === t && e.draft);
196
+ }, R = (e, t) => {
197
+ let n = t.content.action;
198
+ if (n?.kind !== "form") return g;
199
+ let [r, i] = e.args;
200
+ if (e.args.length !== 2 || typeof r != "string") return _(m.fillArguments(e));
201
+ let a = n.fields.find((e) => e.name === r);
202
+ if (!a) return _(m.noField(e, r, n.fields.map((e) => e.name)));
203
+ if (typeof i != "string") return _(m.notText(a.label));
204
+ let o = {
205
+ "already-pending": m.running(n.label),
206
+ "too-long": m.tooLong(a.label, a.maxLength ?? 0),
207
+ "person-typed": m.personTyped(a.label)
208
+ };
209
+ return t.action.status === "pending" ? _(o["already-pending"]) : a.maxLength !== void 0 && i.length > a.maxLength ? _(o["too-long"]) : M.forms.get(t.handle)?.authors.get(r) === "user" ? _(o["person-typed"]) : v(() => y(C.fill(t.handle, r, i), c, o));
210
+ }, z = (e, n) => {
211
+ let { label: r } = n, i = n.agent ?? "confirm", a = t({
212
+ target: r,
213
+ within: e.content.title
214
+ });
215
+ return i !== "deny" && e.action.status === "pending" ? _(m.running(r)) : t({
216
+ available: !0,
217
+ permission: i,
218
+ names: a,
219
+ subject: n,
220
+ async perform({ signal: i, approved: a }) {
221
+ let o = C.press(e.handle, a, i);
222
+ if (!(o instanceof Promise)) return o.reason === "stale" ? u : y(o, c, { "already-pending": m.running(r) });
223
+ let s = await o;
224
+ return s.status === "done" ? l : s.status === "replaced" ? u : s.status === "failed" ? t({
225
+ status: "failed",
226
+ message: m.failed(r, n.kind === "form" ? p : s.message)
227
+ }) : s.status === "invalid" ? t({
228
+ status: "failed",
229
+ message: m.notSent(r, x(n, s.errors))
230
+ }) : t({
231
+ status: "done",
232
+ result: "pending",
233
+ ...s.gone ? { gone: !0 } : {}
234
+ });
235
+ }
236
+ });
237
+ }, B = /* @__PURE__ */ new WeakMap(), V = (e) => {
238
+ let n = I(e);
239
+ return n.available ? (n.subject && B.set(e, n.subject), t({
240
+ available: !0,
241
+ permission: n.permission,
242
+ ...n.names ? { names: n.names } : {}
243
+ })) : n;
244
+ }, H = (e, n) => {
245
+ let r = I(e);
246
+ if (!r.available) return r.message === void 0 ? d : t({
247
+ status: "unavailable",
248
+ message: r.message
249
+ });
250
+ if (s[r.permission] > s[n.approved]) return u;
251
+ let i = B.get(e);
252
+ return i !== void 0 && i !== r.subject ? u : r.perform(n);
253
+ }, U = (e) => {
254
+ F();
255
+ let n = P.get(e.ref);
256
+ if (!n) return !1;
257
+ let r = C.summon(n.item.handle);
258
+ return r.status === "rejected" ? r.reason === "no-host" && t({
259
+ reached: !1,
260
+ note: m.noToaster
261
+ }) : t({
262
+ reached: !0,
263
+ note: r.status === "waiting" ? m.islandLater : m.islandOpen
264
+ });
265
+ }, W = (e) => {
266
+ let r = e.controller;
267
+ if (r.revision <= k) return n;
268
+ let { events: i } = e, a = new Map(r.notifications.map((e) => [e.handle, e]));
269
+ for (let [e, t] of D) {
270
+ let n = a.get(e);
271
+ n && (t.label = n.content.title);
272
+ }
273
+ let o = [], s = /* @__PURE__ */ new Map(), c = (e, n, r, i, a, s) => {
274
+ let c = D.get(e)?.label;
275
+ o.push(t({
276
+ ref: E(e),
277
+ component: "notification",
278
+ ...c === void 0 ? {} : { label: c },
279
+ key: n,
280
+ value: r,
281
+ previous: i,
282
+ ...s === void 0 ? {} : { reason: s },
283
+ source: a
284
+ }));
285
+ };
286
+ for (let n of i) switch (n.type) {
287
+ case "admitted":
288
+ E(n.handle), D.set(n.handle, {
289
+ label: a.get(n.handle)?.content.title,
290
+ action: "idle",
291
+ operation: null,
292
+ authors: e.authors.get(n.handle) ?? h
293
+ }), c(n.handle, "present", !0, !1, n.source);
294
+ break;
295
+ case "closed":
296
+ c(n.handle, "present", !1, !0, n.source, n.reason), D.delete(n.handle);
297
+ break;
298
+ case "updated":
299
+ s.set(n.handle, n.source), c(n.handle, "content", null, null, n.source);
300
+ break;
301
+ case "action-started":
302
+ case "action-failed": {
303
+ let e = D.get(n.handle);
304
+ if (!e) break;
305
+ let t = n.type === "action-started" ? "pending" : "failed";
306
+ c(n.handle, "action", t, e.action, n.source), e.action = t;
307
+ break;
308
+ }
309
+ case "operation-started": {
310
+ let e = n.handle && D.get(n.handle);
311
+ if (!e) break;
312
+ s.set(n.handle, n.source), c(n.handle, "operation", "pending", e.operation?.value ?? null, n.source), e.operation = {
313
+ token: n.token,
314
+ value: "pending"
315
+ };
316
+ break;
317
+ }
318
+ case "cancellation-requested":
319
+ case "operation-settled": {
320
+ let e = n.handle && D.get(n.handle);
321
+ if (!e || e.operation?.token !== n.token) break;
322
+ n.type === "operation-settled" && s.set(n.handle, n.source);
323
+ let t = n.type === "operation-settled" ? n.status : "cancel-requested";
324
+ c(n.handle, "operation", t, e.operation.value, n.source), e.operation.value = t;
325
+ break;
326
+ }
327
+ case "overflow-acknowledged": o.push(t({
328
+ ref: b,
329
+ component: "toaster",
330
+ key: "overflow",
331
+ value: 0,
332
+ previous: n.count,
333
+ source: n.source
334
+ }));
335
+ }
336
+ for (let [t, n] of D) {
337
+ let r = a.get(t);
338
+ if (!r) continue;
339
+ let i = s.get(t);
340
+ r.action.status === "idle" && n.action !== "idle" && (c(t, "action", "idle", n.action, i ?? "system"), n.action = "idle");
341
+ let o = e.authors.get(t) ?? h;
342
+ if (o !== n.authors) {
343
+ let e = r.content.action, a = e?.kind === "form" ? e.fields.map((e) => e.name) : [];
344
+ for (let e of /* @__PURE__ */ new Set([
345
+ ...a,
346
+ ...n.authors.keys(),
347
+ ...o.keys()
348
+ ])) {
349
+ let r = o.get(e) ?? null, a = n.authors.get(e) ?? null;
350
+ r !== a && c(t, `field:${e}`, r, a, r ?? i ?? "app");
351
+ }
352
+ n.authors = o;
353
+ }
354
+ }
355
+ let l = r.island.current ? E(r.island.current) : null;
356
+ return l !== O && (o.push(t({
357
+ ref: b,
358
+ component: "toaster",
359
+ key: "island",
360
+ value: l,
361
+ previous: O,
362
+ source: r.island.source ?? e.closedBy ?? "system"
363
+ })), O = l), t(o);
364
+ };
365
+ return t({
366
+ protocol: 1,
367
+ name: b,
368
+ snapshot: F,
369
+ subscribe: (e) => {
370
+ let t = (t) => {
371
+ e(t);
372
+ };
373
+ if (!A.size) {
374
+ F();
375
+ let e = C.read(), t = e.controller;
376
+ D.clear();
377
+ for (let n of t.notifications) {
378
+ let t = n.operation;
379
+ D.set(n.handle, {
380
+ label: n.content.title,
381
+ action: n.action.status,
382
+ operation: t ? {
383
+ token: t.token,
384
+ value: t.status === "pending" && t.cancelRequested ? "cancel-requested" : t.status
385
+ } : null,
386
+ authors: e.forms.get(n.handle)?.authors ?? h
387
+ });
388
+ }
389
+ O = t.island.current ? E(t.island.current) : null, k = t.revision, j = C.subscribe((e) => {
390
+ let t = W(e), n;
391
+ for (let e of [...A]) if (A.has(e)) try {
392
+ e(t);
393
+ } catch (e) {
394
+ n ??= { error: e };
395
+ }
396
+ if (n) throw n.error;
397
+ });
398
+ }
399
+ return A.add(t), () => {
400
+ A.delete(t) && !A.size && (j?.(), j = void 0, D.clear());
401
+ };
402
+ },
403
+ check: V,
404
+ run: H,
405
+ summon: U,
406
+ verbs: o
407
+ });
408
+ }
409
+ function x(e, t) {
410
+ if (t.broken) return `${p}.`;
411
+ if (t.authored) {
412
+ let n = e.fields.flatMap((e) => Object.hasOwn(t.fields, e.name) ? [r(e.label)] : []);
413
+ return `The form's own check did not accept ${n.length ? n.join(", ") : "it"}.`;
414
+ }
415
+ let n = (e) => /[.!?]$/.test(e.trim()) ? e.trim() : `${e.trim()}.`;
416
+ return [...e.fields.flatMap((e) => Object.hasOwn(t.fields, e.name) ? [`${r(e.label)}: ${n(t.fields[e.name])}`] : []), ...t.form ? [n(t.form)] : []].join(" ");
417
+ }
418
+ function S(e, n, r, i, a) {
419
+ let { content: o } = e, s = o.description, c = o.progress, l = e.operation, u = C(e, a), d = e.action.status !== "pending", f = d && u?.agent !== "deny";
420
+ return t({
421
+ ref: n,
422
+ component: "notification",
423
+ actions: t([
424
+ "dismiss",
425
+ ...!r && i ? ["show"] : [],
426
+ ...u?.kind === "command" && f ? ["press"] : [],
427
+ ...u?.kind === "form" && d ? ["fill"] : [],
428
+ ...u?.kind === "form" && f ? ["submit"] : [],
429
+ ...l?.canCancel ? ["cancel"] : [],
430
+ ...l?.canRetry ? ["retry"] : []
431
+ ]),
432
+ label: o.title,
433
+ text: s ? s.kind === "text" ? s.text : s.announcement : null,
434
+ kind: e.kind,
435
+ priority: e.priority,
436
+ occurrences: e.occurrences,
437
+ location: e.location,
438
+ remainingMs: e.remainingMs,
439
+ pauseReasons: t([...e.pauseReasons]),
440
+ progress: c ? t({
441
+ kind: c.kind,
442
+ value: c.kind === "determinate" ? c.value : null,
443
+ label: c.label ?? null
444
+ }) : null,
445
+ draft: e.draft,
446
+ operation: l ? t({
447
+ status: l.status,
448
+ attempt: l.attempt,
449
+ canCancel: l.canCancel,
450
+ canRetry: l.canRetry,
451
+ cancelRequested: l.cancelRequested
452
+ }) : null,
453
+ action: u
454
+ });
455
+ }
456
+ function C(e, n) {
457
+ let r = e.content.action;
458
+ if (!r) return null;
459
+ let i = e.action, a = {
460
+ kind: r.kind,
461
+ label: r.label,
462
+ status: i.status,
463
+ message: i.status === "failed" ? r.kind === "form" ? p : i.message : null
464
+ };
465
+ if (r.kind === "link") return t({
466
+ ...a,
467
+ href: r.href
468
+ });
469
+ if (r.kind === "command") return t({
470
+ ...a,
471
+ agent: r.agent ?? "confirm"
472
+ });
473
+ let o = n?.errors;
474
+ return t({
475
+ ...a,
476
+ agent: r.agent ?? "confirm",
477
+ fields: t(r.fields.map((e) => t({
478
+ name: e.name,
479
+ label: e.label,
480
+ kind: e.kind,
481
+ required: e.required ?? !1,
482
+ maxLength: e.maxLength ?? null,
483
+ inputMode: e.inputMode ?? null,
484
+ filled: n?.filled.has(e.name) ?? !1,
485
+ filledBy: n?.authors.get(e.name) ?? null,
486
+ error: o && Object.hasOwn(o.fields, e.name) ? o.authored ? f : o.fields[e.name] : null
487
+ }))),
488
+ error: o?.form ? o.broken ? p : o.authored ? f : o.form : null
489
+ });
490
+ }
491
+ //#endregion
492
+ export { b as toasterAgent };
493
+
494
+ //# sourceMappingURL=agent.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent.js","names":["freeze","EMPTY","quote","TOASTER_VERBS","NOTIFICATION_VERBS","VERBS","STRICTNESS","DONE","GONE","STALE","UNAVAILABLE","FORM_REJECTED","FORM_FAILED","texts","action","step","name","names","item","field","limit","label","messages","message","NO_AUTHORS","NOT_AVAILABLE","refuse","allowed","outcome","result","done","words","toasterAgent","options","port","createToasterPort","controller","refs","issued","refOf","ref","handle","known","islandRef","seeded","listeners","stop","source","entries","targets","snapshot","reading","state","byHandle","island","count","found","notifications","entry","notification","plan","current","mounted","holdsDraft","target","fillPlan","command","pressPlan","form","operation","value","candidate","permission","started","approved","signal","ended","describe","checked","check","verdict","run","context","subject","summon","collect","commit","live","changes","touched","push","reason","by","event","events","next","authors","previous","own","failure","each","error","errors","labels","sentence","description","content","progress","actionEntry","ready","may","shown","common"],"sources":["../src/agent.ts"],"sourcesContent":["import type { CloudletController } from './contracts/controller.js';\nimport type { ChangeSource } from './contracts/events.js';\nimport type { NotificationHandle } from './contracts/identity.js';\nimport type { FormErrors } from './contracts/internal.js';\nimport type { CommandAction, FormAction, FormFieldKind, FormInputMode, NotificationKind, Priority } from './contracts/notifications.js';\nimport type { CancellationSignal, OperationStatus } from './contracts/operations.js';\nimport type { NotificationLocation, NotificationSnapshot, PauseReason } from './contracts/snapshots.js';\nimport { createToasterPort, type FormReading, type PortCommit, type ToasterReading } from './core/agent-port.js';\n\n// The Toaster's side of the agent bridge. Its protocol types are declared here structurally:\n// this package never imports the bridge package, not even its types.\n\n/**\n * One record of an agent snapshot, as the bridge reads it.\n *\n * @experimental The protocol may change before the bridge reaches 1.0.\n */\nexport type AgentEntryShape = {\n readonly ref: string;\n readonly component: string;\n readonly actions: readonly string[];\n readonly [key: string]: unknown;\n};\n\n/**\n * A cancellation signal as the bridge hands it out; an `AbortSignal` at runtime.\n *\n * @experimental The protocol may change before the bridge reaches 1.0.\n */\nexport interface AgentSignalShape {\n readonly aborted: boolean;\n readonly reason: unknown;\n readonly throwIfAborted: () => void;\n readonly addEventListener: (type: 'abort', listener: () => void, options?: { readonly once?: boolean }) => void;\n readonly removeEventListener: (type: 'abort', listener: () => void) => void;\n}\n\n/**\n * A value a step may return to the agent.\n *\n * @experimental The protocol may change before the bridge reaches 1.0.\n */\nexport type AgentValueShape = string | number | boolean | null | readonly AgentValueShape[] | { readonly [key: string]: AgentValueShape };\n\n/**\n * What a step may do: on its own, with approval, or never.\n *\n * @experimental The protocol may change before the bridge reaches 1.0.\n */\nexport type AgentPermissionShape = 'allow' | 'confirm' | 'deny';\n\n/**\n * A step as the bridge hands it to a component.\n *\n * @experimental The protocol may change before the bridge reaches 1.0.\n */\nexport interface AgentStepCallShape {\n readonly ref: string;\n readonly action: string;\n readonly args: readonly unknown[];\n}\n\n/**\n * How a person names what a step acts on, for the bridge's messages.\n *\n * @experimental The protocol may change before the bridge reaches 1.0.\n */\nexport interface AgentStepNamesShape {\n readonly target: string;\n readonly within?: string;\n}\n\n/**\n * A component's answer to the bridge's `check`.\n *\n * @experimental The protocol may change before the bridge reaches 1.0.\n */\nexport type AgentStepCheckShape =\n | { readonly available: true; readonly permission: AgentPermissionShape; readonly names?: AgentStepNamesShape }\n | { readonly available: false; readonly message?: string };\n\n/**\n * What the bridge's `run` receives besides the step.\n *\n * @experimental The protocol may change before the bridge reaches 1.0.\n */\nexport interface AgentRunContextShape {\n readonly signal: AgentSignalShape;\n readonly approved: 'allow' | 'confirm';\n}\n\n/**\n * A component's answer to the bridge's `run`.\n *\n * @experimental The protocol may change before the bridge reaches 1.0.\n */\nexport type AgentRunOutcomeShape =\n | { readonly status: 'done'; readonly result?: AgentValueShape; readonly gone?: boolean }\n | { readonly status: 'failed'; readonly message: string }\n | { readonly status: 'unavailable'; readonly message?: string }\n | { readonly status: 'stale' };\n\n/**\n * A component's answer to the bridge's `summon`.\n *\n * @experimental The protocol may change before the bridge reaches 1.0.\n */\nexport type AgentSummonOutcomeShape = boolean | { readonly reached: boolean; readonly note: string };\n\n/**\n * One change a component reports to the bridge's subscribers: what changed on which record and who\n * changed it.\n *\n * @experimental The protocol may change before the bridge reaches 1.0.\n */\nexport interface AgentChangeShape {\n readonly ref: string;\n readonly component: string;\n readonly label?: string;\n readonly key: string;\n readonly value: AgentValueShape;\n readonly previous: AgentValueShape;\n readonly reason?: string;\n readonly source: 'user' | 'agent' | 'app' | 'system';\n}\n\n/**\n * What a component's verbs do, by kind of record: each verb with a line or two for an agent.\n *\n * @experimental The protocol may change before the bridge reaches 1.0.\n */\nexport interface AgentVerbsShape {\n readonly [component: string]: { readonly [verb: string]: string };\n}\n\n/**\n * What a component hands to the bridge's `connect`. `check` and `run` come together, `summon` is\n * optional, and a read-only component leaves all three out.\n *\n * @experimental The protocol may change before the bridge reaches 1.0.\n */\nexport interface AgentComponentShape<Entry extends AgentEntryShape = AgentEntryShape> {\n readonly protocol: 1;\n readonly name: string;\n snapshot(): readonly Entry[];\n subscribe(listener: (changes?: readonly AgentChangeShape[]) => void): () => void;\n readonly check?: (step: AgentStepCallShape) => AgentStepCheckShape;\n readonly run?: (step: AgentStepCallShape, context: AgentRunContextShape) => AgentRunOutcomeShape | PromiseLike<AgentRunOutcomeShape>;\n readonly summon?: (step: AgentStepCallShape) => AgentSummonOutcomeShape;\n readonly verbs?: AgentVerbsShape;\n}\n\n/**\n * The Toaster's own record: the Island, the count and the overflow.\n *\n * @experimental The protocol may change before the bridge reaches 1.0.\n */\nexport type ToasterEntry = {\n readonly ref: string;\n readonly component: 'toaster';\n /** `open`, `close`, `clear`, `acknowledge`, by state. */\n readonly actions: readonly string[];\n readonly island: {\n readonly open: boolean;\n /** `ref` of the notification the open Island shows; null while closed. */\n readonly current: string | null;\n };\n readonly count: number;\n readonly overflow: { readonly count: number; readonly pending: boolean };\n /** A mounted `Toaster` renders this controller. */\n readonly mounted: boolean;\n};\n\n/**\n * A form field as a reader sees it. Its value, default and placeholder stay inside Cloudlet.\n *\n * @experimental The protocol may change before the bridge reaches 1.0.\n */\nexport type FormFieldEntry = {\n readonly name: string;\n readonly label: string;\n readonly kind: FormFieldKind;\n readonly required: boolean;\n /** null when the field sets no limit. */\n readonly maxLength: number | null;\n /** null when the field sets no input mode. */\n readonly inputMode: FormInputMode | null;\n /** The field holds non-blank text. */\n readonly filled: boolean;\n /**\n * Who wrote the value last: `app` (the field's default), `user` (the person) or `agent`; null\n * while nobody has and there is no default. An agent can't `fill` a field the person wrote.\n */\n readonly filledBy: 'app' | 'user' | 'agent' | null;\n /**\n * Why the last submit stopped at this field, if it did: the built-in message for a required or\n * too long field, and a fixed phrase when the form's own `validate` did not accept it, because\n * that text may quote what the person typed.\n */\n readonly error: string | null;\n};\n\n/**\n * A notification's primary action.\n *\n * @experimental The protocol may change before the bridge reaches 1.0.\n */\nexport type ActionEntry = {\n readonly kind: 'command' | 'link' | 'form';\n /** The label the application gave the action. */\n readonly label: string;\n readonly status: 'idle' | 'pending' | 'failed';\n /**\n * Why the last attempt failed; null unless `status` is `failed`. For a form it is always\n * `Action failed`: the app's own text may quote what the person typed.\n */\n readonly message: string | null;\n /**\n * What the app lets an agent do with a command or a form: `allow`, `confirm` (a person approves)\n * or `deny`. `confirm` when the app set nothing; absent for a link.\n */\n readonly agent?: 'allow' | 'confirm' | 'deny';\n /** Only for a link. */\n readonly href?: string;\n /** Only for a form. */\n readonly fields?: readonly FormFieldEntry[];\n /**\n * Set when the last submit stopped on the form as a whole; only for a form. A fixed phrase when\n * the form's own `validate` said so, for the same reason as a field's `error`.\n */\n readonly error?: string | null;\n};\n\n/**\n * A notification's operation, without its attempt token.\n *\n * @experimental The protocol may change before the bridge reaches 1.0.\n */\nexport type OperationEntry = {\n readonly status: OperationStatus;\n readonly attempt: number;\n readonly canCancel: boolean;\n readonly canRetry: boolean;\n readonly cancelRequested: boolean;\n};\n\n/**\n * One notification, in presentation order.\n *\n * @experimental The protocol may change before the bridge reaches 1.0.\n */\nexport type NotificationEntry = {\n readonly ref: string;\n readonly component: 'notification';\n /** `dismiss`, `show` (with a mounted `Toaster`), `press`, `fill`, `submit`, `cancel`, `retry`, by state. */\n readonly actions: readonly string[];\n /** The title. */\n readonly label: string;\n /** The description as text; for rich content, its announcement. */\n readonly text: string | null;\n readonly kind: NotificationKind;\n readonly priority: Priority;\n readonly occurrences: number;\n readonly location: NotificationLocation;\n readonly remainingMs: number | null;\n readonly pauseReasons: readonly PauseReason[];\n readonly progress: { readonly kind: 'indeterminate' | 'determinate'; readonly value: number | null; readonly label: string | null } | null;\n readonly draft: boolean;\n readonly operation: OperationEntry | null;\n readonly action: ActionEntry | null;\n};\n\n/** @experimental The protocol may change before the bridge reaches 1.0. */\nexport type ToasterAgentEntry = ToasterEntry | NotificationEntry;\n\n/**\n * What {@link toasterAgent} returns: pass it to the bridge's `connect`.\n *\n * @experimental The protocol may change before the bridge reaches 1.0.\n */\nexport interface ToasterAgent extends AgentComponentShape<ToasterAgentEntry> {\n /** The same frozen array until the controller changes; empty after `dispose`. */\n snapshot(): readonly ToasterAgentEntry[];\n /**\n * Calls `listener` after every change of the controller with what changed and who changed it.\n * On a notification's record: `present` (`true` when it appears, `false` when it closes, with\n * the close reason in `reason`), `content` (the app updated it; both values are null), `action`\n * (`idle`, `pending`, `failed`), `operation` (`pending`, `cancel-requested`, `fulfilled`,\n * `rejected`, `cancelled`) and `field:<name>` (who wrote the form field last: `app`, `user`,\n * `agent` or null; only when the author changes, and never the text). On the Toaster's record:\n * `island` (the `ref` of the notification it shows, or null) and `overflow` (the missed count\n * after it was acknowledged). `label` is the notification's title. The array is empty when the\n * snapshot changed with no author, such as a pause.\n */\n subscribe(listener: (changes?: readonly AgentChangeShape[]) => void): () => void;\n /** Whether a step is available now and the class it needs; no side effects. */\n readonly check: (step: AgentStepCallShape) => AgentStepCheckShape;\n /** Reads the controller again and runs the step, unless it changed since it was approved. */\n readonly run: (step: AgentStepCallShape, context: AgentRunContextShape) => AgentRunOutcomeShape | PromiseLike<AgentRunOutcomeShape>;\n /**\n * Opens the Island on the step's notification for a person, at once or once they stop using the\n * Toaster, without moving focus, and says which in `note`.\n */\n readonly summon: (step: AgentStepCallShape) => AgentSummonOutcomeShape;\n /** What each verb of the `toaster` and `notification` records does, for an agent. */\n readonly verbs: AgentVerbsShape;\n}\n\n/** @experimental The protocol may change before the bridge reaches 1.0. */\nexport interface ToasterAgentOptions {\n /** The component's name and the prefix of its refs; matches `[a-z][a-z0-9-]*`. Default `toaster`. */\n readonly name?: string;\n}\n\nconst freeze = Object.freeze;\nconst EMPTY: readonly never[] = freeze([]);\nconst quote = JSON.stringify;\nconst TOASTER_VERBS: ReadonlySet<string> = new Set(['open', 'close', 'clear', 'acknowledge']);\nconst NOTIFICATION_VERBS: ReadonlySet<string> = new Set(['dismiss', 'show', 'press', 'fill', 'submit', 'cancel', 'retry']);\n// For an agent that has never seen this code: arguments in order, what the step does, when it\n// needs a person. One entry for every verb a record can list.\nconst VERBS: AgentVerbsShape = freeze({\n toaster: freeze({\n open: 'No arguments. Opens the Island on the notification it shows first. Needs a mounted Toaster; refused while the person is using it.',\n close: 'No arguments. Closes the open Island; refused while it holds a form the person or an agent started filling.',\n clear: 'No arguments. Closes every notification at once.',\n acknowledge: 'No arguments. Marks the notifications that did not fit as seen: overflow.pending turns false.',\n }),\n notification: freeze({\n dismiss: 'No arguments. Closes this notification; its record leaves the snapshot.',\n show: 'No arguments. Opens the Island on this notification. Needs a mounted Toaster; refused while the person is using it.',\n press: 'No arguments. Runs the command action (action.kind \"command\") and waits for it: success closes the notification, result \"pending\" means it is still working. Under action.agent \"confirm\" it may need a person to approve. A link action has no verb: the bridge never opens it; its address is action.href.',\n fill: 'args [field name, text]: the field\\'s name from action.fields[].name, not its label, and a string. Writes the field as the agent; never over text the person typed.',\n submit: 'No arguments. Sends the form action (action.kind \"form\") and waits for it: success closes the notification, result \"pending\" means it is still working. Under action.agent \"confirm\" it may need a person to approve. A refusal names the fields that were not accepted.',\n cancel: 'No arguments. Asks the running operation to stop; result \"requested\".',\n retry: 'No arguments. Starts the failed operation again; result \"started\".',\n }),\n});\nconst STRICTNESS = { allow: 0, confirm: 1, deny: 2 } as const;\nconst DONE: AgentRunOutcomeShape = freeze({ status: 'done' });\nconst GONE: AgentRunOutcomeShape = freeze({ status: 'done', gone: true });\nconst STALE: AgentRunOutcomeShape = freeze({ status: 'stale' });\nconst UNAVAILABLE: AgentRunOutcomeShape = freeze({ status: 'unavailable' });\n\n// A form's `validate` and `errorMessage` see what the person typed and may quote it, so their\n// text stays with the person in the Island: an agent reads these instead.\nconst FORM_REJECTED = \"Not accepted by the form's own check\";\nconst FORM_FAILED = 'Action failed';\n\n// Refusals the adapter words itself; the bridge words the rest from the record's `actions`.\n// Labels and titles come from the app, so they are quoted.\nconst texts = {\n noScreen: (action: string) => `No Toaster is on screen: ${quote(action)} needs one.`,\n noArguments: (step: AgentStepCallShape) => `${quote(step.action)} on ${quote(step.ref)} takes no arguments.`,\n fillArguments: (step: AgentStepCallShape) => `${quote(step.action)} on ${quote(step.ref)} takes a field name and a value.`,\n noField: (step: AgentStepCallShape, name: string, names: readonly string[]) =>\n `No field ${quote(name)} on ${quote(step.ref)}. Fields: ${names.map((item) => quote(item)).join(', ')}.`,\n notText: (field: string) => `The value for ${quote(field)} must be a string.`,\n tooLong: (field: string, limit: number) => `${quote(field)} takes at most ${limit} characters.`,\n personTyped: (field: string) => `The person typed in ${quote(field)}. An agent can't overwrite it.`,\n notSent: (label: string, messages: string) => `${quote(label)} was not sent. ${messages}`,\n running: (label: string) => `${quote(label)} is already running.`,\n failed: (label: string, message: string) => `${quote(label)} failed: ${message}`,\n finished: 'This operation has already finished.',\n cancelRequested: 'Cancelling this operation was already requested.',\n notCancellable: \"This operation can't be cancelled.\",\n stillRunning: \"This operation is still running, so it can't be retried yet.\",\n notRetryable: \"This operation can't be retried.\",\n busy: 'The person is using the Island. Try again later.',\n islandOpen: 'The Island is open on it.',\n islandLater: 'The Island will open on it once they stop using it.',\n noToaster: 'No Toaster is on screen, so tell them what it does.',\n};\n\n/** A step as the adapter sees it right now: refused, or allowed under a class with a way to run it. */\ntype Plan =\n | { readonly available: false; readonly message?: string }\n | {\n readonly available: true;\n readonly permission: AgentPermissionShape;\n readonly names?: AgentStepNamesShape;\n /** The action object a press or a submit would run. */\n readonly subject?: object;\n readonly perform: (context: AgentRunContextShape) => AgentRunOutcomeShape | Promise<AgentRunOutcomeShape>;\n };\n\nconst NO_AUTHORS: FormReading['authors'] = new Map();\nconst NOT_AVAILABLE: Plan = freeze({ available: false });\nconst refuse = (message: string): Plan => freeze({ available: false, message });\nconst allowed = (perform: () => AgentRunOutcomeShape): Plan => freeze({ available: true, permission: 'allow', perform });\ntype PortResult = { readonly status: string; readonly reason?: string };\n/** A port refusal after the plan said yes: the state changed in between, so the step is unavailable. */\nconst outcome = (result: PortResult, done: AgentRunOutcomeShape, words: Readonly<Record<string, string>> = {}): AgentRunOutcomeShape => {\n if (result.status !== 'rejected') return done;\n const message = result.reason === undefined ? undefined : words[result.reason];\n return message === undefined ? UNAVAILABLE : freeze({ status: 'unavailable', message });\n};\n\n/**\n * Lets an agent read and drive a controller through the kit's agent bridge:\n * `agent.connect(toasterAgent(controller))`. It touches no DOM, starts no timers, never takes the\n * host from a `Toaster` and never moves focus. Form values never reach the snapshot.\n *\n * Steps: `open`, `close`, `clear` and `acknowledge` on the Toaster record; `show`, `dismiss`,\n * `press`, `fill`, `submit`, `cancel` and `retry` on a notification. `open` and `show` need a\n * mounted `Toaster`. `press` and `submit` follow the action's `agent` marker; every other step is\n * allowed unless the bridge's `allow` says no. `fill` (`args: [name, value]`) writes a form field\n * as the agent, never over what the person typed, and makes a draft as typing does; the snapshot\n * says who wrote each field (`filledBy`), never what. A press or submit that needs a person opens\n * the Island on its notification for them: at once, or after the attention delay once they stop\n * using the Toaster. While they use it (hover, focus, a gesture, a draft in the open Island, the\n * agent's own included), `open` and `show` are refused, and so is `close` over a draft.\n *\n * @throws TypeError for a controller that this copy of `@cloudlet/toast` did not create.\n * @experimental The protocol may change before the bridge reaches 1.0.\n */\nexport function toasterAgent<Slot, Signal extends CancellationSignal>(\n controller: Omit<CloudletController<Slot, Signal>, 'track'>,\n options?: ToasterAgentOptions,\n): ToasterAgent {\n const name = options?.name ?? 'toaster';\n const port = createToasterPort<Slot>(controller);\n // A number per handle, so a closed notification's ref is never handed to another one.\n const refs = new WeakMap<NotificationHandle, string>();\n let issued = 0;\n const refOf = (handle: NotificationHandle): string => {\n let ref = refs.get(handle);\n if (ref === undefined) refs.set(handle, ref = `${name}:${++issued}`);\n return ref;\n };\n // What the last change records said about each open notification, kept while someone listens.\n type Known = {\n label: string | undefined;\n action: 'idle' | 'pending' | 'failed';\n operation: { readonly token: string; value: string } | null;\n authors: FormReading['authors'];\n };\n const known = new Map<NotificationHandle, Known>();\n let islandRef: string | null = null;\n // The revision `known` was read at; a commit up to it is already in there.\n let seeded = 0;\n const listeners = new Set<(changes?: readonly AgentChangeShape[]) => void>();\n let stop: (() => void) | undefined;\n let source: ToasterReading<Slot> | undefined;\n let entries: readonly ToasterAgentEntry[] = EMPTY;\n // The notifications of the current snapshot by ref, for steps.\n let targets: ReadonlyMap<string, { readonly item: NotificationSnapshot<Slot>; readonly entry: NotificationEntry }> = new Map();\n\n const snapshot = (): readonly ToasterAgentEntry[] => {\n const reading = port.read();\n if (reading === source) return entries;\n source = reading;\n const state = reading.controller;\n if (state.disposed) { targets = new Map(); return entries = EMPTY; }\n const byHandle = new Map(state.notifications.map((item) => [item.handle, item] as const));\n const island = state.island;\n const count = state.stack.length;\n const found = new Map<string, { readonly item: NotificationSnapshot<Slot>; readonly entry: NotificationEntry }>();\n // Refs are issued in presentation order, so the top notification gets the lower number.\n const notifications = state.stack.map((handle) => {\n const item = byHandle.get(handle)!;\n const entry = notification(item, refOf(handle), island.open && island.current === handle, reading.mounted, reading.forms.get(handle));\n found.set(entry.ref, { item, entry });\n return entry;\n });\n targets = found;\n const toaster: ToasterEntry = freeze({\n ref: name, component: 'toaster' as const,\n actions: freeze([\n ...(!island.open && count > 0 && reading.mounted ? ['open'] : []),\n ...(island.open ? ['close'] : []),\n ...(count > 0 ? ['clear'] : []),\n ...(state.overflow.pending ? ['acknowledge'] : []),\n ]),\n island: freeze({ open: island.open, current: island.current ? refOf(island.current) : null }),\n count,\n overflow: freeze({ count: state.overflow.count, pending: state.overflow.pending }),\n mounted: reading.mounted,\n });\n return entries = freeze([toaster, ...notifications]);\n };\n\n /** Reads the step against the controller as it is now; `check` and `run` both start here. */\n const plan = (step: AgentStepCallShape): Plan => {\n const current = snapshot();\n const mounted = source?.mounted ?? false;\n const { action } = step;\n if (step.ref === name && current.length) {\n if (!TOASTER_VERBS.has(action)) return NOT_AVAILABLE;\n if (step.args.length) return refuse(texts.noArguments(step));\n if (action === 'open' && !mounted) return refuse(texts.noScreen(action));\n if (!current[0]!.actions.includes(action)) return NOT_AVAILABLE;\n // A busy person is not interrupted; only a draft stops `close`, which a person's Escape would collapse.\n if (action === 'open' && source!.busy) return refuse(texts.busy);\n if (action === 'close' && holdsDraft()) return refuse(texts.busy);\n switch (action) {\n case 'open': return allowed(() => outcome(port.open(), DONE, { 'no-host': texts.noScreen(action), busy: texts.busy }));\n case 'close': return allowed(() => outcome(port.close(), DONE, { busy: texts.busy }));\n case 'clear': return allowed(() => outcome(port.clear(), DONE));\n default: return allowed(() => outcome(port.acknowledge(), DONE));\n }\n }\n const target = targets.get(step.ref);\n if (!target || !NOTIFICATION_VERBS.has(action)) return NOT_AVAILABLE;\n const { item, entry } = target;\n if (action === 'fill') return fillPlan(step, item);\n if (step.args.length) return refuse(texts.noArguments(step));\n const { handle } = item;\n switch (action) {\n case 'show':\n if (!mounted) return refuse(texts.noScreen(action));\n break;\n case 'press': {\n const command = item.content.action;\n return command?.kind === 'command' ? pressPlan(item, command) : NOT_AVAILABLE;\n }\n case 'submit': {\n const form = item.content.action;\n return form?.kind === 'form' ? pressPlan(item, form) : NOT_AVAILABLE;\n }\n case 'cancel': {\n const operation = item.operation;\n if (!operation) return NOT_AVAILABLE;\n if (operation.status !== 'pending') return refuse(texts.finished);\n if (operation.cancelRequested) return refuse(texts.cancelRequested);\n if (!operation.canCancel) return refuse(texts.notCancellable);\n break;\n }\n case 'retry': {\n const operation = item.operation;\n if (!operation) return NOT_AVAILABLE;\n if (operation.status === 'pending') return refuse(texts.stillRunning);\n if (!operation.canRetry) return refuse(texts.notRetryable);\n break;\n }\n }\n if (!entry.actions.includes(action)) return NOT_AVAILABLE;\n if (action === 'show' && source!.busy) return refuse(texts.busy);\n switch (action) {\n case 'show': return allowed(() => outcome(port.show(handle), DONE, { 'no-host': texts.noScreen(action), busy: texts.busy }));\n case 'dismiss': return allowed(() => outcome(port.dismiss(handle), GONE));\n case 'cancel': return allowed(() => {\n const result = port.cancel(handle);\n return result.status === 'requested' ? freeze({ status: 'done', result: 'requested' })\n : outcome(result.status === 'unchanged' ? { status: 'rejected', reason: result.reason } : result, DONE, {\n settled: texts.finished, 'already-requested': texts.cancelRequested, 'not-cancellable': texts.notCancellable,\n });\n });\n default: return allowed(() => outcome(port.retry(handle), freeze({ status: 'done', result: 'started' }), {\n 'already-pending': texts.stillRunning, 'not-retryable': texts.notRetryable,\n }));\n }\n };\n\n /** The open Island shows a notification whose form holds a draft. */\n const holdsDraft = (): boolean => {\n const state = source!.controller;\n const current = state.island.current;\n return current !== null && state.notifications.some((item) => item.handle === current && item.draft);\n };\n\n // An agent's value goes in like a person's keystrokes, except over what the person typed. The\n // step's text names the field, never a value.\n const fillPlan = (step: AgentStepCallShape, item: NotificationSnapshot<Slot>): Plan => {\n const form = item.content.action;\n if (form?.kind !== 'form') return NOT_AVAILABLE;\n const [name, value] = step.args;\n if (step.args.length !== 2 || typeof name !== 'string') return refuse(texts.fillArguments(step));\n const field = form.fields.find((candidate) => candidate.name === name);\n if (!field) return refuse(texts.noField(step, name, form.fields.map((candidate) => candidate.name)));\n if (typeof value !== 'string') return refuse(texts.notText(field.label));\n const words = {\n 'already-pending': texts.running(form.label),\n 'too-long': texts.tooLong(field.label, field.maxLength ?? 0),\n 'person-typed': texts.personTyped(field.label),\n };\n if (item.action.status === 'pending') return refuse(words['already-pending']);\n if (field.maxLength !== undefined && value.length > field.maxLength) return refuse(words['too-long']);\n if (source!.forms.get(item.handle)?.authors.get(name) === 'user') return refuse(words['person-typed']);\n return allowed(() => outcome(port.fill(item.handle, name, value), DONE, words));\n };\n\n /** A command's press or a form's submit: both follow the action's marker and wait for its run. */\n const pressPlan = (item: NotificationSnapshot<Slot>, action: CommandAction | FormAction): Plan => {\n const { label } = action;\n const permission = action.agent ?? 'confirm';\n const names = freeze({ target: label, within: item.content.title });\n // A denied press never runs, so it is reported before its state.\n if (permission !== 'deny' && item.action.status === 'pending') return refuse(texts.running(label));\n return freeze({\n available: true, permission, names, subject: action,\n async perform({ signal, approved }: AgentRunContextShape): Promise<AgentRunOutcomeShape> {\n const started = port.press(item.handle, approved, signal);\n if (!(started instanceof Promise)) {\n return started.reason === 'stale' ? STALE : outcome(started, DONE, { 'already-pending': texts.running(label) });\n }\n const ended = await started;\n if (ended.status === 'done') return GONE;\n if (ended.status === 'replaced') return STALE;\n if (ended.status === 'failed') return freeze({ status: 'failed', message: texts.failed(label, action.kind === 'form' ? FORM_FAILED : ended.message) });\n if (ended.status === 'invalid') return freeze({ status: 'failed', message: texts.notSent(label, describe(action as FormAction, ended.errors)) });\n return freeze({ status: 'done', result: 'pending', ...(ended.gone ? { gone: true } : {}) });\n },\n });\n };\n\n // What a checked press or submit would have run, by step object: the bridge approves a step by\n // its ref and verb, so the action it named to the app or the person is held here until it runs.\n const checked = new WeakMap<AgentStepCallShape, object>();\n\n const check = (step: AgentStepCallShape): AgentStepCheckShape => {\n const verdict = plan(step);\n if (!verdict.available) return verdict;\n if (verdict.subject) checked.set(step, verdict.subject);\n return freeze({ available: true, permission: verdict.permission, ...(verdict.names ? { names: verdict.names } : {}) });\n };\n\n // The bridge approved the step under `approved`; the controller is read again before anything runs.\n const run = (step: AgentStepCallShape, context: AgentRunContextShape): AgentRunOutcomeShape | Promise<AgentRunOutcomeShape> => {\n const verdict = plan(step);\n if (!verdict.available) return verdict.message === undefined ? UNAVAILABLE : freeze({ status: 'unavailable', message: verdict.message });\n if (STRICTNESS[verdict.permission] > STRICTNESS[context.approved]) return STALE;\n // The app replaced the action while the step waited: the approval was for the other one.\n const subject = checked.get(step);\n if (subject !== undefined && subject !== verdict.subject) return STALE;\n return verdict.perform(context);\n };\n\n // A step only a person may take: the Island opens on its notification for them, through the\n // attention queue, so a person busy with the Toaster is not interrupted.\n const summon = (step: AgentStepCallShape): AgentSummonOutcomeShape => {\n snapshot();\n const target = targets.get(step.ref);\n if (!target) return false;\n const result = port.summon(target.item.handle);\n if (result.status === 'rejected') return result.reason === 'no-host' ? freeze({ reached: false, note: texts.noToaster }) : false;\n return freeze({ reached: true, note: result.status === 'waiting' ? texts.islandLater : texts.islandOpen });\n };\n\n /**\n * The records of one committed change: its events in order, then what only the state shows (an\n * action back to idle, a field's new author, the Island). A form's values are never read here.\n */\n const collect = (commit: PortCommit<Slot>): readonly AgentChangeShape[] => {\n // The commit's own state, not the latest: a listener before this one may have committed again.\n const state = commit.controller;\n // Subscribed while this commit was still queued: what it did was read then.\n if (state.revision <= seeded) return EMPTY;\n const { events } = commit;\n const live = new Map(state.notifications.map((item) => [item.handle, item] as const));\n for (const [handle, entry] of known) {\n const item = live.get(handle);\n if (item) entry.label = item.content.title;\n }\n const changes: AgentChangeShape[] = [];\n // Who changed a notification's content in this commit: the author of what follows from it.\n const touched = new Map<NotificationHandle, ChangeSource>();\n const push = (handle: NotificationHandle, key: string, value: AgentValueShape, previous: AgentValueShape, by: ChangeSource, reason?: string): void => {\n const label = known.get(handle)?.label;\n changes.push(freeze({\n ref: refOf(handle), component: 'notification', ...(label === undefined ? {} : { label }), key, value, previous,\n ...(reason === undefined ? {} : { reason }), source: by,\n }));\n };\n for (const event of events) {\n switch (event.type) {\n case 'admitted': {\n // The number is issued here, so a notification closed before anyone reads still has one.\n refOf(event.handle);\n known.set(event.handle, {\n label: live.get(event.handle)?.content.title, action: 'idle', operation: null,\n authors: commit.authors.get(event.handle) ?? NO_AUTHORS,\n });\n push(event.handle, 'present', true, false, event.source);\n break;\n }\n case 'closed':\n push(event.handle, 'present', false, true, event.source, event.reason);\n known.delete(event.handle);\n break;\n case 'updated':\n touched.set(event.handle, event.source);\n push(event.handle, 'content', null, null, event.source);\n break;\n case 'action-started':\n case 'action-failed': {\n const entry = known.get(event.handle);\n if (!entry) break;\n const next = event.type === 'action-started' ? 'pending' : 'failed';\n push(event.handle, 'action', next, entry.action, event.source);\n entry.action = next;\n break;\n }\n case 'operation-started': {\n const entry = event.handle && known.get(event.handle);\n if (!entry) break;\n touched.set(event.handle!, event.source);\n push(event.handle!, 'operation', 'pending', entry.operation?.value ?? null, event.source);\n entry.operation = { token: event.token, value: 'pending' };\n break;\n }\n case 'cancellation-requested':\n case 'operation-settled': {\n const entry = event.handle && known.get(event.handle);\n // An attempt that a newer one replaced no longer speaks for the notification.\n if (!entry || entry.operation?.token !== event.token) break;\n if (event.type === 'operation-settled') touched.set(event.handle!, event.source);\n const next = event.type === 'operation-settled' ? event.status : 'cancel-requested';\n push(event.handle!, 'operation', next, entry.operation.value, event.source);\n entry.operation.value = next;\n break;\n }\n case 'overflow-acknowledged':\n changes.push(freeze({ ref: name, component: 'toaster', key: 'overflow', value: 0, previous: event.count, source: event.source }));\n break;\n }\n }\n for (const [handle, entry] of known) {\n // A notification missing here closed in a later commit; its own records follow.\n const item = live.get(handle);\n if (!item) continue;\n const by = touched.get(handle);\n if (item.action.status === 'idle' && entry.action !== 'idle') {\n push(handle, 'action', 'idle', entry.action, by ?? 'system');\n entry.action = 'idle';\n }\n const authors = commit.authors.get(handle) ?? NO_AUTHORS;\n if (authors !== entry.authors) {\n // In the form's own order; a field of the form that was replaced comes after them.\n const action = item.content.action;\n const names = action?.kind === 'form' ? action.fields.map((field) => field.name) : [];\n for (const field of new Set([...names, ...entry.authors.keys(), ...authors.keys()])) {\n const next = authors.get(field) ?? null;\n const previous = entry.authors.get(field) ?? null;\n // A new author is the source; a field emptied with its form was replaced by the app.\n if (next !== previous) push(handle, `field:${field}`, next, previous, next ?? by ?? 'app');\n }\n entry.authors = authors;\n }\n }\n const current = state.island.current ? refOf(state.island.current) : null;\n if (current !== islandRef) {\n changes.push(freeze({\n ref: name, component: 'toaster', key: 'island', value: current, previous: islandRef,\n source: state.island.source ?? commit.closedBy ?? 'system',\n }));\n islandRef = current;\n }\n return freeze(changes);\n };\n\n const subscribe = (listener: (changes?: readonly AgentChangeShape[]) => void): (() => void) => {\n // The same function may subscribe twice; each subscription is removed on its own.\n const own = (changes?: readonly AgentChangeShape[]): void => { listener(changes); };\n if (!listeners.size) {\n // Refs of what is already there are issued as a snapshot does, top first.\n snapshot();\n const reading = port.read();\n const state = reading.controller;\n known.clear();\n for (const item of state.notifications) {\n const operation = item.operation;\n known.set(item.handle, {\n label: item.content.title, action: item.action.status,\n operation: operation ? { token: operation.token, value: operation.status === 'pending' && operation.cancelRequested ? 'cancel-requested' : operation.status } : null,\n authors: reading.forms.get(item.handle)?.authors ?? NO_AUTHORS,\n });\n }\n islandRef = state.island.current ? refOf(state.island.current) : null;\n seeded = state.revision;\n stop = port.subscribe((commit) => {\n const changes = collect(commit);\n // Every listener hears the change; the first error goes on to the controller's diagnostics.\n let failure: { readonly error: unknown } | undefined;\n for (const each of [...listeners]) {\n if (!listeners.has(each)) continue;\n try { each(changes); } catch (error) { failure ??= { error }; }\n }\n if (failure) throw failure.error;\n });\n }\n listeners.add(own);\n return () => {\n if (!listeners.delete(own) || listeners.size) return;\n stop?.();\n stop = undefined;\n known.clear();\n };\n };\n\n return freeze({ protocol: 1 as const, name, snapshot, subscribe, check, run, summon, verbs: VERBS });\n}\n\n/**\n * Why a form was not sent, by field label and never with a value: the built-in messages as the\n * person sees them, and for the app's own `validate` only which fields it did not accept.\n */\nfunction describe(form: FormAction, errors: FormErrors): string {\n if (errors.broken) return `${FORM_FAILED}.`;\n if (errors.authored) {\n // Own keys only, as below.\n const labels = form.fields.flatMap((field) => Object.hasOwn(errors.fields, field.name) ? [quote(field.label)] : []);\n return `The form's own check did not accept ${labels.length ? labels.join(', ') : 'it'}.`;\n }\n const sentence = (message: string) => /[.!?]$/.test(message.trim()) ? message.trim() : `${message.trim()}.`;\n return [\n // Own keys only: a field named `constructor` must not read `Object.prototype`.\n ...form.fields.flatMap((field) => Object.hasOwn(errors.fields, field.name) ? [`${quote(field.label)}: ${sentence(errors.fields[field.name]!)}`] : []),\n ...(errors.form ? [sentence(errors.form)] : []),\n ].join(' ');\n}\n\nfunction notification<Slot>(item: NotificationSnapshot<Slot>, ref: string, shown: boolean, mounted: boolean, form: FormReading | undefined): NotificationEntry {\n const { content } = item;\n const description = content.description;\n const progress = content.progress;\n const operation = item.operation;\n const action = actionEntry(item, form);\n // `deny` stops pressing and submitting only: a person can still submit what an agent filled.\n const ready = item.action.status !== 'pending';\n const may = ready && action?.agent !== 'deny';\n return freeze({\n ref, component: 'notification' as const,\n actions: freeze([\n 'dismiss',\n ...(!shown && mounted ? ['show'] : []),\n ...(action?.kind === 'command' && may ? ['press'] : []),\n ...(action?.kind === 'form' && ready ? ['fill'] : []),\n ...(action?.kind === 'form' && may ? ['submit'] : []),\n ...(operation?.canCancel ? ['cancel'] : []),\n ...(operation?.canRetry ? ['retry'] : []),\n ]),\n label: content.title,\n text: description ? description.kind === 'text' ? description.text : description.announcement : null,\n kind: item.kind,\n priority: item.priority,\n occurrences: item.occurrences,\n location: item.location,\n remainingMs: item.remainingMs,\n pauseReasons: freeze([...item.pauseReasons]),\n progress: progress ? freeze({\n kind: progress.kind,\n value: progress.kind === 'determinate' ? progress.value : null,\n label: progress.label ?? null,\n }) : null,\n draft: item.draft,\n operation: operation ? freeze({\n status: operation.status, attempt: operation.attempt, canCancel: operation.canCancel,\n canRetry: operation.canRetry, cancelRequested: operation.cancelRequested,\n }) : null,\n action,\n });\n}\n\nfunction actionEntry<Slot>(item: NotificationSnapshot<Slot>, form: FormReading | undefined): ActionEntry | null {\n const action = item.content.action;\n if (!action) return null;\n const state = item.action;\n const common = {\n kind: action.kind, label: action.label, status: state.status,\n message: state.status !== 'failed' ? null : action.kind === 'form' ? FORM_FAILED : state.message,\n };\n if (action.kind === 'link') return freeze({ ...common, href: action.href });\n if (action.kind === 'command') return freeze({ ...common, agent: action.agent ?? 'confirm' });\n const errors = form?.errors;\n return freeze({\n ...common,\n agent: action.agent ?? 'confirm',\n fields: freeze(action.fields.map((field) => freeze({\n name: field.name, label: field.label, kind: field.kind, required: field.required ?? false,\n maxLength: field.maxLength ?? null, inputMode: field.inputMode ?? null,\n filled: form?.filled.has(field.name) ?? false,\n filledBy: form?.authors.get(field.name) ?? null,\n // Own keys only: a field named `constructor` must not read `Object.prototype`.\n error: errors && Object.hasOwn(errors.fields, field.name) ? errors.authored ? FORM_REJECTED : errors.fields[field.name]! : null,\n }))),\n error: errors?.form ? errors.broken ? FORM_FAILED : errors.authored ? FORM_REJECTED : errors.form : null,\n });\n}\n"],"mappings":";;AA0TA,IAAMA,IAAS,OAAO,QAChBC,IAA0BD,EAAO,CAAC,CAAC,GACnCE,IAAQ,KAAK,WACbC,oBAAqC,IAAI,IAAI;CAAC;CAAQ;CAAS;CAAS;AAAa,CAAC,GACtFC,oBAA0C,IAAI,IAAI;CAAC;CAAW;CAAQ;CAAS;CAAQ;CAAU;CAAU;AAAO,CAAC,GAGnHC,IAAyBL,EAAO;CACpC,SAASA,EAAO;EACd,MAAM;EACN,OAAO;EACP,OAAO;EACP,aAAa;CACf,CAAC;CACD,cAAcA,EAAO;EACnB,SAAS;EACT,MAAM;EACN,OAAO;EACP,MA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KAAK;GACxC,UAAUiD,GAAM,QAAQ,IAAIjD,EAAM,IAAI,KAAK;GAE3C,OAAOmF,KAAU,OAAO,OAAOA,EAAO,QAAQnF,EAAM,IAAI,IAAImF,EAAO,WAAW3F,IAAgB2F,EAAO,OAAOnF,EAAM,QAAS;EAC7H,CAAC,CAAC,CAAC;EACH,OAAOmF,GAAQ,OAAOA,EAAO,SAAS1F,IAAc0F,EAAO,WAAW3F,IAAgB2F,EAAO,OAAO;CACtG,CAAC;AACH"}
@@ -9,8 +9,22 @@ export interface Diagnostic {
9
9
  readonly handle?: NotificationHandle;
10
10
  readonly error?: unknown;
11
11
  }
12
+ /**
13
+ * Who caused a change.
14
+ *
15
+ * - `user`: a person, through the `Toaster` on screen: a click, a swipe, a key.
16
+ * - `agent`: a step an agent took through `@cloudlet/toast/agent`.
17
+ * - `app`: the application's own code, through the controller or an operation handle.
18
+ * - `system`: Cloudlet itself: a timer, the outcome of an operation, `dispose()`.
19
+ */
20
+ export type ChangeSource = 'user' | 'agent' | 'app' | 'system';
12
21
  export interface EventBase {
13
22
  readonly controller: ControllerIdentity;
23
+ /**
24
+ * Who caused the event. Both outcomes of an action attempt carry the source of whoever pressed
25
+ * it, however long the action ran; the outcome of an operation is always `system`.
26
+ */
27
+ readonly source: ChangeSource;
14
28
  readonly sequence: number;
15
29
  /** Monotonic milliseconds, not wall-clock time. */
16
30
  readonly at: number;