@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,25 @@
1
+ // Internal compiler interface shared by the window builder and window test config.
2
+ export { eventNamespace, reservedAttribute } from "./component-actions.ts";
3
+ export {
4
+ attributeFilters,
5
+ flattenAttributes,
6
+ isAriaAttribute,
7
+ isSearchAttribute,
8
+ resolveScreenSearch,
9
+ screenElements,
10
+ screenTarget,
11
+ type ScreenSearch,
12
+ type ScreenTree,
13
+ unnamedTargetWarning,
14
+ } from "./screen-search.ts";
15
+ export { Visibility } from "./src/visibility.ts";
16
+ export { windowStateModule } from "./src/window-state-protocol.ts";
17
+ export { clientEntry } from "./tools/client-entry.mjs";
18
+ export {
19
+ definitionInfo,
20
+ pluginCompilerOptions,
21
+ runtimeExportNames,
22
+ serverConfigPath,
23
+ } from "./tools/plugin-compiler.mjs";
24
+ export { readDescriptor } from "./tools/plugin-descriptor.ts";
25
+ export { isInternalReferenceModule, isServerModule, serverDirectory } from "./tools/server-files.mjs";
@@ -0,0 +1,60 @@
1
+ /// <reference types="node" />
2
+ import { createHash } from "node:crypto";
3
+ import { chmod, mkdir, readdir, rmdir, unlink } from "node:fs/promises";
4
+ import { isAbsolute, join } from "node:path";
5
+ import type { LaunchSettings } from "../src/agent-turn";
6
+
7
+ function digest(value: string) {
8
+ return createHash("sha256").update(value).digest("hex");
9
+ }
10
+
11
+ function threadHome(threadId: string) {
12
+ const data = process.env.TOKAMAQ_APP_DATA_DIR;
13
+ if (!data || !isAbsolute(data)) throw new Error("The Runner's data folder is unavailable.");
14
+ return join(data, "ai", "launch-homes", digest(threadId));
15
+ }
16
+
17
+ async function clearDirectory(directory: string) {
18
+ for (const child of await readdir(directory, { withFileTypes: true })) {
19
+ const path = join(directory, child.name);
20
+ if (child.isDirectory()) await clearDirectory(path);
21
+ else await unlink(path);
22
+ }
23
+ await rmdir(directory);
24
+ }
25
+
26
+ /** Remove this Runner's homes after Chat deletes the thread. */
27
+ export async function removeAgentLaunchHomes(threadId: string) {
28
+ await clearDirectory(threadHome(threadId)).catch((cause: unknown) => {
29
+ if (!(cause instanceof Error && "code" in cause && cause.code === "ENOENT")) throw cause;
30
+ });
31
+ }
32
+
33
+ const claudeInherited = /^(?:ANTHROPIC_|CLAUDE_|AWS_BEARER_TOKEN_BEDROCK$)/;
34
+ const codexInherited = /^(?:OPENAI_|CODEX_)/;
35
+
36
+ /** Prepare a CLI's environment for setup or a turn in the same private home. */
37
+ export async function withAgentLaunch<T>(
38
+ settings: LaunchSettings,
39
+ cli: "claude" | "codex",
40
+ turn: (settings: LaunchSettings) => Promise<T>,
41
+ ): Promise<T> {
42
+ if (!/^[a-f0-9]{64}$/.test(settings.identity)) throw new Error("Invalid agent launch identity.");
43
+ const directory = join(threadHome(settings.threadId), cli, settings.identity);
44
+ await mkdir(directory, { recursive: true, mode: 0o700 });
45
+ // Also protect an existing directory, independently of the Runner's umask.
46
+ await chmod(directory, 0o700);
47
+ const homeVariable = cli === "claude" ? "CLAUDE_CONFIG_DIR" : "CODEX_HOME";
48
+ const inherited = cli === "claude" ? claudeInherited : codexInherited;
49
+ const env = new Map<string, string>();
50
+ for (const [name, value] of Object.entries(process.env)) {
51
+ if (value !== undefined && !inherited.test(name)) env.set(name, value);
52
+ }
53
+ for (const [name, value] of Object.entries(settings.env)) {
54
+ // An empty secure-storage override would select Claude's default Keychain service.
55
+ if (cli === "claude" && name === "CLAUDE_SECURESTORAGE_CONFIG_DIR") continue;
56
+ env.set(name, value);
57
+ }
58
+ env.set(homeVariable, directory);
59
+ return turn({ ...settings, env: Object.fromEntries(env) });
60
+ }
package/client.tsx ADDED
@@ -0,0 +1,498 @@
1
+ /** Client extension points share the shell's owner and plugin generations. */
2
+ import { createEffect, createContext, createSignal, onCleanup, useContext } from "solid-js";
3
+ import type { JSX } from "@solidjs/web";
4
+ import { componentActionKind, isComponentAction, type ComponentAction } from "./component-actions";
5
+ export {
6
+ before,
7
+ after,
8
+ prepend,
9
+ append,
10
+ attrs,
11
+ hide,
12
+ layer,
13
+ attach,
14
+ type OriginalElement,
15
+ type ElementAttributes,
16
+ type ComponentAttributes,
17
+ type ComponentPart,
18
+ type RenderFunction,
19
+ type ScreenFind,
20
+ type ComponentActionOptions,
21
+ } from "./component-actions";
22
+ import {
23
+ flattenAttributes,
24
+ resolveScreenSearch,
25
+ screenElements,
26
+ screenTarget,
27
+ type ScreenElement,
28
+ type ScreenSearch,
29
+ type ScreenTree,
30
+ } from "./screen-search";
31
+ import { componentAlerts } from "./component-alerts";
32
+ import type { AttributeWarning } from "./component-attributes";
33
+ export type { AttributeWarning } from "./component-attributes";
34
+ import {
35
+ compareInstallOrder,
36
+ PartActions,
37
+ type LoadedPartAction,
38
+ type PartObserver,
39
+ type PartRegistry,
40
+ } from "./component-parts";
41
+ export { sendFile, UploadHttpError, __bindUploadOrigin, type SendFileOptions } from "./send-file";
42
+ export { auth, useClient, useQuery } from "./solid";
43
+ export { onQuit, quitBlockers, type QuitBlocker, type QuitCheck } from "./quit";
44
+ export { state, derived, type StateOptions, type WindowDerived, type WindowState } from "./window-state";
45
+ export { view, viewRoute, type ViewOptions } from "./view";
46
+
47
+ export interface ExtensionContribution {
48
+ plugin: string;
49
+ id: string;
50
+ kind: string;
51
+ options: Readonly<Record<string, string | number>>;
52
+ installOrder?: number;
53
+ }
54
+ export interface ExtensionHost {
55
+ contributions(kind: "component-action"): ExtensionContribution[];
56
+ version(id: string): number;
57
+ load(id: string): Promise<Record<string, unknown>>;
58
+ partOwner?(id: string): Promise<Record<string, unknown> | undefined>;
59
+ onError(id: string, listener: (cause: unknown) => void): () => void;
60
+ }
61
+ type CatalogExtension = ExtensionContribution & {
62
+ version: number;
63
+ ownerVersion: number;
64
+ resolved?: ScreenElement;
65
+ };
66
+ type MountedAddon = {
67
+ signature: string;
68
+ catalog: string;
69
+ failed: boolean;
70
+ ready?: Promise<LoadedPartAction[]>;
71
+ stop(): void;
72
+ };
73
+
74
+ const partOwner = ({ options }: ExtensionContribution) =>
75
+ typeof options.owner === "string" ? options.owner : String(options.target).split(".")[0]!;
76
+
77
+ /** Catalog discovery loads only extension contributors. Removing a plugin clears
78
+ * its layers synchronously; late loads cannot publish into a retired owner. */
79
+ export function ExtensionProvider(props: {
80
+ host: ExtensionHost;
81
+ onAlerts?: (messages: readonly string[]) => void;
82
+ onAttributeWarning?: (warning: AttributeWarning) => void;
83
+ children?: JSX.Element;
84
+ }) {
85
+ const slots = new Map<string, ReturnType<typeof createSignal<readonly LoadedPartAction[]>>>();
86
+ const current = new Map<string, readonly LoadedPartAction[]>();
87
+ const observers = new Map<string, Set<PartObserver>>();
88
+ function slot(target: string) {
89
+ let signal = slots.get(target);
90
+ if (!signal)
91
+ slots.set(
92
+ target,
93
+ (signal = createSignal<readonly LoadedPartAction[]>(current.get(target) ?? [], { ownedWrite: true })),
94
+ );
95
+ return signal;
96
+ }
97
+
98
+ const alerts = componentAlerts(
99
+ (messages) => props.onAlerts?.(messages),
100
+ (warning) => props.onAttributeWarning?.(warning),
101
+ (message) => console.warn(message),
102
+ );
103
+ const ownerTrees = new Map<string, () => ReadonlySet<string>>();
104
+ const insideSlots = new Map<string, ReturnType<typeof createSignal<readonly LoadedPartAction[]>>>();
105
+ function inOwnerTree(target: string) {
106
+ return ownerTrees.get(target.split(".")[0]!)?.().has(target) ?? true;
107
+ }
108
+ function inside(target: string) {
109
+ let signal = insideSlots.get(target);
110
+ if (!signal) {
111
+ // Packed addresses encode ancestry. Intersect the owner's tree with the
112
+ // installed targets once per watched address, not once per mounted row.
113
+ const actions = [...current].flatMap(([key, items]) =>
114
+ key.startsWith(`${target}.`) && inOwnerTree(key) ? items : [],
115
+ );
116
+ insideSlots.set(
117
+ target,
118
+ (signal = createSignal<readonly LoadedPartAction[]>(actions, { ownedWrite: true })),
119
+ );
120
+ }
121
+ return signal[0]();
122
+ }
123
+
124
+ const registry: PartRegistry = {
125
+ warn: alerts.warn,
126
+ mismatch: alerts.mismatch,
127
+ failure: alerts.failure,
128
+ interference: alerts.interference,
129
+ inside,
130
+ read: (target) => slot(target)[0],
131
+ observe(target, observer) {
132
+ let listeners = observers.get(target);
133
+ if (!listeners) observers.set(target, (listeners = new Set()));
134
+ listeners.add(observer);
135
+ if (current.size) {
136
+ const actions = current.get(target);
137
+ if (actions) observer.update(actions);
138
+ }
139
+ },
140
+ unobserve(target, observer) {
141
+ const listeners = observers.get(target);
142
+ listeners?.delete(observer);
143
+ if (!listeners?.size) observers.delete(target);
144
+ },
145
+ };
146
+ function update(
147
+ target: string,
148
+ change: (items: readonly LoadedPartAction[]) => readonly LoadedPartAction[],
149
+ ) {
150
+ const next = change(current.get(target) ?? []);
151
+ if (next.length) current.set(target, next);
152
+ else current.delete(target);
153
+ if (insideSlots.size && inOwnerTree(target)) {
154
+ for (let end = target.lastIndexOf("."); end !== -1; end = target.lastIndexOf(".", end - 1)) {
155
+ insideSlots.get(target.slice(0, end))?.[1]((items) => [
156
+ ...items.filter((item) => item.action.target !== target),
157
+ ...next,
158
+ ]);
159
+ }
160
+ }
161
+ slots.get(target)?.[1](next);
162
+ for (const observer of observers.get(target) ?? []) observer.update(next);
163
+ }
164
+
165
+ const plugins = new Map<string, MountedAddon>();
166
+ const targets = new Map<string, Set<string>>();
167
+ function clear(id: string) {
168
+ alerts.clear(id);
169
+ for (const target of targets.get(id) ?? [])
170
+ update(target, (items) => items.filter((c) => c.plugin !== id));
171
+ targets.delete(id);
172
+ }
173
+
174
+ function publish(id: string, parts: LoadedPartAction[]) {
175
+ const group = new Map<string, LoadedPartAction[]>();
176
+ for (const part of parts) {
177
+ const target = part.action.target;
178
+ let items = group.get(target);
179
+ if (!items) group.set(target, (items = []));
180
+ items.push(part);
181
+ }
182
+ for (const target of group.keys()) remember(id, target);
183
+ for (const [target, added] of group)
184
+ update(target, (items) =>
185
+ [...items, ...added].sort(
186
+ (a, b) => a.order - b.order || a.plugin.localeCompare(b.plugin) || a.id.localeCompare(b.id),
187
+ ),
188
+ );
189
+ }
190
+ function remember(id: string, target: string) {
191
+ let owned = targets.get(id);
192
+ if (!owned) targets.set(id, (owned = new Set()));
193
+ owned.add(target);
194
+ }
195
+ onCleanup(() => {
196
+ for (const plugin of plugins.values()) plugin.stop();
197
+ plugins.clear();
198
+ });
199
+ // Resolve historical addresses against the current owner before loading additions.
200
+ let generation = 0;
201
+ let versions = new Map<string, number>();
202
+ onCleanup(() => generation++);
203
+ createEffect(
204
+ () =>
205
+ props.host.contributions("component-action").map((contribution) => ({
206
+ ...contribution,
207
+ version: props.host.version(contribution.plugin),
208
+ ownerVersion: props.host.version(partOwner(contribution)),
209
+ })),
210
+ (contributions) => {
211
+ const revision = ++generation;
212
+ // Resolving against a new owner retires bindings, but the failing
213
+ // add-on is still installed at the same generation.
214
+ const nextVersions = new Map(contributions.map(({ plugin, version }) => [plugin, version]));
215
+ for (const [id, version] of versions) if (nextVersions.get(id) !== version) alerts.clear(id, true);
216
+ versions = nextVersions;
217
+ const previous = new Map<string, string>();
218
+ for (const c of contributions)
219
+ previous.set(c.plugin, (previous.get(c.plugin) ?? "") + JSON.stringify(c));
220
+ for (const [id, plugin] of plugins) {
221
+ if (plugin.catalog !== previous.get(id)) {
222
+ plugin.stop();
223
+ plugins.delete(id);
224
+ clear(id);
225
+ }
226
+ }
227
+ if (!props.host.partOwner) return apply(contributions, previous, []);
228
+ const ids = new Set(contributions.map(partOwner));
229
+ if (!ids.size) return apply(contributions, previous, []);
230
+ void Promise.all(
231
+ [...ids].map(async (id) => {
232
+ try {
233
+ const owner = await props.host.partOwner!(id);
234
+ return [id, owner] as const;
235
+ } catch {
236
+ // The next catalog generation rechecks an owner that is not available yet.
237
+ return [id, undefined] as const;
238
+ }
239
+ }),
240
+ ).then((entries) => {
241
+ if (revision !== generation) return;
242
+ const owners = new Map(
243
+ entries.map(([id, owner]) => [
244
+ id,
245
+ {
246
+ parts: typeof owner?.find === "function" ? authoredParts.get(owner.find) : undefined,
247
+ legacy: owner?.parts,
248
+ },
249
+ ]),
250
+ );
251
+ ownerTrees.clear();
252
+ for (const [id, { parts }] of owners) {
253
+ if (!parts) continue;
254
+ let addresses: Set<string> | undefined;
255
+ ownerTrees.set(
256
+ id,
257
+ () =>
258
+ (addresses ??= new Set(
259
+ [...parts("element"), ...parts("render function")].map((p) => p.target),
260
+ )),
261
+ );
262
+ }
263
+ const rejected: string[] = [];
264
+ const valid = contributions.flatMap((c): CatalogExtension[] => {
265
+ const target = screenTarget(c.options);
266
+ const owner = owners.get(partOwner(c));
267
+ if (!owner?.parts && !owner?.legacy) return [c];
268
+ const kind = c.options.action === "attach" ? "render function" : "element";
269
+ const result =
270
+ owner.parts || kind === "render function"
271
+ ? resolveScreenSearch(owner.parts?.(kind) ?? [], target.search, target, kind)
272
+ : resolveLegacyPart(owner.legacy, partOwner(c), target);
273
+ if (!result.element) {
274
+ rejected.push(`Plugin "${c.plugin}": ${result.reason}; skipping this addition`);
275
+ return [];
276
+ }
277
+ const { target: path, fingerprint } = result.element;
278
+ return [{ ...c, resolved: { target: path, fingerprint } }];
279
+ });
280
+ apply(valid, previous, rejected);
281
+ });
282
+ },
283
+ );
284
+
285
+ function apply(contributions: CatalogExtension[], catalog: Map<string, string>, rejected: string[]) {
286
+ alerts.skipped(rejected);
287
+
288
+ const groups = new Map<string, CatalogExtension[]>();
289
+ for (const c of contributions) {
290
+ const group = groups.get(c.plugin) ?? [];
291
+ group.push(c);
292
+ groups.set(c.plugin, group);
293
+ }
294
+ const signatures = new Map([...groups].map(([id, group]) => [id, JSON.stringify(group)]));
295
+ for (const [id, plugin] of plugins) {
296
+ if (plugin.signature !== signatures.get(id)) {
297
+ plugin.stop();
298
+ plugins.delete(id);
299
+ clear(id);
300
+ }
301
+ }
302
+ for (const [id, group] of groups) {
303
+ if (plugins.has(id)) continue;
304
+ const plugin: MountedAddon = {
305
+ signature: signatures.get(id)!,
306
+ catalog: catalog.get(id)!,
307
+ failed: false,
308
+ stop: () => {},
309
+ };
310
+ plugins.set(id, plugin);
311
+ plugin.stop = props.host.onError(id, (cause) => {
312
+ plugin.failed = true;
313
+ clear(id);
314
+ console.warn(`Extension ${id} failed: ${String(cause)}`);
315
+ });
316
+ plugin.ready = props.host.load(id).then(
317
+ (exports) => {
318
+ if (plugins.get(id) !== plugin || plugin.failed) return [];
319
+ const parts: LoadedPartAction[] = [];
320
+ const attachments: LoadedPartAction[] = [];
321
+ for (const c of group) {
322
+ const value = exports[c.id];
323
+ if (
324
+ isComponentAction(value) &&
325
+ value.target === c.options.target &&
326
+ componentActionKind(value) === c.options.action
327
+ ) {
328
+ (c.options.action === "attach" ? attachments : parts).push(loadedPart(c, value, registry));
329
+ } else {
330
+ console.warn(
331
+ `Component action ${id}/${c.id} does not match its manifest: expected ${c.options.action} for ${c.options.target}`,
332
+ );
333
+ }
334
+ }
335
+ if (parts.length) publish(id, parts);
336
+ return attachments;
337
+ },
338
+ (cause) => {
339
+ console.warn(`Extension ${id} failed: ${String(cause)}`);
340
+ return [];
341
+ },
342
+ );
343
+ }
344
+ const attachments = new Map<string, Set<MountedAddon>>();
345
+ for (const c of contributions) {
346
+ if (c.options.action !== "attach") continue;
347
+ const target = c.resolved?.target ?? String(c.options.target);
348
+ let addons = attachments.get(target);
349
+ if (!addons) attachments.set(target, (addons = new Set()));
350
+ addons.add(plugins.get(c.plugin)!);
351
+ }
352
+ const revision = generation;
353
+ for (const [target, addons] of attachments) {
354
+ // Start attachments on a target together so import timing cannot set
355
+ // their order. Placements and attachments on other targets do not wait.
356
+ void Promise.all([...addons].map(async (addon) => ({ addon, items: await addon.ready }))).then(
357
+ (ready) => {
358
+ if (revision !== generation) return;
359
+ const parts = ready
360
+ .flatMap(({ addon, items }) =>
361
+ addon.failed ? [] : (items ?? []).filter((item) => item.action.target === target),
362
+ )
363
+ .sort(compareInstallOrder);
364
+ for (const part of parts) remember(part.plugin, target);
365
+ const previous = current.get(target) ?? [];
366
+ if (parts.length !== previous.length || parts.some((part, i) => part !== previous[i]))
367
+ update(target, () => parts);
368
+ },
369
+ );
370
+ }
371
+ }
372
+ return <PartActions value={registry}>{props.children}</PartActions>;
373
+ }
374
+
375
+ function callableAttributes(value: unknown): ReadonlySet<string> | undefined {
376
+ if (typeof value !== "string") return;
377
+ try {
378
+ const names: unknown = JSON.parse(value);
379
+ if (Array.isArray(names) && names.every((name) => typeof name === "string")) return new Set(names);
380
+ } catch {
381
+ // The build supplies this metadata. Ignore malformed older manifests.
382
+ }
383
+ }
384
+
385
+ function loadedPart(c: CatalogExtension, action: ComponentAction, registry: PartRegistry): LoadedPartAction {
386
+ const item: LoadedPartAction = {
387
+ id: c.id,
388
+ plugin: c.plugin,
389
+ order: Number(c.options.order ?? 0),
390
+ installOrder: c.installOrder,
391
+ callableAttributes: callableAttributes(c.options.callableAttributes),
392
+ action: c.resolved ? { ...action, target: c.resolved.target } : action,
393
+ fingerprint: c.resolved ? c.resolved.fingerprint : screenTarget(c.options).fingerprint,
394
+ enabled(props) {
395
+ try {
396
+ return action.when?.(props) ?? true;
397
+ } catch (cause) {
398
+ registry.failure(item, cause, `Component action ${c.plugin}/${c.id} failed: ${String(cause)}`);
399
+ return false;
400
+ }
401
+ },
402
+ };
403
+ return item;
404
+ }
405
+
406
+ /** Registrations belong to the calling plugin owner, even when its view leaves. */
407
+ export interface Shortcuts {
408
+ /**
409
+ * Runs `handler` on `key` ("Meta+n", "1"). A handler that returns `false`
410
+ * declines this press (say, its field holds text): when every handler
411
+ * declines, the key goes on as if nothing were registered.
412
+ */
413
+ registerShortcut(key: string, handler: () => void | boolean): () => void;
414
+ }
415
+ export const ShortcutContext = createContext<Shortcuts>();
416
+ export function useShortcuts(): Shortcuts {
417
+ const shortcuts = useContext(ShortcutContext);
418
+ if (!shortcuts) throw new Error("Plugin UI requires shell shortcuts");
419
+ return shortcuts;
420
+ }
421
+
422
+ export {
423
+ Region,
424
+ RegionOutlet,
425
+ RegionProvider,
426
+ useRegionFilled,
427
+ usePageTitle,
428
+ usePageTitleValue,
429
+ type RegionName,
430
+ } from "./regions";
431
+
432
+ export {
433
+ attachRenderFunction as __attachRenderFunction,
434
+ renderPart as __renderPart,
435
+ renderPlainPart as __renderPlainPart,
436
+ renderComponentPart as __renderComponentPart,
437
+ renderNativePart as __renderNativePart,
438
+ renderNativeText as __renderNativeText,
439
+ } from "./component-parts";
440
+
441
+ type ScreenKind = NonNullable<Parameters<typeof screenElements>[2]>;
442
+ const authoredParts = new WeakMap<object, (kind: ScreenKind) => ReturnType<typeof screenElements>>();
443
+
444
+ /** Generated by the client compiler. Production calls are resolved during the build. */
445
+ export function __defineScreenFind(plugin: string, packedTree: string) {
446
+ let tree: ScreenTree | undefined;
447
+ const cache = new Map<ScreenKind, ReturnType<typeof screenElements>>();
448
+ function read(kind: ScreenKind) {
449
+ let parts = cache.get(kind);
450
+ if (!parts) cache.set(kind, (parts = screenElements(plugin, (tree ??= JSON.parse(packedTree)), kind)));
451
+ return parts;
452
+ }
453
+ function find(name: string, filters?: Omit<ScreenSearch, "name">) {
454
+ const search = { name, ...filters };
455
+ const element = resolveScreenSearch(read("element"), search);
456
+ const render = resolveScreenSearch(read("render function"), search, undefined, "render function");
457
+ if (element.element) return { target: element.element.target, renderTarget: render.element?.target };
458
+ if (render.element) return { target: render.element.target };
459
+ throw new Error(element.reason);
460
+ }
461
+ authoredParts.set(find, read);
462
+ return find;
463
+ }
464
+
465
+ function resolveLegacyPart(node: unknown, owner: string, target: ReturnType<typeof screenTarget>) {
466
+ // A legacy owner has paths but no attributes to verify a filtered search.
467
+ if (target.search && flattenAttributes(target.search).length)
468
+ return resolveScreenSearch([], target.search, target);
469
+ for (const key of target.target.slice(owner.length + 1).split("."))
470
+ node =
471
+ node && typeof node === "object" && Object.hasOwn(node, key)
472
+ ? (node as Record<string, unknown>)[key]
473
+ : undefined;
474
+ const part = node as typeof target | undefined;
475
+ return resolveScreenSearch(
476
+ part?.target === target.target ? [{ ...part, name: "", ancestors: [] }] : [],
477
+ undefined,
478
+ target,
479
+ );
480
+ }
481
+
482
+ /** Existing owner bundles call this until they are rebuilt. */
483
+ export function __defineScreenParts(prefix: string, shape: Record<string, unknown>) {
484
+ const result: Record<string, unknown> = {};
485
+ for (const [key, value] of Object.entries(shape)) {
486
+ if (key === "") {
487
+ result.target = prefix;
488
+ if (value) result.fingerprint = value;
489
+ } else if (value && typeof value === "object") {
490
+ result[key] = __defineScreenParts(`${prefix}.${key}`, value as Record<string, unknown>);
491
+ }
492
+ }
493
+ return result;
494
+ }
495
+
496
+ export function __partPaths(prefix: string, suffixes: readonly string[]) {
497
+ return suffixes.map((suffix) => (suffix ? `${prefix}.${suffix}` : prefix));
498
+ }