@tokamaq/sdk 0.0.0-stage → 0.1.0-dev.1
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/LICENSE +21 -0
- package/README.md +1403 -2
- package/build-internals.ts +25 -0
- package/caller/agent-launch.ts +60 -0
- package/client.tsx +498 -0
- package/component-actions.ts +327 -0
- package/component-alerts.ts +136 -0
- package/component-attributes.ts +340 -0
- package/component-parts.tsx +1177 -0
- package/core-contracts/auth.ts +40 -0
- package/package.json +98 -4
- package/quit.ts +58 -0
- package/regions.tsx +94 -0
- package/screen-search.ts +211 -0
- package/send-file.ts +175 -0
- package/server-build-internals.ts +11 -0
- package/solid.ts +132 -0
- package/src/agent-command.ts +48 -0
- package/src/agent-info-cache.ts +34 -0
- package/src/agent-reports.ts +140 -0
- package/src/agent-turn.ts +289 -0
- package/src/api.ts +174 -0
- package/src/auth.ts +39 -0
- package/src/call-error.ts +37 -0
- package/src/caller-storage.ts +32 -0
- package/src/client.ts +163 -0
- package/src/database.ts +322 -0
- package/src/functions.ts +726 -0
- package/src/hooks.ts +141 -0
- package/src/host.ts +211 -0
- package/src/http-action.ts +55 -0
- package/src/index.ts +126 -0
- package/src/internal/contracts.ts +260 -0
- package/src/internal/machine-scope.ts +21 -0
- package/src/local.ts +22 -0
- package/src/plugin.ts +162 -0
- package/src/points.ts +79 -0
- package/src/protocol.ts +64 -0
- package/src/schema.ts +136 -0
- package/src/storage.ts +193 -0
- package/src/thread-context.ts +42 -0
- package/src/transport.ts +421 -0
- package/src/triggers.ts +87 -0
- package/src/unstable.ts +66 -0
- package/src/validators.ts +248 -0
- package/src/values.ts +98 -0
- package/src/visibility.ts +8 -0
- package/src/websocket-transport.ts +91 -0
- package/src/window-state-protocol.ts +7 -0
- package/src/within.ts +24 -0
- package/src/worker-limits.ts +5 -0
- package/tools/bundle.mjs +490 -0
- package/tools/client-entry.mjs +10 -0
- package/tools/contracts.mjs +254 -0
- package/tools/http-actions.mjs +42 -0
- package/tools/placement.mjs +535 -0
- package/tools/plugin-boundary.mjs +592 -0
- package/tools/plugin-compiler.mjs +125 -0
- package/tools/plugin-descriptor.ts +75 -0
- package/tools/points.mjs +340 -0
- package/tools/result-validator.mjs +83 -0
- package/tools/server-builtins.mjs +82 -0
- package/tools/server-files.mjs +34 -0
- package/tools/table-references.mjs +98 -0
- package/tools/worker.mjs +110 -0
- package/tsconfig.plugin-server.json +12 -0
- package/tsconfig.plugin-window.json +15 -0
- package/view.ts +27 -0
- package/web.d.ts +6 -0
- package/window-state-host.ts +228 -0
- package/window-state.ts +43 -0
package/src/transport.ts
ADDED
|
@@ -0,0 +1,421 @@
|
|
|
1
|
+
import { LocalReloadTimeout } from "./client";
|
|
2
|
+
import type { ActionSignal } from "./host";
|
|
3
|
+
import type { ActionTarget } from "./functions";
|
|
4
|
+
// Correlation and subscription lifecycle are shared by both transports. Hosts
|
|
5
|
+
// provide an ordered native message connection or an already-open WebSocket;
|
|
6
|
+
// this module installs no browser/Node globals. Only immutable catalog transfers
|
|
7
|
+
// may restart; queries, mutations and actions are never automatically retried.
|
|
8
|
+
import { webSocketConnection, type ClientWebSocket } from "./websocket-transport";
|
|
9
|
+
import type { ClientTransport, SubscriptionEvent } from "./client";
|
|
10
|
+
import type { Event, Request } from "./protocol";
|
|
11
|
+
import { MAX_WIRE_MESSAGE_BYTES } from "./protocol";
|
|
12
|
+
import { RemoteFunctionError } from "./call-error";
|
|
13
|
+
import type { JsonValue } from "./values";
|
|
14
|
+
|
|
15
|
+
export interface MessageConnection {
|
|
16
|
+
send(request: Request): void;
|
|
17
|
+
listen(onEvent: (event: Event) => void, onClose: (error?: Error) => void): () => void;
|
|
18
|
+
close(): void;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export { RemoteFunctionError } from "./call-error";
|
|
22
|
+
|
|
23
|
+
type Pending = { resolve(value: JsonValue): void; reject(error: Error): void };
|
|
24
|
+
type Observer = (event: SubscriptionEvent<JsonValue>) => void;
|
|
25
|
+
// Per-connection admission budget, not a catalog/plugin quota. Correlation and
|
|
26
|
+
// live observers must remain resident until settlement; paging their state
|
|
27
|
+
// would lose ordered outcomes. Catalog/assets use one sequential call per page.
|
|
28
|
+
const CAPACITY = 128;
|
|
29
|
+
class CatalogRevisionChanged extends Error {
|
|
30
|
+
constructor() {
|
|
31
|
+
super("Plugin generation changed during catalog transfer");
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function isCatalogPage(
|
|
36
|
+
value: { [key: string]: JsonValue },
|
|
37
|
+
offset: number,
|
|
38
|
+
): value is { text: string; revision: string; done: boolean; next: number } {
|
|
39
|
+
return (
|
|
40
|
+
typeof value.text === "string" &&
|
|
41
|
+
typeof value.revision === "string" &&
|
|
42
|
+
typeof value.done === "boolean" &&
|
|
43
|
+
typeof value.next === "number" &&
|
|
44
|
+
Number.isSafeInteger(value.next) &&
|
|
45
|
+
value.next >= offset &&
|
|
46
|
+
(value.done || value.next !== offset)
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export class InProcessTransport implements ClientTransport {
|
|
51
|
+
private next = 0;
|
|
52
|
+
private closed: Error | undefined;
|
|
53
|
+
private readonly pending = new Map<number, Pending>();
|
|
54
|
+
private readonly subscriptions = new Map<number, Observer>();
|
|
55
|
+
private readonly pluginListeners = new Set<(event: Extract<Event, { type: "pluginchanged" }>) => void>();
|
|
56
|
+
private unlisten: () => void = () => {};
|
|
57
|
+
|
|
58
|
+
constructor(private readonly connection: MessageConnection) {
|
|
59
|
+
const stop = connection.listen(
|
|
60
|
+
(event) => this.receive(event),
|
|
61
|
+
(error) => this.fail(error ?? new Error("connection closed; mutation outcomes may be unknown")),
|
|
62
|
+
);
|
|
63
|
+
// Some native hosts can report a closed connection synchronously at listen.
|
|
64
|
+
if (this.closed) stop();
|
|
65
|
+
else this.unlisten = stop;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
query(name: string, args: JsonValue): Promise<JsonValue> {
|
|
69
|
+
return this.call("query", name, args);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
mutation(name: string, args: JsonValue): Promise<JsonValue> {
|
|
73
|
+
return this.call("mutation", name, args);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
action(name: string, args: JsonValue, on?: ActionTarget, signal?: ActionSignal): Promise<JsonValue> {
|
|
77
|
+
return this.sendAction(name, args, on, signal);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
dispatchWindowAction(
|
|
81
|
+
name: string,
|
|
82
|
+
args: JsonValue,
|
|
83
|
+
on?: ActionTarget,
|
|
84
|
+
signal?: ActionSignal,
|
|
85
|
+
): Promise<JsonValue> {
|
|
86
|
+
return this.sendAction(name, args, on, signal, true);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
finishWindowAction(id: number): void {
|
|
90
|
+
try {
|
|
91
|
+
this.send({ type: "cancelaction", id });
|
|
92
|
+
} catch {
|
|
93
|
+
// Closing the session also releases its continuation.
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
private async sendAction(
|
|
98
|
+
name: string,
|
|
99
|
+
args: JsonValue,
|
|
100
|
+
on?: ActionTarget,
|
|
101
|
+
signal?: ActionSignal,
|
|
102
|
+
window?: true,
|
|
103
|
+
): Promise<JsonValue> {
|
|
104
|
+
return this.control(
|
|
105
|
+
(id) => ({
|
|
106
|
+
type: "action",
|
|
107
|
+
id,
|
|
108
|
+
name,
|
|
109
|
+
args,
|
|
110
|
+
...(window && { window, hookPlans: true, pointPlans: true }),
|
|
111
|
+
...(on === undefined ? {} : { on }),
|
|
112
|
+
}),
|
|
113
|
+
signal,
|
|
114
|
+
);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Forward the continuation supplied by the Runner on its private socket. */
|
|
118
|
+
async continueLocalCall(
|
|
119
|
+
kind: "query" | "mutation" | "action",
|
|
120
|
+
name: string,
|
|
121
|
+
args: JsonValue,
|
|
122
|
+
parent: { depth: number; thread: string | null; hookScope?: number; proof?: string | null },
|
|
123
|
+
on?: ActionTarget,
|
|
124
|
+
window?: boolean,
|
|
125
|
+
signal?: ActionSignal,
|
|
126
|
+
): Promise<JsonValue> {
|
|
127
|
+
return this.control(
|
|
128
|
+
(id) => ({
|
|
129
|
+
type: "localcall",
|
|
130
|
+
id,
|
|
131
|
+
name,
|
|
132
|
+
args,
|
|
133
|
+
kind,
|
|
134
|
+
depth: parent.depth,
|
|
135
|
+
thread: parent.thread,
|
|
136
|
+
...(parent.proof ? { proof: parent.proof } : {}),
|
|
137
|
+
...(parent.hookScope === undefined ? {} : { hookScope: parent.hookScope }),
|
|
138
|
+
...(window ? { window, hookPlans: true, pointPlans: true } : {}),
|
|
139
|
+
...(on === undefined ? {} : { on }),
|
|
140
|
+
}),
|
|
141
|
+
signal,
|
|
142
|
+
);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
hookStage(scope: number, done?: boolean): Promise<JsonValue> {
|
|
146
|
+
return this.control((id) => ({ type: "hookstage", id, scope, done }));
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
async plugins(): Promise<JsonValue> {
|
|
150
|
+
// A reload may retire any page already in flight. Discard the whole partial
|
|
151
|
+
// transfer and pin a fresh first page, with bounded retries under churn.
|
|
152
|
+
// Pages from different snapshots cannot be combined; endless churn must
|
|
153
|
+
// surface as a transient generation error rather than spin forever.
|
|
154
|
+
for (let attempt = 0; ; attempt++) {
|
|
155
|
+
try {
|
|
156
|
+
return await this.catalog();
|
|
157
|
+
} catch (error) {
|
|
158
|
+
if (
|
|
159
|
+
attempt >= 2 ||
|
|
160
|
+
!(
|
|
161
|
+
error instanceof CatalogRevisionChanged ||
|
|
162
|
+
(error instanceof Error && error.message === "Plugin generation changed")
|
|
163
|
+
)
|
|
164
|
+
)
|
|
165
|
+
throw error;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
private async catalog(): Promise<JsonValue> {
|
|
171
|
+
let value = await this.control((id) => ({ type: "plugins", id }));
|
|
172
|
+
const chunks: string[] = [];
|
|
173
|
+
let offset = 0;
|
|
174
|
+
let revision: string | undefined;
|
|
175
|
+
for (;;) {
|
|
176
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
177
|
+
throw new Error("Invalid catalog page");
|
|
178
|
+
// Accept older hosts and structural test transports with a full catalog.
|
|
179
|
+
if (Array.isArray(value.plugins)) {
|
|
180
|
+
if (revision !== undefined) throw new CatalogRevisionChanged();
|
|
181
|
+
return value;
|
|
182
|
+
}
|
|
183
|
+
if (!isCatalogPage(value, offset)) throw new Error("Invalid catalog page");
|
|
184
|
+
if (revision === undefined) revision = value.revision;
|
|
185
|
+
else if (value.revision !== revision) throw new CatalogRevisionChanged();
|
|
186
|
+
chunks.push(value.text);
|
|
187
|
+
if (value.done) {
|
|
188
|
+
const assembled = JSON.parse(chunks.join("")) as JsonValue;
|
|
189
|
+
if (
|
|
190
|
+
!assembled ||
|
|
191
|
+
typeof assembled !== "object" ||
|
|
192
|
+
Array.isArray(assembled) ||
|
|
193
|
+
assembled.revision !== revision
|
|
194
|
+
)
|
|
195
|
+
throw new CatalogRevisionChanged();
|
|
196
|
+
return assembled;
|
|
197
|
+
}
|
|
198
|
+
offset = value.next;
|
|
199
|
+
const pinned = revision;
|
|
200
|
+
value = await this.control((id) => ({ type: "pluginspage", id, revision: pinned, offset }));
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
async pluginAsset(plugin: string, name: string, revision: string): Promise<string> {
|
|
205
|
+
let offset = 0;
|
|
206
|
+
const chunks: string[] = [];
|
|
207
|
+
for (;;) {
|
|
208
|
+
const value = await this.control((id) => ({ type: "pluginasset", id, plugin, name, revision, offset }));
|
|
209
|
+
if (
|
|
210
|
+
!value ||
|
|
211
|
+
typeof value !== "object" ||
|
|
212
|
+
Array.isArray(value) ||
|
|
213
|
+
typeof value.text !== "string" ||
|
|
214
|
+
typeof value.next !== "number" ||
|
|
215
|
+
typeof value.done !== "boolean" ||
|
|
216
|
+
!Number.isSafeInteger(value.next) ||
|
|
217
|
+
value.next < offset ||
|
|
218
|
+
(!value.done && value.next === offset)
|
|
219
|
+
)
|
|
220
|
+
throw new Error("Invalid plugin asset chunk");
|
|
221
|
+
chunks.push(value.text);
|
|
222
|
+
offset = value.next;
|
|
223
|
+
if (value.done) return chunks.join("");
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
onPluginsChanged(listener: (event: Extract<Event, { type: "pluginchanged" }>) => void): () => void {
|
|
228
|
+
this.pluginListeners.add(listener);
|
|
229
|
+
return () => {
|
|
230
|
+
this.pluginListeners.delete(listener);
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
private control(request: (id: number) => Request, signal?: ActionSignal): Promise<JsonValue> {
|
|
235
|
+
return new Promise((resolve, reject) => {
|
|
236
|
+
if (signal?.aborted) throw new Error("Action cancelled");
|
|
237
|
+
if (this.pending.size >= CAPACITY) throw new Error("client call capacity exceeded");
|
|
238
|
+
const id = this.id();
|
|
239
|
+
const cancel = () => this.finishWindowAction(id);
|
|
240
|
+
const cleanup = () => signal?.removeEventListener("abort", cancel);
|
|
241
|
+
this.pending.set(id, {
|
|
242
|
+
resolve(value) {
|
|
243
|
+
cleanup();
|
|
244
|
+
resolve(value);
|
|
245
|
+
},
|
|
246
|
+
reject(error) {
|
|
247
|
+
cleanup();
|
|
248
|
+
reject(error);
|
|
249
|
+
},
|
|
250
|
+
});
|
|
251
|
+
signal?.addEventListener("abort", cancel, { once: true });
|
|
252
|
+
try {
|
|
253
|
+
this.send(request(id));
|
|
254
|
+
} catch (error) {
|
|
255
|
+
this.pending.delete(id);
|
|
256
|
+
cleanup();
|
|
257
|
+
throw error;
|
|
258
|
+
}
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
private id(): number {
|
|
263
|
+
if (this.closed) throw this.closed;
|
|
264
|
+
// IDs must remain exact across JSON numbers and native u64 correlation;
|
|
265
|
+
// paging cannot extend one numeric identifier beyond that representation.
|
|
266
|
+
if (this.next === Number.MAX_SAFE_INTEGER) throw new Error("request IDs exhausted");
|
|
267
|
+
return ++this.next;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
private send(request: Request): void {
|
|
271
|
+
if (this.closed) throw this.closed;
|
|
272
|
+
// Reject only this operation before admission. UTF-8, not JS code units,
|
|
273
|
+
// determines the native/WebSocket message size (QuickJS has no TextEncoder).
|
|
274
|
+
const text = JSON.stringify(request);
|
|
275
|
+
let bytes = 0;
|
|
276
|
+
for (const char of text) {
|
|
277
|
+
const code = char.codePointAt(0)!;
|
|
278
|
+
bytes += code <= 0x7f ? 1 : code <= 0x7ff ? 2 : code <= 0xffff ? 3 : 4;
|
|
279
|
+
}
|
|
280
|
+
// A data invocation is one atomic JSON value under the existing protocol;
|
|
281
|
+
// splitting it would change admission/transaction semantics. Plugin catalog
|
|
282
|
+
// and asset transfers already page around this per-message bound.
|
|
283
|
+
if (bytes > MAX_WIRE_MESSAGE_BYTES) {
|
|
284
|
+
const error = new Error("request too large (1 MiB limit)");
|
|
285
|
+
this.pending.get(request.id)?.reject(error);
|
|
286
|
+
this.pending.delete(request.id);
|
|
287
|
+
this.subscriptions.delete(request.id);
|
|
288
|
+
throw error;
|
|
289
|
+
}
|
|
290
|
+
try {
|
|
291
|
+
this.connection.send(request);
|
|
292
|
+
} catch (error) {
|
|
293
|
+
const failure = error instanceof Error ? error : new Error(String(error));
|
|
294
|
+
this.fail(failure);
|
|
295
|
+
throw failure;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
private call(type: "query" | "mutation", name: string, args: JsonValue): Promise<JsonValue> {
|
|
300
|
+
return new Promise((resolve, reject) => {
|
|
301
|
+
if (this.pending.size >= CAPACITY) throw new Error("client call capacity exceeded");
|
|
302
|
+
const id = this.id();
|
|
303
|
+
this.pending.set(id, { resolve, reject });
|
|
304
|
+
this.send({ type, id, name, args });
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
subscribe(name: string, args: JsonValue, observer: Observer): () => void {
|
|
309
|
+
if (this.subscriptions.size >= CAPACITY) throw new Error("client subscription capacity exceeded");
|
|
310
|
+
const id = this.id();
|
|
311
|
+
this.subscriptions.set(id, observer);
|
|
312
|
+
try {
|
|
313
|
+
this.send({ type: "subscribe", id, name, args });
|
|
314
|
+
} catch (error) {
|
|
315
|
+
this.subscriptions.delete(id);
|
|
316
|
+
throw error;
|
|
317
|
+
}
|
|
318
|
+
let active = true;
|
|
319
|
+
return () => {
|
|
320
|
+
if (!active) return;
|
|
321
|
+
active = false;
|
|
322
|
+
this.subscriptions.delete(id);
|
|
323
|
+
if (!this.closed) {
|
|
324
|
+
try {
|
|
325
|
+
this.send({ type: "unsubscribe", id });
|
|
326
|
+
} catch {
|
|
327
|
+
// send already failed/closed the stream and rejected pending calls.
|
|
328
|
+
// Disposal must remain safe when native retirement races this send,
|
|
329
|
+
// otherwise one cleanup failure can strand other Solid subscriptions.
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
};
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
private receive(event: Event): void {
|
|
336
|
+
if (this.closed) return;
|
|
337
|
+
if (event.type === "pluginchanged") {
|
|
338
|
+
for (const listener of this.pluginListeners) {
|
|
339
|
+
try {
|
|
340
|
+
listener(event);
|
|
341
|
+
} catch {
|
|
342
|
+
/* isolate window/plugin observers */
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
return;
|
|
346
|
+
}
|
|
347
|
+
if (event.type === "unsubscribed") return;
|
|
348
|
+
const result = event.result;
|
|
349
|
+
if (event.type === "response") {
|
|
350
|
+
const pending = this.pending.get(event.id);
|
|
351
|
+
if (pending) {
|
|
352
|
+
this.pending.delete(event.id);
|
|
353
|
+
if ("Ok" in result) pending.resolve(result.Ok);
|
|
354
|
+
else
|
|
355
|
+
pending.reject(
|
|
356
|
+
event.error?.kind === "LocalReloadTimeout" && event.error.stage === "runner"
|
|
357
|
+
? new LocalReloadTimeout()
|
|
358
|
+
: new RemoteFunctionError(event.error ? { ...event.error, message: result.Err } : result.Err),
|
|
359
|
+
);
|
|
360
|
+
return;
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
// Registration errors use response; query rerun errors use subscription.
|
|
364
|
+
const observer = this.subscriptions.get(event.id);
|
|
365
|
+
if (observer) {
|
|
366
|
+
if (event.type === "response") this.subscriptions.delete(event.id);
|
|
367
|
+
this.notify(
|
|
368
|
+
observer,
|
|
369
|
+
"Ok" in result
|
|
370
|
+
? { value: result.Ok }
|
|
371
|
+
: {
|
|
372
|
+
error: new RemoteFunctionError(
|
|
373
|
+
event.error ? { ...event.error, message: result.Err } : result.Err,
|
|
374
|
+
),
|
|
375
|
+
terminal: event.type === "response",
|
|
376
|
+
},
|
|
377
|
+
);
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
private notify(observer: Observer, event: SubscriptionEvent<JsonValue>): void {
|
|
382
|
+
// A throwing observer must not break stream processing and strand unrelated
|
|
383
|
+
// calls, especially the mutation reply behind this update. Observers should
|
|
384
|
+
// handle their own application failures; transport never retries callbacks.
|
|
385
|
+
try {
|
|
386
|
+
observer(event);
|
|
387
|
+
} catch {
|
|
388
|
+
/* isolate application callbacks */
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
private fail(error: Error): void {
|
|
393
|
+
if (this.closed) return;
|
|
394
|
+
this.closed = error;
|
|
395
|
+
this.unlisten();
|
|
396
|
+
this.pluginListeners.clear();
|
|
397
|
+
const observers = [...this.subscriptions.values()];
|
|
398
|
+
this.subscriptions.clear();
|
|
399
|
+
for (const pending of this.pending.values()) pending.reject(error);
|
|
400
|
+
this.pending.clear();
|
|
401
|
+
try {
|
|
402
|
+
this.connection.close();
|
|
403
|
+
} finally {
|
|
404
|
+
for (const observer of observers) this.notify(observer, { error, terminal: true });
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
close(): void {
|
|
409
|
+
this.fail(new Error("client closed; mutation outcomes may be unknown"));
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
export class WebSocketTransport extends InProcessTransport {
|
|
414
|
+
readonly serverAddress?: string;
|
|
415
|
+
|
|
416
|
+
constructor(socket: ClientWebSocket) {
|
|
417
|
+
super(webSocketConnection(socket));
|
|
418
|
+
if (socket.url) this.serverAddress = socket.url;
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
export type { ClientWebSocket } from "./websocket-transport";
|
package/src/triggers.ts
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { createFunctions, invokeFunction, mutation, type MutationContext } from "./functions";
|
|
2
|
+
import type { HostBridge } from "./host";
|
|
3
|
+
import type { DataModel, ModelFromSchema, SchemaDefinition } from "./schema";
|
|
4
|
+
import type { TableDocument, TableReference } from "./validators";
|
|
5
|
+
import type { Id, JsonObject, JsonValue } from "./values";
|
|
6
|
+
|
|
7
|
+
const triggerBrand = Symbol("tokamaq.trigger");
|
|
8
|
+
|
|
9
|
+
export type TriggerChange<Doc extends { _id: string }> = { id: Doc["_id"] } & (
|
|
10
|
+
| { operation: "insert"; oldDoc: null; newDoc: Doc }
|
|
11
|
+
| { operation: "update"; oldDoc: Doc; newDoc: Doc }
|
|
12
|
+
| { operation: "delete"; oldDoc: Doc; newDoc: null }
|
|
13
|
+
);
|
|
14
|
+
|
|
15
|
+
interface TriggerDefinition {
|
|
16
|
+
readonly [triggerBrand]: true;
|
|
17
|
+
readonly table: string;
|
|
18
|
+
invoke(change: JsonValue, host: HostBridge): Promise<JsonValue>;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
type TriggerBuilder<M extends DataModel, Local extends string = never> = <
|
|
22
|
+
T extends TableReference<string> | Local,
|
|
23
|
+
>(
|
|
24
|
+
table: T,
|
|
25
|
+
handler: (
|
|
26
|
+
ctx: MutationContext<M>,
|
|
27
|
+
change: TriggerChange<
|
|
28
|
+
T extends TableReference<string>
|
|
29
|
+
? TableDocument<T>
|
|
30
|
+
: M[T & keyof M] & { _id: Id<T & string>; _creationTime: number }
|
|
31
|
+
>,
|
|
32
|
+
) => void | Promise<void>,
|
|
33
|
+
) => TriggerDefinition;
|
|
34
|
+
|
|
35
|
+
function triggerBuilder<M extends DataModel, Local extends string>(
|
|
36
|
+
schema?: SchemaDefinition,
|
|
37
|
+
): TriggerBuilder<M, Local> {
|
|
38
|
+
return (table, handler) => {
|
|
39
|
+
const build = schema ? createFunctions(schema).mutation : mutation;
|
|
40
|
+
return Object.freeze({
|
|
41
|
+
[triggerBrand]: true as const,
|
|
42
|
+
table: typeof table === "string" ? table : (table as TableReference<string>).qualifiedName,
|
|
43
|
+
invoke(change: JsonValue, host: HostBridge) {
|
|
44
|
+
const definition = build({
|
|
45
|
+
handler: async (ctx) => {
|
|
46
|
+
await handler(ctx as unknown as MutationContext<M>, change as never);
|
|
47
|
+
return null;
|
|
48
|
+
},
|
|
49
|
+
});
|
|
50
|
+
return invokeFunction({ trigger: definition }, { name: "trigger", args: {} }, host);
|
|
51
|
+
},
|
|
52
|
+
});
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export const trigger = triggerBuilder<Record<string, JsonObject>, never>();
|
|
57
|
+
|
|
58
|
+
export function createTrigger<S extends SchemaDefinition>(
|
|
59
|
+
schema: S,
|
|
60
|
+
): TriggerBuilder<ModelFromSchema<S>, Extract<keyof S["tables"], string>> {
|
|
61
|
+
return triggerBuilder(schema);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function createTriggerRegistry(modules: Record<string, object>) {
|
|
65
|
+
return Object.fromEntries(
|
|
66
|
+
Object.entries(modules).flatMap(([module, exports]) =>
|
|
67
|
+
Object.entries(exports).flatMap(([name, value]) =>
|
|
68
|
+
value?.[triggerBrand] === true ? [[`${module}:${name}`, value as TriggerDefinition] as const] : [],
|
|
69
|
+
),
|
|
70
|
+
),
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
type TriggerRegistry = ReturnType<typeof createTriggerRegistry>;
|
|
75
|
+
|
|
76
|
+
export function triggerMetadata(triggers: TriggerRegistry) {
|
|
77
|
+
return Object.entries(triggers).map(([name, { table }]) => ({ name, table }));
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function invokeTrigger(
|
|
81
|
+
triggers: TriggerRegistry,
|
|
82
|
+
request: { name: string; change: JsonValue },
|
|
83
|
+
host: HostBridge,
|
|
84
|
+
) {
|
|
85
|
+
if (!Object.hasOwn(triggers, request.name)) throw new Error(`Unknown trigger: ${request.name}`);
|
|
86
|
+
return triggers[request.name].invoke(request.change, host);
|
|
87
|
+
}
|
package/src/unstable.ts
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
ActionContext,
|
|
3
|
+
CallerActionContext,
|
|
4
|
+
Failure,
|
|
5
|
+
MachineId,
|
|
6
|
+
MutationContext,
|
|
7
|
+
QueryContext,
|
|
8
|
+
} from "./functions";
|
|
9
|
+
import { callHost } from "./host";
|
|
10
|
+
import { machineScopeOf } from "./internal/machine-scope";
|
|
11
|
+
import type { DataModel } from "./schema";
|
|
12
|
+
|
|
13
|
+
export interface MachineEntry {
|
|
14
|
+
id: MachineId;
|
|
15
|
+
name: string;
|
|
16
|
+
owner: { kind: "plugin"; plugin: string } | { kind: "person"; user: string };
|
|
17
|
+
online: boolean;
|
|
18
|
+
lastSeen: number | null;
|
|
19
|
+
member?: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
interface MachineList {
|
|
23
|
+
/** A snapshot; presence changes do not invalidate query subscriptions. */
|
|
24
|
+
list(): Promise<MachineEntry[]>;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
interface MachineManagement extends MachineList {
|
|
28
|
+
create(options: { name: string; member?: string }): Promise<MachineCreation>;
|
|
29
|
+
/** Available in a server action. Lists all machines owned by this plugin. */
|
|
30
|
+
listAll(): Promise<MachineEntry[]>;
|
|
31
|
+
remove(id: MachineId): Promise<null | Failure<"machineForbidden", null>>;
|
|
32
|
+
waitOnline(
|
|
33
|
+
id: MachineId,
|
|
34
|
+
options?: { timeoutMs?: number },
|
|
35
|
+
): Promise<null | Failure<"machineForbidden" | "machineOffline", null>>;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export type MachineCreation =
|
|
39
|
+
| { id: MachineId; key: string }
|
|
40
|
+
| Failure<"machineLimit" | "machineForbidden", null>;
|
|
41
|
+
|
|
42
|
+
/** Unstable machine management API. May change before the first sandbox plugin. */
|
|
43
|
+
export function machines(ctx: ActionContext): MachineManagement;
|
|
44
|
+
export function machines<M extends DataModel>(
|
|
45
|
+
ctx: QueryContext<M> | MutationContext<M> | CallerActionContext | ActionContext,
|
|
46
|
+
): MachineList;
|
|
47
|
+
export function machines(ctx: object): MachineList {
|
|
48
|
+
const { host, besideServer } = machineScopeOf(ctx);
|
|
49
|
+
const list = () => callHost(host, "machines.list", {});
|
|
50
|
+
|
|
51
|
+
if (!besideServer) return Object.freeze({ list });
|
|
52
|
+
|
|
53
|
+
return Object.freeze({
|
|
54
|
+
list,
|
|
55
|
+
create: (options) => besideServer(() => callHost(host, "machines.create", options)),
|
|
56
|
+
listAll: () => besideServer(() => callHost(host, "machines.listAll", {})),
|
|
57
|
+
remove: (id) => besideServer(() => callHost(host, "machines.remove", { id })),
|
|
58
|
+
waitOnline: (id, options) =>
|
|
59
|
+
besideServer(() =>
|
|
60
|
+
callHost(host, "machines.waitOnline", {
|
|
61
|
+
id,
|
|
62
|
+
...(options?.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs }),
|
|
63
|
+
}),
|
|
64
|
+
),
|
|
65
|
+
} satisfies MachineManagement);
|
|
66
|
+
}
|