@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,1421 @@
1
+ import {
2
+ Code2,
3
+ Reason2,
4
+ Status2,
5
+ Errors2,
6
+ isDescriptor,
7
+ TembraError2,
8
+ failure,
9
+ refuse
10
+ } from "./index-c1w7z9hx.js";
11
+ import {
12
+ KernelOp,
13
+ EnvironmentPhase
14
+ } from "./index-kr4x67wt.js";
15
+
16
+ // src/authoring/service-identities.ts
17
+ var identityKey = Symbol.for("@syntropika/tembra-sdk/service-identities");
18
+ var existing = Object.getOwnPropertyDescriptor(globalThis, identityKey)?.value;
19
+ if (existing !== undefined && !(existing instanceof WeakMap))
20
+ throw new TypeError("The SDK service identity slot must contain a WeakMap");
21
+ var serviceIdentities = existing instanceof WeakMap ? existing : new WeakMap;
22
+ if (existing === undefined)
23
+ Object.defineProperty(globalThis, identityKey, { value: serviceIdentities });
24
+
25
+ // src/authoring/services.ts
26
+ function associateServices(orb, apiVersion, services) {
27
+ const pending = new Map;
28
+ for (const [name, original, captured] of services) {
29
+ const identity = { orb, name, apiVersion };
30
+ for (const definition of [original, captured]) {
31
+ const previous = pending.get(definition) ?? serviceIdentities.get(definition);
32
+ if (previous && (previous.orb !== orb || previous.name !== name || previous.apiVersion !== apiVersion))
33
+ refuse(Errors2.Invalid.Service, "A service definition must have one orb, name and API version");
34
+ pending.set(definition, identity);
35
+ }
36
+ }
37
+ for (const [definition, identity] of pending)
38
+ serviceIdentities.set(definition, identity);
39
+ }
40
+ function serviceAcquisition(service, options = {}) {
41
+ if (typeof service === "string")
42
+ return { name: service, options };
43
+ const identity = serviceIdentities.get(service);
44
+ if (!identity)
45
+ refuse(Errors2.Invalid.Service, "Declare this service in an orb before acquiring it");
46
+ if (options.apiVersion !== undefined && options.apiVersion !== identity.apiVersion)
47
+ refuse(Errors2.Invalid.Service, "The acquisition API version must match the service declaration");
48
+ return { name: identity.name, options: { ...options, apiVersion: identity.apiVersion } };
49
+ }
50
+
51
+ // src/context-key.ts
52
+ var ContextKind2 = Object.freeze({
53
+ Text: "text",
54
+ Integer: "integer",
55
+ Boolean: "boolean",
56
+ Opaque: "opaque"
57
+ });
58
+
59
+ class ContextKey2 {
60
+ name;
61
+ version;
62
+ kind;
63
+ constructor(name, version, kind) {
64
+ this.name = name;
65
+ this.version = version;
66
+ this.kind = kind;
67
+ Object.freeze(this);
68
+ }
69
+ static text(name, version = 1) {
70
+ return new ContextKey2(name, version, ContextKind2.Text);
71
+ }
72
+ static integer(name, version = 1) {
73
+ return new ContextKey2(name, version, ContextKind2.Integer);
74
+ }
75
+ static boolean(name, version = 1) {
76
+ return new ContextKey2(name, version, ContextKind2.Boolean);
77
+ }
78
+ static opaque(name, version = 1) {
79
+ return new ContextKey2(name, version, ContextKind2.Opaque);
80
+ }
81
+ source(value, ctx) {
82
+ if (this.kind !== ContextKind2.Opaque)
83
+ return;
84
+ const token = typeof value === "object" && value !== null ? ctx.session.contextTokens.get(value) : undefined;
85
+ if (!token || token.root !== ctx.root)
86
+ throw new TypeError("An owner-issued opaque reference from this host and root is required");
87
+ return token.source;
88
+ }
89
+ }
90
+ function readContextValue(ctx, key, frame) {
91
+ const entry = ctx.session.kernel.command(KernelOp.ContextValue, {
92
+ root: ctx.root,
93
+ context: frame,
94
+ call: ctx.invocation?.id,
95
+ key
96
+ });
97
+ if (!entry)
98
+ return;
99
+ if (entry.kind !== ContextKind2.Opaque)
100
+ return entry.value;
101
+ const token = Object.freeze({ opaque: true });
102
+ ctx.session.contextTokens.set(token, { root: ctx.root, source: entry.source });
103
+ return token;
104
+ }
105
+ function opaqueFrom2(ctx, key, issuedFrame) {
106
+ const token = readContextValue(ctx, key, issuedFrame);
107
+ if (!token)
108
+ throw new TypeError("The owner did not issue a reference");
109
+ return token;
110
+ }
111
+
112
+ // src/interpreter/wit-shape.ts
113
+ var U64_MAX = (1n << 64n) - 1n;
114
+ var S64_MIN = -(1n << 63n);
115
+ var S64_MAX = (1n << 63n) - 1n;
116
+ var CANONICAL = { u64: /^(?:0|[1-9][0-9]{0,19})$/, s64: /^(?:0|-?[1-9][0-9]{0,18})$/ };
117
+ function isInteger(kind, value) {
118
+ return typeof value === "bigint" && (kind === "u64" ? value >= 0n && value <= U64_MAX : value >= S64_MIN && value <= S64_MAX);
119
+ }
120
+ function integerValue(kind, text) {
121
+ if (typeof text !== "string" || !CANONICAL[kind].test(text))
122
+ throw new TypeError(`${kind} requires canonical decimal text`);
123
+ const value = BigInt(text);
124
+ if (!isInteger(kind, value))
125
+ throw new TypeError(`${kind} value is out of range`);
126
+ return value;
127
+ }
128
+ function shapes(graph) {
129
+ const kinds = new Map(graph.types.map(({ id, definition }) => [id, definition.kind]));
130
+ const compiled = new Map;
131
+ const field = (name) => {
132
+ const spelling = graph.javascriptNames[name];
133
+ if (spelling === undefined)
134
+ throw new Error(`Missing WIT JavaScript name for ${name}`);
135
+ return spelling;
136
+ };
137
+ const cases = (entries) => {
138
+ const shapes = new Map(entries.map(([name, type]) => [name, compile(type)]));
139
+ return [...shapes.values()].some(Boolean) ? { cases: shapes } : undefined;
140
+ };
141
+ const compile = (type) => {
142
+ if (type === "u64" || type === "s64")
143
+ return type;
144
+ if (typeof type !== "number")
145
+ return;
146
+ if (compiled.has(type))
147
+ return compiled.get(type);
148
+ const kind = kinds.get(type);
149
+ if (!kind)
150
+ throw new Error("Unknown WIT type reference");
151
+ if (typeof kind === "string")
152
+ return;
153
+ let shape;
154
+ if (kind.type !== undefined)
155
+ shape = compile(kind.type);
156
+ else if (kind.list !== undefined) {
157
+ const item = compile(kind.list);
158
+ shape = item && { list: item };
159
+ } else if (kind.option !== undefined) {
160
+ const item = compile(kind.option);
161
+ shape = item && { option: item };
162
+ } else if (kind.record) {
163
+ const fields = new Map(kind.record.fields.map(({ name, type }) => [field(name), compile(type)]));
164
+ shape = [...fields.values()].some(Boolean) ? { fields } : undefined;
165
+ } else if (kind.tuple) {
166
+ const items = kind.tuple.types.map(compile);
167
+ shape = items.some(Boolean) ? { items } : undefined;
168
+ } else if (kind.variant)
169
+ shape = cases(kind.variant.cases.map(({ name, type }) => [name, type]));
170
+ else if (kind.result)
171
+ shape = cases([
172
+ ["ok", kind.result.ok],
173
+ ["err", kind.result.err]
174
+ ]);
175
+ compiled.set(type, shape);
176
+ return shape;
177
+ };
178
+ return (fn) => {
179
+ const items = fn.params.map(({ type }) => compile(type));
180
+ return {
181
+ params: items.some(Boolean) ? { items } : undefined,
182
+ result: compile(fn.result)
183
+ };
184
+ };
185
+ }
186
+ function lift(shape, value) {
187
+ if (shape === undefined || value === null || value === undefined)
188
+ return value;
189
+ if (typeof shape === "string")
190
+ return integerValue(shape, value);
191
+ if ("option" in shape)
192
+ return lift(shape.option, value);
193
+ if ("list" in shape) {
194
+ if (!Array.isArray(value))
195
+ throw new TypeError("WIT list requires an array");
196
+ return value.map((item) => lift(shape.list, item));
197
+ }
198
+ if ("items" in shape) {
199
+ if (!Array.isArray(value) || value.length !== shape.items.length)
200
+ throw new TypeError("WIT tuple length differs");
201
+ return value.map((item, index) => lift(shape.items[index], item));
202
+ }
203
+ if (typeof value !== "object" || Array.isArray(value))
204
+ throw new TypeError("WIT record or tagged value requires an object");
205
+ const copy = { ...value };
206
+ if ("fields" in shape) {
207
+ for (const [name, item] of shape.fields)
208
+ if (item && Object.hasOwn(copy, name))
209
+ copy[name] = lift(item, copy[name]);
210
+ } else {
211
+ const item = shape.cases.get(copy.tag);
212
+ if (item && Object.hasOwn(copy, "val"))
213
+ copy.val = lift(item, copy.val);
214
+ }
215
+ return copy;
216
+ }
217
+
218
+ // src/interpreter/codec.ts
219
+ var VALUE_LIMIT = 8 << 20;
220
+ var VALUE_DEPTH = 64;
221
+ var issued = Symbol("tembra.encoded");
222
+ var quote = JSON.stringify;
223
+ var descriptor = Reflect.getOwnPropertyDescriptor;
224
+ var ownKeys = Reflect.ownKeys;
225
+ var prototypeOf = Reflect.getPrototypeOf;
226
+ var hasOwn = Object.hasOwn;
227
+ var isArray = Array.isArray;
228
+ var isView = ArrayBuffer.isView;
229
+ var objectPrototype = Object.prototype;
230
+ var arrayPrototype = Array.prototype;
231
+ var typedArray = prototypeOf(Uint8Array.prototype);
232
+ var typedLength = descriptor(typedArray, "length").get;
233
+ var typedTag = descriptor(typedArray, Symbol.toStringTag).get;
234
+
235
+ class Encoded {
236
+ #text;
237
+ constructor(token, text) {
238
+ if (token !== issued)
239
+ throw new TypeError("Encoded values are issued by the value codec");
240
+ this.#text = text;
241
+ }
242
+ get text() {
243
+ return this.#text;
244
+ }
245
+ }
246
+ function refused(reason) {
247
+ throw failure(`Portable value rejected: ${reason}`);
248
+ }
249
+ function number(value) {
250
+ if (value !== value || value === Infinity || value === -Infinity)
251
+ refused("non-finite numbers are outside the value profile");
252
+ if (value === 0 && 1 / value < 0)
253
+ refused("negative zero is outside the value profile");
254
+ return "" + value;
255
+ }
256
+ function listKind(shape) {
257
+ return typeof shape === "object" && "list" in shape && typeof shape.list === "string" ? shape.list : undefined;
258
+ }
259
+ function encode(value, limit = VALUE_LIMIT, shape) {
260
+ const ancestors = [];
261
+ let size = 0;
262
+ const emit = (text) => {
263
+ size += text.length;
264
+ if (size > limit)
265
+ refused("value exceeds its size bound");
266
+ return text;
267
+ };
268
+ const visit = (value, shape) => {
269
+ if (typeof shape === "string") {
270
+ if (!isInteger(shape, value))
271
+ refused(typeof value === "bigint" ? `${shape} value is out of range` : `${shape} requires a bigint, not ${value === null ? "null" : typeof value}`);
272
+ return emit(`"${value}"`);
273
+ }
274
+ if (shape !== undefined && "option" in shape) {
275
+ if (value === null || value === undefined)
276
+ return emit("null");
277
+ shape = shape.option;
278
+ if (typeof shape === "string")
279
+ return visit(value, shape);
280
+ }
281
+ switch (typeof value) {
282
+ case "string":
283
+ return emit(quote(value));
284
+ case "number":
285
+ return emit(number(value));
286
+ case "boolean":
287
+ return emit(value ? "true" : "false");
288
+ case "undefined":
289
+ return emit("null");
290
+ case "bigint":
291
+ return refused("BigInt is portable only in a WIT u64/s64 position");
292
+ case "symbol":
293
+ case "function":
294
+ return refused(`${typeof value} values are not portable data`);
295
+ }
296
+ if (value === null)
297
+ return emit("null");
298
+ const object = value;
299
+ if (ancestors.length >= VALUE_DEPTH)
300
+ refused("value nesting exceeds its limit");
301
+ if (ancestors.includes(object))
302
+ refused("cyclic values are not portable");
303
+ ancestors.push(object);
304
+ try {
305
+ if (isView(object))
306
+ return typed(object, listKind(shape));
307
+ if (isArray(object))
308
+ return list(object, shape);
309
+ return record(object, shape);
310
+ } finally {
311
+ ancestors.pop();
312
+ }
313
+ };
314
+ const typed = (view, kind) => {
315
+ const tag = typedTag.call(view);
316
+ if (tag === undefined)
317
+ refused("DataView is not a portable list");
318
+ const wide = tag === "BigInt64Array" || tag === "BigUint64Array";
319
+ if (kind !== undefined && tag !== (kind === "u64" ? "BigUint64Array" : "BigInt64Array"))
320
+ refused(`list<${kind}> requires a ${kind === "u64" ? "BigUint64Array" : "BigInt64Array"}`);
321
+ if (kind === undefined && wide)
322
+ refused("64-bit lists are portable only as WIT list<u64/s64>");
323
+ const elements = view;
324
+ const length = typedLength.call(view);
325
+ let text = emit("[");
326
+ for (let index = 0;index < length; index++) {
327
+ if (index)
328
+ text += emit(",");
329
+ const element = elements[index];
330
+ text += emit(typeof element === "bigint" ? `"${element}"` : number(element));
331
+ }
332
+ return text + emit("]");
333
+ };
334
+ const list = (array, shape) => {
335
+ const length = array.length;
336
+ if (!Number.isSafeInteger(length) || length < 0 || length > limit - size)
337
+ refused("list length exceeds its size bound");
338
+ const items = typeof shape === "object" && "items" in shape ? shape.items : undefined;
339
+ if (items && items.length !== length)
340
+ refused("tuple length differs from WIT");
341
+ const item = typeof shape === "object" && "list" in shape ? shape.list : undefined;
342
+ let text = emit("[");
343
+ for (let index = 0;index < length; index++) {
344
+ if (index)
345
+ text += emit(",");
346
+ const element = descriptor(array, "" + index);
347
+ if (!element)
348
+ refused("sparse arrays are not portable");
349
+ if (!element.enumerable || !hasOwn(element, "value"))
350
+ refused("array accessors and non-enumerable elements are not portable");
351
+ text += visit(element.value, items ? items[index] : item);
352
+ }
353
+ if (prototypeOf(array) !== arrayPrototype)
354
+ refused("array subclasses are not portable data");
355
+ if (ownKeys(array).length !== length + 1)
356
+ refused("extra array properties are not portable data");
357
+ return text + emit("]");
358
+ };
359
+ const record = (object, shape) => {
360
+ const prototype = prototypeOf(object);
361
+ if (prototype !== objectPrototype && prototype !== null)
362
+ refused("only plain objects, arrays and numeric typed arrays are portable");
363
+ const fields = typeof shape === "object" && "fields" in shape ? shape.fields : undefined;
364
+ const cases = typeof shape === "object" && "cases" in shape ? shape.cases : undefined;
365
+ const property = (key) => {
366
+ if (typeof key !== "string")
367
+ refused("symbol-keyed properties are not portable");
368
+ const found = descriptor(object, key);
369
+ if (found === undefined || !found.enumerable || !hasOwn(found, "value"))
370
+ refused("accessors and non-enumerable properties are not portable");
371
+ return found.value;
372
+ };
373
+ let text = emit("{");
374
+ if (cases) {
375
+ const keys = ownKeys(object);
376
+ if (keys.length > 2)
377
+ refused("WIT tagged values have only tag and val");
378
+ const entries = keys.map((key) => [key, property(key)]);
379
+ const tag = entries.find(([key]) => key === "tag")?.[1];
380
+ if (typeof tag !== "string" || !cases.has(tag))
381
+ refused("WIT tagged value needs a known tag");
382
+ entries.forEach(([key, value], index) => {
383
+ const type = key === "val" ? cases.get(tag) : undefined;
384
+ text += emit(index ? "," : "") + emit(quote(key)) + emit(":") + visit(value, type);
385
+ });
386
+ return text + emit("}");
387
+ }
388
+ let first = true;
389
+ for (const key of ownKeys(object)) {
390
+ const value = property(key);
391
+ if (fields && !fields.has(key))
392
+ refused(`record field ${quote(key)} is not declared by WIT`);
393
+ text += emit(first ? "" : ",") + emit(quote(key)) + emit(":") + visit(value, fields?.get(key));
394
+ first = false;
395
+ }
396
+ return text + emit("}");
397
+ };
398
+ let text;
399
+ try {
400
+ text = visit(value, shape);
401
+ } catch (error) {
402
+ throw failure(error);
403
+ }
404
+ return new Encoded(issued, text);
405
+ }
406
+ var ACCEPTED = '{"ok":null}';
407
+ function check(contract, slot, arguments_, value) {
408
+ const answer = contract.validate(slot, arguments_, value.text);
409
+ if (answer === ACCEPTED)
410
+ return value;
411
+ let error;
412
+ try {
413
+ error = JSON.parse(answer).error;
414
+ } catch {
415
+ error = undefined;
416
+ }
417
+ throw failure(error ?? "Interpreter value validation failed");
418
+ }
419
+ function checkedResult(contract, slot, text) {
420
+ return check(contract, slot, false, new Encoded(issued, text));
421
+ }
422
+ function reply(value) {
423
+ return value instanceof Encoded ? value.text : encode(value ?? null).text;
424
+ }
425
+ function refusal(error) {
426
+ if (!isDescriptor(error))
427
+ return JSON.stringify({ error: error instanceof Error ? error.message : String(error) });
428
+ const { code, reason, message } = error;
429
+ return JSON.stringify({ error: { code, reason, message } });
430
+ }
431
+ function packet(control, field, value) {
432
+ const head = quote(control);
433
+ return `${head.slice(0, -1)}${head.length > 2 ? "," : ""}${quote(field)}:${value.text}}`;
434
+ }
435
+
436
+ // src/runtime/context.ts
437
+ var issued2 = new WeakMap;
438
+
439
+ class Context {
440
+ session;
441
+ root;
442
+ invocation;
443
+ frame;
444
+ constructor(session, root, invocation, frame = 0) {
445
+ this.session = session;
446
+ this.root = root;
447
+ this.invocation = invocation;
448
+ this.frame = frame;
449
+ issued2.set(this, this);
450
+ }
451
+ with(key, value) {
452
+ const source = key.source(value, this);
453
+ const frame = this.session.kernel.command(KernelOp.ContextDerive, {
454
+ root: this.root,
455
+ context: this.frame,
456
+ call: this.invocation?.id,
457
+ key,
458
+ ...key.kind === ContextKind2.Opaque ? { source } : { value }
459
+ });
460
+ return new Context(this.session, this.root, this.invocation, frame);
461
+ }
462
+ value(key) {
463
+ return readContextValue(this, key, this.frame);
464
+ }
465
+ exportValues(keys) {
466
+ const result = {};
467
+ for (const key of keys) {
468
+ if (key.kind === ContextKind2.Opaque)
469
+ throw new TypeError("Local opaque references cannot be exported");
470
+ const value = this.value(key);
471
+ if (value !== undefined)
472
+ result[`${key.name}@${key.version}`] = value;
473
+ }
474
+ return result;
475
+ }
476
+ get principal() {
477
+ return this.session.kernel.command(KernelOp.RootPrincipal, { root: this.root });
478
+ }
479
+ get signal() {
480
+ return this.session.calls.signal(this.root);
481
+ }
482
+ check() {
483
+ this.session.kernel.check(this.root, this.invocation?.id);
484
+ }
485
+ cancel() {
486
+ this.session.kernel.command(KernelOp.CancelRoot, { root: this.root });
487
+ this.session.lifecycle.flush();
488
+ }
489
+ get(service, key, options = {}) {
490
+ this.check();
491
+ return this.session.handles.get(service, key, options, this);
492
+ }
493
+ resource(name) {
494
+ this.check();
495
+ return this.session.scopes.hostResource(name);
496
+ }
497
+ }
498
+ function issuedContext(value, session) {
499
+ if (typeof value !== "object" || value === null || issued2.get(value)?.session !== session) {
500
+ throw new TembraError2(Errors2.Forbidden.Context, "An issued context from this host is required");
501
+ }
502
+ return issued2.get(value);
503
+ }
504
+ function context(value, session) {
505
+ const result = issuedContext(value, session);
506
+ result.check();
507
+ return result;
508
+ }
509
+ function isContext(value) {
510
+ return typeof value === "object" && value !== null && issued2.has(value);
511
+ }
512
+
513
+ // src/values.ts
514
+ class Values {
515
+ allocate;
516
+ #next = 1;
517
+ #values = new Map;
518
+ constructor(allocate) {
519
+ this.allocate = allocate;
520
+ }
521
+ put(value) {
522
+ if (this.#next > 4294967295)
523
+ refuse(Errors2.Invalid.ValuesExhausted);
524
+ const id = this.allocate ? this.allocate() : this.#next++;
525
+ this.#values.set(id, value);
526
+ return id;
527
+ }
528
+ get(id) {
529
+ if (!this.#values.has(id))
530
+ refuse(Errors2.Invalid.ValueGone);
531
+ return this.#values.get(id);
532
+ }
533
+ drop(id) {
534
+ this.#values.delete(id);
535
+ }
536
+ has(id) {
537
+ return this.#values.has(id);
538
+ }
539
+ set(id, value) {
540
+ this.#values.set(id, value);
541
+ }
542
+ clear() {
543
+ this.#values.clear();
544
+ }
545
+ get size() {
546
+ return this.#values.size;
547
+ }
548
+ }
549
+ var protectedValues = new WeakSet;
550
+ function protect(value) {
551
+ const visiting = new WeakSet;
552
+ function visit(value) {
553
+ if (value === null || typeof value !== "object") {
554
+ if (["function", "symbol"].includes(typeof value))
555
+ refuse(Errors2.Invalid.StateValue, "State must contain plain data");
556
+ return;
557
+ }
558
+ if (protectedValues.has(value))
559
+ return;
560
+ if (visiting.has(value))
561
+ refuse(Errors2.Invalid.StateCycle, "State cannot contain cycles");
562
+ const proto = Object.getPrototypeOf(value);
563
+ if (!Array.isArray(value) && proto !== Object.prototype && proto !== null)
564
+ refuse(Errors2.Invalid.StateValue, "State requires plain objects and arrays");
565
+ visiting.add(value);
566
+ for (const key of Reflect.ownKeys(value)) {
567
+ if (typeof key !== "string")
568
+ refuse(Errors2.Invalid.StateValue, "State cannot contain symbol properties");
569
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
570
+ if (!Object.hasOwn(descriptor, "value"))
571
+ refuse(Errors2.Invalid.StateValue, "State cannot contain accessors");
572
+ visit(descriptor.value);
573
+ }
574
+ visiting.delete(value);
575
+ Object.freeze(value);
576
+ protectedValues.add(value);
577
+ }
578
+ visit(value);
579
+ return value;
580
+ }
581
+
582
+ // src/state/selection.ts
583
+ class Selection {
584
+ compute;
585
+ report;
586
+ check;
587
+ #value;
588
+ #listeners = new Set;
589
+ #children = new Set;
590
+ #active = true;
591
+ #cleanups;
592
+ #cleanup;
593
+ #remove;
594
+ constructor(compute, value, report, check) {
595
+ this.compute = compute;
596
+ this.report = report;
597
+ this.check = check;
598
+ this.#value = protect(compute(value));
599
+ }
600
+ get value() {
601
+ this.check();
602
+ return this.#value;
603
+ }
604
+ track(cleanups, remove) {
605
+ this.#cleanups = cleanups;
606
+ this.#remove = remove;
607
+ const weak = new WeakRef(this);
608
+ this.#cleanup = () => weak.deref()?.detach();
609
+ cleanups?.add(this.#cleanup);
610
+ }
611
+ detach() {
612
+ if (!this.#active)
613
+ return;
614
+ this.#active = false;
615
+ if (this.#cleanup)
616
+ this.#cleanups?.delete(this.#cleanup);
617
+ this.#remove?.();
618
+ this.#listeners.clear();
619
+ for (const weak of this.#children)
620
+ weak.deref()?.detach();
621
+ this.#children.clear();
622
+ }
623
+ prepare(value) {
624
+ if (!this.#active)
625
+ return;
626
+ try {
627
+ this.check();
628
+ } catch {
629
+ this.detach();
630
+ return;
631
+ }
632
+ let next;
633
+ try {
634
+ next = protect(this.compute(value));
635
+ } catch (error) {
636
+ this.detach();
637
+ this.report(error);
638
+ return;
639
+ }
640
+ if (!this.#active)
641
+ return;
642
+ const children = [];
643
+ if (!Object.is(next, this.#value)) {
644
+ for (const weak of this.#children) {
645
+ const child = weak.deref();
646
+ const prepared = child?.prepare(next);
647
+ if (prepared)
648
+ children.push(prepared);
649
+ else
650
+ this.#children.delete(weak);
651
+ }
652
+ }
653
+ return {
654
+ adopt: () => {
655
+ if (!this.#active || Object.is(next, this.#value))
656
+ return () => {};
657
+ this.#value = next;
658
+ const notifyChildren = children.map((child) => child.adopt());
659
+ const listeners = [...this.#listeners];
660
+ return () => {
661
+ if (!this.#active)
662
+ return;
663
+ for (const notify of notifyChildren)
664
+ notify();
665
+ for (const listener of listeners) {
666
+ try {
667
+ listener(next);
668
+ } catch (error) {
669
+ this.report(error);
670
+ }
671
+ }
672
+ };
673
+ }
674
+ };
675
+ }
676
+ select(compute) {
677
+ this.check();
678
+ const child = new Selection(compute, this.#value, this.report, this.check);
679
+ this.check();
680
+ const weak = new WeakRef(child);
681
+ this.#children.add(weak);
682
+ child.track(this.#cleanups, () => this.#children.delete(weak));
683
+ return child;
684
+ }
685
+ subscribe(listener) {
686
+ this.check();
687
+ this.#listeners.add(listener);
688
+ try {
689
+ listener(this.#value);
690
+ } catch (error) {
691
+ this.report(error);
692
+ }
693
+ return () => {
694
+ this.#listeners.delete(listener);
695
+ };
696
+ }
697
+ }
698
+
699
+ // src/state/binding.ts
700
+ class StateBinding {
701
+ backend;
702
+ object;
703
+ closed = false;
704
+ #value;
705
+ #listeners = new Set;
706
+ #selections = new Set;
707
+ constructor(backend, object, initial) {
708
+ this.backend = backend;
709
+ this.object = object;
710
+ this.#value = arguments.length >= 3 ? initial : backend.value(backend.snapshot(object).value);
711
+ }
712
+ check() {
713
+ if (this.closed)
714
+ throw new TembraError2(Errors2.Gone.State, "State owner is gone");
715
+ }
716
+ get value() {
717
+ this.check();
718
+ return this.#value;
719
+ }
720
+ view(options, check = () => this.check()) {
721
+ const binding = this;
722
+ return {
723
+ get value() {
724
+ check();
725
+ return binding.value;
726
+ },
727
+ update(context, change) {
728
+ check();
729
+ binding.backend.check(context, binding.object);
730
+ const previous = binding.backend.snapshot(binding.object);
731
+ const current = binding.backend.value(previous.value);
732
+ const candidate = change(current);
733
+ validate(candidate, options);
734
+ binding.backend.check(context, binding.object);
735
+ if (Object.is(candidate, current))
736
+ return current;
737
+ const selected = binding.prepare(candidate);
738
+ binding.backend.adopt(binding.object, context, previous.revision, candidate);
739
+ const publish = binding.adopt(selected, candidate);
740
+ binding.backend.publish(publish);
741
+ return candidate;
742
+ },
743
+ select: (compute) => {
744
+ check();
745
+ return binding.select(compute, check);
746
+ },
747
+ subscribe: (listener) => {
748
+ check();
749
+ return binding.subscribe(listener);
750
+ }
751
+ };
752
+ }
753
+ select(compute, check = () => this.check(), cleanups) {
754
+ check();
755
+ const selection = new Selection(compute, this.value, (error) => this.backend.report(error), check);
756
+ check();
757
+ const weak = new WeakRef(selection);
758
+ this.#selections.add(weak);
759
+ selection.track(cleanups, () => this.#selections.delete(weak));
760
+ return selection;
761
+ }
762
+ subscribe(listener) {
763
+ this.check();
764
+ this.#listeners.add(listener);
765
+ try {
766
+ listener(this.value);
767
+ } catch (error) {
768
+ this.backend.report(error);
769
+ }
770
+ return () => {
771
+ this.#listeners.delete(listener);
772
+ };
773
+ }
774
+ prepare(candidate) {
775
+ const prepared = [];
776
+ for (const weak of this.#selections) {
777
+ const selection = weak.deref();
778
+ const next = selection?.prepare(candidate);
779
+ if (next)
780
+ prepared.push(next);
781
+ else
782
+ this.#selections.delete(weak);
783
+ }
784
+ return prepared;
785
+ }
786
+ adopt(prepared, candidate) {
787
+ this.#value = candidate;
788
+ const selections = prepared.map((p) => p.adopt());
789
+ const listeners = [...this.#listeners];
790
+ return () => {
791
+ for (const notify of selections)
792
+ notify();
793
+ for (const listener of listeners) {
794
+ try {
795
+ listener(candidate);
796
+ } catch (error) {
797
+ this.backend.report(error);
798
+ }
799
+ }
800
+ };
801
+ }
802
+ close() {
803
+ this.closed = true;
804
+ this.#value = undefined;
805
+ this.#listeners.clear();
806
+ for (const weak of this.#selections)
807
+ weak.deref()?.detach();
808
+ this.#selections.clear();
809
+ }
810
+ }
811
+ function validate(candidate, options) {
812
+ if (candidate && typeof candidate.then === "function")
813
+ refuse(Errors2.Invalid.AsyncState, "State updates and migrations must be synchronous");
814
+ const protectedValue = protect(candidate);
815
+ const result = options.validate?.(protectedValue);
816
+ if (result !== undefined && result !== true)
817
+ refuse(Errors2.Invalid.StateValidation, "Orb rejected the candidate state");
818
+ return protectedValue;
819
+ }
820
+ // src/authoring/declaration.ts
821
+ class Declaration {
822
+ session;
823
+ environment;
824
+ constructor(session, environment) {
825
+ this.session = session;
826
+ this.environment = environment;
827
+ }
828
+ check() {
829
+ if (this.environment.phase !== EnvironmentPhase.Declaring)
830
+ refuse(Errors2.Invalid.FactoryExpired, "Declarations must be synchronous");
831
+ }
832
+ get principal() {
833
+ return this.session.principalFor(this.environment.object?.id ?? 0);
834
+ }
835
+ get orb() {
836
+ return this.environment.orb.scope?.value;
837
+ }
838
+ get key() {
839
+ return this.environment.object?.address.key ?? ["main"];
840
+ }
841
+ state(initial, options = {}) {
842
+ this.check();
843
+ const environment = this.environment;
844
+ const object = environment.object;
845
+ if (!object || environment.state)
846
+ refuse(Errors2.Invalid.State, "An object declares exactly one state");
847
+ const version = options.version ?? 1;
848
+ if (!Number.isInteger(version) || version <= 0)
849
+ refuse(Errors2.Invalid.StateVersion);
850
+ let binding = object.binding;
851
+ if (!binding && object.live)
852
+ binding = new StateBinding(this.session, object.id, validate(initial, options));
853
+ if (!binding) {
854
+ const value = validate(initial, options);
855
+ const id = this.session.values.put(value);
856
+ try {
857
+ this.session.kernel.command(KernelOp.StateInit, { object: object.id, value: id, version });
858
+ } catch (error) {
859
+ this.session.values.drop(id);
860
+ throw error;
861
+ }
862
+ object.binding = binding = new StateBinding(this.session, object.id);
863
+ }
864
+ const handle = binding.view(options);
865
+ environment.state = { initial, options, binding };
866
+ return handle;
867
+ }
868
+ get(service, key, options = {}) {
869
+ this.check();
870
+ const acquisition = serviceAcquisition(service, options);
871
+ const requirement = this.session.scopes.requirement(this.environment, acquisition.name);
872
+ const resolved = requirement.service;
873
+ if (typeof service !== "string" && resolved !== acquisition.name)
874
+ refuse(Errors2.Invalid.Service, "A typed dependency must resolve its declared service name");
875
+ if (!this.environment.object && this.environment.orb.definition.services?.[resolved])
876
+ refuse(Errors2.Invalid.DependencyCycle);
877
+ const admitted = serviceAcquisition(service, {
878
+ ...options,
879
+ ...requirement.apiVersion ? { apiVersion: requirement.apiVersion } : {},
880
+ ...requirement.methods ? { methods: requirement.methods } : {},
881
+ principal: options.principal ?? this.principal
882
+ });
883
+ const identity = JSON.stringify([resolved, key, options.principal ?? this.principal]);
884
+ const existing = this.environment.dependencies.get(identity);
885
+ if (existing)
886
+ return existing;
887
+ const reference = this.session.handles.hold(resolved, key, admitted.options);
888
+ if (this.environment.object) {
889
+ try {
890
+ this.session.kernel.command(KernelOp.Dependency, {
891
+ object: this.environment.object.id,
892
+ reference: this.session.handles.reference(reference).id
893
+ });
894
+ } catch (error) {
895
+ reference.release();
896
+ throw error;
897
+ }
898
+ }
899
+ this.environment.dependencies.set(identity, reference);
900
+ return reference;
901
+ }
902
+ resource(name, options) {
903
+ this.check();
904
+ if (!options)
905
+ return this.session.scopes.hostResource(name);
906
+ if (this.environment.resources.has(name))
907
+ refuse(Errors2.Invalid.DuplicateResource, name);
908
+ const resource = this.session.resources.declare(this.environment, name, options);
909
+ this.environment.resources.set(name, resource);
910
+ return resource.handle;
911
+ }
912
+ task(start) {
913
+ this.check();
914
+ if (typeof start !== "function")
915
+ refuse(Errors2.Invalid.Task);
916
+ this.environment.tasks.push({ start });
917
+ }
918
+ on(name, source, handle, options = {}) {
919
+ this.check();
920
+ if (!this.session.kernel.features.subscriptions)
921
+ refuse(Errors2.Invalid.SubscriptionsDisabled);
922
+ if (options.maxBytes !== undefined && !options.sizeOf)
923
+ refuse(Errors2.Invalid.SubscriptionSize, "A local byte budget requires an explicit sizeOf function");
924
+ if (!name || this.environment.listeners.some((listener) => listener.name === name))
925
+ refuse(Errors2.Invalid.DuplicateListener, name);
926
+ this.environment.listeners.push({ name, source, handle, options });
927
+ }
928
+ hook(name) {
929
+ this.check();
930
+ if (!this.session.kernel.features.hooks)
931
+ refuse(Errors2.Invalid.HooksDisabled);
932
+ if (!this.environment.orb.definition.hooks?.[name])
933
+ refuse(Errors2.Invalid.Hook, name);
934
+ const operation = this.session.kernel.command(KernelOp.Allocate);
935
+ return {
936
+ run: (context, input) => this.session.orbs.runHook(this.environment, name, context, input),
937
+ observe: (source, input) => this.session.orbs.observe(this.environment, name, operation, source, input)
938
+ };
939
+ }
940
+ }
941
+ function consumerState(binding, check, cleanups) {
942
+ return {
943
+ get value() {
944
+ check();
945
+ return binding.value;
946
+ },
947
+ select(compute) {
948
+ check();
949
+ return binding.select(compute, check, cleanups);
950
+ },
951
+ subscribe(listener) {
952
+ check();
953
+ const detach = binding.subscribe((value) => {
954
+ try {
955
+ check();
956
+ } catch {
957
+ return;
958
+ }
959
+ listener(value);
960
+ });
961
+ let active = true;
962
+ const cleanup = () => {
963
+ if (!active)
964
+ return;
965
+ active = false;
966
+ cleanups.delete(cleanup);
967
+ detach();
968
+ };
969
+ cleanups.add(cleanup);
970
+ try {
971
+ check();
972
+ } catch {
973
+ cleanup();
974
+ }
975
+ return cleanup;
976
+ }
977
+ };
978
+ }
979
+
980
+ // src/runtime/records.ts
981
+ function deferred() {
982
+ let resolve;
983
+ let reject;
984
+ const promise = new Promise((accept, refuse) => {
985
+ resolve = accept;
986
+ reject = refuse;
987
+ });
988
+ promise.catch(() => {});
989
+ return { promise, resolve, reject };
990
+ }
991
+
992
+ // src/runtime/references.ts
993
+ var references = new WeakMap;
994
+ var finalizer = typeof FinalizationRegistry === "undefined" ? undefined : new FinalizationRegistry((held) => held.session.deref()?.handles.release(held.id));
995
+ function referenceOrigin(value) {
996
+ const issued = references.get(value);
997
+ if (!issued)
998
+ refuse(Errors2.Invalid.Reference, "An issued local reference is required");
999
+ return issued;
1000
+ }
1001
+
1002
+ class References {
1003
+ session;
1004
+ constructor(session) {
1005
+ this.session = session;
1006
+ }
1007
+ #metadata = new Map;
1008
+ #byObject = new Map;
1009
+ activateAcquired(acquired, address, requiredMethods = []) {
1010
+ const session = this.session;
1011
+ let object = session.objects.get(acquired.object);
1012
+ if (!object) {
1013
+ const activation = deferred();
1014
+ object = {
1015
+ id: acquired.object,
1016
+ address,
1017
+ orb: acquired.orb,
1018
+ versions: new Map,
1019
+ activation: activation.promise
1020
+ };
1021
+ session.objects.set(object.id, object);
1022
+ const record = object;
1023
+ session.track(session.scopes.activate(record, acquired).then(activation.resolve, (error) => {
1024
+ record.error = error;
1025
+ try {
1026
+ session.kernel.command(KernelOp.Fail, { object: record.id });
1027
+ } catch {}
1028
+ activation.reject(error);
1029
+ session.lifecycle.flush();
1030
+ }));
1031
+ }
1032
+ if (!this.claimExists(acquired.reference))
1033
+ return object.activation;
1034
+ const provider = this.orbMetadata(object.orb);
1035
+ const methods = provider.services.find((service) => service.name === address.service)?.methods ?? [];
1036
+ const record = {
1037
+ id: acquired.reference,
1038
+ object: acquired.object,
1039
+ address,
1040
+ methods: new Set(methods),
1041
+ requiredMethods: new Set(requiredMethods),
1042
+ stateCleanups: new Set,
1043
+ ready: object.activation,
1044
+ released: false,
1045
+ nativeOwned: true
1046
+ };
1047
+ const access = session.orbs.records.get(object.orb)?.definition.services?.[address.service]?.access;
1048
+ try {
1049
+ this.referenceMethods(record, methods, access);
1050
+ } catch (error) {
1051
+ if (session.kernel.features.views && this.claimExists(record.id))
1052
+ session.kernel.command(KernelOp.Restrict, { reference: record.id, methods: [] });
1053
+ throw error;
1054
+ }
1055
+ session.references.set(record.id, record);
1056
+ let owned = this.#byObject.get(record.object);
1057
+ if (!owned)
1058
+ this.#byObject.set(record.object, owned = new Set);
1059
+ owned.add(record);
1060
+ return object.activation;
1061
+ }
1062
+ hold(definition, key, options = {}, ctx) {
1063
+ let service;
1064
+ if (typeof definition === "string")
1065
+ service = definition;
1066
+ else {
1067
+ const acquisition = serviceAcquisition(definition, options);
1068
+ service = acquisition.name;
1069
+ options = acquisition.options;
1070
+ }
1071
+ const session = this.session;
1072
+ if (ctx)
1073
+ context(ctx, session);
1074
+ session.kernel.command(KernelOp.Tick, { now: session.now() });
1075
+ const address = this.address(service, key, options, ctx);
1076
+ const acquired = session.kernel.command(KernelOp.Acquire, {
1077
+ ...address,
1078
+ apiVersion: options.apiVersion ?? 0,
1079
+ methods: options.methods ?? []
1080
+ });
1081
+ let object = session.objects.get(acquired.object);
1082
+ if (!object) {
1083
+ const activation = deferred();
1084
+ object = {
1085
+ id: acquired.object,
1086
+ address,
1087
+ orb: acquired.orb,
1088
+ versions: new Map,
1089
+ activation: activation.promise
1090
+ };
1091
+ session.objects.set(object.id, object);
1092
+ const record = object;
1093
+ queueMicrotask(() => {
1094
+ session.track(session.scopes.activate(record, acquired).then(activation.resolve, (error) => {
1095
+ record.error = error;
1096
+ try {
1097
+ session.kernel.command(KernelOp.Fail, { object: record.id });
1098
+ } catch {}
1099
+ activation.reject(error);
1100
+ session.lifecycle.flush();
1101
+ }));
1102
+ });
1103
+ }
1104
+ const provider = this.orbMetadata(acquired.orb);
1105
+ const methods = new Set(provider.services.find((s) => s.name === service)?.methods ?? []);
1106
+ const record = {
1107
+ id: acquired.reference,
1108
+ object: acquired.object,
1109
+ address,
1110
+ methods,
1111
+ requiredMethods: new Set(options.methods ?? []),
1112
+ stateCleanups: new Set,
1113
+ ready: object.activation,
1114
+ released: false,
1115
+ ...ctx ? { context: ctx } : {}
1116
+ };
1117
+ const nativeAccess = session.options.native?.access?.(acquired.orb, service, address.principal);
1118
+ const access = nativeAccess ? () => ({ methods: nativeAccess }) : session.orbs.records.get(acquired.orb)?.definition.services?.[service]?.access;
1119
+ try {
1120
+ this.referenceMethods(record, methods, access);
1121
+ } catch (error) {
1122
+ session.kernel.command(KernelOp.Release, { reference: record.id });
1123
+ session.kernel.command(KernelOp.Forget, { reference: record.id });
1124
+ session.lifecycle.flush();
1125
+ throw error;
1126
+ }
1127
+ session.references.set(record.id, record);
1128
+ let owned = this.#byObject.get(record.object);
1129
+ if (!owned) {
1130
+ owned = new Set;
1131
+ this.#byObject.set(record.object, owned);
1132
+ }
1133
+ owned.add(record);
1134
+ if (ctx) {
1135
+ let owned = session.rootReferences.get(ctx.root);
1136
+ if (!owned) {
1137
+ owned = new Set;
1138
+ session.rootReferences.set(ctx.root, owned);
1139
+ }
1140
+ owned.add(record.id);
1141
+ }
1142
+ const check = () => {
1143
+ if (record.released)
1144
+ throw new TembraError2(Errors2.Released.Reference);
1145
+ if (session.closing)
1146
+ throw new TembraError2(Errors2.Gone.Reference);
1147
+ const object = session.objects.get(record.object);
1148
+ if (!object || object.disposing || object.error)
1149
+ throw new TembraError2(Errors2.Gone.Reference);
1150
+ if (!object.live)
1151
+ throw new TembraError2(Errors2.Unavailable.NotReady);
1152
+ };
1153
+ const target = {
1154
+ get ready() {
1155
+ return record.ready;
1156
+ },
1157
+ get status() {
1158
+ return record.released ? Status2.Released : recordSession.closing ? Status2.Gone : recordSession.kernel.command(KernelOp.Status, { reference: record.id });
1159
+ },
1160
+ get state() {
1161
+ check();
1162
+ const binding = recordSession.objects.get(record.object)?.binding;
1163
+ if (!binding)
1164
+ refuse(Errors2.Invalid.State, "Service does not expose state");
1165
+ return consumerState(binding, check, record.stateCleanups);
1166
+ },
1167
+ release: () => this.release(record.id),
1168
+ opaque: (name) => {
1169
+ check();
1170
+ const object = session.objects.get(record.object);
1171
+ const resource = object.versions.get(object.orb)?.resources.get(name);
1172
+ if (!resource?.options.opaque)
1173
+ throw new TembraError2(Errors2.Forbidden.Opaque, name);
1174
+ return resource.handle.value;
1175
+ }
1176
+ };
1177
+ const recordSession = session;
1178
+ const proxy = new Proxy(target, {
1179
+ get: (target, property, receiver) => {
1180
+ if (property === "then")
1181
+ return;
1182
+ if (Object.hasOwn(target, property))
1183
+ return Reflect.get(target, property, receiver);
1184
+ if (typeof property !== "string")
1185
+ return;
1186
+ if (!record.methods.has(property))
1187
+ return;
1188
+ return (...arguments_) => {
1189
+ let callContext = record.context;
1190
+ if (isContext(arguments_.at(-1)))
1191
+ callContext = arguments_.pop();
1192
+ return callContext ? session.calls.invoke(record, property, arguments_, context(callContext, session)) : session.calls.root((ctx) => session.calls.invoke(record, property, arguments_, ctx), false, undefined, record.address.principal);
1193
+ };
1194
+ }
1195
+ });
1196
+ references.set(proxy, { session, record });
1197
+ finalizer?.register(proxy, { session: new WeakRef(session), id: record.id }, record);
1198
+ return proxy;
1199
+ }
1200
+ service(definition, options) {
1201
+ if (typeof definition === "string")
1202
+ return { service: definition, options };
1203
+ const acquisition = serviceAcquisition(definition, options);
1204
+ return { service: acquisition.name, options: acquisition.options };
1205
+ }
1206
+ address(service, key, options, ctx) {
1207
+ return {
1208
+ service,
1209
+ key: typeof key === "string" ? [key] : [...key],
1210
+ principal: options.principal ?? ctx?.principal ?? this.session.principal
1211
+ };
1212
+ }
1213
+ closing(error, definition, key, options, ctx) {
1214
+ if (!(error instanceof TembraError2) || error.code !== Code2.Unavailable || error.reason !== Reason2.Disposing)
1215
+ return;
1216
+ let address;
1217
+ try {
1218
+ const resolved = this.service(definition, options);
1219
+ address = this.address(resolved.service, key, resolved.options, ctx);
1220
+ } catch {
1221
+ return;
1222
+ }
1223
+ for (const object of this.session.objects.values()) {
1224
+ const previous = object.address;
1225
+ if (object.disposing && previous.service === address.service && previous.principal === address.principal && previous.key.length === address.key.length && previous.key.every((part, index) => part === address.key[index]))
1226
+ return object.disposing;
1227
+ }
1228
+ return;
1229
+ }
1230
+ async get(service, key, options = {}, ctx) {
1231
+ let reference;
1232
+ let waited;
1233
+ for (;; ) {
1234
+ try {
1235
+ reference = this.hold(service, key, options, ctx);
1236
+ break;
1237
+ } catch (error) {
1238
+ const closing = this.closing(error, service, key, options, ctx);
1239
+ if (!closing || closing === waited)
1240
+ throw error;
1241
+ waited = closing;
1242
+ const settled = closing.then(() => {}, () => {});
1243
+ if (ctx)
1244
+ await this.session.calls.observe(settled, ctx.signal);
1245
+ else
1246
+ await settled;
1247
+ }
1248
+ }
1249
+ try {
1250
+ await reference.ready;
1251
+ return reference;
1252
+ } catch (error) {
1253
+ reference.release();
1254
+ throw error;
1255
+ }
1256
+ }
1257
+ duplicate(original) {
1258
+ if (this.session.references.get(original.id) !== original || original.released)
1259
+ throw new TembraError2(Errors2.Released.Reference);
1260
+ const id = this.session.kernel.command(KernelOp.Duplicate, { reference: original.id });
1261
+ const record = {
1262
+ ...original,
1263
+ id,
1264
+ address: { ...original.address, key: [...original.address.key] },
1265
+ methods: new Set(original.methods),
1266
+ requiredMethods: new Set(original.requiredMethods),
1267
+ stateCleanups: new Set,
1268
+ nativeOwned: false,
1269
+ released: false
1270
+ };
1271
+ delete record.context;
1272
+ this.session.references.set(id, record);
1273
+ let owned = this.#byObject.get(record.object);
1274
+ if (!owned)
1275
+ this.#byObject.set(record.object, owned = new Set);
1276
+ owned.add(record);
1277
+ return record;
1278
+ }
1279
+ reference(value) {
1280
+ const issued = typeof value === "object" && value !== null ? references.get(value) : undefined;
1281
+ if (!issued || issued.session !== this.session)
1282
+ refuse(Errors2.Invalid.Reference, "An issued local reference is required");
1283
+ return issued.record;
1284
+ }
1285
+ orbMetadata(id) {
1286
+ const definition = this.session.orbs.records.get(id)?.info;
1287
+ if (definition)
1288
+ return definition;
1289
+ let metadata = this.#metadata.get(id);
1290
+ if (!metadata) {
1291
+ metadata = this.session.kernel.command(KernelOp.Orb, { id });
1292
+ this.#metadata.set(id, metadata);
1293
+ }
1294
+ return metadata;
1295
+ }
1296
+ referenceMethods(record, methods, access, resetAccess = false) {
1297
+ const session = this.session;
1298
+ if (access && !session.kernel.features.views)
1299
+ throw new TembraError2(Errors2.Unsupported.Views);
1300
+ const allowed = access ? new Set(access(record.address.principal).methods) : undefined;
1301
+ const visible = new Set([...methods].filter((method) => (!record.requiredMethods.size || record.requiredMethods.has(method)) && (!allowed || allowed.has(method))));
1302
+ if (access || resetAccess && session.kernel.features.views)
1303
+ session.kernel.command(KernelOp.Restrict, {
1304
+ reference: record.id,
1305
+ methods: [...visible]
1306
+ });
1307
+ record.methods = visible;
1308
+ }
1309
+ refreshReferences(object, orb) {
1310
+ const session = this.session;
1311
+ const service = orb.definition.services?.[object.address.service];
1312
+ if (!service)
1313
+ return;
1314
+ const methods = Object.keys(service.methods);
1315
+ for (const reference of this.#byObject.get(object.id) ?? []) {
1316
+ if (reference.released)
1317
+ continue;
1318
+ if (reference.nativeOwned && !this.claimExists(reference.id)) {
1319
+ this.revoke(reference.id);
1320
+ continue;
1321
+ }
1322
+ try {
1323
+ this.referenceMethods(reference, methods, service.access, true);
1324
+ } catch (error) {
1325
+ reference.methods.clear();
1326
+ if (!reference.released && session.kernel.features.views)
1327
+ session.kernel.command(KernelOp.Restrict, { reference: reference.id, methods: [] });
1328
+ session.report(error);
1329
+ }
1330
+ }
1331
+ }
1332
+ claimExists(reference) {
1333
+ try {
1334
+ const status = this.session.kernel.command(KernelOp.Status, { reference });
1335
+ return status !== Status2.Released && status !== Status2.Gone;
1336
+ } catch (error) {
1337
+ if (error instanceof TembraError2 && (error.code === Code2.Gone || error.code === Code2.Released))
1338
+ return false;
1339
+ throw error;
1340
+ }
1341
+ }
1342
+ forget(record) {
1343
+ for (const cleanup of record.stateCleanups)
1344
+ cleanup();
1345
+ record.stateCleanups.clear();
1346
+ this.session.references.delete(record.id);
1347
+ const owned = this.#byObject.get(record.object);
1348
+ owned?.delete(record);
1349
+ if (!owned?.size)
1350
+ this.#byObject.delete(record.object);
1351
+ }
1352
+ release(id) {
1353
+ const session = this.session;
1354
+ const record = session.references.get(id);
1355
+ if (!record || record.released)
1356
+ return;
1357
+ record.released = true;
1358
+ finalizer?.unregister(record);
1359
+ if (session.lifecycle.closedDiagnostics) {
1360
+ this.forget(record);
1361
+ return;
1362
+ }
1363
+ session.kernel.command(KernelOp.Tick, { now: session.now() });
1364
+ session.kernel.command(KernelOp.Release, { reference: id });
1365
+ session.kernel.command(KernelOp.Forget, { reference: id });
1366
+ this.forget(record);
1367
+ session.lifecycle.flush();
1368
+ }
1369
+ revoke(id) {
1370
+ const record = this.session.references.get(id);
1371
+ if (!record)
1372
+ return;
1373
+ record.released = true;
1374
+ finalizer?.unregister(record);
1375
+ this.forget(record);
1376
+ }
1377
+ retire(orb) {
1378
+ this.#metadata.delete(orb);
1379
+ }
1380
+ clear() {
1381
+ for (const reference of this.session.references.values())
1382
+ this.forget(reference);
1383
+ this.session.references.clear();
1384
+ this.#byObject.clear();
1385
+ this.#metadata.clear();
1386
+ }
1387
+ }
1388
+
1389
+ // src/runtime/signals.ts
1390
+ function checkSignal(signal) {
1391
+ if (signal.aborted)
1392
+ throw signal.reason ?? new TembraError2(Errors2.Cancelled.Root);
1393
+ }
1394
+ function combinedSignal(owner, ended) {
1395
+ if (typeof AbortSignal.any === "function")
1396
+ return AbortSignal.any([owner, ended]);
1397
+ const controller = new AbortController;
1398
+ const detach = () => {
1399
+ owner.removeEventListener("abort", cancelOwner);
1400
+ ended.removeEventListener("abort", cancelEnded);
1401
+ };
1402
+ const cancelOwner = () => {
1403
+ detach();
1404
+ controller.abort(owner.reason);
1405
+ };
1406
+ const cancelEnded = () => {
1407
+ detach();
1408
+ controller.abort(ended.reason);
1409
+ };
1410
+ if (owner.aborted)
1411
+ cancelOwner();
1412
+ else if (ended.aborted)
1413
+ cancelEnded();
1414
+ else {
1415
+ owner.addEventListener("abort", cancelOwner, { once: true });
1416
+ ended.addEventListener("abort", cancelEnded, { once: true });
1417
+ }
1418
+ return controller.signal;
1419
+ }
1420
+
1421
+ export { associateServices, ContextKind2, ContextKey2, opaqueFrom2, shapes, lift, VALUE_LIMIT, Encoded, encode, check, checkedResult, reply, refusal, packet, Context, issuedContext, context, isContext, Values, protect, StateBinding, validate, Declaration, deferred, referenceOrigin, References, checkSignal, combinedSignal };