@tokamaq/runtime 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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 pixelscortex
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,19 @@
1
- # Temporary Holding Version
1
+ # Runtime support
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The Rust crate is server-only. Its optional `server` feature re-exports the
4
+ server backend, storage, and engine types. The engine still runs server plugins.
5
+
6
+ The TypeScript package keeps reusable client lifecycle code:
7
+
8
+ - `@tokamaq/runtime/plugins`: `createPluginLoader`, catalog lookup, paged asset
9
+ retrieval, dependency invalidation, and generation retirement.
10
+ - `@tokamaq/runtime/subscriptions`: the retained-query transport cache.
11
+
12
+ The loader accepts a `PluginModuleHost` interface. There is no evaluator or web
13
+ module host implementation. The next loader agent must connect server-provided
14
+ ES modules while preserving shared runtime identities and generation disposal.
15
+ The app skeleton does not instantiate this loader.
16
+
17
+ `tools/local-server.ts` and `tools/run-app.ts` retain independent local server
18
+ start, status, and stop operations. They do not launch a desktop client.
19
+ The app's disposable development server is separate; see `app/README.md`.
package/js/plugins.ts ADDED
@@ -0,0 +1,245 @@
1
+ /** Manifest-first loading and generation retirement. No UI asset is requested
2
+ * until load() is called by a contribution or a cross-plugin import. */
3
+ import { createMemo, createSignal } from "solid-js";
4
+ import type { JsonValue } from "@tokamaq/sdk";
5
+ type ContributionKind = "component-action" | "view";
6
+ export type ModuleExports = Readonly<Record<string, unknown>>;
7
+ export interface PluginModuleHost {
8
+ importModule?(name: string, manifest: PluginManifest, revision: string): Promise<ModuleExports>;
9
+ affected(names: readonly string[]): Set<string>;
10
+ remove(names: Iterable<string>): void;
11
+ evaluate(name: string, code: string): void;
12
+ dependencies(name: string): readonly string[];
13
+ has(name: string): boolean;
14
+ require(name: string): ModuleExports;
15
+ setLoader(load: (name: string) => Promise<ModuleExports>): void;
16
+ notifyError(name: string, cause: unknown): void;
17
+ onError(name: string, listener: (cause: unknown) => void): () => void;
18
+ }
19
+
20
+ export interface PluginManifest {
21
+ installOrder?: number;
22
+ plugin: {
23
+ id: string;
24
+ version: string;
25
+ depends?: Readonly<Record<string, string>>;
26
+ contributes?: Partial<
27
+ Record<ContributionKind, readonly { id: string; [key: string]: string | number }[]>
28
+ >;
29
+ };
30
+ entries: { ui?: { code: string; css: string } };
31
+ hashes: Readonly<Record<string, string>>;
32
+ }
33
+ export interface PluginCatalog {
34
+ revision: string;
35
+ plugins: readonly PluginManifest[];
36
+ }
37
+ export interface PluginAssets {
38
+ plugins(): Promise<JsonValue>;
39
+ pluginAsset(plugin: string, name: string, revision: string): Promise<string>;
40
+ onPluginsChanged(listener: (event: { plugins: string[]; catalog: JsonValue }) => void): () => void;
41
+ }
42
+ export interface CatalogContribution {
43
+ plugin: string;
44
+ id: string;
45
+ kind: ContributionKind;
46
+ options: Readonly<Record<string, string | number>>;
47
+ installOrder?: number;
48
+ }
49
+ const moduleName = (id: string) => `@plugins/${id}/ui`;
50
+ function catalog(value: JsonValue): PluginCatalog {
51
+ const candidate = value as unknown as PluginCatalog;
52
+ if (
53
+ !candidate ||
54
+ typeof candidate.revision !== "string" ||
55
+ !Array.isArray(candidate.plugins) ||
56
+ candidate.plugins.some((p) => !p?.plugin || typeof p.plugin.id !== "string" || !p.entries)
57
+ )
58
+ throw new Error("Invalid plugin catalog");
59
+ return candidate;
60
+ }
61
+
62
+ export function createPluginLoader(registry: PluginModuleHost, assets: PluginAssets) {
63
+ const [metadata, setMetadata] = createSignal<PluginCatalog>({ revision: "", plugins: [] });
64
+ const [versions, setVersions] = createSignal<Readonly<Record<string, number>>>({});
65
+ const [styles, setStyles] = createSignal<Readonly<Record<string, string>>>({});
66
+ const loaded = new Map<string, ModuleExports>();
67
+ const pending = new Map<string, Promise<ModuleExports>>();
68
+ let disposed = false;
69
+ let changes = 0;
70
+ const invalidations = new Set<string>();
71
+ const version = (id: string) => versions()[id] ?? 0;
72
+ const manifests = createMemo(() => new Map(metadata().plugins.map((p) => [p.plugin.id, p])));
73
+ const manifest = (id: string) => manifests().get(id);
74
+
75
+ function invalidate(ids: readonly string[], next = metadata()) {
76
+ const affected = registry.affected(ids.map(moduleName));
77
+ // Include not-yet-evaluated importers using the static dependency graph.
78
+ const importers = new Map<string, Set<string>>();
79
+ for (const p of [...metadata().plugins, ...next.plugins]) {
80
+ for (const id of Object.keys(p.plugin.depends ?? {})) {
81
+ const dependency = moduleName(id);
82
+ let names = importers.get(dependency);
83
+ if (!names) importers.set(dependency, (names = new Set()));
84
+ names.add(moduleName(p.plugin.id));
85
+ }
86
+ }
87
+ expandImporters(affected, importers);
88
+ for (const id of pending.keys()) affected.add(moduleName(id));
89
+ const updated = { ...versions() };
90
+ const css = { ...styles() };
91
+ for (const name of affected) {
92
+ const id = name.slice("@plugins/".length, -"/ui".length);
93
+ updated[id] = (updated[id] ?? 0) + 1;
94
+ delete css[id];
95
+ pending.delete(id);
96
+ loaded.delete(id);
97
+ }
98
+ setVersions(updated);
99
+ setStyles(css);
100
+ registry.remove(affected);
101
+ setMetadata(next);
102
+ }
103
+
104
+ async function load(id: string, stack: readonly string[] = []): Promise<ModuleExports> {
105
+ if (disposed) throw new Error("Plugin loader disposed");
106
+ if (stack.includes(id)) throw new Error(`UI dependency cycle: ${[...stack, id].join(" -> ")}`);
107
+ if (loaded.has(id)) return loaded.get(id)!;
108
+ if (pending.has(id)) return pending.get(id)!;
109
+ const p = manifest(id);
110
+ if (!p?.entries.ui) throw new Error(`Plugin has no UI module: ${id}`);
111
+ const revision = metadata().revision;
112
+ const generation = version(id);
113
+ const live = () => {
114
+ if (disposed || generation !== version(id) || revision !== metadata().revision)
115
+ throw new Error(`Retired plugin generation: ${id}`);
116
+ };
117
+ const task = (async () => {
118
+ if (registry.importModule) return registry.importModule(moduleName(id), p, revision);
119
+ const entry = p.entries.ui!;
120
+ // Manifest depends also includes backend requirements. Register this
121
+ // inert factory first, then resolve only its actual UI imports; otherwise
122
+ // a backend dependency would prematurely fetch an unrelated UI module.
123
+ const code = await assets.pluginAsset(id, entry.code, revision);
124
+ live();
125
+ registry.evaluate(moduleName(id), code);
126
+ for (const dependency of registry.dependencies(moduleName(id))) {
127
+ if (dependency.startsWith("@plugins/")) await load(dependency.slice(9, -3), [...stack, id]);
128
+ else if (!registry.has(dependency)) throw new Error(`Unsupported host module: ${dependency}`);
129
+ }
130
+ const css = await assets.pluginAsset(id, entry.css, revision);
131
+ live();
132
+ const exports = registry.require(moduleName(id));
133
+ setStyles((previous) => ({ ...previous, [id]: css }));
134
+ return exports;
135
+ })();
136
+ pending.set(id, task);
137
+ try {
138
+ const exports = await task;
139
+ live();
140
+ loaded.set(id, exports);
141
+ pending.delete(id);
142
+ return exports;
143
+ } catch (error) {
144
+ if (generation === version(id)) {
145
+ registry.remove([moduleName(id)]);
146
+ pending.delete(id);
147
+ }
148
+ throw error;
149
+ }
150
+ }
151
+
152
+ registry.setLoader((name) => load(name.slice(9, -3)));
153
+ const stop = assets.onPluginsChanged((event) => {
154
+ changes++;
155
+ for (const id of event.plugins) invalidations.add(id);
156
+ const publish = (next: JsonValue) => {
157
+ const parsed = catalog(next);
158
+ const nextManifests = new Map(parsed.plugins.map((p) => [p.plugin.id, p]));
159
+ // Very large change-id lists are omitted from the bounded notification.
160
+ // Diff the complete paged catalog too, so no installed-count ceiling can
161
+ // silently prevent a module from retiring (including added/removed ids).
162
+ for (const [id, previous] of manifests()) {
163
+ if (JSON.stringify(previous) !== JSON.stringify(nextManifests.get(id))) invalidations.add(id);
164
+ }
165
+ for (const id of nextManifests.keys()) if (!manifests().has(id)) invalidations.add(id);
166
+ invalidate([...invalidations], parsed);
167
+ invalidations.clear();
168
+ };
169
+ const value = event.catalog as unknown as { paged?: boolean };
170
+ if (value.paged) {
171
+ const change = changes;
172
+ // Multiple reloads can race a paged fetch. Accumulate every changed id
173
+ // until the latest complete catalog arrives, so none escapes retirement.
174
+ void assets
175
+ .plugins()
176
+ .then((next) => {
177
+ if (!disposed && change === changes) publish(next);
178
+ })
179
+ .catch((error) => {
180
+ if (!disposed && change === changes)
181
+ for (const id of invalidations) registry.notifyError(moduleName(id), error);
182
+ });
183
+ } else publish(event.catalog);
184
+ });
185
+ return {
186
+ metadata,
187
+ version,
188
+ styles,
189
+ load,
190
+ onError(id: string, listener: (cause: unknown) => void) {
191
+ return registry.onError(moduleName(id), listener);
192
+ },
193
+ async connect() {
194
+ const before = changes;
195
+ try {
196
+ const value = await assets.plugins();
197
+ if (!disposed && changes === before) setMetadata(catalog(value));
198
+ } catch (error) {
199
+ // A newer catalog fetch owns the outcome after a reload. An older
200
+ // transfer's stale-page failure must not become a permanent shell alert.
201
+ if (!disposed && changes === before) throw error;
202
+ }
203
+ },
204
+ async partOwner(id: string) {
205
+ if (manifest(id)?.entries.ui) return load(id);
206
+ },
207
+ contributions(kind: ContributionKind): CatalogContribution[] {
208
+ return metadata().plugins.flatMap((p) =>
209
+ (p.plugin.contributes?.[kind] ?? []).map((options) => ({
210
+ plugin: p.plugin.id,
211
+ id: options.id,
212
+ kind,
213
+ options,
214
+ ...(kind === "component-action" && p.installOrder !== undefined
215
+ ? { installOrder: p.installOrder }
216
+ : {}),
217
+ })),
218
+ );
219
+ },
220
+ reload(id: string) {
221
+ invalidate([id]);
222
+ },
223
+ dispose() {
224
+ disposed = true;
225
+ stop();
226
+ invalidate(metadata().plugins.map((p) => p.plugin.id));
227
+ },
228
+ };
229
+ }
230
+ export type PluginLoader = ReturnType<typeof createPluginLoader>;
231
+
232
+ export function expandImporters(
233
+ affected: Set<string>,
234
+ importers: ReadonlyMap<string, ReadonlySet<string>>,
235
+ ): void {
236
+ const queue = [...affected];
237
+ for (let index = 0; index < queue.length; index++) {
238
+ for (const name of importers.get(queue[index]!) ?? []) {
239
+ if (!affected.has(name)) {
240
+ affected.add(name);
241
+ queue.push(name);
242
+ }
243
+ }
244
+ }
245
+ }
package/js/router.ts ADDED
@@ -0,0 +1,132 @@
1
+ /** The legacy plugin navigation surface backed by the shell TanStack history. */
2
+ import {
3
+ createMemoryHistory,
4
+ createRootRoute,
5
+ createRoute,
6
+ createRouter,
7
+ type AnyRouter,
8
+ } from "@tanstack/solid-router";
9
+ import { createContext, useContext, createSignal, getOwner, onCleanup, type Accessor } from "solid-js";
10
+
11
+ export interface RouteLocation {
12
+ readonly href: string;
13
+ readonly pathname: string;
14
+ readonly search: string;
15
+ readonly hash: string;
16
+ }
17
+ export interface RouteMatch {
18
+ readonly params: Readonly<Record<string, string>>;
19
+ }
20
+ export interface MemoryRouter {
21
+ readonly location: Accessor<RouteLocation>;
22
+ navigate(href: string, options?: { replace?: boolean }): void;
23
+ back(): void;
24
+ forward(): void;
25
+ match(pattern: string): RouteMatch | undefined;
26
+ dispose(): void;
27
+ }
28
+
29
+ function checkHref(href: string): void {
30
+ if (
31
+ typeof href !== "string" ||
32
+ href.length > 2048 ||
33
+ !href.startsWith("/") ||
34
+ href.startsWith("//") ||
35
+ /[\\\x00-\x20\x7f]/.test(href)
36
+ ) {
37
+ throw new Error("Routes must be local absolute paths, at most 2048 characters");
38
+ }
39
+ }
40
+
41
+ /** Exact segments, :parameters and one terminal *splat; no browser URL parser. */
42
+ export function matchRoute(pattern: string, pathname: string): RouteMatch | undefined {
43
+ checkHref(pattern);
44
+ checkHref(pathname);
45
+ if (pattern.includes("?") || pattern.includes("#")) throw new Error("Route patterns contain paths only");
46
+ const segments = (value: string) => (value === "/" ? [] : value.replace(/\/$/, "").slice(1).split("/"));
47
+ const expected = segments(pattern);
48
+ const actual = segments(pathname);
49
+ const params: Record<string, string> = Object.create(null);
50
+ for (let index = 0; index < expected.length; index++) {
51
+ const part = expected[index]!;
52
+ const parameter = part.startsWith(":") || part.startsWith("*");
53
+ const name = part.slice(1);
54
+ if (parameter && (!/^[A-Za-z][A-Za-z0-9_]*$/.test(name) || Object.hasOwn(params, name))) {
55
+ throw new Error("Invalid or duplicate route parameter");
56
+ }
57
+ if (part.startsWith("*") && index !== expected.length - 1) throw new Error("Route splats must be last");
58
+ try {
59
+ if (part.startsWith("*")) {
60
+ params[name] = actual.slice(index).map(decodeURIComponent).join("/");
61
+ return Object.freeze({ params: Object.freeze(params) });
62
+ }
63
+ if (actual[index] === undefined || actual[index] === "") return;
64
+ const value = decodeURIComponent(actual[index]!);
65
+ if (part.startsWith(":")) params[name] = value;
66
+ else if (value !== part) return;
67
+ } catch {
68
+ return;
69
+ } // Malformed encoded route input is a non-match.
70
+ }
71
+ return expected.length === actual.length ? Object.freeze({ params: Object.freeze(params) }) : undefined;
72
+ }
73
+
74
+ export function createMemoryRouter(initial = "/"): MemoryRouter {
75
+ checkHref(initial);
76
+ const root = createRootRoute();
77
+ const catchAll = createRoute({ getParentRoute: () => root, path: "$" });
78
+ return routerFacade(
79
+ createRouter({
80
+ routeTree: root.addChildren([catchAll]),
81
+ history: createMemoryHistory({ initialEntries: [initial] }),
82
+ }),
83
+ true,
84
+ );
85
+ }
86
+
87
+ export function routerFacade(router: AnyRouter, ownsHistory = false): MemoryRouter {
88
+ const snapshot = (): RouteLocation => {
89
+ const { href, pathname, search, hash } = router.history.location;
90
+ return { href, pathname, search, hash };
91
+ };
92
+ const [location, setLocation] = createSignal(snapshot(), { ownedWrite: true });
93
+ const unsubscribe = router.history.subscribe(() => setLocation(snapshot()));
94
+ let disposed = false;
95
+ const live = () => {
96
+ if (disposed) throw new Error("Router is disposed");
97
+ };
98
+ const dispose = () => {
99
+ if (disposed) return;
100
+ disposed = true;
101
+ unsubscribe();
102
+ if (ownsHistory) router.history.destroy();
103
+ };
104
+ if (getOwner()) onCleanup(dispose);
105
+ return {
106
+ location,
107
+ navigate(href, options) {
108
+ live();
109
+ checkHref(href);
110
+ void router.navigate({ href, replace: options?.replace });
111
+ },
112
+ back() {
113
+ live();
114
+ router.history.back();
115
+ },
116
+ forward() {
117
+ live();
118
+ router.history.forward();
119
+ },
120
+ match: (pattern) => matchRoute(pattern, location().pathname),
121
+ dispose,
122
+ };
123
+ }
124
+
125
+ /** Navigation is owned by the shell, shared through the same Solid context as
126
+ * plugin components. A plugin never needs to construct a second history. */
127
+ export const RouterContext = createContext<MemoryRouter>();
128
+ export function useRouter(): MemoryRouter {
129
+ const router = useContext(RouterContext);
130
+ if (!router) throw new Error("Plugin UI requires the shell router");
131
+ return router;
132
+ }
@@ -0,0 +1,67 @@
1
+ /** Window-owned query cache bridges contribution remounts during UI reload.
2
+ * Dormant entries stay subscribed until the window closes, bounded by the same
3
+ * 128-entry limit as the wire transport. Terminal failures evict dead entries
4
+ * so Reload can re-subscribe without closing the SDK session. */
5
+ import type { ClientTransport, JsonValue, SubscriptionEvent } from "@tokamaq/sdk";
6
+ export function retainSubscriptions(transport: ClientTransport): ClientTransport & { dispose(): void } {
7
+ const entries = new Map<
8
+ string,
9
+ {
10
+ observers: Set<(event: SubscriptionEvent<JsonValue>) => void>;
11
+ last?: SubscriptionEvent<JsonValue>;
12
+ stop: () => void;
13
+ }
14
+ >();
15
+ return {
16
+ query: (name, args) => transport.query(name, args),
17
+ mutation: (name, args) => transport.mutation(name, args),
18
+ action: transport.action ? (name, args, on) => transport.action!(name, args, on) : undefined,
19
+ subscribe(name, args, observer) {
20
+ const key = JSON.stringify([name, args]);
21
+ let entry = entries.get(key);
22
+ if (!entry) {
23
+ if (entries.size >= 128) {
24
+ const dormant = [...entries].find(([, e]) => !e.observers.size);
25
+ if (!dormant) throw new Error("Window query subscription capacity exceeded");
26
+ dormant[1].stop();
27
+ entries.delete(dormant[0]);
28
+ }
29
+ entry = { observers: new Set(), stop: () => {} };
30
+ const current = entry;
31
+ entries.set(key, entry);
32
+ try {
33
+ entry.stop = transport.subscribe(name, args, (event) => {
34
+ current.last = event;
35
+ // Terminal responses release the wire observer. Keep the failure
36
+ // for existing owners, but a remount must open a fresh subscription.
37
+ if ("error" in event && event.terminal && entries.get(key) === current) entries.delete(key);
38
+ for (const notify of current.observers) {
39
+ try {
40
+ notify(event);
41
+ } catch {
42
+ /* isolate contribution observers */
43
+ }
44
+ }
45
+ });
46
+ } catch (error) {
47
+ if (entries.get(key) === current) entries.delete(key);
48
+ throw error;
49
+ }
50
+ }
51
+ entry.observers.add(observer);
52
+ try {
53
+ if (entry.last) observer(entry.last);
54
+ } catch (error) {
55
+ entry.observers.delete(observer);
56
+ throw error;
57
+ }
58
+ return () => {
59
+ entry.observers.delete(observer);
60
+ };
61
+ },
62
+ dispose() {
63
+ for (const entry of entries.values()) entry.stop();
64
+ entries.clear();
65
+ },
66
+ };
67
+ }
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
1
  {
2
2
  "name": "@tokamaq/runtime",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0-dev.2",
4
+ "description": "Plugin loading, routing, and subscriptions for Tokamaq windows.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/pixelscortex/tokamaq.git",
9
+ "directory": "packages/runtime"
10
+ },
11
+ "files": [
12
+ "js/plugins.ts",
13
+ "js/router.ts",
14
+ "js/subscriptions.ts"
15
+ ],
16
+ "type": "module",
17
+ "exports": {
18
+ "./plugins": "./js/plugins.ts",
19
+ "./subscriptions": "./js/subscriptions.ts",
20
+ "./router": "./js/router.ts"
21
+ },
22
+ "publishConfig": {
23
+ "access": "public",
24
+ "tag": "dev"
25
+ },
26
+ "dependencies": {
27
+ "@solidjs/web": "2.0.0",
28
+ "@tanstack/solid-router": "2.0.0-rc.10",
29
+ "solid-js": "2.0.0"
30
+ },
31
+ "devDependencies": {
32
+ "@types/node": "26.6.6"
33
+ },
34
+ "peerDependencies": {
35
+ "@tokamaq/sdk": "0.1.0-dev.2"
36
+ }
37
+ }