@syntropika/tembra-sdk 0.2.1 → 0.3.0

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 (241) hide show
  1. package/README.md +43 -17
  2. package/dist/authoring/types.d.ts +64 -3
  3. package/dist/authoring/wit.d.ts +6 -0
  4. package/dist/bridge/commands.d.ts +1190 -0
  5. package/dist/bridge/identifiers.d.ts +2 -0
  6. package/dist/bridge/kernel.d.ts +18 -107
  7. package/dist/bridge/protocol.d.ts +3 -138
  8. package/dist/browser.d.ts +14 -1
  9. package/dist/browser.js +141 -3298
  10. package/dist/chunks/browser-b8jamxw2.js +3399 -0
  11. package/dist/chunks/execution-nsqc6nrt.js +1419 -0
  12. package/dist/chunks/index-01zk0xqx.js +160 -0
  13. package/dist/chunks/index-3fjdfdfd.js +152 -0
  14. package/dist/chunks/index-aaymjn7v.js +787 -0
  15. package/dist/chunks/index-c1w7z9hx.js +356 -0
  16. package/dist/chunks/index-h8t0n42q.js +738 -0
  17. package/dist/chunks/index-hfds9mzp.js +308 -0
  18. package/dist/chunks/index-kr4x67wt.js +177 -0
  19. package/dist/chunks/index-kr6bnh34.js +117 -0
  20. package/dist/chunks/index-kyt9dj0a.js +1421 -0
  21. package/dist/chunks/index-n1wxzc9w.js +830 -0
  22. package/dist/chunks/index-pvac426d.js +74 -0
  23. package/dist/chunks/index-smyds5ce.js +3234 -0
  24. package/dist/chunks/index-sse8aapb.js +121 -0
  25. package/dist/chunks/index-v6heph77.js +643 -0
  26. package/dist/chunks/index-xrdvnv37.js +3448 -0
  27. package/dist/chunks/index-za4mg94e.js +26 -0
  28. package/dist/chunks/index-zkqmnjj8.js +167 -0
  29. package/dist/coordinator.js +9 -500
  30. package/dist/error.d.ts +2 -0
  31. package/dist/errors.d.ts +3 -0
  32. package/dist/guest.d.ts +173 -0
  33. package/dist/guest.js +26 -0
  34. package/dist/host.d.ts +36 -30
  35. package/dist/host.js +37 -3276
  36. package/dist/http/bytes.d.ts +8 -0
  37. package/dist/http/events.d.ts +7 -0
  38. package/dist/http.d.ts +45 -0
  39. package/dist/http.js +291 -0
  40. package/dist/index.d.ts +2 -0
  41. package/dist/index.js +49 -862
  42. package/dist/infrastructure/rpc/client.d.ts +2 -1
  43. package/dist/infrastructure/rpc/resources.d.ts +28 -0
  44. package/dist/interpreter/abi.d.ts +54 -0
  45. package/dist/interpreter/acquire.d.ts +18 -0
  46. package/dist/interpreter/browser-network.d.ts +52 -0
  47. package/dist/interpreter/browser-port.d.ts +55 -0
  48. package/dist/interpreter/browser.d.ts +79 -0
  49. package/dist/interpreter/cli.d.ts +5 -0
  50. package/dist/interpreter/codec.d.ts +42 -0
  51. package/dist/interpreter/component/execution.d.ts +42 -0
  52. package/dist/interpreter/component/host.d.ts +69 -0
  53. package/dist/interpreter/component/instance.d.ts +40 -0
  54. package/dist/interpreter/component/kernel.d.ts +120 -0
  55. package/dist/interpreter/component/names.d.ts +5 -0
  56. package/dist/interpreter/component/port.d.ts +85 -0
  57. package/dist/interpreter/component/prepared.d.ts +97 -0
  58. package/dist/interpreter/component/resources.d.ts +45 -0
  59. package/dist/interpreter/component/revision.d.ts +87 -0
  60. package/dist/interpreter/component/scope.d.ts +116 -0
  61. package/dist/interpreter/component/streams.d.ts +28 -0
  62. package/dist/interpreter/component/values.d.ts +79 -0
  63. package/dist/interpreter/component/wasi-filesystem.d.ts +21 -0
  64. package/dist/interpreter/component/wasi-host.d.ts +64 -0
  65. package/dist/interpreter/component/wasi-http.d.ts +33 -0
  66. package/dist/interpreter/component/wasi-sockets.d.ts +183 -0
  67. package/dist/interpreter/component/wasi.d.ts +41 -0
  68. package/dist/interpreter/core.d.ts +64 -0
  69. package/dist/interpreter/fetch-http-provider.d.ts +17 -0
  70. package/dist/interpreter/filesystem/contract.d.ts +85 -0
  71. package/dist/interpreter/filesystem/memory.d.ts +3 -0
  72. package/dist/interpreter/filesystem/opfs.d.ts +3 -0
  73. package/dist/interpreter/filesystem/scope.d.ts +35 -0
  74. package/dist/interpreter/filesystem.d.ts +8 -0
  75. package/dist/interpreter/gate.d.ts +6 -0
  76. package/dist/interpreter/host-protocol.d.ts +100 -0
  77. package/dist/interpreter/http-ingress-fetch.d.ts +7 -0
  78. package/dist/interpreter/http-ingress.d.ts +96 -0
  79. package/dist/interpreter/http-provider.d.ts +85 -0
  80. package/dist/interpreter/io.d.ts +20 -0
  81. package/dist/interpreter/mobile.d.ts +149 -0
  82. package/dist/interpreter/native-ingress.d.ts +95 -0
  83. package/dist/interpreter/node-port.d.ts +25 -0
  84. package/dist/interpreter/node.d.ts +36 -0
  85. package/dist/interpreter/revision.d.ts +64 -0
  86. package/dist/interpreter/scope.d.ts +89 -0
  87. package/dist/interpreter/socket-addresses.d.ts +50 -0
  88. package/dist/interpreter/socket-provider.d.ts +110 -0
  89. package/dist/interpreter/standard-cli.d.ts +34 -0
  90. package/dist/interpreter/standard-codec.d.ts +96 -0
  91. package/dist/interpreter/standard-filesystem.d.ts +47 -0
  92. package/dist/interpreter/standard-host.d.ts +71 -0
  93. package/dist/interpreter/standard-http-values.d.ts +159 -0
  94. package/dist/interpreter/standard-http.d.ts +9 -0
  95. package/dist/interpreter/standard-ingress.d.ts +63 -0
  96. package/dist/interpreter/standard-sockets.d.ts +177 -0
  97. package/dist/interpreter/standard-streams.d.ts +218 -0
  98. package/dist/interpreter/standard-system.d.ts +35 -0
  99. package/dist/interpreter/standard-utf8.d.ts +4 -0
  100. package/dist/interpreter/standard.d.ts +18 -0
  101. package/dist/interpreter/types.d.ts +152 -0
  102. package/dist/interpreter/wit-shape.d.ts +92 -0
  103. package/dist/manager.js +5 -332
  104. package/dist/msgpack.js +9 -615
  105. package/dist/node.d.ts +8 -1
  106. package/dist/node.js +248 -3287
  107. package/dist/rpc.js +196 -699
  108. package/dist/runtime/adapters.d.ts +120 -0
  109. package/dist/runtime/adapters.js +38 -0
  110. package/dist/runtime/calls.d.ts +9 -3
  111. package/dist/runtime/lifecycle.d.ts +3 -1
  112. package/dist/runtime/orbs.d.ts +5 -4
  113. package/dist/runtime/references.d.ts +27 -1
  114. package/dist/runtime/reload.d.ts +5 -3
  115. package/dist/runtime/scopes.d.ts +1 -1
  116. package/dist/runtime/signals.d.ts +4 -0
  117. package/dist/runtime/wit-client.d.ts +38 -0
  118. package/dist/telemetry.js +4 -25
  119. package/dist/tooling/build.d.ts +2 -2
  120. package/dist/tooling/client-resources.d.ts +23 -0
  121. package/dist/tooling/client.d.ts +10 -0
  122. package/dist/tooling/component-glue.d.ts +17 -0
  123. package/dist/tooling/component.d.ts +11 -0
  124. package/dist/tooling/index.d.ts +3 -1
  125. package/dist/tooling/index.js +1155 -102
  126. package/dist/tooling/resolver.d.ts +4 -4
  127. package/dist/tooling/typecheck.d.ts +2 -1
  128. package/dist/tooling/types.d.ts +27 -12
  129. package/dist/tooling/wit.d.ts +9 -0
  130. package/dist/wasi/wasi-clocks-types.d.ts +2 -0
  131. package/dist/wasi/wasi-http-client.d.ts +5 -0
  132. package/dist/wasi/wasi-http-types.d.ts +285 -0
  133. package/dist/wasi/wasi-sockets-ip-name-lookup.d.ts +23 -0
  134. package/dist/wasi/wasi-sockets-types.d.ts +146 -0
  135. package/package.json +62 -35
  136. package/src/authoring/declaration.ts +1 -1
  137. package/src/authoring/types.ts +53 -3
  138. package/src/authoring/wit.ts +15 -0
  139. package/src/bridge/commands.ts +1105 -0
  140. package/src/bridge/identifiers.ts +2 -0
  141. package/src/bridge/kernel.ts +56 -98
  142. package/src/bridge/protocol.ts +3 -142
  143. package/src/browser.ts +90 -6
  144. package/src/context-key.ts +4 -7
  145. package/src/error.ts +1 -1
  146. package/src/errors.ts +7 -0
  147. package/src/guest.ts +327 -0
  148. package/src/host.ts +128 -23
  149. package/src/http/bytes.ts +87 -0
  150. package/src/http/events.ts +34 -0
  151. package/src/http.ts +272 -0
  152. package/src/index.ts +3 -0
  153. package/src/infrastructure/rpc/client.ts +136 -17
  154. package/src/infrastructure/rpc/resources.ts +123 -0
  155. package/src/interpreter/abi.ts +69 -0
  156. package/src/interpreter/acquire.ts +58 -0
  157. package/src/interpreter/browser-network.ts +170 -0
  158. package/src/interpreter/browser-port.ts +425 -0
  159. package/src/interpreter/browser.ts +340 -0
  160. package/src/interpreter/cli.ts +30 -0
  161. package/src/interpreter/codec.ts +298 -0
  162. package/src/interpreter/component/execution.ts +264 -0
  163. package/src/interpreter/component/host.ts +409 -0
  164. package/src/interpreter/component/instance.ts +138 -0
  165. package/src/interpreter/component/kernel.ts +611 -0
  166. package/src/interpreter/component/names.ts +13 -0
  167. package/src/interpreter/component/port.ts +598 -0
  168. package/src/interpreter/component/prepared.ts +194 -0
  169. package/src/interpreter/component/resources.ts +345 -0
  170. package/src/interpreter/component/revision.ts +702 -0
  171. package/src/interpreter/component/scope.ts +447 -0
  172. package/src/interpreter/component/streams.ts +180 -0
  173. package/src/interpreter/component/values.ts +254 -0
  174. package/src/interpreter/component/wasi-filesystem.ts +472 -0
  175. package/src/interpreter/component/wasi-host.ts +197 -0
  176. package/src/interpreter/component/wasi-http.ts +939 -0
  177. package/src/interpreter/component/wasi-sockets.ts +958 -0
  178. package/src/interpreter/component/wasi.ts +238 -0
  179. package/src/interpreter/core.ts +386 -0
  180. package/src/interpreter/fetch-http-provider.ts +98 -0
  181. package/src/interpreter/filesystem/contract.ts +138 -0
  182. package/src/interpreter/filesystem/memory.ts +180 -0
  183. package/src/interpreter/filesystem/opfs.ts +294 -0
  184. package/src/interpreter/filesystem/scope.ts +390 -0
  185. package/src/interpreter/filesystem.ts +20 -0
  186. package/src/interpreter/gate.ts +55 -0
  187. package/src/interpreter/host-protocol.ts +242 -0
  188. package/src/interpreter/http-ingress-fetch.ts +133 -0
  189. package/src/interpreter/http-ingress.ts +203 -0
  190. package/src/interpreter/http-provider.ts +105 -0
  191. package/src/interpreter/io.ts +66 -0
  192. package/src/interpreter/mobile.ts +385 -0
  193. package/src/interpreter/native-ingress.ts +550 -0
  194. package/src/interpreter/node-port.ts +218 -0
  195. package/src/interpreter/node.ts +114 -0
  196. package/src/interpreter/revision.ts +450 -0
  197. package/src/interpreter/scope.ts +453 -0
  198. package/src/interpreter/socket-addresses.ts +246 -0
  199. package/src/interpreter/socket-provider.ts +126 -0
  200. package/src/interpreter/standard-cli.ts +184 -0
  201. package/src/interpreter/standard-codec.ts +403 -0
  202. package/src/interpreter/standard-filesystem.ts +545 -0
  203. package/src/interpreter/standard-host.ts +840 -0
  204. package/src/interpreter/standard-http-values.ts +624 -0
  205. package/src/interpreter/standard-http.ts +622 -0
  206. package/src/interpreter/standard-ingress.ts +344 -0
  207. package/src/interpreter/standard-sockets.ts +847 -0
  208. package/src/interpreter/standard-streams.ts +710 -0
  209. package/src/interpreter/standard-system.ts +182 -0
  210. package/src/interpreter/standard-utf8.ts +72 -0
  211. package/src/interpreter/standard.ts +283 -0
  212. package/src/interpreter/types.ts +163 -0
  213. package/src/interpreter/wit-shape.ts +175 -0
  214. package/src/node.ts +43 -14
  215. package/src/runtime/activities.ts +6 -6
  216. package/src/runtime/adapters.ts +314 -0
  217. package/src/runtime/calls.ts +218 -56
  218. package/src/runtime/context.ts +7 -7
  219. package/src/runtime/lifecycle.ts +36 -17
  220. package/src/runtime/orbs.ts +81 -39
  221. package/src/runtime/programs.ts +16 -8
  222. package/src/runtime/references.ts +128 -11
  223. package/src/runtime/reload.ts +71 -30
  224. package/src/runtime/resources.ts +2 -2
  225. package/src/runtime/scopes.ts +17 -17
  226. package/src/runtime/session.ts +3 -1
  227. package/src/runtime/signals.ts +31 -0
  228. package/src/runtime/wit-client.ts +228 -0
  229. package/src/tooling/build.ts +152 -54
  230. package/src/tooling/client-resources.ts +74 -0
  231. package/src/tooling/client.ts +531 -0
  232. package/src/tooling/component-glue.ts +288 -0
  233. package/src/tooling/component.ts +225 -0
  234. package/src/tooling/index.ts +3 -7
  235. package/src/tooling/resolver.ts +42 -25
  236. package/src/tooling/typecheck.ts +59 -4
  237. package/src/tooling/types.ts +27 -12
  238. package/src/tooling/wit.ts +188 -0
  239. package/dist/embedded.d.ts +0 -1
  240. package/dist/embedded.js +0 -1
  241. package/src/embedded.ts +0 -293
@@ -0,0 +1,288 @@
1
+ /**
2
+ * Exact, fail-closed instrumentation of JCO 0.23.0 glue, applied at build time by Tembra tooling
3
+ * to bindings generated from natively verified component bytes; browsers never run this code.
4
+ * It adds per-instance export-task start, task exit (with rejection) and trap notifications plus
5
+ * a current-root-task accessor through the official 4th `instantiate(..., options)` argument.
6
+ * Every anchor must occur exactly once; any vendor drift refuses the glue instead of emitting
7
+ * uninstrumented code.
8
+ */
9
+ export const JCO_VERSION = "0.23.0";
10
+
11
+ const HEADER =
12
+ '"use components";\nexport function instantiate(getCoreModule, imports, instantiateCore, options) {\n';
13
+ const TASK_ANCHOR = " const newTaskMeta = { id: newTaskID, componentIdx, task: newTask };\n";
14
+ const TRAP_ANCHOR =
15
+ " this.#trapped = true;\n if (this.#trapError === null) { this.#trapError = err; }\n";
16
+
17
+ const PRELUDE = ` const __tembraObserver = options?.tembraObserver ?? null;
18
+ function __tembraObserveTask(task, args) {
19
+ if (__tembraObserver === null || !args.callingWasmExport) { return; }
20
+ const id = task.id();
21
+ __tembraObserver.taskStarted({ id, entry: args.entryFnName, isAsync: !!args.isAsync });
22
+ task.exitPromise().then(
23
+ () => __tembraObserver.taskExited({ id, rejected: task.isRejected(), error: task.isErrored() ?? undefined }),
24
+ (error) => __tembraObserver.taskExited({ id, error }),
25
+ );
26
+ }
27
+ function __tembraObserveTrap(error) {
28
+ if (__tembraObserver !== null) { __tembraObserver.trapped(error); }
29
+ }
30
+ if (__tembraObserver !== null) {
31
+ __tembraObserver.attach({
32
+ /** Root export task of the guest code running now (call synchronously at host-import entry). */
33
+ currentRootTask() {
34
+ const meta = CURRENT_TASK_META.current;
35
+ if (!meta || meta.taskID === undefined || meta.componentIdx === undefined) { return null; }
36
+ const task = getCurrentTask(meta.componentIdx, meta.taskID)?.task;
37
+ return task ? task.getRootTask().id() : null;
38
+ },
39
+ });
40
+ }
41
+ `;
42
+
43
+ function once(source: string, anchor: string, label: string): number {
44
+ const first = source.indexOf(anchor);
45
+ if (first < 0 || source.indexOf(anchor, first + 1) >= 0) {
46
+ throw new Error(
47
+ `unsupported trusted compiler output: anchor "${label}" must occur exactly once (expected JCO ${JCO_VERSION})`,
48
+ );
49
+ }
50
+ return first;
51
+ }
52
+
53
+ /** Instrument generated glue through its task and trap notifications. */
54
+ export function instrumentGlue(source: string): string {
55
+ if (!source.startsWith(HEADER)) {
56
+ throw new Error(
57
+ `unsupported trusted compiler output: instantiate signature (expected JCO ${JCO_VERSION})`,
58
+ );
59
+ }
60
+ once(source, TASK_ANCHOR, "task creation");
61
+ once(source, TRAP_ANCHOR, "trap record");
62
+ once(source, " const CURRENT_TASK_META = {};\n", "current task metadata");
63
+ once(source, " getRootTask() {\n", "root task");
64
+ once(source, " isErrored() { return this.#errored; }\n", "task error");
65
+ const out =
66
+ HEADER +
67
+ PRELUDE +
68
+ source
69
+ .slice(HEADER.length)
70
+ .replace(TASK_ANCHOR, TASK_ANCHOR + " __tembraObserveTask(newTask, args);\n")
71
+ .replace(TRAP_ANCHOR, TRAP_ANCHOR + " __tembraObserveTrap(this.#trapError);\n");
72
+ return out;
73
+ }
74
+
75
+ /**
76
+ * JCO 0.23.0 vendor bug fix.
77
+ *
78
+ * In the canonical future/stream intrinsics (`futureRead`/`futureWrite`/`streamRead`/...), the
79
+ * element lift metadata `_liftFlatOwn({ componentIdx, tableIdx, createResourceFn })` reads and
80
+ * removes the guest handle from `handleTable<resource index>` instead of `handleTable<tableIdx>`.
81
+ * The resource index equals the capture-table index, so the lift consults a table of another
82
+ * component (`unknown handle index N`). Import-lowering sites already use the right table.
83
+ * Effect: a guest that writes an owned imported resource into a future or stream read by the host
84
+ * (for example `wasi:http` request trailers, `result<option<fields>, error-code>`) traps the read.
85
+ *
86
+ * Imported-resource sites must have the shape below, with a target table declared for the same
87
+ * component and paired with the same capture table. Exported-resource sites instead retain
88
+ * their handle until disposal; admit that distinct pinned shape unchanged only when its class,
89
+ * table, finalization registry and destructor agree. Every other shape refuses the glue.
90
+ */
91
+ const LIFT_OWN =
92
+ /_liftFlatOwn\(\{\n\s*componentIdx: (\d+),\n\s*tableIdx: (\d+),\n\s*classNameFn: \(\) => [\w$]+,\n\s*createResourceFn: \n\s*\(handle\) => \{\n\s*const rep = handleTable(\d+)\[\(handle << 1\) \+ 1\] % T_OWN;\n\s*let resourceObj = captureTable(\d+)\.get\(rep\);\n(?:.*\n){1,8}?\s*rscTableRemove\(handleTable(\d+), handle\);\n/g;
93
+ const TABLE =
94
+ /const handleTable(\d+) = \[T_FLAG, 0\];\n\s*handleTable\1\._createdReps = new Set\(\);\n\s*handleTable\1\._componentIdx = (\d+);\n\s*\n\s*\n\s*const captureTable(\d+)= new Map\(\);\n/g;
95
+ const EXPORTED_TABLE =
96
+ /const handleTable(\d+) = \[T_FLAG, 0\];\n\s*handleTable\1\._createdReps = new Set\(\);\n\s*handleTable\1\._componentIdx = (\d+);\n\s*const finalizationRegistry(\d+) = finalizationRegistryCreate\(\(handle\) => \{\n\s*const \{ rep \} = rscTableRemove\(handleTable\1, handle\);\n\s*callResourceDestructor\(\{ componentIdx: \2, dtor: (exports\d+\["\d+"\]), rep \}\);\n\s*\}\);\n\s*HANDLE_TABLES\[\1\] = handleTable\1;\n/g;
97
+ const EXPORTED_LIFT_OWN = new RegExp(
98
+ [
99
+ String.raw`_liftFlatOwn\(\{\n\s*componentIdx: (\d+),\n\s*tableIdx: (\d+),\n\s*classNameFn: \(\) => ([\w$]+),\n\s*createResourceFn: \n\s*\(handle\) => \{\n`,
100
+ String.raw`\s*const resourceObj = Object\.create\(\3\.prototype\);\n\s*Object\.defineProperty\(resourceObj, symbolRscHandle, \{\n\s*writable: true,\n\s*value: handle,\n\s*\}\);\n`,
101
+ String.raw`\s*finalizationRegistry(\d+)\.register\(resourceObj, handle, resourceObj\);\n\s*Object\.defineProperty\(\n\s*resourceObj,\n\s*symbolDispose,\n\s*\{\n\s*writable: true,\n\s*value: function\(\) \{\n`,
102
+ String.raw`\s*finalizationRegistry\4\.unregister\(resourceObj\);\n\s*const handleEntry = rscTableRemove\(handleTable\2, handle\);\n\s*resourceObj\[symbolDispose\] = emptyFunc;\n\s*resourceObj\[symbolRscHandle\] = undefined;\n`,
103
+ String.raw`\s*callResourceDestructor\(\{ componentIdx: \1, dtor: (exports\d+\["\d+"\]), rep: handleEntry\.rep \}\);\n\s*\}\n\s*\}\n\s*\);\n\s*return resourceObj;\n\s*\}\n\s*,\n\s*\}\)`,
104
+ ].join(""),
105
+ "g",
106
+ );
107
+
108
+ export function fixLiftOwnTables(source: string): string {
109
+ const tables = new Map<string, { component: string; capture: string }>();
110
+ for (const [, table, component, capture] of source.matchAll(TABLE))
111
+ tables.set(table!, { component: component!, capture: capture! });
112
+ const exportedTables = new Map<string, { component: string; registry: string; dtor: string }>();
113
+ for (const [, table, component, registry, dtor] of source.matchAll(EXPORTED_TABLE))
114
+ exportedTables.set(table!, { component: component!, registry: registry!, dtor: dtor! });
115
+ const classes = new Set([...source.matchAll(/\bclass ([\w$]+)\{/g)].map((match) => match[1]));
116
+ const sites = source.split("_liftFlatOwn({").length - 1;
117
+ let fixed = 0;
118
+ for (const [, component, table, className, registry, dtor] of source.matchAll(
119
+ EXPORTED_LIFT_OWN,
120
+ )) {
121
+ const declared = exportedTables.get(table!);
122
+ if (
123
+ !declared ||
124
+ declared.component !== component ||
125
+ declared.registry !== registry ||
126
+ declared.dtor !== dtor ||
127
+ !classes.has(className)
128
+ )
129
+ throw new Error(
130
+ "unsupported trusted compiler output: exported owned-resource lift table (expected JCO 0.23.0)",
131
+ );
132
+ fixed++;
133
+ }
134
+ const out = source.replace(LIFT_OWN, (site, component, table, read, capture, removed) => {
135
+ const declared = tables.get(table);
136
+ if (
137
+ !declared ||
138
+ declared.component !== component ||
139
+ declared.capture !== capture ||
140
+ read !== removed
141
+ )
142
+ throw new Error(
143
+ "unsupported trusted compiler output: owned-resource lift table (expected JCO 0.23.0)",
144
+ );
145
+ fixed++;
146
+ return site
147
+ .replace(`const rep = handleTable${read}[`, `const rep = handleTable${table}[`)
148
+ .replace(
149
+ `rscTableRemove(handleTable${removed}, handle)`,
150
+ `rscTableRemove(handleTable${table}, handle)`,
151
+ );
152
+ });
153
+ if (fixed !== sites)
154
+ throw new Error(
155
+ "unsupported trusted compiler output: owned-resource lift shape (expected JCO 0.23.0)",
156
+ );
157
+ return out;
158
+ }
159
+
160
+ /**
161
+ * JCO 0.23.0 converts a typed result error inside the async wrapper's own try block. Its
162
+ * catch then exits a task whose callback driver still owns guest work. Only that converted
163
+ * error must bypass the early exit; genuine failures retain the vendor exit path.
164
+ */
165
+ const THROW = "if (taskRes.tag === 'err') { throw new ComponentError(taskRes.val);}";
166
+ const MARKED =
167
+ "if (taskRes.tag === 'err') { throw __tembraResultErr(new ComponentError(taskRes.val));}";
168
+ const EXIT = "if (!task.isExited()) { task.exit({ skipExclusiveLockCheck: true }); }";
169
+ const GUARDED =
170
+ "if (!task.isExited() && !__tembraResultErrs.has(err)) { task.exit({ skipExclusiveLockCheck: true }); }";
171
+ const RESULT_ERR_PRELUDE = ` const __tembraResultErrs = new WeakSet();
172
+ function __tembraResultErr(error) { __tembraResultErrs.add(error); return error; }
173
+ `;
174
+
175
+ export function fixResultErrExit(source: string): string {
176
+ if (!source.startsWith(HEADER))
177
+ throw new Error(
178
+ "unsupported trusted compiler output: instantiate signature (expected JCO 0.23.0)",
179
+ );
180
+ const throws = source.split(THROW).length - 1;
181
+ if (throws === 0) return source;
182
+ const exits = source.split(EXIT).length - 1;
183
+ if (exits === 0)
184
+ throw new Error("unsupported trusted compiler output: result error exit (expected JCO 0.23.0)");
185
+ const out =
186
+ HEADER +
187
+ RESULT_ERR_PRELUDE +
188
+ source.slice(HEADER.length).split(THROW).join(MARKED).split(EXIT).join(GUARDED);
189
+ if (out.includes(THROW) || out.includes(EXIT))
190
+ throw new Error(
191
+ "unsupported trusted compiler output: result error rewrite (expected JCO 0.23.0)",
192
+ );
193
+ return out;
194
+ }
195
+
196
+ /**
197
+ * JCO's scheduler yields after each resumed thread before checking another thread. Nested
198
+ * browser timers clamp that zero-delay turn to 4 ms. Use the browser's native task scheduler
199
+ * when available, retaining a real event-loop turn so host timers, cancellation and microtask
200
+ * continuations can run. Initial and idle polling remain on JCO's existing timers; no CABI
201
+ * readiness, task ownership, rejection or exit handling changes.
202
+ */
203
+ const SCHEDULER_TURN = ` // After resuming a task, re-tick as soon as the resumed
204
+ // slice's microtask continuations have drained (timeout 0)
205
+ // so queued sibling resumptions aren't charged the idle
206
+ // polling interval; otherwise poll at the idle cadence.
207
+ const delay = result === ComponentAsyncState.TickResult.RESUMED ? 0 : 10;
208
+ await new Promise((resolve) => setTimeout(resolve, delay));
209
+ result = this.tick();
210
+ `;
211
+ const SCHEDULER_TURN_PRELUDE = ` function __tembraSchedulerTurn(delay) {
212
+ const timer = () => new Promise((resolve) => setTimeout(resolve, delay));
213
+ if (delay === 0) {
214
+ try {
215
+ const scheduler = globalThis.scheduler;
216
+ if (typeof scheduler?.postTask === 'function') {
217
+ return scheduler.postTask(() => {}, { priority: 'user-visible' }).catch(timer);
218
+ }
219
+ } catch {
220
+ // An unavailable host scheduling API retains the vendor timer path.
221
+ }
222
+ }
223
+ return timer();
224
+ }
225
+ `;
226
+
227
+ export function fixSchedulerTurns(source: string): string {
228
+ if (!source.startsWith(HEADER))
229
+ throw new Error(
230
+ `unsupported trusted compiler output: instantiate signature (expected JCO ${JCO_VERSION})`,
231
+ );
232
+ once(source, " async runTickLoop() {\n", "async scheduler");
233
+ once(source, SCHEDULER_TURN, "resumed scheduler turn");
234
+ return (
235
+ HEADER +
236
+ SCHEDULER_TURN_PRELUDE +
237
+ source
238
+ .slice(HEADER.length)
239
+ .replace(
240
+ SCHEDULER_TURN,
241
+ SCHEDULER_TURN.replace(
242
+ "await new Promise((resolve) => setTimeout(resolve, delay));",
243
+ "await __tembraSchedulerTurn(delay);",
244
+ ),
245
+ )
246
+ );
247
+ }
248
+
249
+ /**
250
+ * JCO 0.23.0 lifts list elements into function-scoped `var` temporaries. Each resource's
251
+ * destructor then closes the final iteration's handle/object, leaking earlier elements.
252
+ * Bind both temporaries to their lexical block. Match the complete pinned ownership block:
253
+ * changing an unrelated variable or accepting a partial vendor shape would hide a compiler bug.
254
+ */
255
+ const RESOURCE_CLOSURE = new RegExp(
256
+ [
257
+ String.raw`var (handle\d+) = [^\n]+;\n\s*var (rsc\d+) = new\.target === ([\w$]+) \? this : Object\.create\(\3\.prototype\);\n`,
258
+ String.raw`\s*Object\.defineProperty\(\2, symbolRscHandle, \{ writable: true, value: \1\}\);\n`,
259
+ String.raw`\s*finalizationRegistry(\d+)\.register\(\2, \1, \2\);\n`,
260
+ String.raw`\s*Object\.defineProperty\(\2, symbolDispose, \{ writable: true, value: function \(\) \{\n`,
261
+ String.raw`\s*finalizationRegistry\4\.unregister\(\2\);\n`,
262
+ String.raw`\s*const handleEntry = rscTableRemove\(handleTable\d+, \1\);\n`,
263
+ String.raw`\s*\2\[symbolDispose\] = emptyFunc;\n\s*\2\[symbolRscHandle\] = undefined;\n`,
264
+ String.raw`\s*callResourceDestructor\(\{ componentIdx: \d+, dtor: exports\d+\["\d+"\], rep: handleEntry\.rep \}\);\n\s*\}\}\);`,
265
+ ].join(""),
266
+ "g",
267
+ );
268
+
269
+ export function fixResourceClosures(source: string): string {
270
+ const sites = [...source.matchAll(/Object\.defineProperty\(rsc\d+, symbolDispose,/g)].length;
271
+ let changed = 0;
272
+ const output = source.replace(RESOURCE_CLOSURE, (block) => {
273
+ changed++;
274
+ return block.replace(/\bvar (handle\d+|rsc\d+) =/g, "let $1 =");
275
+ });
276
+ if (changed !== sites)
277
+ throw new Error(
278
+ `unsupported trusted compiler output: resource destructor closure (expected JCO ${JCO_VERSION})`,
279
+ );
280
+ return output;
281
+ }
282
+
283
+ /** Apply every required rewrite to generated glue, in the order the anchors expect. */
284
+ export function prepareGlue(source: string): string {
285
+ return fixSchedulerTurns(
286
+ fixResourceClosures(fixLiftOwnTables(fixResultErrExit(instrumentGlue(source)))),
287
+ );
288
+ }
@@ -0,0 +1,225 @@
1
+ /**
2
+ * Build-time browser preparation of a compiled Orb.
3
+ *
4
+ * The native verifier first checks the component's real WIT types against its contract. JCO then
5
+ * generates bindings once; Tembra instruments the glue (task, exit and trap observation) and every
6
+ * component core module (fuel and page limits), and writes an ES module that the application
7
+ * imports and registers explicitly. The module binds itself to the SHA-256 of the exact artifact.
8
+ * Browsers receive no generator, parser or encoder.
9
+ */
10
+ import { createRequire } from "node:module";
11
+ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
12
+ import { createHash } from "node:crypto";
13
+ import path from "node:path";
14
+ import { query } from "../interpreter/types.ts";
15
+ import { HTTP_HANDLER } from "../interpreter/http-ingress.ts";
16
+ import {
17
+ COMPONENT_CORE,
18
+ PREPARED_FORMAT,
19
+ PREPARED_GENERATOR,
20
+ PREPARED_MAXIMUM_PAGES,
21
+ TRAMPOLINE_CORE,
22
+ type PreparedComponentSource,
23
+ } from "../interpreter/component/prepared.ts";
24
+ import type { Described } from "../interpreter/component/revision.ts";
25
+ import { converters, type GraphFunction } from "../interpreter/component/values.ts";
26
+ import { referenceView } from "../interpreter/component/host.ts";
27
+ import { resourceDataFunction, resourceRoles } from "../interpreter/component/resources.ts";
28
+ import { BROWSER_WASI } from "../interpreter/component/wasi.ts";
29
+ import { JCO_VERSION, prepareGlue } from "./component-glue.ts";
30
+
31
+ /** Core modules up to this size are inlined into the adapter module instead of fetched. */
32
+ const INLINE_BYTES = 4096;
33
+
34
+ /** Files written for one prepared adapter. */
35
+ export interface BrowserAdapter {
36
+ /** The ES module the application imports and passes to `createHost`. */
37
+ readonly module: string;
38
+ readonly files: readonly string[];
39
+ }
40
+
41
+ /** Refuse a JCO release whose output the glue instrumentation does not recognize exactly. */
42
+ async function generator() {
43
+ const entry = createRequire(import.meta.url).resolve("@bytecodealliance/jco-transpile/component");
44
+ const manifest = JSON.parse(
45
+ await readFile(path.join(path.dirname(entry), "..", "package.json"), "utf8"),
46
+ ) as { name?: string; version?: string };
47
+ if (
48
+ manifest.name !== "@bytecodealliance/jco-transpile" ||
49
+ manifest.version !== JCO_VERSION ||
50
+ PREPARED_GENERATOR !== `${manifest.name}@${manifest.version}`
51
+ )
52
+ throw new Error(`Browser preparation requires @bytecodealliance/jco-transpile ${JCO_VERSION}`);
53
+ const bindgen = await import("@bytecodealliance/jco-transpile/component");
54
+ await bindgen.$init;
55
+ return bindgen;
56
+ }
57
+
58
+ /** Check what browser execution provides before generating anything. */
59
+ function plan(graph: Described, imports: readonly string[]) {
60
+ const convert = converters(graph);
61
+ const check = (binding: string, name: string, signature: unknown) => {
62
+ try {
63
+ const fn = { ...(signature as GraphFunction), name };
64
+ convert(resourceDataFunction(fn, resourceRoles(graph, binding, fn)));
65
+ } catch (error) {
66
+ throw new Error(
67
+ `Browser preparation cannot execute ${binding}#${name}: ${(error as Error).message}`,
68
+ );
69
+ }
70
+ };
71
+ const suspending: string[] = [];
72
+ for (const name of imports) {
73
+ if (name.startsWith("wasi:")) {
74
+ if (!BROWSER_WASI.has(name))
75
+ throw new Error(`Browser hosts do not provide ${name}; this Orb cannot run in browsers`);
76
+ continue;
77
+ }
78
+ const selected = graph.imports.find((item) => item.binding === name);
79
+ if (!selected) throw new Error(`The component imports ${name}, which its contract lacks`);
80
+ if (selected.type_only) continue;
81
+ const view = graph.references[name];
82
+ if (view) {
83
+ // A checked reference view: only its acquisition and method receivers are handles, both
84
+ // host-local; every other position is data. No resource crosses between Orbs.
85
+ try {
86
+ referenceView(graph, name, view, convert);
87
+ } catch (error) {
88
+ throw new Error(`Browser preparation cannot execute ${name}: ${(error as Error).message}`);
89
+ }
90
+ for (const fn of Object.keys(selected.functions ?? {})) suspending.push(`${name}#${fn}`);
91
+ continue;
92
+ }
93
+ // Orb dependency calls are asynchronous host work behind a synchronous WIT import.
94
+ for (const [fn, signature] of Object.entries(selected.functions ?? {})) {
95
+ check(selected.contract ?? name, fn, signature);
96
+ suspending.push(`${name}#${fn}`);
97
+ }
98
+ }
99
+ const promising: string[] = [];
100
+ for (const entry of graph.exports)
101
+ for (const [fn, signature] of Object.entries(entry.functions ?? {})) {
102
+ // The incoming HTTP handler uses the WASI adapter's own resources, not value conversion.
103
+ if (entry.contract !== HTTP_HANDLER) check(entry.contract ?? entry.binding, fn, signature);
104
+ promising.push(`${entry.binding}#${fn}`);
105
+ }
106
+ return { suspending, promising };
107
+ }
108
+
109
+ /**
110
+ * Prepare a verified compiled artifact for browsers into the build-owned `directory`.
111
+ * `artifact` must be the exact bytes the application will load; `sha256` is their digest.
112
+ */
113
+ export async function prepareBrowserComponent(
114
+ artifact: Uint8Array,
115
+ sha256: string,
116
+ directory: string,
117
+ ): Promise<BrowserAdapter> {
118
+ const engine = await import("@syntropika/tembra-engine-node");
119
+ if (createHash("sha256").update(artifact).digest("hex") !== sha256)
120
+ throw new Error("Browser preparation received an artifact digest for other bytes");
121
+ // Full native verification of the real component types against the contract.
122
+ const verified = new engine.NodeArtifact(artifact);
123
+ const identity = JSON.parse(verified.description()) as {
124
+ name: string;
125
+ apiVersion: number;
126
+ kind: string;
127
+ };
128
+ if (identity.kind !== "component")
129
+ throw new Error("Only compiled component artifacts need browser preparation");
130
+ const graph = query<Described>(verified, { kind: "describe" });
131
+ const imports = engine.componentImports(artifact);
132
+ if (new Set(imports).size !== imports.length)
133
+ throw new Error("The component imports one name twice");
134
+ const { suspending, promising } = plan(graph, imports);
135
+ const bindgen = await generator();
136
+ const output = bindgen.generate(artifact, {
137
+ name: "orb",
138
+ noTypescript: true,
139
+ instantiation: { tag: "async" },
140
+ noNodejsCompat: true,
141
+ base64Cutoff: 0,
142
+ // JCO drops import versions by default; exact entries keep every versioned key apart.
143
+ map: imports.map((name): [string, string] => [name, name]),
144
+ asyncMode: { tag: "jspi", val: { imports: suspending, exports: promising } },
145
+ emitConditionalSuspendingWasm: true,
146
+ });
147
+ let glue: string | undefined;
148
+ const cores: { name: string; pages?: number; bytes: Uint8Array }[] = [];
149
+ for (const [name, bytes] of output.files) {
150
+ if (name === "orb.js") glue = prepareGlue(new TextDecoder().decode(bytes));
151
+ else if (COMPONENT_CORE.test(name)) {
152
+ const core = engine.instrumentCore(bytes, PREPARED_MAXIMUM_PAGES);
153
+ cores.push({ name, pages: core.initialPages, bytes: core.bytes });
154
+ } else if (TRAMPOLINE_CORE.test(name)) cores.push({ name, bytes });
155
+ else throw new Error(`Unexpected generated file ${name}`);
156
+ }
157
+ if (!glue) throw new Error("The bindings generator produced no glue");
158
+ if (!cores.some((core) => core.pages !== undefined))
159
+ throw new Error("The bindings generator produced no component core module");
160
+ const files = new Map<string, string | Uint8Array>([["glue.js", glue]]);
161
+ const entries = cores.map((core) => {
162
+ const fields = `name: ${JSON.stringify(core.name)}${
163
+ core.pages === undefined ? "" : `, pages: ${core.pages}`
164
+ }`;
165
+ if (core.bytes.byteLength <= INLINE_BYTES)
166
+ return `{ ${fields}, load: () => bytes(${JSON.stringify(Buffer.from(core.bytes).toString("base64"))}) }`;
167
+ const hash = createHash("sha256").update(core.bytes).digest("hex").slice(0, 16);
168
+ const file = `${core.name.slice(0, -".wasm".length)}.${hash}.wasm`;
169
+ files.set(file, core.bytes);
170
+ return `{ ${fields}, load: () => fetch(new URL(${JSON.stringify(`./${file}`)}, import.meta.url)) }`;
171
+ });
172
+ const description: Omit<PreparedComponentSource, "cores" | "instantiate"> = {
173
+ format: PREPARED_FORMAT,
174
+ generator: PREPARED_GENERATOR,
175
+ orb: { name: identity.name, apiVersion: identity.apiVersion },
176
+ artifact: sha256,
177
+ maximumPages: PREPARED_MAXIMUM_PAGES,
178
+ imports,
179
+ suspending,
180
+ promising,
181
+ };
182
+ const fields = Object.entries(description)
183
+ .map(([key, value]) => ` ${key}: ${JSON.stringify(value)},`)
184
+ .join("\n");
185
+ files.set(
186
+ "index.js",
187
+ `// Generated by Tembra tooling; do not edit.
188
+ // Host-trusted application code: import this module and register its default export with
189
+ // createHost({ isolated: { components: [...] } }). It runs only the artifact with digest
190
+ // ${sha256}.
191
+ import { preparedComponent } from "@syntropika/tembra-sdk/browser";
192
+ import { instantiate } from "./glue.js";
193
+
194
+ const bytes = (text) => Uint8Array.from(atob(text), (character) => character.charCodeAt(0));
195
+
196
+ export default preparedComponent({
197
+ ${fields}
198
+ cores: [
199
+ ${entries.join(",\n ")},
200
+ ],
201
+ instantiate,
202
+ });
203
+ `,
204
+ );
205
+ files.set(
206
+ "index.d.ts",
207
+ `declare const component: import("@syntropika/tembra-sdk/browser").PreparedComponent;
208
+ export default component;
209
+ `,
210
+ );
211
+ const temporary = `${directory}.${process.pid}.tmp`;
212
+ await rm(temporary, { recursive: true, force: true });
213
+ await mkdir(temporary, { recursive: true });
214
+ try {
215
+ for (const [name, contents] of files) await writeFile(path.join(temporary, name), contents);
216
+ await rm(directory, { recursive: true, force: true });
217
+ await rename(temporary, directory);
218
+ } finally {
219
+ await rm(temporary, { recursive: true, force: true });
220
+ }
221
+ return {
222
+ module: path.join(directory, "index.js"),
223
+ files: [...files.keys()].map((name) => path.join(directory, name)),
224
+ };
225
+ }
@@ -1,8 +1,4 @@
1
1
  export { build } from "./build.ts";
2
- export {
3
- Platform,
4
- defineConfig,
5
- type Artifact,
6
- type BuildConfig,
7
- type BuildTarget,
8
- } from "./types.ts";
2
+ export { client, type ClientOptions } from "./client.ts";
3
+ export { prepareBrowserComponent, type BrowserAdapter } from "./component.ts";
4
+ export { defineConfig, type Artifact, type BuildConfig, type BuildTarget } from "./types.ts";
@@ -5,38 +5,45 @@ import { builtinModules } from "node:module";
5
5
  import path from "node:path";
6
6
  import ts from "typescript";
7
7
 
8
- import { Platform, type BuildTarget } from "./types.ts";
8
+ import { METHODS, RESOURCES } from "../interpreter/standard.ts";
9
+ import { resourceClassName } from "../interpreter/standard-codec.ts";
10
+ import type { BuildTarget } from "./types.ts";
9
11
 
10
- /** Check whether the selected target permits this external dependency. */
11
- export function external(specifier: string, target: BuildTarget): boolean {
12
- return (
13
- target.platform === Platform.Node &&
14
- (builtinModules.includes(specifier.replace(/^node:/, "")) ||
15
- (target.nativeExternals ?? []).some(
16
- (name) => specifier === name || specifier.startsWith(`${name}/`),
17
- ))
12
+ /** Interfaces with generated standard WASI source bindings. */
13
+ export const STANDARD_INTERFACES: ReadonlySet<string> = new Set([
14
+ ...METHODS.map((method) => method.interface),
15
+ ...RESOURCES.map((name) => name.split("#")[0]!),
16
+ ]);
17
+
18
+ /** Re-export the interpreter's generated module for one imported standard interface. */
19
+ function standardModule(contract: string): string {
20
+ const names = new Set(
21
+ METHODS.filter((method) => method.interface === contract && method.resource === undefined).map(
22
+ (method) => method.name,
23
+ ),
18
24
  );
25
+ for (const name of RESOURCES)
26
+ if (name.startsWith(`${contract}#`)) names.add(resourceClassName(name));
27
+ return [
28
+ `const module = globalThis.__tembraStandard[${JSON.stringify(contract)}];`,
29
+ `if (!module) throw new Error(${JSON.stringify(`The Orb contract does not import ${contract}`)});`,
30
+ ...[...names].map((name) => `export const ${name} = module.${name};`),
31
+ ].join("\n");
19
32
  }
20
33
 
21
34
  /** Resolve and bundle dependencies under the selected runtime rules. */
22
- export function resolver(root: string, target: BuildTarget): Bun.BunPlugin {
23
- const web = target.platform === Platform.Browser || target.platform === Platform.Worker;
35
+ export function resolver(
36
+ root: string,
37
+ target: BuildTarget,
38
+ imports: ReadonlySet<string>,
39
+ ): Bun.BunPlugin {
24
40
  const resolveModule = resolve.create.sync({
25
41
  fileSystem: fs,
26
- conditionNames: [
27
- "source",
28
- ...(web
29
- ? ["browser"]
30
- : target.platform === Platform.Node
31
- ? ["node", "node-addons"]
32
- : ["tembra-embedded"]),
33
- "import",
34
- "default",
35
- ],
42
+ conditionNames: ["tembra-wasm", "source", "import", "default"],
36
43
  extensions: [".ts", ".tsx", ".mts", ".js", ".jsx", ".mjs", ".cjs", ".json"],
37
44
  extensionAlias: { ".js": [".ts", ".tsx", ".js"], ".mjs": [".mts", ".mjs"] },
38
- mainFields: web ? ["browser", "module", "main"] : ["module", "main"],
39
- aliasFields: web ? ["browser"] : [],
45
+ mainFields: ["module", "main"],
46
+ aliasFields: [],
40
47
  });
41
48
  return {
42
49
  name: "tembra-platform",
@@ -50,8 +57,18 @@ export function resolver(root: string, target: BuildTarget): Bun.BunPlugin {
50
57
  contents: `import orb from ${JSON.stringify(path.resolve(root, target.entry))}; globalThis.__tembraOrb = orb;`,
51
58
  loader: "js",
52
59
  }));
60
+ builder.onResolve({ filter: /^wasi:/ }, (request) => {
61
+ if (!imports.has(request.path))
62
+ throw new Error(`${request.importer}: the Orb contract does not import ${request.path}`);
63
+ if (!STANDARD_INTERFACES.has(request.path))
64
+ throw new Error(`${request.importer}: ${request.path} has no source binding yet`);
65
+ return { path: request.path, namespace: "tembra-standard" };
66
+ });
67
+ builder.onLoad({ filter: /.*/, namespace: "tembra-standard" }, (request) => ({
68
+ contents: standardModule(request.path),
69
+ loader: "js",
70
+ }));
53
71
  builder.onResolve({ filter: /.*/ }, (request) => {
54
- if (external(request.path, target)) return { path: request.path, external: true };
55
72
  if (
56
73
  request.path.startsWith("node:") ||
57
74
  request.path.startsWith("bun:") ||
@@ -66,7 +83,7 @@ export function resolver(root: string, target: BuildTarget): Bun.BunPlugin {
66
83
  if (!resolved)
67
84
  throw new Error(`${request.importer}: no compatible implementation for ${request.path}`);
68
85
  if (resolved.endsWith(".node"))
69
- throw new Error("Declare native Node packages as nativeExternals in a node build");
86
+ throw new Error("Native Node packages cannot run inside an Orb");
70
87
  return { path: resolved };
71
88
  });
72
89
  builder.onLoad({ filter: /\.[cm]?[jt]sx?$/ }, async (request) => {