@tokamaq/sdk 0.0.0-stage → 0.1.0-dev.2

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,260 @@
1
+ import type { FunctionDefinition, MachineFailure, FunctionKind, WireResult } from "../functions";
2
+ import { callHost, type HostBridge, type LocalChannel, type ChannelHandler } from "../host";
3
+ import { jsonSnapshot, type JsonValue } from "../values";
4
+
5
+ export const contractName = /^[A-Za-z][A-Za-z0-9_-]*$/;
6
+ export const MEMBER_HOOK_RUN = "run";
7
+
8
+ const contractBrand: unique symbol = Symbol.for("tokamaq.contract");
9
+ const providerBrand: unique symbol = Symbol.for("tokamaq.contract.provider");
10
+ export const contractScope = Symbol.for("tokamaq.contract.scope");
11
+ export const providerIdentity = Symbol.for("tokamaq.contract.buildIdentity");
12
+
13
+ /** A stable cache key for this registration in this local build. */
14
+ export function localProviderIdentity(provider: object): object | undefined {
15
+ return (provider as { [providerIdentity]?: object })[providerIdentity];
16
+ }
17
+
18
+ export const openChannel = Symbol.for("tokamaq.contract.channel");
19
+
20
+ export function hasLocalChannel(provider: object): boolean {
21
+ return typeof (provider as { [openChannel]?: unknown })[openChannel] === "function";
22
+ }
23
+
24
+ /** Open a linked data call, when the provider runs in another QuickJS process. */
25
+ export function openLocalChannel(
26
+ provider: object,
27
+ method: string,
28
+ args: unknown,
29
+ receive: ChannelHandler,
30
+ ): LocalChannel | undefined {
31
+ const entry = provider as {
32
+ [openChannel]?: (method: string, args: unknown, receive: ChannelHandler) => LocalChannel;
33
+ };
34
+ return entry[openChannel]?.(method, args, receive);
35
+ }
36
+
37
+ export type ContractTarget = "caller" | "server";
38
+ export interface ContractKey {
39
+ readonly name: string;
40
+ readonly owner?: string;
41
+ readonly on: ContractTarget;
42
+ /** Route every method across local QuickJS processes. */
43
+ readonly dataMethods?: true;
44
+ }
45
+
46
+ export interface Contract<T extends object, P extends ContractTarget = ContractTarget> extends ContractKey {
47
+ readonly [contractBrand]: (shape: T) => T;
48
+ readonly on: P;
49
+ list(...context: LookupContext<P>): Promise<readonly BoundProvider<T, P>[]>;
50
+ get(id: string, ...context: LookupContext<P>): ProviderSelection<BoundProvider<T, P>>;
51
+ }
52
+
53
+ interface LocalLookupOptions {
54
+ readonly onIncompatible?: (plugin: string) => void;
55
+ /** Cancel provider discovery and calls made through the returned list. */
56
+ readonly signal?: NonNullable<HostBridge["signal"]>;
57
+ /** When the live input uses a different signal, identify it so it stays off the wire. */
58
+ readonly inputSignal?: NonNullable<HostBridge["signal"]>;
59
+ /** Handle process failures without hiding healthy providers or their own errors. */
60
+ readonly onUnavailable?: (failure: { plugin: string; message: string; notice?: string }) => void;
61
+ }
62
+
63
+ export interface ContractContext {
64
+ readonly [contractScope]: ContractScope;
65
+ }
66
+
67
+ type LookupContext<P extends ContractTarget> = P extends "caller"
68
+ ? [context: ContractContext, options?: LocalLookupOptions]
69
+ : [context?: ContractContext];
70
+
71
+ type BoundProvider<T, P extends ContractTarget> = {
72
+ [K in keyof T]: NonNullable<T[K]> extends (...args: infer A) => infer R
73
+ ? P extends "server"
74
+ ? (...args: A) => Promise<WireResult<R>>
75
+ : T[K]
76
+ : T[K];
77
+ };
78
+
79
+ /** Await a selection for its data and optional methods, or call a required method directly. */
80
+ type ProviderSelection<T> = PromiseLike<T | undefined> & {
81
+ [K in keyof T as T[K] extends (...args: never[]) => unknown ? K : never]: T[K] extends (
82
+ ...args: infer A
83
+ ) => infer R
84
+ ? (...args: A) => Promise<Awaited<R>>
85
+ : never;
86
+ };
87
+
88
+ function select<T extends object>(id: string, lookup: () => Promise<T | undefined>): ProviderSelection<T> {
89
+ const selection: PromiseLike<T | undefined> = {
90
+ then: (resolve, reject) => lookup().then(resolve, reject),
91
+ };
92
+ return new Proxy(selection, {
93
+ get(target, member) {
94
+ if (member === "then") return target.then;
95
+ if (typeof member !== "string") return undefined;
96
+ return async (...args: unknown[]) => {
97
+ const provider = await lookup();
98
+ const method = provider && (provider as Record<string, unknown>)[member];
99
+ if (typeof method !== "function") throw new Error(`Contract provider ${id} has no ${member} method`);
100
+ return method(...args);
101
+ };
102
+ },
103
+ }) as ProviderSelection<T>;
104
+ }
105
+
106
+ type Implementation<T, P extends ContractTarget> = {
107
+ [K in keyof T]: NonNullable<T[K]> extends (...args: infer A) => infer R
108
+ ? P extends "caller"
109
+ ? ((...args: A) => R) | LocalImplementation<A, R>
110
+ : A extends [infer Input] | []
111
+ ? FunctionDefinition<FunctionKind, Input, WireResult<R>>
112
+ : never
113
+ : T[K];
114
+ };
115
+ type LocalImplementation<A extends unknown[], R> = A extends [infer Input] | []
116
+ ? FunctionDefinition<"action", Input, WireResult<R | MachineFailure>> & { readonly on: "caller" }
117
+ : never;
118
+
119
+ export interface Provider<P extends ContractTarget> {
120
+ readonly [providerBrand]: true;
121
+ readonly contract: ContractKey & { readonly on: P };
122
+ readonly implementation: Readonly<Record<string, unknown>>;
123
+ }
124
+
125
+ export function contract<T extends object>(
126
+ name: string,
127
+ options: { on: "caller"; dataMethods?: true },
128
+ ): Contract<T, "caller">;
129
+ export function contract<T extends object>(name: string, options?: { on: "server" }): Contract<T, "server">;
130
+ export function contract<T extends object>(
131
+ name: string,
132
+ options?: { on: ContractTarget; dataMethods?: true },
133
+ ) {
134
+ return options?.on === "caller"
135
+ ? contractReference<T, "caller">(name, "caller", undefined, true)
136
+ : contractReference<T, "server">(name, "server");
137
+ }
138
+
139
+ /** Used by the build to import contract keys without importing the defining plugin's code. */
140
+ export function contractReference<T extends object, P extends ContractTarget>(
141
+ name: string,
142
+ on: P,
143
+ owner?: string,
144
+ dataMethods?: true,
145
+ ): Contract<T, P> {
146
+ if (!contractName.test(name)) throw new Error(`Invalid contract name: ${name}`);
147
+ const key = Object.freeze({
148
+ name,
149
+ on,
150
+ ...(owner === undefined ? {} : { owner }),
151
+ ...(dataMethods === undefined ? {} : { dataMethods }),
152
+ });
153
+ const resolve = async (
154
+ context?: ContractContext,
155
+ id?: string,
156
+ options?: LocalLookupOptions,
157
+ ): Promise<readonly ContractEntry[]> => {
158
+ const scoped = context?.[contractScope] ?? (on === "server" ? serverScope : undefined);
159
+ if (!scoped) throw new Error("Contract lookup requires a plugin function; pass ctx in actions");
160
+ return scoped.list(key, id, options);
161
+ };
162
+ return Object.freeze({
163
+ ...key,
164
+ [contractBrand]: (shape: T) => shape,
165
+ list: async (context?: ContractContext, options?: LocalLookupOptions) =>
166
+ (await resolve(context, undefined, options)).map(
167
+ ({ implementation }) => implementation as BoundProvider<T, P>,
168
+ ),
169
+ get: (id: string, context?: ContractContext, options?: LocalLookupOptions) =>
170
+ select(
171
+ id,
172
+ async () =>
173
+ (await resolve(context, id, options)).find((provider) => provider.id === id)?.implementation as
174
+ | BoundProvider<T, P>
175
+ | undefined,
176
+ ),
177
+ });
178
+ }
179
+
180
+ /** A provider is registered by exporting it from an authored plugin module. */
181
+ export function provide<T extends object, P extends ContractTarget>(
182
+ key: Contract<T, P>,
183
+ implementation: Implementation<NoInfer<T>, P>,
184
+ _options?: P extends "caller" ? { unavailable: string } : never,
185
+ ): Provider<P> {
186
+ return Object.freeze({
187
+ [providerBrand]: true as const,
188
+ contract: key,
189
+ implementation: implementation as Readonly<Record<string, unknown>>,
190
+ });
191
+ }
192
+
193
+ export interface ContractEntry {
194
+ readonly id: string;
195
+ readonly implementation: object;
196
+ }
197
+
198
+ export interface ContractScope {
199
+ list(key: ContractKey, id?: string, options?: LocalLookupOptions): Promise<readonly ContractEntry[]>;
200
+ }
201
+
202
+ /** List usable local providers alongside builds whose declarations no longer match. */
203
+ export async function localProviders<T extends object>(key: Contract<T, "caller">, context: ContractContext) {
204
+ const incompatible: string[] = [];
205
+ const entries = await context[contractScope].list(key, undefined, {
206
+ onIncompatible: (plugin) => incompatible.push(plugin),
207
+ });
208
+ return {
209
+ providers: entries.map((entry) => entry.implementation as BoundProvider<T, "caller">),
210
+ incompatible,
211
+ };
212
+ }
213
+
214
+ let serverScope: ContractScope | undefined;
215
+
216
+ export function serverContracts(host: HostBridge): ContractScope {
217
+ return {
218
+ async list(key) {
219
+ if (key.on !== "server") throw new Error("Local contracts run in a plugin process");
220
+ const providers = await callHost(host, "contract.list", {
221
+ name: key.name,
222
+ ...(key.owner && { owner: key.owner }),
223
+ });
224
+ return providers.map(({ id, data, methods }) => ({
225
+ id,
226
+ implementation: Object.freeze({
227
+ ...data,
228
+ ...Object.fromEntries(
229
+ Object.entries(methods).map(([member, name]) => [
230
+ member,
231
+ (args: unknown = {}) =>
232
+ callHost(host, "plugin.call", {
233
+ name,
234
+ args: jsonSnapshot(args, "contract arguments"),
235
+ contract: key.name,
236
+ }),
237
+ ]),
238
+ ),
239
+ }),
240
+ }));
241
+ },
242
+ };
243
+ }
244
+
245
+ export function withServerContracts<T>(host: HostBridge, invoke: () => Promise<T>): Promise<T> {
246
+ // Legacy query/mutation lookup. Their bundle instance serves one invocation.
247
+ // Concurrent action and local workers carry scope on the handler context.
248
+ const previous = serverScope;
249
+ serverScope = serverContracts(host);
250
+ return invoke().finally(() => {
251
+ serverScope = previous;
252
+ });
253
+ }
254
+
255
+ export function contractData(implementation: object, methods: readonly string[]): JsonValue {
256
+ return jsonSnapshot(
257
+ Object.fromEntries(Object.entries(implementation).filter(([name]) => !methods.includes(name))),
258
+ "contract provider data",
259
+ );
260
+ }
@@ -0,0 +1,21 @@
1
+ import type { HostBridge } from "../host";
2
+
3
+ export interface MachineScope {
4
+ readonly host: HostBridge;
5
+ readonly besideServer?: <T>(operation: () => Promise<T>) => Promise<T>;
6
+ }
7
+
8
+ // Kept off the context object, so plugin code cannot reach the host bridge
9
+ // through it. One entry per context, released with it.
10
+ const scopes = new WeakMap<object, MachineScope>();
11
+
12
+ export function bindMachineScope<T extends object>(ctx: T, scope: MachineScope): T {
13
+ scopes.set(ctx, scope);
14
+ return ctx;
15
+ }
16
+
17
+ export function machineScopeOf(ctx: object): MachineScope {
18
+ const scope = scopes.get(ctx);
19
+ if (!scope) throw new TypeError("machines(ctx) needs the ctx of a Tokamaq function");
20
+ return scope;
21
+ }
package/src/local.ts ADDED
@@ -0,0 +1,22 @@
1
+ export interface LocalProcessOptions {
2
+ cwd?: string;
3
+ env?: Readonly<Record<string, string>>;
4
+ /** Let a bounded write finish on ordinary cancellation, so it can release its locks. */
5
+ finishOnCancel?: boolean;
6
+ }
7
+
8
+ /** Output is decoded as UTF-8 and split on LF or CRLF. Each stream is read once. */
9
+ export interface RunningProcess {
10
+ readonly stdout: AsyncIterable<string>;
11
+ readonly stderr: AsyncIterable<string>;
12
+ readonly exited: Promise<number>;
13
+ write(input: string | Uint8Array): void;
14
+ closeInput(): void;
15
+ stop(signal?: "SIGTERM" | "SIGKILL"): void;
16
+ }
17
+
18
+ /** Start an executable directly with an argument vector. No shell is implied. */
19
+ export type LocalProcess = (
20
+ argv: readonly [string, ...string[]],
21
+ options?: LocalProcessOptions,
22
+ ) => RunningProcess;
package/src/plugin.ts ADDED
@@ -0,0 +1,162 @@
1
+ /** Portable packaging identity. Loading/lifecycle/capabilities are host concerns. */
2
+ import { jsonSnapshot, type JsonValue } from "./values";
3
+
4
+ export interface PluginDefinition {
5
+ readonly id: string;
6
+ readonly version: string;
7
+ readonly name?: string;
8
+ readonly description?: string;
9
+ readonly api?: string;
10
+ readonly depends?: Readonly<Record<string, string>>;
11
+ readonly optional?: Readonly<Record<string, string>>;
12
+ readonly breaks?: Readonly<Record<string, string>>;
13
+ readonly permissions?: readonly string[];
14
+ readonly maintenance?: string;
15
+ readonly contributes?: Readonly<Record<string, readonly JsonValue[]>>;
16
+ readonly exports?: string;
17
+ }
18
+
19
+ export function declaresAccessTo(
20
+ plugin: Pick<PluginDefinition, "id" | "depends" | "optional">,
21
+ owner: string,
22
+ ): boolean {
23
+ return (
24
+ plugin.id === owner ||
25
+ Object.hasOwn(plugin.depends ?? {}, owner) ||
26
+ Object.hasOwn(plugin.optional ?? {}, owner)
27
+ );
28
+ }
29
+
30
+ function versionSyntax(version: string): boolean {
31
+ const [head, build, ...extra] = version.split("+");
32
+ if (extra.length) return false;
33
+ const separator = head!.indexOf("-");
34
+ const core = separator < 0 ? head! : head!.slice(0, separator);
35
+ const prerelease = separator < 0 ? undefined : head!.slice(separator + 1);
36
+ if (!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(core)) return false;
37
+ const identifiers = (part: string, pre: boolean) =>
38
+ part
39
+ .split(".")
40
+ .every(
41
+ (id) => /^[0-9A-Za-z-]+$/.test(id) && !(pre && /^\d+$/.test(id) && id.length > 1 && id[0] === "0"),
42
+ );
43
+ return (
44
+ (prerelease === undefined || identifiers(prerelease, true)) &&
45
+ (build === undefined || identifiers(build, false))
46
+ );
47
+ }
48
+
49
+ export function definePlugin(
50
+ authored: Omit<PluginDefinition, "depends" | "optional"> & {
51
+ readonly depends?: PluginDefinition["depends"] | readonly string[];
52
+ readonly optional?: PluginDefinition["optional"] | readonly string[];
53
+ },
54
+ ): Readonly<PluginDefinition> {
55
+ for (const key of ["depends", "optional"] as const) {
56
+ const ids = authored[key];
57
+ if (Array.isArray(ids) && (ids.some((id) => typeof id !== "string") || new Set(ids).size !== ids.length))
58
+ throw new Error(`Invalid plugin ${key} requirements`);
59
+ }
60
+ let definition: PluginDefinition = {
61
+ ...authored,
62
+ ...(Array.isArray(authored.depends)
63
+ ? { depends: Object.fromEntries(authored.depends.map((id) => [id, "*"])) }
64
+ : {}),
65
+ ...(Array.isArray(authored.optional)
66
+ ? { optional: Object.fromEntries(authored.optional.map((id) => [id, "*"])) }
67
+ : {}),
68
+ } as PluginDefinition;
69
+ definition = jsonSnapshot(definition, "plugin descriptor") as unknown as PluginDefinition;
70
+ if (
71
+ !definition ||
72
+ typeof definition.id !== "string" ||
73
+ !/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(definition.id)
74
+ ) {
75
+ throw new Error("Plugin id must be a stable lowercase identifier");
76
+ }
77
+ const fields = [
78
+ "id",
79
+ "name",
80
+ "description",
81
+ "version",
82
+ "api",
83
+ "depends",
84
+ "optional",
85
+ "breaks",
86
+ "permissions",
87
+ "maintenance",
88
+ "contributes",
89
+ "exports",
90
+ ];
91
+ if (Object.keys(definition).some((key) => !fields.includes(key))) {
92
+ throw new Error("Unsupported plugin descriptor field");
93
+ }
94
+ if (typeof definition.version !== "string" || !versionSyntax(definition.version)) {
95
+ throw new Error("Plugin version must be a semantic version");
96
+ }
97
+ validateRequirements(definition);
98
+ validateLists(definition);
99
+ validateMetadata(definition);
100
+ function freeze(value: unknown): void {
101
+ if (value && typeof value === "object") {
102
+ for (const child of Object.values(value)) freeze(child);
103
+ Object.freeze(value);
104
+ }
105
+ }
106
+ freeze(definition);
107
+ return definition;
108
+ }
109
+
110
+ function validateRequirements(definition: PluginDefinition) {
111
+ for (const key of ["depends", "optional", "breaks"] as const) {
112
+ const map = definition[key];
113
+ if (map === undefined) continue;
114
+ if (
115
+ !map ||
116
+ typeof map !== "object" ||
117
+ Array.isArray(map) ||
118
+ Object.entries(map).some(
119
+ ([id, range]) =>
120
+ !/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(id) || typeof range !== "string" || !range,
121
+ )
122
+ ) {
123
+ throw new Error(`Invalid plugin ${key} requirements`);
124
+ }
125
+ }
126
+ }
127
+
128
+ function validateLists(definition: PluginDefinition) {
129
+ for (const key of ["permissions"] as const) {
130
+ const list = definition[key];
131
+ if (
132
+ list !== undefined &&
133
+ (!Array.isArray(list) ||
134
+ list.some((value) => typeof value !== "string" || !value) ||
135
+ new Set(list).size !== list.length)
136
+ )
137
+ throw new Error(`Invalid plugin ${key}`);
138
+ }
139
+ }
140
+
141
+ function validateMetadata(definition: PluginDefinition) {
142
+ for (const field of ["name", "description", "maintenance"] as const)
143
+ if (definition[field] !== undefined && typeof definition[field] !== "string")
144
+ throw new Error(`Invalid plugin ${field}`);
145
+ if (
146
+ definition.api !== undefined &&
147
+ (typeof definition.api !== "string" || !definition.api.startsWith("tokamaq@"))
148
+ ) {
149
+ throw new Error("Invalid host API requirement");
150
+ }
151
+ if (definition.exports !== undefined && typeof definition.exports !== "string")
152
+ throw new Error("Invalid plugin exports path");
153
+ if (
154
+ definition.contributes !== undefined &&
155
+ (!definition.contributes ||
156
+ typeof definition.contributes !== "object" ||
157
+ Array.isArray(definition.contributes) ||
158
+ Object.values(definition.contributes).some((value) => !Array.isArray(value)))
159
+ ) {
160
+ throw new Error("Plugin contributions must be static arrays");
161
+ }
162
+ }
package/src/points.ts ADDED
@@ -0,0 +1,79 @@
1
+ import type { ActionContext, MutationContext, QueryContext } from "./functions";
2
+ import { callHost, type HostBridge } from "./host";
3
+ import { jsonSnapshot } from "./values";
4
+
5
+ declare const pointBrand: unique symbol;
6
+
7
+ type PointContext = Pick<QueryContext<{}> | MutationContext<{}> | ActionContext, "call">;
8
+
9
+ interface Point {
10
+ readonly [pointBrand]: true;
11
+ <T>(ctx: PointContext, name: string, value: T): Promise<T>;
12
+ <T>(
13
+ ctx: PointContext,
14
+ name: string,
15
+ value: T,
16
+ options: { collect: true },
17
+ ): Promise<readonly PointContribution<T>[]>;
18
+ <I, R>(ctx: PointContext, name: string, input: I, run: (input: I) => R): Promise<PointResult<Awaited<R>>>;
19
+ }
20
+ export type PointContribution<T> = { readonly plugin: string; readonly value: T };
21
+
22
+ type PointResult<T> = T extends void ? null : T;
23
+ type PointOption<I, R> = { collect: true } | ((args: I) => R);
24
+ type PointBinding = <I, R>(name: string, args: I, option?: PointOption<I, R>) => Promise<unknown>;
25
+ export type PointLifetime = { active: boolean };
26
+
27
+ const bindings = new WeakMap<PointContext, PointBinding>();
28
+
29
+ export const point = (async <I, R>(ctx: PointContext, name: string, args: I, option?: PointOption<I, R>) => {
30
+ const binding = bindings.get(ctx);
31
+ if (!binding) throw new Error("point(ctx, ...) requires the context of its query, mutation or action");
32
+ return binding(name, args, option);
33
+ }) as Point;
34
+
35
+ export function bindPoint<C extends PointContext>(
36
+ ctx: C,
37
+ host: HostBridge,
38
+ lifetime: PointLifetime,
39
+ scope: Pick<HostBridge, "pointOwner" | "hookPoints"> = host,
40
+ ): C {
41
+ const { name: owner, declared } = scope.pointOwner ?? {};
42
+ const active = scope.hookPoints;
43
+ const points = active?.length ? new Set(active) : undefined;
44
+ const requireActive = () => {
45
+ if (!lifetime.active) throw new Error("Cannot use point(ctx, ...) after its call has ended");
46
+ };
47
+
48
+ bindings.set(ctx, async <I, R>(name: string, args: I, option?: PointOption<I, R>) => {
49
+ requireActive();
50
+ if (!declared?.includes(name))
51
+ throw new Error(`Point "${name}" is not declared by function "${owner ?? "unknown"}"`);
52
+ const run = typeof option === "function" ? option : undefined;
53
+ const collect = typeof option === "object" && option.collect === true;
54
+ if (!points?.has(name)) {
55
+ if (collect) return [];
56
+ if (!run) return args;
57
+ const result = await run(args);
58
+ return result === undefined ? null : result;
59
+ }
60
+
61
+ const input = await callHost(host, "point.stage", {
62
+ name,
63
+ stage: collect ? "collect" : "before",
64
+ args: jsonSnapshot(args, "point input", Infinity, true),
65
+ });
66
+ if (!run) return input;
67
+
68
+ requireActive();
69
+ const result = await run(input as I);
70
+ requireActive();
71
+ return callHost(host, "point.stage", {
72
+ name,
73
+ stage: "after",
74
+ args: input,
75
+ result: jsonSnapshot(result === undefined ? null : result, "point result", Infinity, true),
76
+ });
77
+ });
78
+ return ctx;
79
+ }
@@ -0,0 +1,64 @@
1
+ // Generated by cargo run -p server --features protocol-codegen --bin export-protocol.
2
+ // Edit packages/server/src/protocol.rs, not this file.
3
+ import type { JsonValue } from "./values";
4
+ import type { ActionTarget } from "./functions";
5
+
6
+ export const MAX_WIRE_MESSAGE_BYTES = 1048576;
7
+ export const LOCAL_RELOAD_GRACE_MS = 5000;
8
+
9
+ export type CallErrorDetails = {
10
+ plugin: string;
11
+ hook: string;
12
+ stage: string;
13
+ kind: string;
14
+ data: JsonValue;
15
+ table?: string;
16
+ point?: string;
17
+ };
18
+
19
+ export type Request =
20
+ | { type: "query"; id: number; name: string; args: JsonValue }
21
+ | { type: "mutation"; id: number; name: string; args: JsonValue }
22
+ | {
23
+ type: "action";
24
+ id: number;
25
+ name: string;
26
+ args: JsonValue;
27
+ on?: ActionTarget;
28
+ window?: boolean;
29
+ hookPlans?: boolean;
30
+ pointPlans?: boolean;
31
+ }
32
+ | {
33
+ type: "localcall";
34
+ id: number;
35
+ name: string;
36
+ args: JsonValue;
37
+ kind: "query" | "mutation" | "action";
38
+ depth: number;
39
+ thread: string | null;
40
+ hookScope?: number;
41
+ proof?: string;
42
+ on?: ActionTarget;
43
+ window?: boolean;
44
+ hookPlans?: boolean;
45
+ pointPlans?: boolean;
46
+ }
47
+ | { type: "hookstage"; id: number; scope: number; done?: boolean }
48
+ | { type: "cancelaction"; id: number }
49
+ | { type: "subscribe"; id: number; name: string; args: JsonValue }
50
+ | { type: "plugins"; id: number }
51
+ | { type: "pluginspage"; id: number; revision: string; offset: number }
52
+ | { type: "pluginasset"; id: number; plugin: string; name: string; revision: string; offset: number }
53
+ | { type: "unsubscribe"; id: number };
54
+
55
+ export type Event =
56
+ | { type: "pluginchanged"; plugins: Array<string>; catalog: JsonValue }
57
+ | { type: "response"; id: number; result: { Ok: JsonValue } | { Err: string }; error?: CallErrorDetails }
58
+ | {
59
+ type: "subscription";
60
+ id: number;
61
+ result: { Ok: JsonValue } | { Err: string };
62
+ error?: CallErrorDetails;
63
+ }
64
+ | { type: "unsubscribed"; id: number };