@northtalk/ts 0.0.0-stage → 0.1.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.
@@ -0,0 +1,341 @@
1
+ import { E as listValues, V as text, c as bool, i as ScriptError, k as map, t as HostError } from "./errors-DHwz1Vho.js";
2
+ import { Q as sizeOf, t as encodeValue, ut as compareText } from "./encoding-DWlbPq-e.js";
3
+ import { t as sha256 } from "./sha256-0jiTgVJu.js";
4
+ import { n as hostScriptError } from "./store-capability-CDoVafZL.js";
5
+ //#region src/notify/router.ts
6
+ /**
7
+ * Whether a commit changed a key's value: compared by the bytes of the Value
8
+ * Encoding, with a missing key and Nothing one state (Net changes).
9
+ */
10
+ const changed = (before, after) => encoded(before) !== encoded(after);
11
+ const encoded = (v) => v === void 0 || v.kind === "nothing" ? void 0 : encodeValue(v);
12
+ const HEADER = "northtalk notify checkpoint 1\n";
13
+ const payloadOf = (w, keys, resync) => map([
14
+ ["grant", text(w.grant)],
15
+ ["watch", text(w.name)],
16
+ ["prefix", text(w.prefix)],
17
+ ["keys", listValues(keys.map((k) => text(k)))],
18
+ ["resync", bool(resync)]
19
+ ]);
20
+ const textSize = (s) => sizeOf(text(s));
21
+ const watchSize = (w) => textSize(w.name) + textSize(w.prefix) + textSize(w.message);
22
+ const markerSize = (w) => sizeOf(payloadOf(w, [], true));
23
+ const label = (w) => `${w.script}.${w.grant}.${w.name}`;
24
+ const invalidCheckpoint = (detail) => {
25
+ throw new HostError("invalid checkpoint", detail);
26
+ };
27
+ const createRouter = (o) => {
28
+ const groups = /* @__PURE__ */ new Map();
29
+ const stores = /* @__PURE__ */ new Map();
30
+ let ranks = 0;
31
+ const ownerOf = (w, group, script, grant) => w.group === group && w.script === script && w.grant === grant;
32
+ const find = (group, script, grant, name) => {
33
+ for (const w of groups.get(group)?.watches ?? []) if (ownerOf(w, group, script, grant) && w.name === name) return w;
34
+ };
35
+ const order = (watches) => {
36
+ const loads = /* @__PURE__ */ new Map();
37
+ const loadIndex = (group, script) => {
38
+ let names = loads.get(group);
39
+ if (!names) {
40
+ names = new Map(group.scriptNames().map((n, i) => [n, i]));
41
+ loads.set(group, names);
42
+ }
43
+ return names.get(script) ?? names.size;
44
+ };
45
+ return [...watches].sort((a, b) => groups.get(a.group).rank - groups.get(b.group).rank || loadIndex(a.group, a.script) - loadIndex(b.group, b.script) || compareText(a.grant, b.grant) || compareText(a.name, b.name));
46
+ };
47
+ const after = (group, a, p) => {
48
+ const names = group.scriptNames();
49
+ const index = (s) => {
50
+ const i = names.indexOf(s);
51
+ return i < 0 ? names.length : i;
52
+ };
53
+ return (index(a.script) - index(p.script) || compareText(a.grant, p.grant) || compareText(a.name, p.name)) > 0;
54
+ };
55
+ const add = (w) => {
56
+ let state = groups.get(w.group);
57
+ if (!state) {
58
+ state = {
59
+ rank: ranks++,
60
+ watches: /* @__PURE__ */ new Set()
61
+ };
62
+ groups.set(w.group, state);
63
+ }
64
+ state.watches.add(w);
65
+ let watches = stores.get(w.store);
66
+ if (!watches) {
67
+ watches = /* @__PURE__ */ new Set();
68
+ stores.set(w.store, watches);
69
+ }
70
+ watches.add(w);
71
+ };
72
+ const remove = (w) => {
73
+ const state = groups.get(w.group);
74
+ if (state?.watches.delete(w) && !state.watches.size) groups.delete(w.group);
75
+ stores.get(w.store)?.delete(w);
76
+ };
77
+ const totals = (store, without) => {
78
+ let watches = 0;
79
+ let size = 0;
80
+ let pending = 0;
81
+ let pendingSize = 0;
82
+ for (const w of stores.get(store) ?? []) if (w !== without) {
83
+ watches++;
84
+ size += watchSize(w);
85
+ pending += 1 + w.held.length;
86
+ pendingSize += markerSize(w) + w.heldSize;
87
+ }
88
+ return {
89
+ watches,
90
+ size,
91
+ pending,
92
+ pendingSize
93
+ };
94
+ };
95
+ const deliver = (w, payload) => {
96
+ const script = w.group.script(w.script);
97
+ if (!script) return "refused";
98
+ try {
99
+ script.deliver({
100
+ name: w.message,
101
+ args: [payload]
102
+ });
103
+ o.admitted?.(w.group);
104
+ return "admitted";
105
+ } catch (error) {
106
+ return error?.name === "MailboxFull" ? "full" : "refused";
107
+ }
108
+ };
109
+ const hold = (w, keys, payload) => {
110
+ const size = sizeOf(payload);
111
+ const limits = o.limits(w.store);
112
+ const now = totals(w.store);
113
+ if (now.pending + 1 > limits.pending || now.pendingSize + size > limits.pendingSize) {
114
+ w.held = [];
115
+ w.heldSize = 0;
116
+ w.resyncing = true;
117
+ return;
118
+ }
119
+ w.held.push({
120
+ keys,
121
+ size
122
+ });
123
+ w.heldSize += size;
124
+ };
125
+ const drain = (w) => {
126
+ while (w.resyncing || w.held.length) {
127
+ const outcome = deliver(w, payloadOf(w, w.resyncing ? [] : w.held[0].keys, w.resyncing));
128
+ if (outcome === "full") return;
129
+ if (outcome === "refused") {
130
+ remove(w);
131
+ return;
132
+ }
133
+ if (w.resyncing) w.resyncing = false;
134
+ else w.heldSize -= w.held.shift().size;
135
+ }
136
+ };
137
+ const hasWork = (w) => w.resyncing || w.held.length > 0;
138
+ return {
139
+ watch(call, name, prefix, message) {
140
+ const store = call.binding;
141
+ const existing = find(call.group, call.scriptName, call.grantName, name);
142
+ if (existing?.prefix === prefix && existing.message === message) return;
143
+ const limits = o.limits(store);
144
+ const now = totals(store, existing);
145
+ const next = {
146
+ name,
147
+ prefix,
148
+ message
149
+ };
150
+ const marker = markerSize({
151
+ grant: call.grantName,
152
+ ...next
153
+ });
154
+ const limit = now.watches + 1 > limits.watches ? "watches" : now.size + watchSize(next) > limits.watchSize ? "size" : now.pending + 1 > limits.pending || now.pendingSize + marker > limits.pendingSize ? "pending" : void 0;
155
+ if (limit) throw watchLimit(limit);
156
+ if (existing) {
157
+ existing.prefix = prefix;
158
+ existing.message = message;
159
+ existing.held = [];
160
+ existing.heldSize = 0;
161
+ existing.resyncing = false;
162
+ return;
163
+ }
164
+ add({
165
+ group: call.group,
166
+ script: call.scriptName,
167
+ grant: call.grantName,
168
+ store,
169
+ ...next,
170
+ held: [],
171
+ heldSize: 0,
172
+ resyncing: false
173
+ });
174
+ },
175
+ unwatch(call, name) {
176
+ const w = find(call.group, call.scriptName, call.grantName, name);
177
+ if (w) remove(w);
178
+ },
179
+ release(context) {
180
+ for (const w of groups.get(context.group)?.watches ?? []) if (ownerOf(w, context.group, context.scriptName, context.grantName)) remove(w);
181
+ },
182
+ commit(store, apply) {
183
+ const keys = [...new Set(apply())].sort(compareText);
184
+ if (!keys.length) return;
185
+ for (const w of order(stores.get(store) ?? [])) {
186
+ const matched = keys.filter((k) => k.startsWith(w.prefix));
187
+ if (!matched.length || w.resyncing) continue;
188
+ const payload = payloadOf(w, matched, false);
189
+ if (w.held.length) {
190
+ hold(w, matched, payload);
191
+ continue;
192
+ }
193
+ const outcome = deliver(w, payload);
194
+ if (outcome === "full") hold(w, matched, payload);
195
+ else if (outcome === "refused") remove(w);
196
+ }
197
+ },
198
+ pumped(group) {
199
+ const state = groups.get(group);
200
+ if (!state) return false;
201
+ const waiting = order(state.watches).filter(hasWork);
202
+ if (!waiting.length) return false;
203
+ const retry = state.retry;
204
+ const start = retry ? Math.max(0, waiting.findIndex((w) => after(group, w, retry))) : 0;
205
+ const round = [...waiting.slice(start), ...waiting.slice(0, start)];
206
+ const first = round[0];
207
+ state.retry = {
208
+ script: first.script,
209
+ grant: first.grant,
210
+ name: first.name
211
+ };
212
+ for (const w of round) drain(w);
213
+ return [...groups.get(group)?.watches ?? []].some(hasWork);
214
+ },
215
+ detach(group) {
216
+ for (const w of groups.get(group)?.watches ?? []) remove(w);
217
+ },
218
+ save(group) {
219
+ const bytes = group.save();
220
+ const state = groups.get(group);
221
+ const watches = order(state?.watches ?? []);
222
+ const routing = {
223
+ digest: sha256(bytes),
224
+ ...state?.retry ? { retry: state.retry } : {},
225
+ revisions: Object.fromEntries([...new Set(watches.map((w) => w.store))].sort(compareText).map((store) => [store, o.revision(store)])),
226
+ watches: watches.map((w) => ({
227
+ script: w.script,
228
+ grant: w.grant,
229
+ name: w.name,
230
+ store: w.store,
231
+ prefix: w.prefix,
232
+ message: w.message,
233
+ resyncing: w.resyncing,
234
+ held: w.held.map((h) => [...h.keys])
235
+ }))
236
+ };
237
+ const head = new TextEncoder().encode(HEADER + JSON.stringify(routing) + "\n");
238
+ const checkpoint = new Uint8Array(head.length + bytes.length);
239
+ checkpoint.set(head);
240
+ checkpoint.set(bytes, head.length);
241
+ return checkpoint;
242
+ },
243
+ restore(core, checkpoint, options) {
244
+ const { routing, save } = readCheckpoint(checkpoint);
245
+ const { group, result } = core.restore(save, options);
246
+ const out = {
247
+ restored: [],
248
+ dropped: [],
249
+ resynced: []
250
+ };
251
+ if (result.variablesOnly) return {
252
+ group,
253
+ result,
254
+ routing: out
255
+ };
256
+ const restored = [];
257
+ const dropped = [];
258
+ for (const saved of routing.watches) {
259
+ const w = {
260
+ group,
261
+ script: saved.script,
262
+ grant: saved.grant,
263
+ name: saved.name,
264
+ store: saved.store,
265
+ prefix: saved.prefix,
266
+ message: saved.message,
267
+ held: [],
268
+ heldSize: 0,
269
+ resyncing: saved.resyncing
270
+ };
271
+ for (const keys of saved.held) {
272
+ const size = sizeOf(payloadOf(w, keys, false));
273
+ w.held.push({
274
+ keys,
275
+ size
276
+ });
277
+ w.heldSize += size;
278
+ }
279
+ if (reboundTo(options.grants(saved.script, saved.grant), saved.store)) {
280
+ add(w);
281
+ restored.push(w);
282
+ } else dropped.push(w);
283
+ }
284
+ const state = groups.get(group);
285
+ if (state && routing.retry) state.retry = routing.retry;
286
+ const resynced = order(restored).filter((w) => o.revision(w.store) !== routing.revisions[w.store]);
287
+ for (const w of resynced) {
288
+ w.held = [];
289
+ w.heldSize = 0;
290
+ w.resyncing = true;
291
+ }
292
+ out.restored = order(restored).map(label);
293
+ out.resynced = resynced.map(label);
294
+ const names = group.scriptNames();
295
+ const index = (script) => {
296
+ const i = names.indexOf(script);
297
+ return i < 0 ? names.length : i;
298
+ };
299
+ out.dropped = dropped.sort((a, b) => index(a.script) - index(b.script) || compareText(a.grant, b.grant) || compareText(a.name, b.name)).map(label);
300
+ for (const w of resynced) drain(w);
301
+ return {
302
+ group,
303
+ result,
304
+ routing: out
305
+ };
306
+ }
307
+ };
308
+ };
309
+ const watchLimit = (limit) => {
310
+ const error = hostScriptError("watch limit", [["limit", text(limit)]]);
311
+ return error.message === "watch limit" ? new ScriptError(error.code, `The Store's ${text(limit).toString()} limit for watches would be exceeded`, error.data) : error;
312
+ };
313
+ const reboundTo = (grant, store) => grant !== void 0 && grant.capability.name === "store" && grant.binding === store;
314
+ const readCheckpoint = (checkpoint) => {
315
+ const header = new TextEncoder().encode(HEADER);
316
+ if (checkpoint.length < header.length || header.some((b, i) => checkpoint[i] !== b)) invalidCheckpoint("A checkpoint without routing state");
317
+ const end = checkpoint.indexOf(10, header.length);
318
+ if (end < 0) invalidCheckpoint("Unreadable routing state");
319
+ let routing;
320
+ try {
321
+ routing = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(checkpoint.subarray(header.length, end)));
322
+ } catch {
323
+ return invalidCheckpoint("Unreadable routing state");
324
+ }
325
+ if (!wellFormed(routing)) invalidCheckpoint("Unreadable routing state");
326
+ const save = checkpoint.slice(end + 1);
327
+ if (sha256(save) !== routing.digest) invalidCheckpoint("The routing state is for another Group save");
328
+ return {
329
+ routing,
330
+ save
331
+ };
332
+ };
333
+ const isText = (v) => typeof v === "string";
334
+ const isPosition = (v) => !!v && typeof v === "object" && isText(v.script) && isText(v.grant) && isText(v.name);
335
+ const wellFormed = (r) => {
336
+ if (!r || typeof r !== "object") return false;
337
+ const s = r;
338
+ return isText(s.digest) && (s.retry === void 0 || isPosition(s.retry)) && !!s.revisions && typeof s.revisions === "object" && Object.values(s.revisions).every(isText) && Array.isArray(s.watches) && s.watches.every((w) => isPosition(w) && isText(w.store) && isText(w.prefix) && isText(w.message) && typeof w.resyncing === "boolean" && Array.isArray(w.held) && w.held.every((keys) => Array.isArray(keys) && keys.every(isText)) && isText(s.revisions[w.store]));
339
+ };
340
+ //#endregion
341
+ export { createRouter as n, changed as t };
@@ -0,0 +1,54 @@
1
+ import { At as Call, T as RestoreResult, at as Value, m as Group, w as RestoreOptions, zt as GrantContext } from "./debug-D8Z_u244.js";
2
+ import { t as Core } from "./core-eU5KaYkz.js";
3
+ //#region src/notify/router.d.ts
4
+ /** A Store's four limits on its watches (Store Notifications, Limits). */
5
+ type WatchLimits = {
6
+ /** The most pending Notifications, with one marker reserved per watch. */
7
+ pending: number;
8
+ /** The most their payloads may total, with every marker reserved. */
9
+ pendingSize: number;
10
+ /** The most watches, across every Script and Group. */
11
+ watches: number;
12
+ /** The most their names, prefixes and effective messages may total. */
13
+ watchSize: number;
14
+ };
15
+ type RouterOptions = {
16
+ /** Told after each Notification a Group admits; it mustn't call the router. */
17
+ admitted?(group: Group): void;
18
+ limits(store: string): WatchLimits;
19
+ /** The Store's current revision; read under its synchronization. */
20
+ revision(store: string): string;
21
+ };
22
+ /** Each entry is "<script>.<grant>.<watch>", in the order of watches. */
23
+ type RoutingResult = {
24
+ dropped: string[];
25
+ restored: string[];
26
+ resynced: string[];
27
+ };
28
+ type NotificationRouter = {
29
+ /** Applies a commit under the Store's synchronization; apply returns its changed keys. */
30
+ commit(store: string, apply: () => readonly string[]): void;
31
+ detach(group: Group): void;
32
+ /** After each Pump of the Group returns. True while the Group still has pending work. */
33
+ pumped(group: Group): boolean;
34
+ release(context: GrantContext<string>): void;
35
+ /** Throws HostError `invalid checkpoint`, or whatever Core.restore throws. */
36
+ restore(core: Pick<Core, 'restore'>, checkpoint: Uint8Array, o: RestoreOptions): {
37
+ group: Group;
38
+ result: RestoreResult;
39
+ routing: RoutingResult;
40
+ };
41
+ /** A checkpoint; throws effects pending as Group.save does. */
42
+ save(group: Group): Uint8Array;
43
+ unwatch(call: Call<string>, name: string): void;
44
+ /** Registers or replaces a watch; throws ScriptError `watch limit` {limit}. */
45
+ watch(call: Call<string>, name: string, prefix: string, message: string): void;
46
+ };
47
+ /**
48
+ * Whether a commit changed a key's value: compared by the bytes of the Value
49
+ * Encoding, with a missing key and Nothing one state (Net changes).
50
+ */
51
+ declare const changed: (before?: Value, after?: Value) => boolean;
52
+ declare const createRouter: (o: RouterOptions) => NotificationRouter;
53
+ //#endregion
54
+ export { changed as a, WatchLimits as i, RouterOptions as n, createRouter as o, RoutingResult as r, NotificationRouter as t };
package/session.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ import { C as Setup, _ as UserPrompt, a as ReplayOptions, c as parseTranscript, d as DebugAction, f as MOCK_ARGUMENTS, g as SourcePlacement, h as SessionHost, i as parseEnvelope, l as replayTranscript, m as SessionEnvironment, n as ObjectReference, o as Replayed, p as Mock, r as SessionObjects, s as TranscriptItem, t as Envelope, u as writeTranscript, v as Waiting } from "./objects-MeXIDDFo.js";
2
+ //#region src/generated/builtin-docs.d.ts
3
+ export declare const builtinDocs: Readonly<Record<string, {
4
+ call: string;
5
+ gives: string;
6
+ }>>;
7
+ //#endregion
8
+ export { type DebugAction, type Envelope, MOCK_ARGUMENTS, type Mock, type ObjectReference, type ReplayOptions, type Replayed, type SessionEnvironment, SessionHost, SessionObjects, type Setup, type SourcePlacement, type TranscriptItem, type UserPrompt, type Waiting, parseEnvelope, parseTranscript, replayTranscript, writeTranscript };