@syntropika/tembra-sdk 0.2.2 → 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 -3332
  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 -3310
  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 -3321
  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 +7 -6
  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 +213 -90
  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 -301
@@ -1,46 +1,197 @@
1
+ import"../chunks/index-c1w7z9hx.js";
2
+ import {
3
+ HTTP_HANDLER,
4
+ query,
5
+ RESOURCES,
6
+ METHODS,
7
+ resourceClassName
8
+ } from "../chunks/index-h8t0n42q.js";
9
+ import {
10
+ PREPARED_FORMAT,
11
+ PREPARED_GENERATOR,
12
+ PREPARED_MAXIMUM_PAGES,
13
+ COMPONENT_CORE,
14
+ TRAMPOLINE_CORE
15
+ } from "../chunks/index-n1wxzc9w.js";
16
+ import {
17
+ referenceView,
18
+ converters,
19
+ BROWSER_WASI
20
+ } from "../chunks/index-smyds5ce.js";
21
+ import"../chunks/index-v6heph77.js";
22
+ import {
23
+ bindingName,
24
+ resourceRoles,
25
+ resourceDataFunction
26
+ } from "../chunks/index-hfds9mzp.js";
27
+
1
28
  // src/tooling/build.ts
29
+ import { createHash as createHash3 } from "node:crypto";
30
+ import { mkdir as mkdir2, readFile as readFile3, rename as rename2, writeFile as writeFile2 } from "node:fs/promises";
31
+ import path5 from "node:path";
32
+ import ts4 from "typescript";
33
+ import { NodeContract } from "@syntropika/tembra-engine-node";
34
+
35
+ // src/tooling/wit.ts
2
36
  import { createHash } from "node:crypto";
3
- import { mkdir, rename, writeFile } from "node:fs/promises";
4
- import path2 from "node:path";
5
- import ts3 from "typescript";
37
+ import path from "node:path";
38
+ import ts from "typescript";
39
+ async function witTypes(file, world, root = path.dirname(path.resolve(file))) {
40
+ const { NodeContract } = await import("@syntropika/tembra-engine-node");
41
+ const { $init, generateTypes } = await import("@bytecodealliance/jco-transpile/component");
42
+ const absolute = path.resolve(file);
43
+ if (!absolute.endsWith(".wit"))
44
+ throw new Error("Direct WIT imports require a .wit entry file");
45
+ const contract = new NodeContract(path.dirname(absolute), world);
46
+ await $init;
47
+ const generated = generateTypes("contract", {
48
+ wit: { tag: "binary", val: contract.wit() },
49
+ ...world ? { world } : {}
50
+ });
51
+ const entries = [...generated].map(([name, bytes]) => {
52
+ if (!name.endsWith(".d.ts"))
53
+ return [name, bytes];
54
+ const text = new TextDecoder().decode(bytes);
55
+ const source = ts.createSourceFile(name, text, ts.ScriptTarget.ESNext, true);
56
+ const resources = source.statements.filter((statement) => ts.isClassDeclaration(statement) && statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword) === true);
57
+ const disposable = resources.map((resource) => `export interface ${resource.name.text} extends Disposable {}`);
58
+ return [
59
+ name,
60
+ disposable.length ? new TextEncoder().encode(`/// <reference lib="esnext.disposable" />
61
+ ` + text + `
62
+ ` + disposable.join(`
63
+ `) + `
64
+ `) : bytes
65
+ ];
66
+ }).sort(([left], [right]) => left.localeCompare(right));
67
+ const digest = createHash("sha256");
68
+ for (const [name, bytes] of entries)
69
+ digest.update(JSON.stringify([name, bytes.length])).update(bytes);
70
+ const sha256 = digest.digest("hex");
71
+ const directory = path.join(path.dirname(absolute), ".tembra", "types", sha256);
72
+ const files = new Map(entries.map(([name, bytes]) => [path.join(directory, name), new TextDecoder().decode(bytes)]));
73
+ const alias = absolute.slice(0, -4) + ".d.wit.ts";
74
+ const target = "./" + path.relative(path.dirname(alias), path.join(directory, "contract.js")).split(path.sep).join("/");
75
+ const references = [];
76
+ const imports = new Map;
77
+ const generatedFiles = new Map(entries.map(([name, bytes]) => [name, new TextDecoder().decode(bytes)]));
78
+ const description = query(contract, { kind: "describe" });
79
+ for (const imported of description.imports) {
80
+ if (!imported.contract)
81
+ continue;
82
+ const identity = /^([^:]+):([^/]+)\/([^@]+)(?:@[^@]+)?$/.exec(imported.contract);
83
+ if (!identity)
84
+ continue;
85
+ const [, namespace, name, interfaceName] = identity;
86
+ const declaration = `interfaces/${namespace}-${name}-${interfaceName}.d.ts`;
87
+ const contents = generatedFiles.get(declaration);
88
+ if (!contents)
89
+ continue;
90
+ const declared = /@module Interface ([^\s*]+)/.exec(contents)?.[1];
91
+ if (declared !== imported.contract)
92
+ throw new Error(`Ambiguous generated WIT interface: ${imported.contract} resolves to ${declared}`);
93
+ const closure = declarationClosure(declaration, generatedFiles);
94
+ const fingerprint = createHash("sha256").update(imported.contract);
95
+ for (const [name, contents] of [...closure].sort(([a], [b]) => a.localeCompare(b)))
96
+ fingerprint.update(JSON.stringify([name, contents]));
97
+ const digest = fingerprint.digest("hex");
98
+ imports.set(imported.contract, digest);
99
+ const shared = path.join(root, ".tembra", "imports", digest);
100
+ for (const [name, contents] of closure)
101
+ files.set(path.join(shared, name), contents);
102
+ const module = "./" + declaration.replace(/\.d\.ts$/, ".js");
103
+ const ambient = path.join(shared, "index.d.ts");
104
+ files.set(ambient, canonicalModule(imported.contract, module, contents));
105
+ const reference = "./" + path.relative(path.dirname(alias), ambient).split(path.sep).join("/");
106
+ references.push(`/// <reference path=${JSON.stringify(reference)} />`);
107
+ }
108
+ files.set(alias, [...references, `export * from ${JSON.stringify(target)};`, ""].join(`
109
+ `));
110
+ return { files, sha256, contract, imports };
111
+ }
112
+ function declarationClosure(entry, generated) {
113
+ const files = new Map;
114
+ function include(file) {
115
+ if (files.has(file))
116
+ return;
117
+ const contents = generated.get(file);
118
+ if (contents === undefined)
119
+ throw new Error(`Missing generated WIT declaration: ${file}`);
120
+ files.set(file, contents);
121
+ const source = ts.createSourceFile(file, contents, ts.ScriptTarget.ESNext, true);
122
+ function visit(node) {
123
+ const specifier = ts.isImportTypeNode(node) && ts.isLiteralTypeNode(node.argument) ? node.argument.literal : ts.isImportDeclaration(node) || ts.isExportDeclaration(node) ? node.moduleSpecifier : undefined;
124
+ if (specifier && ts.isStringLiteral(specifier) && specifier.text.startsWith("."))
125
+ include(path.posix.normalize(path.posix.join(path.posix.dirname(file), specifier.text)).replace(/\.js$/, ".d.ts"));
126
+ ts.forEachChild(node, visit);
127
+ }
128
+ visit(source);
129
+ }
130
+ include(entry);
131
+ return files;
132
+ }
133
+ function canonicalModule(identity, module, contents) {
134
+ const source = ts.createSourceFile(module, contents, ts.ScriptTarget.ESNext, true);
135
+ const types = new Map;
136
+ const values = new Set;
137
+ for (const statement of source.statements) {
138
+ if (!ts.canHaveModifiers(statement) || !ts.getModifiers(statement)?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword))
139
+ continue;
140
+ if (ts.isInterfaceDeclaration(statement) || ts.isTypeAliasDeclaration(statement))
141
+ types.set(statement.name.text, statement.typeParameters ?? []);
142
+ else if (ts.isFunctionDeclaration(statement) && statement.name)
143
+ values.add(statement.name.text);
144
+ else if ((ts.isClassDeclaration(statement) || ts.isEnumDeclaration(statement)) && statement.name) {
145
+ types.set(statement.name.text, ts.isClassDeclaration(statement) ? statement.typeParameters ?? [] : []);
146
+ values.add(statement.name.text);
147
+ } else
148
+ throw new Error(`Unsupported generated WIT declaration in ${identity}`);
149
+ }
150
+ const from = `import(${JSON.stringify(module)})`;
151
+ return [
152
+ `declare module ${JSON.stringify(identity)} {`,
153
+ ...[...types].map(([name, parameters]) => {
154
+ const declaration = parameters.length ? `<${parameters.map((parameter) => parameter.getText(source)).join(", ")}>` : "";
155
+ const arguments_ = parameters.length ? `<${parameters.map((parameter) => parameter.name.text).join(", ")}>` : "";
156
+ return ` export type ${name}${declaration} = ${from}.${name}${arguments_};`;
157
+ }),
158
+ ...[...values].map((name) => ` export const ${name}: typeof ${from}.${name};`),
159
+ "}"
160
+ ].join(`
161
+ `);
162
+ }
6
163
 
7
164
  // src/tooling/resolver.ts
8
165
  import resolve from "enhanced-resolve";
9
166
  import fs from "node:fs";
10
167
  import { readFile } from "node:fs/promises";
11
168
  import { builtinModules } from "node:module";
12
- import path from "node:path";
13
- import ts from "typescript";
14
-
15
- // src/tooling/types.ts
16
- var Platform = Object.freeze({
17
- Browser: "browser",
18
- Worker: "worker",
19
- Node: "node",
20
- Embedded: "embedded"
21
- });
22
- function defineConfig(config) {
23
- return config;
24
- }
25
-
26
- // src/tooling/resolver.ts
27
- function external(specifier, target) {
28
- return target.platform === Platform.Node && (builtinModules.includes(specifier.replace(/^node:/, "")) || (target.nativeExternals ?? []).some((name) => specifier === name || specifier.startsWith(`${name}/`)));
169
+ import path2 from "node:path";
170
+ import ts2 from "typescript";
171
+ var STANDARD_INTERFACES = new Set([
172
+ ...METHODS.map((method) => method.interface),
173
+ ...RESOURCES.map((name) => name.split("#")[0])
174
+ ]);
175
+ function standardModule(contract) {
176
+ const names = new Set(METHODS.filter((method) => method.interface === contract && method.resource === undefined).map((method) => method.name));
177
+ for (const name of RESOURCES)
178
+ if (name.startsWith(`${contract}#`))
179
+ names.add(resourceClassName(name));
180
+ return [
181
+ `const module = globalThis.__tembraStandard[${JSON.stringify(contract)}];`,
182
+ `if (!module) throw new Error(${JSON.stringify(`The Orb contract does not import ${contract}`)});`,
183
+ ...[...names].map((name) => `export const ${name} = module.${name};`)
184
+ ].join(`
185
+ `);
29
186
  }
30
- function resolver(root, target) {
31
- const web = target.platform === Platform.Browser || target.platform === Platform.Worker;
187
+ function resolver(root, target, imports) {
32
188
  const resolveModule = resolve.create.sync({
33
189
  fileSystem: fs,
34
- conditionNames: [
35
- "source",
36
- ...web ? ["browser"] : target.platform === Platform.Node ? ["node", "node-addons"] : ["tembra-embedded"],
37
- "import",
38
- "default"
39
- ],
190
+ conditionNames: ["tembra-wasm", "source", "import", "default"],
40
191
  extensions: [".ts", ".tsx", ".mts", ".js", ".jsx", ".mjs", ".cjs", ".json"],
41
192
  extensionAlias: { ".js": [".ts", ".tsx", ".js"], ".mjs": [".mts", ".mjs"] },
42
- mainFields: web ? ["browser", "module", "main"] : ["module", "main"],
43
- aliasFields: web ? ["browser"] : []
193
+ mainFields: ["module", "main"],
194
+ aliasFields: []
44
195
  });
45
196
  return {
46
197
  name: "tembra-platform",
@@ -50,33 +201,42 @@ function resolver(root, target) {
50
201
  namespace: "tembra-orb"
51
202
  }));
52
203
  builder.onLoad({ filter: /.*/, namespace: "tembra-orb" }, () => ({
53
- contents: `import orb from ${JSON.stringify(path.resolve(root, target.entry))}; globalThis.__tembraOrb = orb;`,
204
+ contents: `import orb from ${JSON.stringify(path2.resolve(root, target.entry))}; globalThis.__tembraOrb = orb;`,
205
+ loader: "js"
206
+ }));
207
+ builder.onResolve({ filter: /^wasi:/ }, (request) => {
208
+ if (!imports.has(request.path))
209
+ throw new Error(`${request.importer}: the Orb contract does not import ${request.path}`);
210
+ if (!STANDARD_INTERFACES.has(request.path))
211
+ throw new Error(`${request.importer}: ${request.path} has no source binding yet`);
212
+ return { path: request.path, namespace: "tembra-standard" };
213
+ });
214
+ builder.onLoad({ filter: /.*/, namespace: "tembra-standard" }, (request) => ({
215
+ contents: standardModule(request.path),
54
216
  loader: "js"
55
217
  }));
56
218
  builder.onResolve({ filter: /.*/ }, (request) => {
57
- if (external(request.path, target))
58
- return { path: request.path, external: true };
59
219
  if (request.path.startsWith("node:") || request.path.startsWith("bun:") || builtinModules.includes(request.path))
60
220
  throw new Error(`${request.importer}: ${request.path} requires its host runtime`);
61
221
  if (request.kind === "entry-point-build")
62
222
  return;
63
- const resolved = resolveModule(path.dirname(request.importer || path.join(root, "entry.js")), request.path);
223
+ const resolved = resolveModule(path2.dirname(request.importer || path2.join(root, "entry.js")), request.path);
64
224
  if (!resolved)
65
225
  throw new Error(`${request.importer}: no compatible implementation for ${request.path}`);
66
226
  if (resolved.endsWith(".node"))
67
- throw new Error("Declare native Node packages as nativeExternals in a node build");
227
+ throw new Error("Native Node packages cannot run inside an Orb");
68
228
  return { path: resolved };
69
229
  });
70
230
  builder.onLoad({ filter: /\.[cm]?[jt]sx?$/ }, async (request) => {
71
231
  const source = await readFile(request.path, "utf8");
72
- const parsed = ts.createSourceFile(request.path, source, ts.ScriptTarget.Latest, true);
232
+ const parsed = ts2.createSourceFile(request.path, source, ts2.ScriptTarget.Latest, true);
73
233
  function check(node) {
74
- if (ts.isCallExpression(node) && (node.expression.kind === ts.SyntaxKind.ImportKeyword || ts.isIdentifier(node.expression) && node.expression.text === "require")) {
234
+ if (ts2.isCallExpression(node) && (node.expression.kind === ts2.SyntaxKind.ImportKeyword || ts2.isIdentifier(node.expression) && node.expression.text === "require")) {
75
235
  const argument = node.arguments[0];
76
- if (!argument || !ts.isStringLiteralLike(argument))
236
+ if (!argument || !ts2.isStringLiteralLike(argument))
77
237
  throw new Error(`${request.path}: dynamic module names must be resolved before publishing an orb`);
78
238
  }
79
- ts.forEachChild(node, check);
239
+ ts2.forEachChild(node, check);
80
240
  }
81
241
  check(parsed);
82
242
  return;
@@ -86,96 +246,989 @@ function resolver(root, target) {
86
246
  }
87
247
 
88
248
  // src/tooling/typecheck.ts
89
- import ts2 from "typescript";
90
- function typecheck(entry, root) {
91
- const configFile = ts2.findConfigFile(root, ts2.sys.fileExists);
92
- const loaded = configFile ? ts2.readConfigFile(configFile, ts2.sys.readFile) : { config: {} };
249
+ import ts3 from "typescript";
250
+ import path3 from "node:path";
251
+ import { fileURLToPath } from "node:url";
252
+ function typecheck(entry, root, virtual = new Map, conditions = []) {
253
+ const configFile = ts3.findConfigFile(root, ts3.sys.fileExists);
254
+ const loaded = configFile ? ts3.readConfigFile(configFile, ts3.sys.readFile) : { config: {} };
93
255
  if (loaded.error)
94
- throw new Error(ts2.flattenDiagnosticMessageText(loaded.error.messageText, `
256
+ throw new Error(ts3.flattenDiagnosticMessageText(loaded.error.messageText, `
95
257
  `));
96
- const parsed = ts2.parseJsonConfigFileContent(loaded.config, ts2.sys, root);
97
- const program = ts2.createProgram([entry], {
258
+ const parsed = ts3.parseJsonConfigFileContent(loaded.config, ts3.sys, configFile ? path3.dirname(configFile) : root);
259
+ const options = {
98
260
  ...parsed.options,
99
- target: ts2.ScriptTarget.ES2023,
100
- module: ts2.ModuleKind.ESNext,
101
- moduleResolution: ts2.ModuleResolutionKind.Bundler,
261
+ target: ts3.ScriptTarget.ES2023,
262
+ module: ts3.ModuleKind.ESNext,
263
+ moduleResolution: ts3.ModuleResolutionKind.Bundler,
102
264
  allowImportingTsExtensions: true,
103
265
  noEmit: true,
104
266
  strict: true,
105
- skipLibCheck: true
106
- });
107
- const diagnostics = ts2.getPreEmitDiagnostics(program);
267
+ skipLibCheck: true,
268
+ lib: ["lib.es2023.d.ts", "lib.esnext.disposable.d.ts"],
269
+ types: [],
270
+ allowArbitraryExtensions: true,
271
+ customConditions: [...conditions, "source"]
272
+ };
273
+ const host = ts3.createCompilerHost(options);
274
+ const readFile = host.readFile;
275
+ const fileExists = host.fileExists;
276
+ const getSourceFile = host.getSourceFile;
277
+ const directoryExists = host.directoryExists;
278
+ const directories = new Set;
279
+ for (const file of virtual.keys()) {
280
+ let directory = path3.dirname(file);
281
+ while (!directories.has(directory)) {
282
+ directories.add(directory);
283
+ const parent = path3.dirname(directory);
284
+ if (parent === directory)
285
+ break;
286
+ directory = parent;
287
+ }
288
+ }
289
+ host.directoryExists = (directory) => directories.has(directory) || directoryExists?.(directory) === true;
290
+ host.readFile = (file) => virtual.get(file) ?? readFile(file);
291
+ host.fileExists = (file) => virtual.has(file) || fileExists(file);
292
+ host.getSourceFile = (file, language, onError, create) => {
293
+ const source = virtual.get(file);
294
+ return source === undefined ? getSourceFile(file, language, onError, create) : ts3.createSourceFile(file, source, typeof language === "object" ? language.languageVersion : language, true);
295
+ };
296
+ const packageEntry = new URL(import.meta.resolve("@syntropika/tembra-sdk"));
297
+ const environment = fileURLToPath(new URL(packageEntry.pathname.endsWith(".ts") ? "guest.ts" : "guest.d.ts", packageEntry));
298
+ const ambient = parsed.fileNames.filter((file) => /\.d\.[cm]?ts$/.test(file));
299
+ const aliases = [...virtual.keys()].filter((file) => file.endsWith(".d.wit.ts"));
300
+ const program = ts3.createProgram([entry, environment, ...ambient, ...aliases], options, host);
301
+ const diagnostics = ts3.getPreEmitDiagnostics(program);
108
302
  if (diagnostics.length)
109
- throw new Error(ts2.formatDiagnosticsWithColorAndContext(diagnostics, {
303
+ throw new Error(ts3.formatDiagnosticsWithColorAndContext(diagnostics, {
110
304
  getCurrentDirectory: () => root,
111
305
  getCanonicalFileName: (name) => name,
112
306
  getNewLine: () => `
113
307
  `
114
308
  }));
309
+ return program;
310
+ }
311
+
312
+ // src/tooling/component.ts
313
+ import { createRequire } from "node:module";
314
+ import { mkdir, readFile as readFile2, rename, rm, writeFile } from "node:fs/promises";
315
+ import { createHash as createHash2 } from "node:crypto";
316
+ import path4 from "node:path";
317
+
318
+ // src/tooling/component-glue.ts
319
+ var JCO_VERSION = "0.23.0";
320
+ var HEADER = `"use components";
321
+ export function instantiate(getCoreModule, imports, instantiateCore, options) {
322
+ `;
323
+ var TASK_ANCHOR = ` const newTaskMeta = { id: newTaskID, componentIdx, task: newTask };
324
+ `;
325
+ var TRAP_ANCHOR = ` this.#trapped = true;
326
+ if (this.#trapError === null) { this.#trapError = err; }
327
+ `;
328
+ var PRELUDE = ` const __tembraObserver = options?.tembraObserver ?? null;
329
+ function __tembraObserveTask(task, args) {
330
+ if (__tembraObserver === null || !args.callingWasmExport) { return; }
331
+ const id = task.id();
332
+ __tembraObserver.taskStarted({ id, entry: args.entryFnName, isAsync: !!args.isAsync });
333
+ task.exitPromise().then(
334
+ () => __tembraObserver.taskExited({ id, rejected: task.isRejected(), error: task.isErrored() ?? undefined }),
335
+ (error) => __tembraObserver.taskExited({ id, error }),
336
+ );
337
+ }
338
+ function __tembraObserveTrap(error) {
339
+ if (__tembraObserver !== null) { __tembraObserver.trapped(error); }
340
+ }
341
+ if (__tembraObserver !== null) {
342
+ __tembraObserver.attach({
343
+ /** Root export task of the guest code running now (call synchronously at host-import entry). */
344
+ currentRootTask() {
345
+ const meta = CURRENT_TASK_META.current;
346
+ if (!meta || meta.taskID === undefined || meta.componentIdx === undefined) { return null; }
347
+ const task = getCurrentTask(meta.componentIdx, meta.taskID)?.task;
348
+ return task ? task.getRootTask().id() : null;
349
+ },
350
+ });
351
+ }
352
+ `;
353
+ function once(source, anchor, label) {
354
+ const first = source.indexOf(anchor);
355
+ if (first < 0 || source.indexOf(anchor, first + 1) >= 0) {
356
+ throw new Error(`unsupported trusted compiler output: anchor "${label}" must occur exactly once (expected JCO ${JCO_VERSION})`);
357
+ }
358
+ return first;
359
+ }
360
+ function instrumentGlue(source) {
361
+ if (!source.startsWith(HEADER)) {
362
+ throw new Error(`unsupported trusted compiler output: instantiate signature (expected JCO ${JCO_VERSION})`);
363
+ }
364
+ once(source, TASK_ANCHOR, "task creation");
365
+ once(source, TRAP_ANCHOR, "trap record");
366
+ once(source, ` const CURRENT_TASK_META = {};
367
+ `, "current task metadata");
368
+ once(source, ` getRootTask() {
369
+ `, "root task");
370
+ once(source, ` isErrored() { return this.#errored; }
371
+ `, "task error");
372
+ const out = HEADER + PRELUDE + source.slice(HEADER.length).replace(TASK_ANCHOR, TASK_ANCHOR + ` __tembraObserveTask(newTask, args);
373
+ `).replace(TRAP_ANCHOR, TRAP_ANCHOR + ` __tembraObserveTrap(this.#trapError);
374
+ `);
375
+ return out;
376
+ }
377
+ var LIFT_OWN = /_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;
378
+ var TABLE = /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;
379
+ var EXPORTED_TABLE = /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;
380
+ var EXPORTED_LIFT_OWN = new RegExp([
381
+ String.raw`_liftFlatOwn\(\{\n\s*componentIdx: (\d+),\n\s*tableIdx: (\d+),\n\s*classNameFn: \(\) => ([\w$]+),\n\s*createResourceFn: \n\s*\(handle\) => \{\n`,
382
+ 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`,
383
+ 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`,
384
+ 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`,
385
+ 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*\}\)`
386
+ ].join(""), "g");
387
+ function fixLiftOwnTables(source) {
388
+ const tables = new Map;
389
+ for (const [, table, component, capture] of source.matchAll(TABLE))
390
+ tables.set(table, { component, capture });
391
+ const exportedTables = new Map;
392
+ for (const [, table, component, registry, dtor] of source.matchAll(EXPORTED_TABLE))
393
+ exportedTables.set(table, { component, registry, dtor });
394
+ const classes = new Set([...source.matchAll(/\bclass ([\w$]+)\{/g)].map((match) => match[1]));
395
+ const sites = source.split("_liftFlatOwn({").length - 1;
396
+ let fixed = 0;
397
+ for (const [, component, table, className, registry, dtor] of source.matchAll(EXPORTED_LIFT_OWN)) {
398
+ const declared = exportedTables.get(table);
399
+ if (!declared || declared.component !== component || declared.registry !== registry || declared.dtor !== dtor || !classes.has(className))
400
+ throw new Error("unsupported trusted compiler output: exported owned-resource lift table (expected JCO 0.23.0)");
401
+ fixed++;
402
+ }
403
+ const out = source.replace(LIFT_OWN, (site, component, table, read, capture, removed) => {
404
+ const declared = tables.get(table);
405
+ if (!declared || declared.component !== component || declared.capture !== capture || read !== removed)
406
+ throw new Error("unsupported trusted compiler output: owned-resource lift table (expected JCO 0.23.0)");
407
+ fixed++;
408
+ return site.replace(`const rep = handleTable${read}[`, `const rep = handleTable${table}[`).replace(`rscTableRemove(handleTable${removed}, handle)`, `rscTableRemove(handleTable${table}, handle)`);
409
+ });
410
+ if (fixed !== sites)
411
+ throw new Error("unsupported trusted compiler output: owned-resource lift shape (expected JCO 0.23.0)");
412
+ return out;
413
+ }
414
+ var THROW = "if (taskRes.tag === 'err') { throw new ComponentError(taskRes.val);}";
415
+ var MARKED = "if (taskRes.tag === 'err') { throw __tembraResultErr(new ComponentError(taskRes.val));}";
416
+ var EXIT = "if (!task.isExited()) { task.exit({ skipExclusiveLockCheck: true }); }";
417
+ var GUARDED = "if (!task.isExited() && !__tembraResultErrs.has(err)) { task.exit({ skipExclusiveLockCheck: true }); }";
418
+ var RESULT_ERR_PRELUDE = ` const __tembraResultErrs = new WeakSet();
419
+ function __tembraResultErr(error) { __tembraResultErrs.add(error); return error; }
420
+ `;
421
+ function fixResultErrExit(source) {
422
+ if (!source.startsWith(HEADER))
423
+ throw new Error("unsupported trusted compiler output: instantiate signature (expected JCO 0.23.0)");
424
+ const throws = source.split(THROW).length - 1;
425
+ if (throws === 0)
426
+ return source;
427
+ const exits = source.split(EXIT).length - 1;
428
+ if (exits === 0)
429
+ throw new Error("unsupported trusted compiler output: result error exit (expected JCO 0.23.0)");
430
+ const out = HEADER + RESULT_ERR_PRELUDE + source.slice(HEADER.length).split(THROW).join(MARKED).split(EXIT).join(GUARDED);
431
+ if (out.includes(THROW) || out.includes(EXIT))
432
+ throw new Error("unsupported trusted compiler output: result error rewrite (expected JCO 0.23.0)");
433
+ return out;
434
+ }
435
+ var SCHEDULER_TURN = ` // After resuming a task, re-tick as soon as the resumed
436
+ // slice's microtask continuations have drained (timeout 0)
437
+ // so queued sibling resumptions aren't charged the idle
438
+ // polling interval; otherwise poll at the idle cadence.
439
+ const delay = result === ComponentAsyncState.TickResult.RESUMED ? 0 : 10;
440
+ await new Promise((resolve) => setTimeout(resolve, delay));
441
+ result = this.tick();
442
+ `;
443
+ var SCHEDULER_TURN_PRELUDE = ` function __tembraSchedulerTurn(delay) {
444
+ const timer = () => new Promise((resolve) => setTimeout(resolve, delay));
445
+ if (delay === 0) {
446
+ try {
447
+ const scheduler = globalThis.scheduler;
448
+ if (typeof scheduler?.postTask === 'function') {
449
+ return scheduler.postTask(() => {}, { priority: 'user-visible' }).catch(timer);
450
+ }
451
+ } catch {
452
+ // An unavailable host scheduling API retains the vendor timer path.
453
+ }
454
+ }
455
+ return timer();
456
+ }
457
+ `;
458
+ function fixSchedulerTurns(source) {
459
+ if (!source.startsWith(HEADER))
460
+ throw new Error(`unsupported trusted compiler output: instantiate signature (expected JCO ${JCO_VERSION})`);
461
+ once(source, ` async runTickLoop() {
462
+ `, "async scheduler");
463
+ once(source, SCHEDULER_TURN, "resumed scheduler turn");
464
+ return HEADER + SCHEDULER_TURN_PRELUDE + source.slice(HEADER.length).replace(SCHEDULER_TURN, SCHEDULER_TURN.replace("await new Promise((resolve) => setTimeout(resolve, delay));", "await __tembraSchedulerTurn(delay);"));
465
+ }
466
+ var RESOURCE_CLOSURE = new RegExp([
467
+ String.raw`var (handle\d+) = [^\n]+;\n\s*var (rsc\d+) = new\.target === ([\w$]+) \? this : Object\.create\(\3\.prototype\);\n`,
468
+ String.raw`\s*Object\.defineProperty\(\2, symbolRscHandle, \{ writable: true, value: \1\}\);\n`,
469
+ String.raw`\s*finalizationRegistry(\d+)\.register\(\2, \1, \2\);\n`,
470
+ String.raw`\s*Object\.defineProperty\(\2, symbolDispose, \{ writable: true, value: function \(\) \{\n`,
471
+ String.raw`\s*finalizationRegistry\4\.unregister\(\2\);\n`,
472
+ String.raw`\s*const handleEntry = rscTableRemove\(handleTable\d+, \1\);\n`,
473
+ String.raw`\s*\2\[symbolDispose\] = emptyFunc;\n\s*\2\[symbolRscHandle\] = undefined;\n`,
474
+ String.raw`\s*callResourceDestructor\(\{ componentIdx: \d+, dtor: exports\d+\["\d+"\], rep: handleEntry\.rep \}\);\n\s*\}\}\);`
475
+ ].join(""), "g");
476
+ function fixResourceClosures(source) {
477
+ const sites = [...source.matchAll(/Object\.defineProperty\(rsc\d+, symbolDispose,/g)].length;
478
+ let changed = 0;
479
+ const output = source.replace(RESOURCE_CLOSURE, (block) => {
480
+ changed++;
481
+ return block.replace(/\bvar (handle\d+|rsc\d+) =/g, "let $1 =");
482
+ });
483
+ if (changed !== sites)
484
+ throw new Error(`unsupported trusted compiler output: resource destructor closure (expected JCO ${JCO_VERSION})`);
485
+ return output;
486
+ }
487
+ function prepareGlue(source) {
488
+ return fixSchedulerTurns(fixResourceClosures(fixLiftOwnTables(fixResultErrExit(instrumentGlue(source)))));
489
+ }
490
+
491
+ // src/tooling/component.ts
492
+ var INLINE_BYTES = 4096;
493
+ async function generator() {
494
+ const entry = createRequire(import.meta.url).resolve("@bytecodealliance/jco-transpile/component");
495
+ const manifest = JSON.parse(await readFile2(path4.join(path4.dirname(entry), "..", "package.json"), "utf8"));
496
+ if (manifest.name !== "@bytecodealliance/jco-transpile" || manifest.version !== JCO_VERSION || PREPARED_GENERATOR !== `${manifest.name}@${manifest.version}`)
497
+ throw new Error(`Browser preparation requires @bytecodealliance/jco-transpile ${JCO_VERSION}`);
498
+ const bindgen = await import("@bytecodealliance/jco-transpile/component");
499
+ await bindgen.$init;
500
+ return bindgen;
501
+ }
502
+ function plan(graph, imports) {
503
+ const convert = converters(graph);
504
+ const check = (binding, name, signature) => {
505
+ try {
506
+ const fn = { ...signature, name };
507
+ convert(resourceDataFunction(fn, resourceRoles(graph, binding, fn)));
508
+ } catch (error) {
509
+ throw new Error(`Browser preparation cannot execute ${binding}#${name}: ${error.message}`);
510
+ }
511
+ };
512
+ const suspending = [];
513
+ for (const name of imports) {
514
+ if (name.startsWith("wasi:")) {
515
+ if (!BROWSER_WASI.has(name))
516
+ throw new Error(`Browser hosts do not provide ${name}; this Orb cannot run in browsers`);
517
+ continue;
518
+ }
519
+ const selected = graph.imports.find((item) => item.binding === name);
520
+ if (!selected)
521
+ throw new Error(`The component imports ${name}, which its contract lacks`);
522
+ if (selected.type_only)
523
+ continue;
524
+ const view = graph.references[name];
525
+ if (view) {
526
+ try {
527
+ referenceView(graph, name, view, convert);
528
+ } catch (error) {
529
+ throw new Error(`Browser preparation cannot execute ${name}: ${error.message}`);
530
+ }
531
+ for (const fn of Object.keys(selected.functions ?? {}))
532
+ suspending.push(`${name}#${fn}`);
533
+ continue;
534
+ }
535
+ for (const [fn, signature] of Object.entries(selected.functions ?? {})) {
536
+ check(selected.contract ?? name, fn, signature);
537
+ suspending.push(`${name}#${fn}`);
538
+ }
539
+ }
540
+ const promising = [];
541
+ for (const entry of graph.exports)
542
+ for (const [fn, signature] of Object.entries(entry.functions ?? {})) {
543
+ if (entry.contract !== HTTP_HANDLER)
544
+ check(entry.contract ?? entry.binding, fn, signature);
545
+ promising.push(`${entry.binding}#${fn}`);
546
+ }
547
+ return { suspending, promising };
548
+ }
549
+ async function prepareBrowserComponent(artifact, sha256, directory) {
550
+ const engine = await import("@syntropika/tembra-engine-node");
551
+ if (createHash2("sha256").update(artifact).digest("hex") !== sha256)
552
+ throw new Error("Browser preparation received an artifact digest for other bytes");
553
+ const verified = new engine.NodeArtifact(artifact);
554
+ const identity = JSON.parse(verified.description());
555
+ if (identity.kind !== "component")
556
+ throw new Error("Only compiled component artifacts need browser preparation");
557
+ const graph = query(verified, { kind: "describe" });
558
+ const imports = engine.componentImports(artifact);
559
+ if (new Set(imports).size !== imports.length)
560
+ throw new Error("The component imports one name twice");
561
+ const { suspending, promising } = plan(graph, imports);
562
+ const bindgen = await generator();
563
+ const output = bindgen.generate(artifact, {
564
+ name: "orb",
565
+ noTypescript: true,
566
+ instantiation: { tag: "async" },
567
+ noNodejsCompat: true,
568
+ base64Cutoff: 0,
569
+ map: imports.map((name) => [name, name]),
570
+ asyncMode: { tag: "jspi", val: { imports: suspending, exports: promising } },
571
+ emitConditionalSuspendingWasm: true
572
+ });
573
+ let glue;
574
+ const cores = [];
575
+ for (const [name, bytes] of output.files) {
576
+ if (name === "orb.js")
577
+ glue = prepareGlue(new TextDecoder().decode(bytes));
578
+ else if (COMPONENT_CORE.test(name)) {
579
+ const core = engine.instrumentCore(bytes, PREPARED_MAXIMUM_PAGES);
580
+ cores.push({ name, pages: core.initialPages, bytes: core.bytes });
581
+ } else if (TRAMPOLINE_CORE.test(name))
582
+ cores.push({ name, bytes });
583
+ else
584
+ throw new Error(`Unexpected generated file ${name}`);
585
+ }
586
+ if (!glue)
587
+ throw new Error("The bindings generator produced no glue");
588
+ if (!cores.some((core) => core.pages !== undefined))
589
+ throw new Error("The bindings generator produced no component core module");
590
+ const files = new Map([["glue.js", glue]]);
591
+ const entries = cores.map((core) => {
592
+ const fields = `name: ${JSON.stringify(core.name)}${core.pages === undefined ? "" : `, pages: ${core.pages}`}`;
593
+ if (core.bytes.byteLength <= INLINE_BYTES)
594
+ return `{ ${fields}, load: () => bytes(${JSON.stringify(Buffer.from(core.bytes).toString("base64"))}) }`;
595
+ const hash = createHash2("sha256").update(core.bytes).digest("hex").slice(0, 16);
596
+ const file = `${core.name.slice(0, -".wasm".length)}.${hash}.wasm`;
597
+ files.set(file, core.bytes);
598
+ return `{ ${fields}, load: () => fetch(new URL(${JSON.stringify(`./${file}`)}, import.meta.url)) }`;
599
+ });
600
+ const description = {
601
+ format: PREPARED_FORMAT,
602
+ generator: PREPARED_GENERATOR,
603
+ orb: { name: identity.name, apiVersion: identity.apiVersion },
604
+ artifact: sha256,
605
+ maximumPages: PREPARED_MAXIMUM_PAGES,
606
+ imports,
607
+ suspending,
608
+ promising
609
+ };
610
+ const fields = Object.entries(description).map(([key, value]) => ` ${key}: ${JSON.stringify(value)},`).join(`
611
+ `);
612
+ files.set("index.js", `// Generated by Tembra tooling; do not edit.
613
+ // Host-trusted application code: import this module and register its default export with
614
+ // createHost({ isolated: { components: [...] } }). It runs only the artifact with digest
615
+ // ${sha256}.
616
+ import { preparedComponent } from "@syntropika/tembra-sdk/browser";
617
+ import { instantiate } from "./glue.js";
618
+
619
+ const bytes = (text) => Uint8Array.from(atob(text), (character) => character.charCodeAt(0));
620
+
621
+ export default preparedComponent({
622
+ ${fields}
623
+ cores: [
624
+ ${entries.join(`,
625
+ `)},
626
+ ],
627
+ instantiate,
628
+ });
629
+ `);
630
+ files.set("index.d.ts", `declare const component: import("@syntropika/tembra-sdk/browser").PreparedComponent;
631
+ export default component;
632
+ `);
633
+ const temporary = `${directory}.${process.pid}.tmp`;
634
+ await rm(temporary, { recursive: true, force: true });
635
+ await mkdir(temporary, { recursive: true });
636
+ try {
637
+ for (const [name, contents] of files)
638
+ await writeFile(path4.join(temporary, name), contents);
639
+ await rm(directory, { recursive: true, force: true });
640
+ await rename(temporary, directory);
641
+ } finally {
642
+ await rm(temporary, { recursive: true, force: true });
643
+ }
644
+ return {
645
+ module: path4.join(directory, "index.js"),
646
+ files: [...files.keys()].map((name) => path4.join(directory, name))
647
+ };
115
648
  }
116
649
 
117
650
  // src/tooling/build.ts
118
651
  async function build(config) {
119
- const root = path2.resolve(config.root ?? process.cwd());
120
- const outDir = path2.resolve(root, config.outDir ?? "dist/tembra");
652
+ if (typeof Bun === "undefined")
653
+ throw new Error("Tembra build requires Bun");
654
+ const root = path5.resolve(config.root ?? process.cwd());
655
+ const outDir = path5.resolve(root, config.outDir ?? "dist/tembra");
121
656
  const artifacts = [];
122
- for (const [name, target] of Object.entries(config.builds)) {
123
- let verify = function(node) {
124
- let specifier;
125
- if (ts3.isImportDeclaration(node) || ts3.isExportDeclaration(node))
126
- specifier = node.moduleSpecifier;
127
- if (ts3.isCallExpression(node) && node.expression.kind === ts3.SyntaxKind.ImportKeyword)
128
- specifier = node.arguments[0];
129
- if (specifier && (!ts3.isStringLiteralLike(specifier) || !external(specifier.text, target)))
130
- throw new Error(`Build ${name} contains an unresolved import`);
131
- ts3.forEachChild(node, verify);
132
- };
133
- if (!/^[\w-]+$/.test(name) || !Object.values(Platform).includes(target.platform))
134
- throw new Error("Invalid build name or platform");
135
- const entry = path2.resolve(root, target.entry);
136
- if (target.typecheck !== false)
137
- typecheck(entry, root);
138
- const result = await Bun.build({
139
- entrypoints: [target.platform === Platform.Embedded ? "tembra:entry" : entry],
140
- root,
141
- format: target.platform === Platform.Embedded ? "iife" : "esm",
142
- target: target.platform === Platform.Node ? "node" : "browser",
143
- splitting: false,
144
- minify: target.minify ?? true,
145
- ...target.define ? { define: { ...target.define } } : {},
146
- plugins: [resolver(root, target)]
657
+ const declarations = new Map;
658
+ const worlds = new Map;
659
+ for (const target of Object.values(config.builds)) {
660
+ if (target.entry.endsWith(".wasm"))
661
+ continue;
662
+ const file = path5.resolve(root, target.wit);
663
+ if (worlds.has(file) && worlds.get(file) !== target.world)
664
+ throw new Error(`Source builds for ${target.wit} must select the same WIT world`);
665
+ worlds.set(file, target.world);
666
+ }
667
+ const identities = new Map;
668
+ const editorFiles = new Map;
669
+ for (const [wit, world] of worlds) {
670
+ const types = await witTypes(wit, world, root);
671
+ declarations.set(wit, types);
672
+ for (const [identity, digest] of types.imports) {
673
+ const previous = identities.get(identity);
674
+ if (previous !== undefined && previous !== digest)
675
+ throw new Error(`Conflicting WIT declarations for ${identity} in one project`);
676
+ identities.set(identity, digest);
677
+ }
678
+ for (const [file, contents] of types.files)
679
+ editorFiles.set(file, contents);
680
+ }
681
+ for (const [file, contents] of editorFiles) {
682
+ const previous = await readFile3(file, "utf8").catch((error) => {
683
+ if (error.code === "ENOENT")
684
+ return;
685
+ throw error;
147
686
  });
148
- if (!result.success)
149
- throw new AggregateError(result.logs, `Build ${name} failed`);
150
- if (result.outputs.length !== 1 || result.outputs[0]?.kind !== "entry-point")
151
- throw new Error(`Build ${name} requires external assets; publish them explicitly instead of silently expanding the orb bundle`);
152
- const output = result.outputs[0];
153
- const source = await output.text();
154
- const parsed = ts3.createSourceFile("bundle.js", source, ts3.ScriptTarget.Latest, true, ts3.ScriptKind.JS);
155
- const hasDefault = parsed.statements.some((statement) => ts3.isExportAssignment(statement) || ts3.isExportDeclaration(statement) && statement.exportClause && ts3.isNamedExports(statement.exportClause) && statement.exportClause.elements.some((element) => element.name.text === "default"));
156
- if (target.platform !== Platform.Embedded && !hasDefault)
157
- throw new Error(`Build ${name} must export a default orb`);
158
- verify(parsed);
159
- const bytes = Buffer.from(source);
160
- const hash = createHash("sha256").update(bytes).digest("hex");
161
- const directory = path2.join(outDir, name);
162
- const destination = path2.join(directory, `orb.${hash}.js`);
163
- await mkdir(directory, { recursive: true });
687
+ if (previous === contents)
688
+ continue;
689
+ await mkdir2(path5.dirname(file), { recursive: true });
690
+ await writeFile2(file, contents);
691
+ }
692
+ for (const [name, target] of Object.entries(config.builds)) {
693
+ if (!/^[\w-]+$/.test(name))
694
+ throw new Error("Invalid build name");
695
+ const entry = path5.resolve(root, target.entry);
696
+ const wit = path5.resolve(root, target.wit);
697
+ const compiled = entry.endsWith(".wasm");
698
+ const types = compiled ? undefined : declarations.get(wit);
699
+ let bytes;
700
+ const contract = types?.contract ?? new NodeContract(path5.dirname(wit), target.world);
701
+ if (compiled) {
702
+ if (!target.apiVersion)
703
+ throw new Error(`Build ${name} requires apiVersion for a compiled Orb`);
704
+ bytes = contract.componentArtifact(await Bun.file(entry).bytes(), name, target.apiVersion, target.contributes, target.references);
705
+ } else {
706
+ let verify = function(node) {
707
+ let specifier;
708
+ if (ts4.isImportDeclaration(node) || ts4.isExportDeclaration(node))
709
+ specifier = node.moduleSpecifier;
710
+ if (ts4.isCallExpression(node) && (node.expression.kind === ts4.SyntaxKind.ImportKeyword || ts4.isIdentifier(node.expression) && node.expression.text === "require"))
711
+ specifier = node.arguments[0];
712
+ if (specifier)
713
+ throw new Error(`Build ${name} contains an unresolved import`);
714
+ ts4.forEachChild(node, verify);
715
+ };
716
+ if (target.browser !== undefined)
717
+ throw new Error(`Build ${name} is a source Orb; browsers run it without preparation`);
718
+ if (target.apiVersion !== undefined)
719
+ throw new Error(`Build ${name} declares apiVersion in its source Orb`);
720
+ if (target.contributes !== undefined)
721
+ throw new Error(`Build ${name} declares contributions in its source Orb`);
722
+ if (target.references !== undefined)
723
+ throw new Error(`Build ${name} declares reference views in its source Orb`);
724
+ const program = typecheck(entry, root, types.files, ["tembra-wasm"]);
725
+ const description = query(contract, { kind: "describe" });
726
+ const imports = new Set(description.imports.flatMap((item) => item.type_only === false && item.contract ? [item.contract] : []));
727
+ const result = await Bun.build({
728
+ entrypoints: ["tembra:entry"],
729
+ root,
730
+ format: "iife",
731
+ target: "browser",
732
+ splitting: false,
733
+ minify: target.minify ?? true,
734
+ ...target.define ? { define: { ...target.define } } : {},
735
+ plugins: [resolver(root, target, imports)]
736
+ }).catch((error) => {
737
+ if (error instanceof AggregateError)
738
+ throw new AggregateError(error.errors, `Build ${name} failed: ${error.errors.map(String).join(`
739
+ `)}`);
740
+ throw error;
741
+ });
742
+ if (!result.success)
743
+ throw new AggregateError(result.logs, `Build ${name} failed`);
744
+ if (result.outputs.length !== 1 || result.outputs[0]?.kind !== "entry-point")
745
+ throw new Error(`Build ${name} requires exactly one closed bundle`);
746
+ const source = await result.outputs[0].text();
747
+ const parsed = ts4.createSourceFile("bundle.js", source, ts4.ScriptTarget.Latest, true, ts4.ScriptKind.JS);
748
+ verify(parsed);
749
+ const registration = identity(program, entry);
750
+ bytes = contract.sourceArtifact(source, registration.name, registration.apiVersion);
751
+ }
752
+ const hash = createHash3("sha256").update(bytes).digest("hex");
753
+ const directory = path5.join(outDir, name);
754
+ const destination = path5.join(directory, `orb.${hash}.wasm`);
755
+ await mkdir2(directory, { recursive: true });
164
756
  const temporary = `${destination}.${process.pid}.tmp`;
165
- await writeFile(temporary, bytes);
166
- await rename(temporary, destination);
757
+ await writeFile2(temporary, bytes);
758
+ await rename2(temporary, destination);
759
+ const browser = compiled && target.browser ? (await prepareBrowserComponent(bytes, hash, path5.join(directory, "browser"))).module : undefined;
167
760
  artifacts.push({
168
761
  name,
169
- platform: target.platform,
170
762
  path: destination,
171
763
  sha256: hash,
172
- bytes: bytes.length
764
+ bytes: bytes.length,
765
+ ...browser ? { browser } : {}
173
766
  });
174
767
  }
175
768
  return artifacts;
176
769
  }
770
+ function identity(program, entry) {
771
+ const checker = program.getTypeChecker();
772
+ const file = program.getSourceFile(entry);
773
+ const module = checker.getSymbolAtLocation(file);
774
+ const exported = module && checker.getExportsOfModule(module).find((symbol) => symbol.name === "default");
775
+ if (!exported)
776
+ throw new Error("Wasm source must export a default orb");
777
+ const definition = checker.getTypeOfSymbolAtLocation(exported, file);
778
+ const property = (name) => {
779
+ const symbol = definition.getProperty(name);
780
+ return symbol && checker.getTypeOfSymbolAtLocation(symbol, file);
781
+ };
782
+ const name = property("name");
783
+ const version = property("apiVersion");
784
+ if (!name?.isStringLiteral() || !version?.isNumberLiteral() || !name.value || !Number.isInteger(version.value) || version.value <= 0)
785
+ throw new Error("Wasm source requires literal name and positive apiVersion metadata");
786
+ return { name: name.value, apiVersion: version.value };
787
+ }
788
+ // src/tooling/client.ts
789
+ import { mkdir as mkdir3, readFile as readFile4, rename as rename3, writeFile as writeFile3 } from "node:fs/promises";
790
+ import path6 from "node:path";
791
+ import { NodeContract as NodeContract2 } from "@syntropika/tembra-engine-node";
792
+
793
+ // src/tooling/client-resources.ts
794
+ function resourceNames(graph, resources, identity, occupied) {
795
+ const definitions = new Map(graph.types.map(({ id, definition }) => [id, definition]));
796
+ const canonical = (id) => {
797
+ const kind = definitions.get(id)?.kind;
798
+ return typeof kind === "object" && typeof kind.type === "number" ? canonical(kind.type) : id;
799
+ };
800
+ const groups = new Map;
801
+ for (const [name, id] of Object.entries(resources)) {
802
+ const key = canonical(id);
803
+ const aliases = groups.get(key) ?? [];
804
+ aliases.push(name);
805
+ groups.set(key, aliases);
806
+ }
807
+ const names = new Map;
808
+ const nominals = new Map;
809
+ const aliases = [];
810
+ const allocate = (name) => {
811
+ let spelling = name.split("-").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("");
812
+ while (occupied.has(spelling))
813
+ spelling += "_";
814
+ occupied.add(spelling);
815
+ return spelling;
816
+ };
817
+ for (const [id, spellings] of groups) {
818
+ const definition = definitions.get(id);
819
+ if (definition?.kind !== "resource" || !definition.owner || !definition.name)
820
+ throw new Error(`${identity}: resource has no portable nominal identity`);
821
+ const preferred = definition.owner === identity && spellings.includes(definition.name) ? definition.name : spellings[0];
822
+ const name = allocate(preferred);
823
+ names.set(id, name);
824
+ nominals.set(id, `${definition.owner}#${definition.name}`);
825
+ for (const spelling of spellings) {
826
+ if (spelling === preferred)
827
+ continue;
828
+ const alias = allocate(spelling);
829
+ aliases.push(`/** The transparent WIT resource alias \`${spelling}\`. */`, `export type ${alias} = ${name};`, "");
830
+ }
831
+ }
832
+ return { names, nominals, aliases, canonical };
833
+ }
834
+
835
+ // src/tooling/client.ts
836
+ var PRIMITIVES = {
837
+ bool: "boolean",
838
+ u8: "number",
839
+ u16: "number",
840
+ u32: "number",
841
+ s8: "number",
842
+ s16: "number",
843
+ s32: "number",
844
+ f32: "number",
845
+ f64: "number",
846
+ u64: "bigint",
847
+ s64: "bigint",
848
+ char: "string",
849
+ string: "string"
850
+ };
851
+ var RESERVED = new Set([
852
+ "arguments",
853
+ "await",
854
+ "break",
855
+ "case",
856
+ "catch",
857
+ "class",
858
+ "const",
859
+ "continue",
860
+ "debugger",
861
+ "default",
862
+ "delete",
863
+ "do",
864
+ "else",
865
+ "enum",
866
+ "eval",
867
+ "export",
868
+ "extends",
869
+ "false",
870
+ "finally",
871
+ "for",
872
+ "function",
873
+ "if",
874
+ "implements",
875
+ "import",
876
+ "in",
877
+ "instanceof",
878
+ "interface",
879
+ "let",
880
+ "new",
881
+ "null",
882
+ "package",
883
+ "private",
884
+ "protected",
885
+ "public",
886
+ "return",
887
+ "static",
888
+ "super",
889
+ "switch",
890
+ "this",
891
+ "throw",
892
+ "true",
893
+ "try",
894
+ "typeof",
895
+ "var",
896
+ "void",
897
+ "while",
898
+ "with",
899
+ "yield",
900
+ "context"
901
+ ]);
902
+ var MEMBERS = {
903
+ ready: true,
904
+ status: true,
905
+ state: true,
906
+ release: true,
907
+ opaque: true,
908
+ then: true,
909
+ reference: true
910
+ };
911
+ var OWN = new Set([
912
+ "AcquisitionOptions",
913
+ "Context",
914
+ "DynamicReference",
915
+ "Promise",
916
+ "ReferenceBase",
917
+ "WitResource",
918
+ "WitClientSchema"
919
+ ]);
920
+ async function client(options) {
921
+ const wit = path6.resolve(options.wit);
922
+ if (!wit.endsWith(".wit"))
923
+ throw new Error("Client generation requires a .wit entry file");
924
+ const contract = new NodeContract2(path6.dirname(wit), options.world);
925
+ const graph = query(contract, { kind: "describe" });
926
+ const names = query(contract, { kind: "type-names" });
927
+ const signatures = query(contract, {
928
+ kind: "client-signatures"
929
+ });
930
+ const source = `${path6.basename(wit)}${options.world ? `, world ${options.world}` : ""}`;
931
+ const out = path6.resolve(options.out);
932
+ const modules = new Map;
933
+ for (const entry of graph.exports) {
934
+ const identity = entry.contract;
935
+ if (!identity || !entry.functions || entry.type_only || identity === HTTP_HANDLER)
936
+ continue;
937
+ const file = path6.join(out, `${identity.replace(/@[^@]*$/, "").replace(/[:/]/g, "-")}.ts`);
938
+ if (modules.has(file))
939
+ throw new Error(`${identity} and another exported interface share the module ${file}`);
940
+ modules.set(file, clientModule(graph, names, identity, entry, source, signatures[identity]));
941
+ }
942
+ if (modules.size === 0)
943
+ throw new Error(`${source} exports no interface a host can call`);
944
+ await mkdir3(out, { recursive: true });
945
+ for (const [file, contents] of modules) {
946
+ const previous = await readFile4(file, "utf8").catch((error) => {
947
+ if (error.code === "ENOENT")
948
+ return;
949
+ throw error;
950
+ });
951
+ if (previous === contents)
952
+ continue;
953
+ const temporary = `${file}.${process.pid}.tmp`;
954
+ await writeFile3(temporary, contents);
955
+ await rename3(temporary, file);
956
+ }
957
+ return [...modules.keys()].sort();
958
+ }
959
+ function clientModule(graph, names, identity, entry, source, signature) {
960
+ const interfaceName = /\/([^@/]+)(?:@[^@]*)?$/.exec(identity)?.[1];
961
+ if (!interfaceName)
962
+ throw new Error(`${identity} is not a versioned interface identity`);
963
+ const spelled = graph.javascriptNames[interfaceName] ?? bindingName(interfaceName, false);
964
+ const pascal = spelled.charAt(0).toUpperCase() + spelled.slice(1);
965
+ const service = OWN.has(pascal) ? `${pascal}_` : pascal;
966
+ const functions = Object.values(entry.functions ?? {});
967
+ const occupied = new Set([...OWN, service]);
968
+ const resourceTypes = resourceNames(graph, entry.resources ?? {}, identity, occupied);
969
+ const resourceNames2 = resourceTypes.names;
970
+ const resources = resourceNames2.size > 0;
971
+ const { render, declarations } = renderer(graph, names, identity, occupied, functions.flatMap((fn) => [
972
+ ...fn.params.filter((p) => p.name !== "self").map((p) => p.type),
973
+ fn.result
974
+ ]), resourceNames2);
975
+ const signatures = [];
976
+ const members = [];
977
+ const resourceSignatures = new Map([...resourceNames2].map(([id]) => [id, []]));
978
+ const used = new Map;
979
+ for (const fn of functions.sort((a, b) => a.name.localeCompare(b.name))) {
980
+ const kind = typeof fn.kind === "object" ? Object.entries(fn.kind)[0] : undefined;
981
+ const receiver = kind?.[0] === "method" || kind?.[0] === "async-method";
982
+ const resource = kind ? resourceNames2.get(resourceTypes.canonical(kind[1])) : undefined;
983
+ const member = fn.name.split(".").at(-1);
984
+ const method = kind?.[0] === "constructor" ? `new${resource}` : kind ? receiver ? bindingName(member, false) : `${resource.charAt(0).toLowerCase()}${resource.slice(1)}${bindingName(member, false).charAt(0).toUpperCase()}${bindingName(member, false).slice(1)}` : graph.javascriptNames[fn.name] ?? bindingName(fn.name, false);
985
+ if (kind && !resource)
986
+ throw new Error(`${identity}: resource function has no defining resource`);
987
+ if (Object.hasOwn(MEMBERS, fn.name) || Object.hasOwn(MEMBERS, method) || method === "resourceType")
988
+ throw new Error(`${identity}: ${fn.name} collides with a member every client has (${Object.keys(MEMBERS).join(", ")})`);
989
+ const scope = receiver ? resource : service;
990
+ const methodNames = used.get(scope) ?? new Set;
991
+ if (methodNames.has(method))
992
+ throw new Error(`${identity}: generated method collision: ${scope}.${method}`);
993
+ methodNames.add(method);
994
+ used.set(scope, methodNames);
995
+ const taken = new Set;
996
+ const params = receiver ? fn.params.slice(1) : fn.params;
997
+ const parameters = params.map((parameter) => {
998
+ let name = bindingName(parameter.name, false);
999
+ while (RESERVED.has(name) || taken.has(name))
1000
+ name += "_";
1001
+ taken.add(name);
1002
+ return `${name}: ${render(parameter.type)}`;
1003
+ });
1004
+ parameters.push("context?: Context");
1005
+ const result = fn.result === undefined || fn.result === null ? "void" : render(fn.result);
1006
+ const key = method === "new" ? JSON.stringify(method) : method;
1007
+ const declaration = ` ${key}(${parameters.join(", ")}): Promise<${result}>;`;
1008
+ if (receiver)
1009
+ resourceSignatures.get(resourceTypes.canonical(kind[1])).push(declaration);
1010
+ else {
1011
+ signatures.push(declaration);
1012
+ members.push(` ${method}: (...args) => calls.call<${result}>(${JSON.stringify(fn.name)}, sent(args, ${params.length})),`);
1013
+ }
1014
+ }
1015
+ const wrappers = [...resourceNames2].flatMap(([id, name]) => {
1016
+ return [
1017
+ `/** An owned WIT resource. Release it when its work ends. */`,
1018
+ `export interface ${name} extends WitResource {`,
1019
+ ` readonly resourceType: ${JSON.stringify(resourceTypes.nominals.get(id))};`,
1020
+ ...resourceSignatures.get(id),
1021
+ `}`,
1022
+ ``
1023
+ ];
1024
+ });
1025
+ const schema = [
1026
+ `const schema = ${JSON.stringify({ identity, signature, resources: entry.resources ?? {}, functions: entry.functions, types: graph.types, javascriptNames: graph.javascriptNames, imports: (graph.imports ?? []).map(({ binding, contract }) => ({ binding, ...contract ? { contract } : {} })) })} satisfies WitClientSchema;`,
1027
+ ``
1028
+ ];
1029
+ return [
1030
+ `// Generated by \`client\` from @syntropika/tembra-sdk/tooling: the typed client of`,
1031
+ `// ${identity} (${source}). Regenerate it instead of editing it.`,
1032
+ `import { witClient } from "@syntropika/tembra-sdk";`,
1033
+ `import type {`,
1034
+ ` AcquisitionOptions,`,
1035
+ ` Context,`,
1036
+ ` DynamicReference,`,
1037
+ ` ReferenceBase,`,
1038
+ ...resources ? [` WitResource,`] : [],
1039
+ ` WitClientSchema,`,
1040
+ `} from "@syntropika/tembra-sdk";`,
1041
+ ``,
1042
+ `/** The interface identity; an Orb's service is named \`<orb>::<identity>\`. */`,
1043
+ `export const IDENTITY = ${JSON.stringify(identity)};`,
1044
+ ``,
1045
+ ...declarations(),
1046
+ ...wrappers,
1047
+ ...resourceTypes.aliases,
1048
+ ...schema,
1049
+ `/** One object's \`${identity}\`, with the values a host sends and receives. */`,
1050
+ `export interface ${service} {`,
1051
+ ` /** The acquired reference: its readiness, status, state and \`release()\`. */`,
1052
+ ` readonly reference: ReferenceBase;`,
1053
+ ...signatures,
1054
+ `}`,
1055
+ ``,
1056
+ `/** Acquire the service of \`orb\` under \`key\` through a \`Host\` or a \`Context\`. */`,
1057
+ `export async function get(`,
1058
+ ` scope: {`,
1059
+ ` get(`,
1060
+ ` service: string,`,
1061
+ ` key: string | readonly string[],`,
1062
+ ` options?: AcquisitionOptions,`,
1063
+ ` ): Promise<DynamicReference>;`,
1064
+ ` },`,
1065
+ ` address: { orb: string; key: string | readonly string[] },`,
1066
+ ` options?: AcquisitionOptions,`,
1067
+ `): Promise<${service}> {`,
1068
+ ` const reference = await scope.get(\`\${address.orb}::\${IDENTITY}\`, address.key, options);`,
1069
+ ` let calls;`,
1070
+ ` try { calls = witClient(reference, schema); }`,
1071
+ ` catch (error) { reference.release(); throw error; }`,
1072
+ ` const client: ${service} = {`,
1073
+ ` reference,`,
1074
+ ...members,
1075
+ ` };`,
1076
+ ` return client;`,
1077
+ `}`,
1078
+ ``,
1079
+ `/** The arguments a call sends: a trailing context given as \`undefined\` is not one of them. */`,
1080
+ `function sent(args: readonly unknown[], count: number): readonly unknown[] {`,
1081
+ ` return args.length === count + 1 && args[count] === undefined ? args.slice(0, count) : args;`,
1082
+ `}`,
1083
+ ``
1084
+ ].join(`
1085
+ `);
1086
+ }
1087
+ function renderer(graph, names, identity, taken, roots, resources = new Map) {
1088
+ const kinds = new Map(graph.types.map(({ id, definition }) => [id, definition.kind]));
1089
+ const wit = new Map(names.map((entry) => [entry.id, entry]));
1090
+ const rendered = new Map;
1091
+ const target = (type) => {
1092
+ const kind = kinds.get(type);
1093
+ return typeof kind === "object" && typeof kind.type === "number" ? target(kind.type) : type;
1094
+ };
1095
+ const reached = new Set;
1096
+ const visited = new Set;
1097
+ const reach = (type) => {
1098
+ if (typeof type !== "number" || visited.has(type))
1099
+ return;
1100
+ visited.add(type);
1101
+ if (wit.has(type))
1102
+ reached.add(type);
1103
+ const kind = kinds.get(wit.has(type) ? target(type) : type);
1104
+ if (kind === undefined || typeof kind === "string")
1105
+ return;
1106
+ [
1107
+ kind.type,
1108
+ kind.list,
1109
+ kind.option,
1110
+ ...kind.record?.fields.map((field) => field.type) ?? [],
1111
+ ...kind.tuple?.types ?? [],
1112
+ ...kind.variant?.cases.map((item) => item.type) ?? [],
1113
+ kind.result?.ok,
1114
+ kind.result?.err
1115
+ ].forEach(reach);
1116
+ };
1117
+ roots.forEach(reach);
1118
+ const ordered = [...reached].sort((a, b) => a - b);
1119
+ const spellings = new Map;
1120
+ for (const type of ordered) {
1121
+ const { javascript } = wit.get(type);
1122
+ spellings.set(javascript, (spellings.get(javascript) ?? new Set).add(target(type)));
1123
+ }
1124
+ const naming = new Map;
1125
+ const named = new Map;
1126
+ for (const type of ordered) {
1127
+ const entry = wit.get(type);
1128
+ let spelled = spellings.get(entry.javascript).size > 1 ? entry.qualified : entry.javascript;
1129
+ while (taken.has(spelled))
1130
+ spelled += "_";
1131
+ const other = named.get(spelled);
1132
+ if (other === undefined)
1133
+ named.set(spelled, type);
1134
+ else if (target(other) !== target(type)) {
1135
+ const [first, second] = [wit.get(other), entry].map((each) => `${each.name}${each.interface ? ` of ${each.interface}` : ""}`).sort();
1136
+ throw new Error(`${identity}: the WIT types ${first} and ${second} both name ${spelled}`);
1137
+ }
1138
+ naming.set(type, spelled);
1139
+ }
1140
+ const refuse = (what) => {
1141
+ throw new Error(`${identity}: ${what} is outside the portable value profile`);
1142
+ };
1143
+ const spelling = (name) => {
1144
+ const spelled = graph.javascriptNames[name];
1145
+ if (spelled === undefined)
1146
+ throw new Error(`${identity}: missing JavaScript name for ${name}`);
1147
+ return spelled;
1148
+ };
1149
+ const union = (type) => {
1150
+ if (typeof type !== "number")
1151
+ return false;
1152
+ const kind = kinds.get(type);
1153
+ if (kind === undefined || typeof kind === "string" || wit.has(type))
1154
+ return false;
1155
+ if (kind.type !== undefined)
1156
+ return union(kind.type);
1157
+ return kind.option !== undefined || kind.variant !== undefined || kind.result !== undefined || kind.enum !== undefined && kind.enum.cases.length > 1;
1158
+ };
1159
+ const payload = (tag, type) => type === null || type === undefined ? `{ tag: ${JSON.stringify(tag)} }` : `{ tag: ${JSON.stringify(tag)}; val: ${render(type)} }`;
1160
+ const kind = (definition) => {
1161
+ if (typeof definition === "string")
1162
+ return refuse(definition);
1163
+ if (definition.type !== undefined)
1164
+ return render(definition.type);
1165
+ if (definition.handle?.own !== undefined)
1166
+ return resources.get(target(definition.handle.own)) ?? refuse("a foreign owned resource");
1167
+ if (definition.handle?.borrow !== undefined)
1168
+ return refuse("an explicit resource borrow");
1169
+ if (definition.list !== undefined) {
1170
+ const item = render(definition.list);
1171
+ return union(definition.list) ? `(${item})[]` : `${item}[]`;
1172
+ }
1173
+ if (definition.option !== undefined)
1174
+ return `${render(definition.option)} | null`;
1175
+ if (definition.record)
1176
+ return `{ ${definition.record.fields.map((field) => `${spelling(field.name)}: ${render(field.type)}`).join("; ")} }`;
1177
+ if (definition.tuple)
1178
+ return `[${definition.tuple.types.map(render).join(", ")}]`;
1179
+ if (definition.variant)
1180
+ return definition.variant.cases.map((item) => payload(item.name, item.type)).join(" | ");
1181
+ if (definition.enum)
1182
+ return definition.enum.cases.map((item) => JSON.stringify(item.name)).join(" | ");
1183
+ if (definition.flags)
1184
+ return `{ ${definition.flags.flags.map((flag) => `${spelling(flag.name)}?: boolean`).join("; ")} }`;
1185
+ if (definition.result)
1186
+ return `${payload("ok", definition.result.ok)} | ${payload("err", definition.result.err)}`;
1187
+ return refuse(Object.keys(definition)[0] ?? "an unknown WIT type");
1188
+ };
1189
+ const render = (type) => {
1190
+ if (type === null || type === undefined)
1191
+ throw new Error(`${identity}: a type is missing`);
1192
+ if (typeof type === "string")
1193
+ return PRIMITIVES[type] ?? refuse(type);
1194
+ const resource = resources.get(target(type));
1195
+ if (resource !== undefined)
1196
+ return resource;
1197
+ const known = rendered.get(type);
1198
+ if (known !== undefined)
1199
+ return known;
1200
+ const definition = kinds.get(type);
1201
+ if (definition === undefined)
1202
+ throw new Error(`${identity}: unknown WIT type ${type}`);
1203
+ const spelled = naming.get(type);
1204
+ if (spelled !== undefined)
1205
+ return spelled;
1206
+ const text = kind(definition);
1207
+ rendered.set(type, text);
1208
+ return text;
1209
+ };
1210
+ const declarations = () => {
1211
+ const declared = new Map;
1212
+ for (const [spelled, type] of named) {
1213
+ const definition = kinds.get(target(type));
1214
+ const what = Object.keys(definition).find((key) => definition[key] !== undefined);
1215
+ declared.set(spelled, [
1216
+ `/** The WIT ${what} \`${wit.get(type).name}\`. */`,
1217
+ `export type ${spelled} = ${kind(definition)};`,
1218
+ ``
1219
+ ]);
1220
+ }
1221
+ return [...declared].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).flatMap(([, lines]) => lines);
1222
+ };
1223
+ return { render, declarations };
1224
+ }
1225
+ // src/tooling/types.ts
1226
+ function defineConfig(config) {
1227
+ return config;
1228
+ }
177
1229
  export {
178
- Platform,
179
1230
  build,
180
- defineConfig
1231
+ client,
1232
+ defineConfig,
1233
+ prepareBrowserComponent
181
1234
  };