@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.
- 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/api.ts
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
// UI references carry names and compile-time argument/result types, never
|
|
2
|
+
// handlers. The generated api imports backend modules ONLY in type positions.
|
|
3
|
+
import type { FunctionDefinition, FunctionKind } from "./functions";
|
|
4
|
+
import type { Id } from "./values";
|
|
5
|
+
import type { Visibility } from "./visibility";
|
|
6
|
+
|
|
7
|
+
const callableReference: unique symbol = Symbol("tokamaq.reference.callable");
|
|
8
|
+
|
|
9
|
+
const referenceTypes: unique symbol = Symbol("tokamaq.reference.types");
|
|
10
|
+
|
|
11
|
+
export const functionKind: unique symbol = Symbol("tokamaq.function.kind");
|
|
12
|
+
|
|
13
|
+
export const functionName: unique symbol = Symbol("tokamaq.function.name");
|
|
14
|
+
|
|
15
|
+
export interface FunctionReference<
|
|
16
|
+
K extends FunctionKind,
|
|
17
|
+
A,
|
|
18
|
+
R,
|
|
19
|
+
V extends Visibility = Visibility,
|
|
20
|
+
Owner extends string = string,
|
|
21
|
+
> {
|
|
22
|
+
readonly [callableReference]: true;
|
|
23
|
+
readonly [functionName]: string;
|
|
24
|
+
readonly [functionKind]?: K;
|
|
25
|
+
readonly [referenceTypes]: { kind: K; args: A; result: R; visibility: V; owner: Owner };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
type ReferencesFromModule<M, V extends Visibility, Owner extends string> = {
|
|
29
|
+
readonly [
|
|
30
|
+
E in keyof M as M[E] extends FunctionDefinition<FunctionKind, unknown, unknown, V> ? E : never
|
|
31
|
+
]: ReferenceFromDefinition<M[E], Owner>;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
export type ReferenceFromDefinition<D, Owner extends string = string> =
|
|
35
|
+
D extends FunctionDefinition<infer K, infer A, infer R, infer V>
|
|
36
|
+
? FunctionReference<K, A, R, V, Owner>
|
|
37
|
+
: never;
|
|
38
|
+
|
|
39
|
+
export type HookReference<
|
|
40
|
+
K extends FunctionKind,
|
|
41
|
+
A,
|
|
42
|
+
R,
|
|
43
|
+
V extends Visibility = Visibility,
|
|
44
|
+
Owner extends string = string,
|
|
45
|
+
> = Omit<FunctionReference<K, A, R, V, Owner>, typeof callableReference>;
|
|
46
|
+
|
|
47
|
+
export type PointReference<
|
|
48
|
+
K extends FunctionKind,
|
|
49
|
+
A,
|
|
50
|
+
R,
|
|
51
|
+
Owner extends string,
|
|
52
|
+
Name extends string,
|
|
53
|
+
BeforeOnly extends boolean,
|
|
54
|
+
> = HookReference<K, A, R, Visibility, Owner> & {
|
|
55
|
+
readonly [functionName]: Name;
|
|
56
|
+
readonly pointBeforeOnly: BeforeOnly;
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
export type HookReferenceFromDefinition<D, Owner extends string> =
|
|
60
|
+
D extends FunctionDefinition<infer K, infer A, infer R, infer V> ? HookReference<K, A, R, V, Owner> : never;
|
|
61
|
+
|
|
62
|
+
export type ApiFromModule<M, Owner extends string = string> = ReferencesFromModule<
|
|
63
|
+
M,
|
|
64
|
+
typeof Visibility.Public,
|
|
65
|
+
Owner
|
|
66
|
+
>;
|
|
67
|
+
export type InternalFromModule<M, Owner extends string = string> = ReferencesFromModule<
|
|
68
|
+
M,
|
|
69
|
+
typeof Visibility.Internal,
|
|
70
|
+
Owner
|
|
71
|
+
>;
|
|
72
|
+
export type PluginFunctionsFromModule<M, Owner extends string = string> = ReferencesFromModule<
|
|
73
|
+
M,
|
|
74
|
+
typeof Visibility.PluginOnly,
|
|
75
|
+
Owner
|
|
76
|
+
>;
|
|
77
|
+
|
|
78
|
+
type QualifyIds<Owner extends string, T> =
|
|
79
|
+
T extends Id<infer Table>
|
|
80
|
+
? string extends Table
|
|
81
|
+
? T
|
|
82
|
+
: Table extends `${string}.${string}`
|
|
83
|
+
? T
|
|
84
|
+
: Id<`${Owner}.${Table}`>
|
|
85
|
+
: T extends object
|
|
86
|
+
? { [Key in keyof T]: QualifyIds<Owner, T[Key]> }
|
|
87
|
+
: T;
|
|
88
|
+
|
|
89
|
+
/** Cross-plugin references in a consumer that imports the owner's table handles. */
|
|
90
|
+
export type QualifiedPluginApi<Owner extends string, Api> = {
|
|
91
|
+
[Key in keyof Api]: Api[Key] extends HookReference<infer Kind, infer Args, infer Result, infer V, infer O>
|
|
92
|
+
? (Api[Key] extends FunctionReference<Kind, Args, Result, V, O>
|
|
93
|
+
? FunctionReference<Kind, QualifyIds<Owner, Args>, QualifyIds<Owner, Result>, V, O>
|
|
94
|
+
: HookReference<Kind, QualifyIds<Owner, Args>, QualifyIds<Owner, Result>, V, O>) & {
|
|
95
|
+
readonly [functionName]: Api[Key][typeof functionName];
|
|
96
|
+
} & (Api[Key] extends { readonly points: infer Points }
|
|
97
|
+
? { readonly points: QualifiedPluginApi<Owner, Points> }
|
|
98
|
+
: unknown) &
|
|
99
|
+
(Api[Key] extends { readonly pointBeforeOnly: infer BeforeOnly }
|
|
100
|
+
? { readonly pointBeforeOnly: BeforeOnly }
|
|
101
|
+
: unknown)
|
|
102
|
+
: never;
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
export type ArgsOf<R> = R extends HookReference<FunctionKind, infer A, unknown> ? A : never;
|
|
106
|
+
|
|
107
|
+
export type ResultOf<R> = R extends HookReference<FunctionKind, unknown, infer V> ? V : never;
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Generated references have an explicit list of wire names. The lazy form is
|
|
111
|
+
* retained for existing hand-written references.
|
|
112
|
+
* A reference must be at least module.export; folders add module path segments.
|
|
113
|
+
*/
|
|
114
|
+
export function createApi<T>(
|
|
115
|
+
namespace?: string,
|
|
116
|
+
names?: readonly string[],
|
|
117
|
+
kinds?: Readonly<Record<string, FunctionKind>>,
|
|
118
|
+
points?: Readonly<Record<string, readonly string[]>>,
|
|
119
|
+
): T {
|
|
120
|
+
const qualify = (name: string) => (namespace ? `${namespace}/${name}` : name);
|
|
121
|
+
if (names) {
|
|
122
|
+
type Branch = Record<string, object>;
|
|
123
|
+
const root: Branch = Object.create(null);
|
|
124
|
+
const branches = [root];
|
|
125
|
+
for (const name of names) {
|
|
126
|
+
const separator = name.indexOf(":");
|
|
127
|
+
const module = name.slice(0, separator);
|
|
128
|
+
const method = name.slice(separator + 1);
|
|
129
|
+
let branch = root;
|
|
130
|
+
for (const segment of module.split("/")) {
|
|
131
|
+
if (!Object.hasOwn(branch, segment)) {
|
|
132
|
+
const child: Branch = Object.create(null);
|
|
133
|
+
branch[segment] = child;
|
|
134
|
+
branches.push(child);
|
|
135
|
+
}
|
|
136
|
+
branch = branch[segment] as Branch;
|
|
137
|
+
}
|
|
138
|
+
const named = points?.[name];
|
|
139
|
+
branch[method] = Object.freeze({
|
|
140
|
+
[functionName]: qualify(name),
|
|
141
|
+
[functionKind]: kinds?.[name],
|
|
142
|
+
...(named?.length
|
|
143
|
+
? {
|
|
144
|
+
points: Object.freeze(
|
|
145
|
+
Object.fromEntries(
|
|
146
|
+
named.map((point) => [
|
|
147
|
+
point,
|
|
148
|
+
Object.freeze({
|
|
149
|
+
[functionName]: qualify(`${name}#${point}`),
|
|
150
|
+
[functionKind]: kinds?.[name],
|
|
151
|
+
}),
|
|
152
|
+
]),
|
|
153
|
+
),
|
|
154
|
+
),
|
|
155
|
+
}
|
|
156
|
+
: {}),
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
branches.forEach(Object.freeze);
|
|
160
|
+
return root as T;
|
|
161
|
+
}
|
|
162
|
+
const path = (parts: string[]): unknown =>
|
|
163
|
+
new Proxy(Object.create(null) as object, {
|
|
164
|
+
get(_target, key) {
|
|
165
|
+
if (key === functionName) {
|
|
166
|
+
if (parts.length < 2) throw new Error("Expected api.module.export reference");
|
|
167
|
+
return qualify(`${parts.slice(0, -1).join("/")}:${parts[parts.length - 1]}`);
|
|
168
|
+
}
|
|
169
|
+
if (typeof key === "string") return path([...parts, key]);
|
|
170
|
+
return undefined;
|
|
171
|
+
},
|
|
172
|
+
});
|
|
173
|
+
return path([]) as T;
|
|
174
|
+
}
|
package/src/auth.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { createApi, type FunctionReference } from "./api";
|
|
2
|
+
import { internalMutation, type AuthContext, type MutationContext, type User } from "./functions";
|
|
3
|
+
import { MEMBER_HOOK_RUN, provide, type Contract, type Provider } from "./internal/contracts";
|
|
4
|
+
import { v } from "./validators";
|
|
5
|
+
import type { JsonObject } from "./values";
|
|
6
|
+
|
|
7
|
+
/** The core identity query for the current connection, also available live. */
|
|
8
|
+
export const authCaller = createApi<{
|
|
9
|
+
auth: { caller: FunctionReference<"query", Record<string, never>, AuthContext> };
|
|
10
|
+
}>().auth.caller;
|
|
11
|
+
|
|
12
|
+
export type MemberHook = { [MEMBER_HOOK_RUN]: (member: User) => Promise<null> };
|
|
13
|
+
|
|
14
|
+
const memberHookProviderBrand: unique symbol = Symbol.for("tokamaq.auth.memberHook");
|
|
15
|
+
type MemberHookProvider = Provider<"server"> & { readonly [memberHookProviderBrand]: true };
|
|
16
|
+
|
|
17
|
+
export const memberFields = {
|
|
18
|
+
id: v.string(),
|
|
19
|
+
name: v.string(),
|
|
20
|
+
role: v.union(v.literal("owner"), v.literal("admin"), v.literal("member")),
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
/** Register a server mutation triggered by an auth membership change. */
|
|
24
|
+
export function onMember(
|
|
25
|
+
event: Contract<MemberHook, "server">,
|
|
26
|
+
handler: (ctx: MutationContext<Record<string, JsonObject>>, member: User) => unknown,
|
|
27
|
+
): MemberHookProvider {
|
|
28
|
+
// The build erases this argument in the worker bundle; mutations run in QuickJS.
|
|
29
|
+
const run =
|
|
30
|
+
handler &&
|
|
31
|
+
internalMutation({
|
|
32
|
+
args: memberFields,
|
|
33
|
+
async handler(ctx, member) {
|
|
34
|
+
await handler(ctx, member);
|
|
35
|
+
return null;
|
|
36
|
+
},
|
|
37
|
+
});
|
|
38
|
+
return { ...provide(event, { [MEMBER_HOOK_RUN]: run }), [memberHookProviderBrand]: true };
|
|
39
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { CallErrorDetails } from "./protocol";
|
|
2
|
+
|
|
3
|
+
export type CallError = string | ({ message: string } & CallErrorDetails);
|
|
4
|
+
import type { JsonValue } from "./values";
|
|
5
|
+
|
|
6
|
+
const remoteFunctionError = Symbol.for("tokamaq.remoteFunctionError");
|
|
7
|
+
|
|
8
|
+
export function isRemoteFunctionError(value: unknown): value is RemoteFunctionError {
|
|
9
|
+
return value instanceof Error && remoteFunctionError in value;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export class RemoteFunctionError extends Error {
|
|
13
|
+
readonly [remoteFunctionError] = true;
|
|
14
|
+
declare readonly plugin?: string;
|
|
15
|
+
declare readonly hook?: string;
|
|
16
|
+
declare readonly stage?: string;
|
|
17
|
+
declare readonly table?: string;
|
|
18
|
+
declare readonly point?: string;
|
|
19
|
+
declare readonly kind?: string;
|
|
20
|
+
declare readonly data?: JsonValue;
|
|
21
|
+
|
|
22
|
+
constructor(error: CallError) {
|
|
23
|
+
super(typeof error === "string" ? error : error.message);
|
|
24
|
+
if (typeof error !== "string") Object.assign(this, error);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function isStructuredCallError(value: unknown): value is CallErrorDetails {
|
|
29
|
+
return (
|
|
30
|
+
value !== null &&
|
|
31
|
+
typeof value === "object" &&
|
|
32
|
+
["plugin", "hook", "stage", "kind"].every(
|
|
33
|
+
(key) => typeof (value as Record<string, unknown>)[key] === "string",
|
|
34
|
+
) &&
|
|
35
|
+
Object.hasOwn(value, "data")
|
|
36
|
+
);
|
|
37
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { callHost, type HostBridge } from "./host";
|
|
2
|
+
import type { StorageReader } from "./storage";
|
|
3
|
+
|
|
4
|
+
type UploadOptions = { path?: string; name?: string };
|
|
5
|
+
|
|
6
|
+
export interface CallerStorage extends StorageReader {
|
|
7
|
+
upload(field: string, options?: UploadOptions): Promise<{ url: string }>;
|
|
8
|
+
uploadFile(localPath: string, field: string, options?: UploadOptions): Promise<string>;
|
|
9
|
+
downloadTo(id: string, localPath: string): Promise<void>;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function uploadOptions({ path, name }: UploadOptions) {
|
|
13
|
+
return {
|
|
14
|
+
...(path === undefined ? {} : { path }),
|
|
15
|
+
...(name === undefined ? {} : { name }),
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function createCallerStorage(host: HostBridge): CallerStorage {
|
|
20
|
+
return Object.freeze<CallerStorage>({
|
|
21
|
+
get: (id) => callHost(host, "storage.get", { id }),
|
|
22
|
+
byPath: (path) => callHost(host, "storage.byPath", { path }),
|
|
23
|
+
list: ({ prefix } = {}) => callHost(host, "storage.list", prefix === undefined ? {} : { prefix }),
|
|
24
|
+
url: (id) => callHost(host, "storage.url", { id }),
|
|
25
|
+
upload: (field, options = {}) => callHost(host, "storage.upload", { field, ...uploadOptions(options) }),
|
|
26
|
+
uploadFile: (localPath, field, options = {}) =>
|
|
27
|
+
callHost(host, "storage.uploadFile", { localPath, field, ...uploadOptions(options) }),
|
|
28
|
+
async downloadTo(id, localPath) {
|
|
29
|
+
await callHost(host, "storage.downloadTo", { id, localPath });
|
|
30
|
+
},
|
|
31
|
+
});
|
|
32
|
+
}
|
package/src/client.ts
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
// The client is a typed adapter, not a connection manager. In-process and
|
|
2
|
+
// WebSocket transports implement the same injected operations; the SDK never
|
|
3
|
+
// accesses sockets, timers, console, or other environment-specific globals.
|
|
4
|
+
import { functionName } from "./api";
|
|
5
|
+
import type { FunctionReference } from "./api";
|
|
6
|
+
import type { JsonValue } from "./values";
|
|
7
|
+
import { assertJson, jsonSnapshot } from "./values";
|
|
8
|
+
import type { ActionOptions, ActionTarget, MachineFailure } from "./functions";
|
|
9
|
+
import type { ActionSignal } from "./host";
|
|
10
|
+
import { isWindowStateFunction } from "./window-state-protocol";
|
|
11
|
+
|
|
12
|
+
/** An admitted local call did not settle before its old build was closed on reload. */
|
|
13
|
+
export class LocalReloadTimeout extends Error {
|
|
14
|
+
constructor() {
|
|
15
|
+
super("Local plugin build retired");
|
|
16
|
+
this.name = "LocalReloadTimeout";
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** The runtime and the plugin may each have their own copy of the SDK. */
|
|
21
|
+
export function isLocalReloadTimeout(error: unknown): boolean {
|
|
22
|
+
return error instanceof Error && error.name === "LocalReloadTimeout";
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface LocalTransport {
|
|
26
|
+
action(
|
|
27
|
+
name: string,
|
|
28
|
+
args: JsonValue,
|
|
29
|
+
options?: ActionOptions & { signal?: ActionSignal },
|
|
30
|
+
): Promise<JsonValue>;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Terminal errors mean the transport has removed the subscription. A new
|
|
34
|
+
* subscribe call is required to retry; ordinary rerun errors can still recover. */
|
|
35
|
+
export type SubscriptionEvent<T> = { value: T } | { error: Error; terminal?: boolean };
|
|
36
|
+
|
|
37
|
+
export interface ClientTransport {
|
|
38
|
+
query(name: string, args: JsonValue): Promise<JsonValue>;
|
|
39
|
+
mutation(name: string, args: JsonValue): Promise<JsonValue>;
|
|
40
|
+
/** Optional for existing custom transports; current native/WebSocket transports implement it. */
|
|
41
|
+
action?(name: string, args: JsonValue, on?: ActionTarget, signal?: ActionSignal): Promise<JsonValue>;
|
|
42
|
+
/**
|
|
43
|
+
* Transport owns initial delivery, update ordering and error delivery. If
|
|
44
|
+
* registration itself throws, it must clean up resources before throwing.
|
|
45
|
+
*/
|
|
46
|
+
subscribe(
|
|
47
|
+
name: string,
|
|
48
|
+
args: JsonValue,
|
|
49
|
+
onEvent: (event: SubscriptionEvent<JsonValue>) => void,
|
|
50
|
+
): () => void;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export class TokamaqClient {
|
|
54
|
+
readonly #transport: ClientTransport;
|
|
55
|
+
readonly #localTransport?: LocalTransport;
|
|
56
|
+
|
|
57
|
+
constructor(transport: ClientTransport, localTransport?: LocalTransport) {
|
|
58
|
+
this.#transport = transport;
|
|
59
|
+
this.#localTransport = localTransport;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async query<A, R>(reference: FunctionReference<"query", A, R>, args: NoInfer<A>): Promise<R> {
|
|
63
|
+
const value = await this.#transport.query(publicName(reference), jsonSnapshot(args, "args"));
|
|
64
|
+
assertJson(value, "query result");
|
|
65
|
+
return value as R;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async mutation<A, R>(reference: FunctionReference<"mutation", A, R>, args: NoInfer<A>): Promise<R> {
|
|
69
|
+
const value = await this.#transport.mutation(publicName(reference), jsonSnapshot(args, "args"));
|
|
70
|
+
assertJson(value, "mutation result");
|
|
71
|
+
return value as R;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
action<A, R>(reference: FunctionReference<"action", A, R>, args: NoInfer<A>): Promise<R>;
|
|
75
|
+
action<A, R>(
|
|
76
|
+
reference: FunctionReference<"action", A, R>,
|
|
77
|
+
args: NoInfer<A>,
|
|
78
|
+
options: ActionOptions & { signal?: ActionSignal },
|
|
79
|
+
): Promise<R | MachineFailure>;
|
|
80
|
+
async action<A, R>(
|
|
81
|
+
reference: FunctionReference<"action", A, R>,
|
|
82
|
+
args: NoInfer<A>,
|
|
83
|
+
options?: ActionOptions & { signal?: ActionSignal },
|
|
84
|
+
): Promise<R | MachineFailure> {
|
|
85
|
+
const name = publicName(reference);
|
|
86
|
+
const input = jsonSnapshot(args, "args");
|
|
87
|
+
const value = this.#localTransport
|
|
88
|
+
? await this.#localTransport.action(name, input, options)
|
|
89
|
+
: await this.#transport.action?.(name, input, options?.on, options?.signal);
|
|
90
|
+
if (value === undefined) throw new Error("Transport does not support actions");
|
|
91
|
+
assertJson(value, "action result");
|
|
92
|
+
return value as R;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
subscribe<A, R>(
|
|
96
|
+
reference: FunctionReference<"query", A, R>,
|
|
97
|
+
args: NoInfer<A>,
|
|
98
|
+
onEvent: (event: SubscriptionEvent<NoInfer<R>>) => void,
|
|
99
|
+
): () => void {
|
|
100
|
+
let active = true;
|
|
101
|
+
let registering = true;
|
|
102
|
+
let initialFailure = false;
|
|
103
|
+
let initialError: unknown;
|
|
104
|
+
let stop: () => void;
|
|
105
|
+
|
|
106
|
+
const notify = (event: SubscriptionEvent<JsonValue>) => {
|
|
107
|
+
if ("value" in event) {
|
|
108
|
+
try {
|
|
109
|
+
assertJson(event.value, "subscription result");
|
|
110
|
+
} catch (error) {
|
|
111
|
+
onEvent({
|
|
112
|
+
error: error instanceof Error ? error : new Error(String(error)),
|
|
113
|
+
});
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
onEvent(event as SubscriptionEvent<R>);
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
try {
|
|
121
|
+
stop = this.#transport.subscribe(publicName(reference), jsonSnapshot(args, "args"), (event) => {
|
|
122
|
+
if (!active) return;
|
|
123
|
+
try {
|
|
124
|
+
notify(event);
|
|
125
|
+
} catch (error) {
|
|
126
|
+
if (!registering) throw error;
|
|
127
|
+
// A synchronous observer must not abort transport registration:
|
|
128
|
+
// first capture its disposer, then close and rethrow the original
|
|
129
|
+
// failure. A separate flag also preserves `throw undefined`.
|
|
130
|
+
active = false;
|
|
131
|
+
initialFailure = true;
|
|
132
|
+
initialError = error;
|
|
133
|
+
}
|
|
134
|
+
});
|
|
135
|
+
} catch (error) {
|
|
136
|
+
active = false;
|
|
137
|
+
throw error;
|
|
138
|
+
} finally {
|
|
139
|
+
registering = false;
|
|
140
|
+
}
|
|
141
|
+
if (initialFailure) {
|
|
142
|
+
try {
|
|
143
|
+
stop();
|
|
144
|
+
} catch {
|
|
145
|
+
/* The observer failure takes precedence over cleanup failures. */
|
|
146
|
+
}
|
|
147
|
+
throw initialError;
|
|
148
|
+
}
|
|
149
|
+
// Closing twice is harmless; late transport events must not reach the UI.
|
|
150
|
+
return () => {
|
|
151
|
+
if (active) {
|
|
152
|
+
active = false;
|
|
153
|
+
stop();
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function publicName(reference: { readonly [functionName]: string }): string {
|
|
160
|
+
const name = reference[functionName];
|
|
161
|
+
if (isWindowStateFunction(name)) throw new Error("Window state is private to its plugin");
|
|
162
|
+
return name;
|
|
163
|
+
}
|