@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.
Files changed (71) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1403 -2
  3. package/build-internals.ts +25 -0
  4. package/caller/agent-launch.ts +60 -0
  5. package/client.tsx +498 -0
  6. package/component-actions.ts +327 -0
  7. package/component-alerts.ts +136 -0
  8. package/component-attributes.ts +340 -0
  9. package/component-parts.tsx +1177 -0
  10. package/core-contracts/auth.ts +40 -0
  11. package/package.json +98 -4
  12. package/quit.ts +58 -0
  13. package/regions.tsx +94 -0
  14. package/screen-search.ts +211 -0
  15. package/send-file.ts +175 -0
  16. package/server-build-internals.ts +11 -0
  17. package/solid.ts +132 -0
  18. package/src/agent-command.ts +48 -0
  19. package/src/agent-info-cache.ts +34 -0
  20. package/src/agent-reports.ts +140 -0
  21. package/src/agent-turn.ts +289 -0
  22. package/src/api.ts +174 -0
  23. package/src/auth.ts +39 -0
  24. package/src/call-error.ts +37 -0
  25. package/src/caller-storage.ts +32 -0
  26. package/src/client.ts +163 -0
  27. package/src/database.ts +322 -0
  28. package/src/functions.ts +726 -0
  29. package/src/hooks.ts +141 -0
  30. package/src/host.ts +211 -0
  31. package/src/http-action.ts +55 -0
  32. package/src/index.ts +126 -0
  33. package/src/internal/contracts.ts +260 -0
  34. package/src/internal/machine-scope.ts +21 -0
  35. package/src/local.ts +22 -0
  36. package/src/plugin.ts +162 -0
  37. package/src/points.ts +79 -0
  38. package/src/protocol.ts +64 -0
  39. package/src/schema.ts +136 -0
  40. package/src/storage.ts +193 -0
  41. package/src/thread-context.ts +42 -0
  42. package/src/transport.ts +421 -0
  43. package/src/triggers.ts +87 -0
  44. package/src/unstable.ts +66 -0
  45. package/src/validators.ts +248 -0
  46. package/src/values.ts +98 -0
  47. package/src/visibility.ts +8 -0
  48. package/src/websocket-transport.ts +91 -0
  49. package/src/window-state-protocol.ts +7 -0
  50. package/src/within.ts +24 -0
  51. package/src/worker-limits.ts +5 -0
  52. package/tools/bundle.mjs +490 -0
  53. package/tools/client-entry.mjs +10 -0
  54. package/tools/contracts.mjs +254 -0
  55. package/tools/http-actions.mjs +42 -0
  56. package/tools/placement.mjs +535 -0
  57. package/tools/plugin-boundary.mjs +592 -0
  58. package/tools/plugin-compiler.mjs +125 -0
  59. package/tools/plugin-descriptor.ts +75 -0
  60. package/tools/points.mjs +340 -0
  61. package/tools/result-validator.mjs +83 -0
  62. package/tools/server-builtins.mjs +82 -0
  63. package/tools/server-files.mjs +34 -0
  64. package/tools/table-references.mjs +98 -0
  65. package/tools/worker.mjs +110 -0
  66. package/tsconfig.plugin-server.json +12 -0
  67. package/tsconfig.plugin-window.json +15 -0
  68. package/view.ts +27 -0
  69. package/web.d.ts +6 -0
  70. package/window-state-host.ts +228 -0
  71. package/window-state.ts +43 -0
@@ -0,0 +1,248 @@
1
+ // Validators retain a serializable description for host metadata and an inferred
2
+ // TypeScript type. Validation is deliberately non-transforming: wire and handler
3
+ // arguments mean the same thing, unlike general-purpose schema adapters.
4
+ import { assertId, assertJson, assertTable, isPlainObject } from "./values";
5
+ import type { Id, JsonValue } from "./values";
6
+
7
+ export type ValidatorDescription =
8
+ | { kind: "string" | "number" | "boolean" | "null" | "any" }
9
+ | { kind: "file"; accept: readonly string[]; maxSize: number }
10
+ | { kind: "literal"; value: string | number | boolean | null }
11
+ | { kind: "id" | "ref"; table: string }
12
+ | { kind: "array"; item: ValidatorDescription }
13
+ | { kind: "optional"; inner: ValidatorDescription }
14
+ | { kind: "object"; fields: Record<string, ValidatorDescription> }
15
+ | { kind: "union"; members: ValidatorDescription[] };
16
+
17
+ declare const tableReference: unique symbol;
18
+
19
+ /** Generated table handle. Its document type is erased at runtime. */
20
+ export interface TableReference<Table extends string, Fields extends object = object> {
21
+ readonly qualifiedName: Table;
22
+ readonly [tableReference]: Fields & { _id: Id<Table>; _creationTime: number };
23
+ }
24
+ export type TableDocument<T extends TableReference<string>> = T[typeof tableReference];
25
+
26
+ export interface Validator<T, Optional extends boolean = false> {
27
+ readonly description: ValidatorDescription;
28
+ readonly optional: Optional;
29
+ readonly _type?: T;
30
+ }
31
+
32
+ declare const refLocation: unique symbol;
33
+ type RefLocation<V> = V extends { readonly [refLocation]: infer Kind } ? Kind : never;
34
+ type MarkRef<V, Kind> = [Kind] extends [never] ? V : V & { readonly [refLocation]: Kind };
35
+ type NestRef<V, Result> = [RefLocation<V>] extends [never] ? Result : MarkRef<Result, "nested">;
36
+ export type TableField<V> = V extends { readonly [refLocation]: "nested" }
37
+ ? "A ref must be a top-level field (optional allowed)"
38
+ : V;
39
+
40
+ export type Fields = Record<string, Validator<unknown, boolean>>;
41
+
42
+ export type Infer<V> = V extends Validator<infer T, boolean> ? T : never;
43
+
44
+ type OptionalKeys<F extends Fields> = {
45
+ [K in keyof F]: F[K] extends Validator<unknown, true> ? K : never;
46
+ }[keyof F];
47
+
48
+ export type ObjectValue<F extends Fields> = keyof F extends never
49
+ ? Record<string, never>
50
+ : { [K in Exclude<keyof F, OptionalKeys<F>>]: Infer<F[K]> } & {
51
+ [K in OptionalKeys<F>]?: Infer<F[K]>;
52
+ };
53
+
54
+ function freezeDescription(description: ValidatorDescription): ValidatorDescription {
55
+ if (description.kind === "array") freezeDescription(description.item);
56
+ if (description.kind === "optional") freezeDescription(description.inner);
57
+ if (description.kind === "object") {
58
+ for (const field of Object.values(description.fields)) freezeDescription(field);
59
+ Object.freeze(description.fields);
60
+ }
61
+ if (description.kind === "union") {
62
+ for (const member of description.members) freezeDescription(member);
63
+ Object.freeze(description.members);
64
+ }
65
+ return Object.freeze(description);
66
+ }
67
+
68
+ function validator<T>(description: ValidatorDescription): Validator<T> {
69
+ return Object.freeze({
70
+ description: freezeDescription(description),
71
+ optional: false,
72
+ });
73
+ }
74
+
75
+ export interface FileOptions {
76
+ accept?: readonly string[];
77
+ maxSize?: number;
78
+ }
79
+
80
+ export const v = {
81
+ file: ({ accept = [], maxSize = 100_000_000 }: FileOptions = {}) => {
82
+ if (!Number.isSafeInteger(maxSize) || maxSize < 0)
83
+ throw new Error("v.file maxSize must be a nonnegative safe integer");
84
+ if (!Array.isArray(accept) || [...accept].some((pattern) => typeof pattern !== "string"))
85
+ throw new Error("v.file accept must be an array of MIME patterns");
86
+ return validator<string>({ kind: "file", accept: Object.freeze([...accept]), maxSize });
87
+ },
88
+ string: () => validator<string>({ kind: "string" }),
89
+ number: () => validator<number>({ kind: "number" }),
90
+ boolean: () => validator<boolean>({ kind: "boolean" }),
91
+ null: () => validator<null>({ kind: "null" }),
92
+
93
+ // "any" means any JSON value, never TypeScript any or host-specific objects.
94
+ any: () => validator<JsonValue>({ kind: "any" }),
95
+ literal<const T extends string | number | boolean | null>(value: T): Validator<T> {
96
+ assertJson(value, "literal");
97
+ return validator({ kind: "literal", value });
98
+ },
99
+ id<T extends string>(table: T): Validator<Id<T>> {
100
+ assertTable(table);
101
+ return validator({ kind: "id", table });
102
+ },
103
+ ref<T extends string>(table: TableReference<T>): MarkRef<Validator<Id<T>>, "ref"> {
104
+ return validator({ kind: "ref", table: table.qualifiedName }) as MarkRef<Validator<Id<T>>, "ref">;
105
+ },
106
+ array<V extends Validator<unknown>>(item: V): NestRef<V, Validator<Infer<V>[]>> {
107
+ return validator({ kind: "array", item: item.description }) as NestRef<V, Validator<Infer<V>[]>>;
108
+ },
109
+ object<F extends Fields>(fields: F): NestRef<F[keyof F], Validator<ObjectValue<F>>> {
110
+ return validator({
111
+ kind: "object",
112
+ fields: Object.fromEntries(Object.entries(fields).map(([key, field]) => [key, field.description])),
113
+ }) as NestRef<F[keyof F], Validator<ObjectValue<F>>>;
114
+ },
115
+
116
+ optional<V extends Validator<unknown>>(inner: V): MarkRef<Validator<Infer<V>, true>, RefLocation<V>> {
117
+ return Object.freeze({
118
+ description: freezeDescription({
119
+ kind: "optional",
120
+ inner: inner.description,
121
+ }),
122
+ optional: true,
123
+ }) as MarkRef<Validator<Infer<V>, true>, RefLocation<V>>;
124
+ },
125
+ union<V extends readonly [Validator<unknown>, ...Validator<unknown>[]]>(
126
+ ...members: V
127
+ ): NestRef<V[number], Validator<Infer<V[number]>>> {
128
+ return validator({
129
+ kind: "union",
130
+ members: members.map((member) => member.description),
131
+ }) as NestRef<V[number], Validator<Infer<V[number]>>>;
132
+ },
133
+ };
134
+
135
+ export function containsRef(description: ValidatorDescription): boolean {
136
+ return containsKind(description, "ref");
137
+ }
138
+
139
+ export function containsKind(description: ValidatorDescription, kind: "ref" | "file"): boolean {
140
+ if (description.kind === kind) return true;
141
+ switch (description.kind) {
142
+ case "array":
143
+ return containsKind(description.item, kind);
144
+ case "optional":
145
+ return containsKind(description.inner, kind);
146
+ case "object":
147
+ return Object.values(description.fields).some((child) => containsKind(child, kind));
148
+ case "union":
149
+ return description.members.some((child) => containsKind(child, kind));
150
+ default:
151
+ return false;
152
+ }
153
+ }
154
+
155
+ /** Optional means an absent object key; explicit undefined is never a wire value. */
156
+ export function validate(description: ValidatorDescription, value: unknown, path = "args"): void {
157
+ const fail = (expected: string): never => {
158
+ throw new Error(`${path}: expected ${expected}`);
159
+ };
160
+ switch (description.kind) {
161
+ case "any":
162
+ assertJson(value, path);
163
+ return;
164
+ case "optional":
165
+ validate(description.inner, value, path);
166
+ return;
167
+ case "array":
168
+ if (!Array.isArray(value)) return fail("array");
169
+ for (let i = 0; i < value.length; i++) validate(description.item, value[i], `${path}[${i}]`);
170
+ return;
171
+ case "object":
172
+ validateObject(description.fields, value, path);
173
+ return;
174
+ case "union":
175
+ for (const member of description.members) {
176
+ try {
177
+ validate(member, value, path);
178
+ return;
179
+ } catch {
180
+ /* Try the next alternative. */
181
+ }
182
+ }
183
+ fail("one of the declared union members");
184
+ default:
185
+ validateScalar(description, value, path);
186
+ }
187
+ }
188
+
189
+ function validateObject(fields: Record<string, ValidatorDescription>, value: unknown, path: string) {
190
+ if (!isPlainObject(value)) throw new Error(`${path}: expected object`);
191
+ for (const [key, field] of Object.entries(fields)) {
192
+ if (!Object.hasOwn(value, key)) {
193
+ if (field.kind !== "optional") throw new Error(`${path}.${key}: required field is missing`);
194
+ } else validate(field, value[key], `${path}.${key}`);
195
+ }
196
+ for (const key of Object.keys(value)) {
197
+ if (!Object.hasOwn(fields, key)) throw new Error(`${path}.${key}: unexpected field`);
198
+ }
199
+ }
200
+
201
+ function validateScalar(description: ValidatorDescription, value: unknown, path: string) {
202
+ const fail = (expected: string): never => {
203
+ throw new Error(`${path}: expected ${expected}`);
204
+ };
205
+ switch (description.kind) {
206
+ case "file":
207
+ if (typeof value !== "string") fail("file id string");
208
+ return;
209
+ case "string":
210
+ if (typeof value !== "string") fail("string");
211
+ return;
212
+ case "number":
213
+ if (typeof value !== "number" || !Number.isFinite(value)) fail("finite number");
214
+ return;
215
+ case "boolean":
216
+ if (typeof value !== "boolean") fail("boolean");
217
+ return;
218
+ case "null":
219
+ if (value !== null) fail("null");
220
+ return;
221
+ case "literal":
222
+ if (value !== description.value) fail(JSON.stringify(description.value));
223
+ return;
224
+ case "ref":
225
+ validateRef(description.table, value, path);
226
+ return;
227
+ case "id":
228
+ try {
229
+ assertId(value, description.table);
230
+ } catch {
231
+ fail(`id of table ${description.table}`);
232
+ }
233
+ return;
234
+ }
235
+ }
236
+
237
+ function validateRef(qualified: string, value: unknown, path: string): void {
238
+ const dot = qualified.lastIndexOf(".");
239
+ const owner = qualified.slice(0, dot);
240
+ const table = qualified.slice(dot + 1);
241
+ try {
242
+ assertId(value, table);
243
+ if (value.startsWith(`${owner}/`)) return;
244
+ } catch {
245
+ // Report the fully qualified table for invalid and mismatched IDs.
246
+ }
247
+ throw new Error(`${path}: expected id of table ${qualified}`);
248
+ }
package/src/values.ts ADDED
@@ -0,0 +1,98 @@
1
+ // The POC deliberately has one value language: lossless JSON. Keeping this rule
2
+ // shared by validators, the database and the client avoids engine-specific codecs.
3
+ export type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue };
4
+
5
+ export type JsonObject = { [key: string]: JsonValue };
6
+
7
+ export type Id<Table extends string = string> = string & {
8
+ readonly __table: Table;
9
+ };
10
+
11
+ export function assertTable(table: string): void {
12
+ if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(table)) throw new Error(`Invalid table name: ${table}`);
13
+ }
14
+
15
+ export function assertId(value: unknown, table?: string): asserts value is Id {
16
+ const logical = typeof value === "string" ? value.slice(value.indexOf("/") + 1) : "";
17
+ if (
18
+ typeof value !== "string" ||
19
+ !/^(?:[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*\/)?[A-Za-z][A-Za-z0-9_]*:[A-Za-z0-9_-]+$/.test(value) ||
20
+ (table !== undefined && !logical.startsWith(`${table}:`))
21
+ ) {
22
+ throw new Error(`Expected ${table ?? "table"}:key record id`);
23
+ }
24
+ }
25
+
26
+ export function isPlainObject(value: unknown): value is Record<string, unknown> {
27
+ if (value === null || typeof value !== "object") return false;
28
+ const prototype = Object.getPrototypeOf(value);
29
+ return prototype === Object.prototype || prototype === null;
30
+ }
31
+
32
+ /** Reject lossy JSON.stringify conversions rather than quietly changing data. */
33
+ export function assertJson(
34
+ value: unknown,
35
+ path = "value",
36
+ ancestors = new Set<object>(),
37
+ depthLeft = Infinity,
38
+ omitUndefined = false,
39
+ ): asserts value is JsonValue {
40
+ if (value === null || typeof value === "string" || typeof value === "boolean") return;
41
+ if (typeof value === "number" && Number.isFinite(value)) return;
42
+ if (!isJsonContainer(value)) {
43
+ throw new Error(`${path} must be a JSON value (numbers must be finite)`);
44
+ }
45
+
46
+ if (depthLeft <= 0) throw new Error(`${path} exceeds the JSON nesting limit`);
47
+ if (ancestors.has(value)) throw new Error(`${path} contains a cycle`);
48
+ ancestors.add(value);
49
+ try {
50
+ if (Reflect.ownKeys(value).some((key) => typeof key === "symbol"))
51
+ throw new Error(`${path} has a symbol key`);
52
+ if (Array.isArray(value)) {
53
+ assertJsonArray(value, path, ancestors, depthLeft - 1, omitUndefined);
54
+ } else {
55
+ for (const key of Object.getOwnPropertyNames(value)) {
56
+ const descriptor = Object.getOwnPropertyDescriptor(value, key)!;
57
+ if (!descriptor.enumerable || !("value" in descriptor))
58
+ throw new Error(`${path}.${key} must be an enumerable data property`);
59
+ if (omitUndefined && descriptor.value === undefined) continue;
60
+ assertJson(descriptor.value, `${path}.${key}`, ancestors, depthLeft - 1, omitUndefined);
61
+ }
62
+ }
63
+ } finally {
64
+ ancestors.delete(value);
65
+ }
66
+ }
67
+
68
+ /** Snapshot payloads so changing an input cannot mutate a pending query. */
69
+ export function jsonSnapshot(
70
+ value: unknown,
71
+ path = "value",
72
+ maxDepth = Infinity,
73
+ omitUndefined = false,
74
+ ): JsonValue {
75
+ assertJson(value, path, undefined, maxDepth, omitUndefined);
76
+ return JSON.parse(JSON.stringify(value)) as JsonValue;
77
+ }
78
+
79
+ function assertJsonArray(
80
+ value: unknown[],
81
+ path: string,
82
+ ancestors: Set<object>,
83
+ depthLeft: number,
84
+ omitUndefined: boolean,
85
+ ) {
86
+ if (Object.getOwnPropertyNames(value).length !== value.length + 1)
87
+ throw new Error(`${path} must be a dense JSON array without extra properties`);
88
+ for (let i = 0; i < value.length; i++) {
89
+ const descriptor = Object.getOwnPropertyDescriptor(value, String(i));
90
+ if (!descriptor?.enumerable || !("value" in descriptor))
91
+ throw new Error(`${path}[${i}] must be an enumerable data property`);
92
+ assertJson(descriptor.value, `${path}[${i}]`, ancestors, depthLeft, omitUndefined);
93
+ }
94
+ }
95
+
96
+ function isJsonContainer(value: unknown): value is Record<string, unknown> | unknown[] {
97
+ return typeof value === "object" && value !== null && (Array.isArray(value) || isPlainObject(value));
98
+ }
@@ -0,0 +1,8 @@
1
+ // Wire values shared by the function builders and the plugin compiler.
2
+ export const Visibility = {
3
+ Public: "public",
4
+ PluginOnly: "pluginOnly",
5
+ Internal: "internal",
6
+ } as const;
7
+
8
+ export type Visibility = (typeof Visibility)[keyof typeof Visibility];
@@ -0,0 +1,91 @@
1
+ import { isStructuredCallError } from "./call-error";
2
+ import type { MessageConnection } from "./transport";
3
+ import { MAX_WIRE_MESSAGE_BYTES } from "./protocol";
4
+ import type { Event } from "./protocol";
5
+ import { assertJson } from "./values";
6
+
7
+ // Structural subset accepted by browser and Bun WebSockets. Connection creation
8
+ // belongs to the caller; requiring OPEN avoids an unbounded pre-connect buffer.
9
+ export interface ClientWebSocket {
10
+ readonly url?: string;
11
+ readonly readyState: number;
12
+ readonly bufferedAmount: number;
13
+ send(text: string): void;
14
+ close(): void;
15
+ addEventListener(type: "message", listener: (event: { data: unknown }) => void): void;
16
+ addEventListener(type: "close" | "error", listener: () => void): void;
17
+ removeEventListener(type: "message", listener: (event: { data: unknown }) => void): void;
18
+ removeEventListener(type: "close" | "error", listener: () => void): void;
19
+ }
20
+
21
+ function decode(data: unknown): Event {
22
+ if (typeof data !== "string") throw new Error("expected JSON text frame");
23
+ const event: unknown = JSON.parse(data);
24
+ assertJson(event, "server event");
25
+ if (!event || typeof event !== "object" || Array.isArray(event)) throw new Error("invalid event");
26
+ if (event.type === "pluginchanged") {
27
+ validatePluginChange(event);
28
+ return event as Event;
29
+ }
30
+ const { type, id, result } = event;
31
+ if (typeof id !== "number" || !Number.isSafeInteger(id) || id < 0) throw new Error("invalid event ID");
32
+ if (type === "unsubscribed") return event as Event;
33
+ if (type !== "response" && type !== "subscription") throw new Error("invalid event result");
34
+ validateResult(result);
35
+ if ("error" in event && (!("Err" in result) || !isStructuredCallError(event.error)))
36
+ throw new Error("invalid event error details");
37
+ return event as Event;
38
+ }
39
+
40
+ function validatePluginChange(event: Record<string, unknown>): void {
41
+ if (
42
+ !Array.isArray(event.plugins) ||
43
+ event.plugins.some((id) => typeof id !== "string") ||
44
+ !event.catalog ||
45
+ typeof event.catalog !== "object" ||
46
+ Array.isArray(event.catalog)
47
+ )
48
+ throw new Error("invalid plugin change");
49
+ }
50
+
51
+ function validateResult(result: unknown): asserts result is object {
52
+ if (!result || typeof result !== "object" || Array.isArray(result)) throw new Error("invalid event result");
53
+ if (
54
+ Object.keys(result).length !== 1 ||
55
+ (!("Ok" in result) && !("Err" in result && typeof result.Err === "string"))
56
+ )
57
+ throw new Error("invalid event outcome");
58
+ }
59
+
60
+ export function webSocketConnection(socket: ClientWebSocket): MessageConnection {
61
+ if (socket.readyState !== 1) throw new Error("WebSocket must already be open");
62
+ return {
63
+ send(request) {
64
+ const text = JSON.stringify(request);
65
+ // Bound the SDK's socket queue as well as the server queues. A failed
66
+ // send closes the whole connection; admitted mutation outcomes are unknown.
67
+ if (text.length > MAX_WIRE_MESSAGE_BYTES || socket.bufferedAmount > MAX_WIRE_MESSAGE_BYTES)
68
+ throw new Error("WebSocket buffer capacity exceeded");
69
+ socket.send(text);
70
+ },
71
+ listen(onEvent, onClose) {
72
+ const message = (event: { data: unknown }) => {
73
+ try {
74
+ onEvent(decode(event.data));
75
+ } catch (error) {
76
+ onClose(error instanceof Error ? error : new Error(String(error)));
77
+ }
78
+ };
79
+ const closed = () => onClose(new Error("WebSocket closed; mutation outcomes may be unknown"));
80
+ socket.addEventListener("message", message);
81
+ socket.addEventListener("close", closed);
82
+ socket.addEventListener("error", closed);
83
+ return () => {
84
+ socket.removeEventListener("message", message);
85
+ socket.removeEventListener("close", closed);
86
+ socket.removeEventListener("error", closed);
87
+ };
88
+ },
89
+ close: () => socket.close(),
90
+ };
91
+ }
@@ -0,0 +1,7 @@
1
+ export const windowStateModule = "tokamaq:window-state";
2
+ export const readWindowState = "tokamaq:readWindowState";
3
+ export const writeWindowState = "tokamaq:writeWindowState";
4
+
5
+ export function isWindowStateFunction(name: string): boolean {
6
+ return name === readWindowState || name === writeWindowState;
7
+ }
package/src/within.ts ADDED
@@ -0,0 +1,24 @@
1
+ /** A promise that did not settle in time. */
2
+ export const TIMED_OUT: unique symbol = Symbol("timed out");
3
+
4
+ // Timers exist where waiting makes sense (window, local part); server functions have none to wait on.
5
+ const timers = globalThis as unknown as {
6
+ setTimeout(run: () => void, ms: number): unknown;
7
+ clearTimeout(timer: unknown): void;
8
+ };
9
+
10
+ /**
11
+ * Waits at most `ms` for `promise`: its value, or TIMED_OUT once the time is
12
+ * up. The promise keeps running; only the wait ends. For window and local code.
13
+ */
14
+ export async function within<T>(promise: PromiseLike<T>, ms: number): Promise<T | typeof TIMED_OUT> {
15
+ let timer: unknown;
16
+ try {
17
+ return await Promise.race([
18
+ promise,
19
+ new Promise<typeof TIMED_OUT>((resolve) => (timer = timers.setTimeout(() => resolve(TIMED_OUT), ms))),
20
+ ]);
21
+ } finally {
22
+ timers.clearTimeout(timer);
23
+ }
24
+ }
@@ -0,0 +1,5 @@
1
+ // Keep worker pipes and per-worker tables bounded even when a plugin is busy.
2
+ export const WORKER_FRAME_BYTES = 1024 * 1024;
3
+ export const WORKER_CAPACITY = 128;
4
+ // Leave room for operation, invocation and channel envelopes.
5
+ export const WORKER_DATA_BYTES = WORKER_FRAME_BYTES - 16 * 1024;