@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
package/dist/rpc.js CHANGED
@@ -1,630 +1,28 @@
1
- // src/bridge/identifiers.ts
2
- var Code = Object.freeze({
3
- Invalid: "invalid",
4
- Unavailable: "unavailable",
5
- Released: "released",
6
- Gone: "gone",
7
- Expired: "expired",
8
- Cancelled: "cancelled",
9
- Forbidden: "forbidden",
10
- Conflict: "conflict",
11
- Unsupported: "unsupported",
12
- Closed: "closed",
13
- Exhausted: "exhausted"
14
- });
15
- var Reason = Object.freeze({
16
- ActivationBusy: "activation_busy",
17
- Address: "address",
18
- AlreadyCommitted: "already_committed",
19
- AmbiguousScope: "ambiguous_scope",
20
- ApiVersion: "api_version",
21
- Arguments: "arguments",
22
- AsyncFactory: "async_factory",
23
- AsyncState: "async_state",
24
- Bigint: "bigint",
25
- ByteResult: "byte_result",
26
- Call: "call",
27
- Callback: "callback",
28
- CleanupBusy: "cleanup_busy",
29
- Clock: "clock",
30
- Codec: "codec",
31
- Connection: "connection",
32
- Context: "context",
33
- Contribution: "contribution",
34
- CoordinationLimits: "coordination_limits",
35
- Deadline: "deadline",
36
- Dependency: "dependency",
37
- DependencyCycle: "dependency_cycle",
38
- DependencyService: "dependency_service",
39
- Disposing: "disposing",
40
- Driver: "driver",
41
- Duplicate: "duplicate",
42
- DuplicateContribution: "duplicate_contribution",
43
- DuplicateListener: "duplicate_listener",
44
- DuplicateResource: "duplicate_resource",
45
- DuplicateService: "duplicate_service",
46
- EffectResults: "effect_results",
47
- EffectsRunning: "effects_running",
48
- EngineEffect: "engine_effect",
49
- EventSource: "event_source",
50
- ExclusiveDependent: "exclusive_dependent",
51
- Executor: "executor",
52
- Orb: "orb",
53
- OrbGone: "orb_gone",
54
- OrbInstalled: "orb_installed",
55
- OrbScope: "orb_scope",
56
- Factory: "factory",
57
- FactoryExpired: "factory_expired",
58
- FrameSize: "frame_size",
59
- GateBusy: "gate_busy",
60
- GateOrb: "gate_orb",
61
- GateObject: "gate_object",
62
- Hook: "hook",
63
- HookDependency: "hook_dependency",
64
- Hooks: "hooks",
65
- HooksDisabled: "hooks_disabled",
66
- Host: "host",
67
- HostAddress: "host_address",
68
- HostResource: "host_resource",
69
- HostResourceReload: "host_resource_reload",
70
- Identities: "identities",
71
- Implementation: "implementation",
72
- Invocation: "invocation",
73
- Javascript: "javascript",
74
- JsonAccessor: "json_accessor",
75
- JsonCycle: "json_cycle",
76
- JsonNumber: "json_number",
77
- JsonSymbol: "json_symbol",
78
- JsonTag: "json_tag",
79
- JsonType: "json_type",
80
- JsonValue: "json_value",
81
- Lifetime: "lifetime",
82
- Linger: "linger",
83
- ListenerCallback: "listener_callback",
84
- LiveConsumer: "live_consumer",
85
- LiveReference: "live_reference",
86
- LocalValue: "local_value",
87
- Memory: "memory",
88
- Metadata: "metadata",
89
- MetadataSize: "metadata_size",
90
- Method: "method",
91
- MigrationGate: "migration_gate",
92
- MigrationRequired: "migration_required",
93
- MigrationValue: "migration_value",
94
- MissingHook: "missing_hook",
95
- MissingMethod: "missing_method",
96
- NativeEffect: "native_effect",
97
- NativeMethod: "native_method",
98
- NativeObject: "native_object",
99
- NativeService: "native_service",
100
- Next: "next",
101
- NextUsed: "next_used",
102
- NotReady: "not_ready",
103
- Object: "object",
104
- ObjectState: "object_state",
105
- ObservationSource: "observation_source",
106
- ObservationAdmitted: "observation_admitted",
107
- Opaque: "opaque",
108
- Operation: "operation",
109
- OperationOwner: "operation_owner",
110
- Owner: "owner",
111
- Payload: "payload",
112
- PendingRequests: "pending_requests",
113
- PrepareDeadline: "prepare_deadline",
114
- Priority: "priority",
115
- Program: "program",
116
- ProgramPhase: "program_phase",
117
- ProgramRunning: "program_running",
118
- Reference: "reference",
119
- ReloadAborted: "reload_aborted",
120
- ReloadDeadline: "reload_deadline",
121
- ReloadPreparing: "reload_preparing",
122
- ReloadRunning: "reload_running",
123
- ReloadTicket: "reload_ticket",
124
- RemoteOpaque: "remote_opaque",
125
- RemoteReferences: "remote_references",
126
- Request: "request",
127
- RequestIds: "request_ids",
128
- Requires: "requires",
129
- Resource: "resource",
130
- ResourceDependencies: "resource_dependencies",
131
- ResourceDependency: "resource_dependency",
132
- ResourceHost: "resource_host",
133
- ResourceInFactory: "resource_in_factory",
134
- ResourceState: "resource_state",
135
- ResourceVersion: "resource_version",
136
- Result: "result",
137
- RetainedVersions: "retained_versions",
138
- RevisionExhausted: "revision_exhausted",
139
- Root: "root",
140
- Route: "route",
141
- RpcFrame: "rpc_frame",
142
- RpcOperation: "rpc_operation",
143
- RpcRequest: "rpc_request",
144
- RustType: "rust_type",
145
- Scope: "scope",
146
- ScopeClosed: "scope_closed",
147
- ScopeOrb: "scope_orb",
148
- ScopeOwner: "scope_owner",
149
- ScopeResource: "scope_resource",
150
- Serialization: "serialization",
151
- Service: "service",
152
- ServiceGone: "service_gone",
153
- State: "state",
154
- StateCycle: "state_cycle",
155
- StateInitialized: "state_initialized",
156
- StateOwner: "state_owner",
157
- StateRevision: "state_revision",
158
- StateValidation: "state_validation",
159
- StateValue: "state_value",
160
- StateVersion: "state_version",
161
- Subscription: "subscription",
162
- SubscriptionBusy: "subscription_busy",
163
- SubscriptionIdle: "subscription_idle",
164
- SubscriptionQueue: "subscription_queue",
165
- SubscriptionSize: "subscription_size",
166
- SubscriptionsDisabled: "subscriptions_disabled",
167
- Superseded: "superseded",
168
- Task: "task",
169
- Telemetry: "telemetry",
170
- UndeclaredDependency: "undeclared_dependency",
171
- UndeclaredService: "undeclared_service",
172
- UnknownService: "unknown_service",
173
- UpgradeConflict: "upgrade_conflict",
174
- Utf8: "utf8",
175
- Value: "value",
176
- ValueGone: "value_gone",
177
- ValuesExhausted: "values_exhausted",
178
- Views: "views"
179
- });
180
- var Lifetime = Object.freeze({
181
- Referenced: "referenced",
182
- Host: "host"
183
- });
184
- var Status = Object.freeze({
185
- Loading: "loading",
186
- Live: "live",
187
- Released: "released",
188
- Gone: "gone"
189
- });
190
- var ReloadStatus = Object.freeze({
191
- Prepared: "prepared",
192
- Committed: "committed",
193
- Aborted: "aborted"
194
- });
195
- var HookCapability = Object.freeze({
196
- Observe: "observe",
197
- Transform: "transform",
198
- Decide: "decide"
199
- });
200
-
201
- // src/bridge/protocol.ts
202
- var KernelOp = Object.freeze({
203
- ContextDerive: "context-derive",
204
- ContextValue: "context-value",
205
- ContextStats: "context-stats",
206
- Allocate: "allocate",
207
- ScopeRegister: "scope-register",
208
- ScopeExists: "scope-exists",
209
- ScopesForOwner: "scopes-for-owner",
210
- ScopesForOrb: "scopes-for-orb",
211
- ScopeAddResource: "scope-add-resource",
212
- ScopeActivate: "scope-activate",
213
- ScopesCleanup: "scopes-cleanup",
214
- ScopesReloadRegistered: "scopes-reload-registered",
215
- ScopesReload: "scopes-reload",
216
- ProgramRun: "program-run",
217
- ProgramNext: "program-next",
218
- ProgramCompleteStep: "program-complete-step",
219
- ProgramCommit: "program-commit",
220
- ProgramAbort: "program-abort",
221
- ProgramForget: "program-forget",
222
- Features: "features",
223
- Prepare: "prepare",
224
- Gate: "gate",
225
- GateOrbs: "gate-orbs",
226
- Commit: "commit",
227
- Abort: "abort",
228
- Orbs: "orbs",
229
- Orb: "orb",
230
- OrbNamed: "orb-named",
231
- NextDeadline: "next-deadline",
232
- Address: "address",
233
- Acquire: "acquire",
234
- Ready: "ready",
235
- Dependency: "dependency",
236
- Undepend: "undepend",
237
- Fail: "fail",
238
- Status: "status",
239
- Release: "release",
240
- Forget: "forget",
241
- Root: "root",
242
- CleanupRoot: "cleanup-root",
243
- RootPrincipal: "root-principal",
244
- CheckContext: "check-context",
245
- CheckRoot: "check-root",
246
- EndRoot: "end-root",
247
- CancelRoot: "cancel-root",
248
- BeginCall: "begin-call",
249
- BeginOperation: "begin-operation",
250
- BeginHookObservation: "begin-hook-observation",
251
- FinishCall: "finish-call",
252
- Invocation: "invocation",
253
- StateInit: "state-init",
254
- Snapshot: "snapshot",
255
- StateAdopt: "state-adopt",
256
- Task: "task",
257
- TaskRoot: "task-root",
258
- StopTask: "stop-task",
259
- FinishTask: "finish-task",
260
- Resource: "resource",
261
- ResourceOpened: "resource-opened",
262
- ResourceValue: "resource-value",
263
- CloseResource: "close-resource",
264
- ResourceClosed: "resource-closed",
265
- Disposed: "disposed",
266
- Tick: "tick",
267
- NextWake: "next-wake",
268
- NextIdle: "next-idle",
269
- Close: "close",
270
- FinishClose: "finish-close",
271
- Diagnostics: "diagnostics",
272
- Drain: "drain",
273
- Restrict: "restrict",
274
- Contribute: "contribute",
275
- ContributionOrdinal: "contribution-ordinal",
276
- HookPlan: "hook-plan",
277
- Listen: "listen",
278
- Subscribe: "subscribe",
279
- Enqueue: "enqueue",
280
- NextDelivery: "next-delivery",
281
- FinishDelivery: "finish-delivery",
282
- Unsubscribe: "unsubscribe"
283
- });
284
- var ActionType = Object.freeze({
285
- Execute: "execute",
286
- CancelEffects: "cancel-effects",
287
- ProgramPrepared: "program-prepared",
288
- ProgramComplete: "program-complete",
289
- Dispose: "dispose",
290
- CloseResource: "close-resource",
291
- DropValue: "drop-value",
292
- CancelRoot: "cancel-root",
293
- CancelTask: "cancel-task",
294
- RetireOrb: "retire-orb",
295
- State: "state",
296
- SubscriptionFailed: "subscription-failed",
297
- DetachSubscription: "detach-subscription",
298
- Deliver: "deliver"
299
- });
300
- var EffectType = Object.freeze({
301
- Stop: "stop",
302
- Open: "open",
303
- Close: "close",
304
- Restore: "restore",
305
- Prepare: "prepare",
306
- Validate: "validate",
307
- Initialize: "initialize",
308
- Migrate: "migrate",
309
- Adopt: "adopt",
310
- Start: "start",
311
- Drop: "drop"
312
- });
313
- var StepType = Object.freeze({
314
- Execute: "execute",
315
- Wait: "wait",
316
- Prepared: "prepared",
317
- Complete: "complete",
318
- Failed: "failed"
319
- });
320
- var NativeOp = Object.freeze({
321
- Activate: "activate",
322
- Dispose: "dispose",
323
- CancelEffect: "cancel-effect",
324
- Effect: "effect",
325
- Invoke: "invoke",
326
- Contribute: "contribute"
327
- });
328
- var RpcOp = Object.freeze({
329
- Describe: "describe",
330
- Get: "get",
331
- Release: "release",
332
- Call: "call",
333
- Cancel: "cancel"
334
- });
335
- var RpcEvent = Object.freeze({
336
- State: "state"
337
- });
338
- var OwnerKind = Object.freeze({
339
- Host: "host",
340
- Orb: "orb",
341
- Object: "object"
342
- });
343
- var EnvironmentPhase = Object.freeze({
344
- Declaring: "declaring",
345
- Prepared: "prepared",
346
- Live: "live",
347
- Closed: "closed"
348
- });
349
- var CoordinationDecision = Object.freeze({
350
- Preparing: "preparing",
351
- Commit: "commit",
352
- Abort: "abort"
353
- });
354
- var Outcome = Object.freeze({
355
- Ok: "ok",
356
- Error: "error"
357
- });
358
- var CodecTag = Object.freeze({
359
- Bigint: "bigint",
360
- Bytes: "bytes",
361
- Object: "object"
362
- });
363
- var CodecId = Object.freeze({
364
- Json: "tembra-json/1",
365
- MessagePack: "tembra-msgpack/1"
366
- });
367
-
368
- // src/errors.ts
369
- function define(code, reason, message) {
370
- return Object.freeze({ code, reason, message });
371
- }
372
- var Errors = Object.freeze({
373
- Cancelled: Object.freeze({
374
- EngineEffect: define(Code.Cancelled, Reason.EngineEffect, "The engine effect was cancelled"),
375
- Request: define(Code.Cancelled, Reason.Request, "The request was cancelled"),
376
- Resource: define(Code.Cancelled, Reason.Resource, "Resource opening was cancelled"),
377
- Root: define(Code.Cancelled, Reason.Root, "The operation was cancelled"),
378
- Task: define(Code.Cancelled, Reason.Task, "The task was cancelled")
379
- }),
380
- Closed: Object.freeze({
381
- Host: define(Code.Closed, Reason.Host, "The host is closing")
382
- }),
383
- Conflict: Object.freeze({
384
- AlreadyCommitted: define(Code.Conflict, Reason.AlreadyCommitted, "The replacement is already committed"),
385
- Codec: define(Code.Conflict, Reason.Codec, "The Rust and JS host codecs must agree"),
386
- PrepareDeadline: define(Code.Conflict, Reason.PrepareDeadline, "The preparation deadline expired"),
387
- ReloadRunning: define(Code.Conflict, Reason.ReloadRunning, "A replacement is already running"),
388
- ReloadTicket: define(Code.Conflict, Reason.ReloadTicket, "The replacement is no longer prepared")
389
- }),
390
- Exhausted: Object.freeze({
391
- FrameSize: define(Code.Exhausted, Reason.FrameSize, "The frame exceeds the configured size limit"),
392
- PendingRequests: define(Code.Exhausted, Reason.PendingRequests, "The pending request limit was reached"),
393
- RemoteReferences: define(Code.Exhausted, Reason.RemoteReferences, "The remote reference limit was reached"),
394
- RequestIds: define(Code.Exhausted, Reason.RequestIds, "Request identities are exhausted"),
395
- SubscriptionQueue: define(Code.Exhausted, Reason.SubscriptionQueue, "The subscription queue is full")
396
- }),
397
- Expired: Object.freeze({
398
- Next: define(Code.Expired, Reason.Next, "Continuation scope has ended")
399
- }),
400
- Forbidden: Object.freeze({
401
- Context: define(Code.Forbidden, Reason.Context, "An issued context from this host is required"),
402
- HostResource: define(Code.Forbidden, Reason.HostResource, "The host resource was not declared"),
403
- Method: define(Code.Forbidden, Reason.Method, "The method is not allowed by this reference"),
404
- ObservationSource: define(Code.Forbidden, Reason.ObservationSource, "Hook observation requires the original physical invocation"),
405
- Opaque: define(Code.Forbidden, Reason.Opaque, "The resource is not available as an opaque local value"),
406
- Service: define(Code.Forbidden, Reason.Service, "Access to this service is forbidden"),
407
- StateOwner: define(Code.Forbidden, Reason.StateOwner, "Only the owning orb may change this state"),
408
- UndeclaredDependency: define(Code.Forbidden, Reason.UndeclaredDependency, "The dependency was not declared"),
409
- UndeclaredService: define(Code.Forbidden, Reason.UndeclaredService, "The service was not declared as a dependency")
410
- }),
411
- Gone: Object.freeze({
412
- Connection: define(Code.Gone, Reason.Connection, "The connection is closed"),
413
- Contribution: define(Code.Gone, Reason.Contribution, "The contribution is no longer available"),
414
- Implementation: define(Code.Gone, Reason.Implementation, "The implementation is no longer available"),
415
- ListenerCallback: define(Code.Gone, Reason.ListenerCallback, "The listener callback is no longer available"),
416
- Reference: define(Code.Gone, Reason.Reference, "The reference is no longer available"),
417
- Resource: define(Code.Gone, Reason.Resource, "The resource is no longer available"),
418
- Scope: define(Code.Gone, Reason.Scope, "The declaration scope is no longer available"),
419
- State: define(Code.Gone, Reason.State, "State owner is gone")
420
- }),
421
- Invalid: Object.freeze({
422
- Address: define(Code.Invalid, Reason.Address, "Invalid address"),
423
- AsyncFactory: define(Code.Invalid, Reason.AsyncFactory, "Factories must be synchronous"),
424
- AsyncState: define(Code.Invalid, Reason.AsyncState, "State updates and migrations must be synchronous"),
425
- CoordinationLimits: define(Code.Invalid, Reason.CoordinationLimits, "Invalid coordination limits"),
426
- DependencyCycle: define(Code.Invalid, Reason.DependencyCycle, "Orb factories cannot acquire their own services"),
427
- DependencyService: define(Code.Invalid, Reason.DependencyService, "Invalid dependency service"),
428
- DuplicateListener: define(Code.Invalid, Reason.DuplicateListener, "Invalid duplicate listener"),
429
- DuplicateResource: define(Code.Invalid, Reason.DuplicateResource, "Invalid duplicate resource"),
430
- EventSource: define(Code.Invalid, Reason.EventSource, "Invalid event source"),
431
- Orb: define(Code.Invalid, Reason.Orb, "An orb needs a name and positive API version"),
432
- OrbGone: define(Code.Invalid, Reason.OrbGone, "Invalid orb gone"),
433
- OrbInstalled: define(Code.Invalid, Reason.OrbInstalled, "Use reload to replace an installed orb"),
434
- Factory: define(Code.Invalid, Reason.Factory, "Invalid factory"),
435
- FactoryExpired: define(Code.Invalid, Reason.FactoryExpired, "Declarations must be synchronous"),
436
- Hook: define(Code.Invalid, Reason.Hook, "Hooks need a run function"),
437
- HookDependency: define(Code.Invalid, Reason.HookDependency, "Invalid hook dependency"),
438
- HooksDisabled: define(Code.Invalid, Reason.HooksDisabled, "Invalid hooks disabled"),
439
- JsonAccessor: define(Code.Invalid, Reason.JsonAccessor, "Invalid json accessor"),
440
- JsonCycle: define(Code.Invalid, Reason.JsonCycle, "Invalid json cycle"),
441
- JsonNumber: define(Code.Invalid, Reason.JsonNumber, "Use BigInt for integers outside the safe Number range"),
442
- JsonSymbol: define(Code.Invalid, Reason.JsonSymbol, "Invalid json symbol"),
443
- JsonTag: define(Code.Invalid, Reason.JsonTag, "Unknown or malformed portable type tag"),
444
- JsonType: define(Code.Invalid, Reason.JsonType, "Supply a codec for custom object types"),
445
- JsonValue: define(Code.Invalid, Reason.JsonValue, "This JSON codec requires explicit portable values"),
446
- Method: define(Code.Invalid, Reason.Method, "Methods must be functions"),
447
- NextUsed: define(Code.Invalid, Reason.NextUsed, "Invalid next used"),
448
- Priority: define(Code.Invalid, Reason.Priority, "Invalid priority"),
449
- Reference: define(Code.Invalid, Reason.Reference, "An issued local reference is required"),
450
- Resource: define(Code.Invalid, Reason.Resource, "Invalid resource"),
451
- ResourceHost: define(Code.Invalid, Reason.ResourceHost, "Resource dependencies must belong to the same host"),
452
- ResourceInFactory: define(Code.Invalid, Reason.ResourceInFactory, "Resources open after declaration"),
453
- RpcFrame: define(Code.Invalid, Reason.RpcFrame, "Invalid rpc frame"),
454
- RpcOperation: define(Code.Invalid, Reason.RpcOperation, "Invalid rpc operation"),
455
- RpcRequest: define(Code.Invalid, Reason.RpcRequest, "Invalid rpc request"),
456
- Service: define(Code.Invalid, Reason.Service, "Invalid service"),
457
- ServiceGone: define(Code.Invalid, Reason.ServiceGone, "Invalid service gone"),
458
- State: define(Code.Invalid, Reason.State, "Service does not expose state"),
459
- StateCycle: define(Code.Invalid, Reason.StateCycle, "State cannot contain cycles"),
460
- StateValidation: define(Code.Invalid, Reason.StateValidation, "The orb rejected the state candidate"),
461
- StateValue: define(Code.Invalid, Reason.StateValue, "State cannot contain accessors"),
462
- StateVersion: define(Code.Invalid, Reason.StateVersion, "Invalid state version"),
463
- SubscriptionsDisabled: define(Code.Invalid, Reason.SubscriptionsDisabled, "Invalid subscriptions disabled"),
464
- SubscriptionSize: define(Code.Invalid, Reason.SubscriptionSize, "A local byte budget requires an explicit sizeOf function"),
465
- Task: define(Code.Invalid, Reason.Task, "Invalid task"),
466
- Utf8: define(Code.Invalid, Reason.Utf8, "Invalid utf8"),
467
- ValueGone: define(Code.Invalid, Reason.ValueGone, "Invalid value gone"),
468
- ValuesExhausted: define(Code.Invalid, Reason.ValuesExhausted, "Invalid values exhausted")
469
- }),
470
- Released: Object.freeze({
471
- Reference: define(Code.Released, Reason.Reference, "The reference has been released")
472
- }),
473
- Unavailable: Object.freeze({
474
- Callback: define(Code.Unavailable, Reason.Callback, "A callback failed"),
475
- OrbScope: define(Code.Unavailable, Reason.OrbScope, "The orb scope is unavailable"),
476
- NotReady: define(Code.Unavailable, Reason.NotReady, "The object is not ready"),
477
- Route: define(Code.Unavailable, Reason.Route, "The route is unavailable")
478
- }),
479
- Unsupported: Object.freeze({
480
- EngineEffect: define(Code.Unsupported, Reason.EngineEffect, "The engine effect is not supported by this adapter"),
481
- RemoteOpaque: define(Code.Unsupported, Reason.RemoteOpaque, "Opaque resources are local to their language environment"),
482
- Telemetry: define(Code.Unsupported, Reason.Telemetry, "Telemetry is disabled in this kernel"),
483
- Views: define(Code.Unsupported, Reason.Views, "Reference views are disabled in this kernel")
484
- })
485
- });
486
-
487
- // src/error.ts
488
- var codes = new Set(Object.values(Code));
489
- function isDescriptor(value) {
490
- return typeof value === "object" && value !== null && "code" in value && codes.has(value.code) && "reason" in value && typeof value.reason === "string" && "message" in value && typeof value.message === "string";
491
- }
492
-
493
- class TembraError extends Error {
494
- code;
495
- reason;
496
- constructor(error, message = error.message, options) {
497
- super(message, options);
498
- this.name = "TembraError";
499
- this.code = error.code;
500
- this.reason = error.reason;
501
- }
502
- }
503
- function failure(error) {
504
- let message = Errors.Unavailable.Callback.message;
505
- try {
506
- if (error instanceof TembraError)
507
- return error;
508
- if (isDescriptor(error))
509
- return new TembraError(error, error.message, { cause: error });
510
- message = String(error instanceof Error ? error.message : error);
511
- } catch {}
512
- return new TembraError(Errors.Unavailable.Callback, message, { cause: error });
513
- }
514
- function refuse(error, message = error.message) {
515
- throw new TembraError(error, message);
516
- }
517
-
518
- // src/codecs/json.ts
519
- var marker = "$tembra";
520
- function pack(value, visiting) {
521
- if (typeof value === "bigint")
522
- return { [marker]: [CodecTag.Bigint, value.toString()] };
523
- if (value instanceof Uint8Array)
524
- return { [marker]: [CodecTag.Bytes, [...value]] };
525
- if (value === null || typeof value === "string" || typeof value === "boolean")
526
- return value;
527
- if (typeof value === "number") {
528
- if (!Number.isFinite(value) || Number.isInteger(value) && !Number.isSafeInteger(value))
529
- refuse(Errors.Invalid.JsonNumber, "Use BigInt for integers outside the safe Number range");
530
- return value;
531
- }
532
- if (typeof value !== "object")
533
- refuse(Errors.Invalid.JsonValue, "This JSON codec requires explicit portable values");
534
- if (visiting.has(value))
535
- refuse(Errors.Invalid.JsonCycle);
536
- const prototype = Object.getPrototypeOf(value);
537
- if (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null)
538
- refuse(Errors.Invalid.JsonType, "Supply a codec for custom object types");
539
- visiting.add(value);
540
- try {
541
- if (Array.isArray(value))
542
- return Array.from(value, (child) => pack(child, visiting));
543
- const entries = Reflect.ownKeys(value).map((key) => {
544
- if (typeof key !== "string")
545
- refuse(Errors.Invalid.JsonSymbol);
546
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
547
- if (!Object.hasOwn(descriptor, "value"))
548
- refuse(Errors.Invalid.JsonAccessor);
549
- return [key, pack(descriptor.value, visiting)];
550
- });
551
- return Object.hasOwn(value, marker) ? { [marker]: [CodecTag.Object, entries] } : Object.fromEntries(entries);
552
- } finally {
553
- visiting.delete(value);
554
- }
555
- }
556
- function unpack(value) {
557
- if (value === null || typeof value !== "object") {
558
- if (typeof value === "number" && Number.isInteger(value) && !Number.isSafeInteger(value))
559
- refuse(Errors.Invalid.JsonNumber);
560
- return value;
561
- }
562
- if (Array.isArray(value))
563
- return value.map(unpack);
564
- if (Object.hasOwn(value, marker)) {
565
- const tag = value[marker];
566
- if (Object.keys(value).length !== 1 || !Array.isArray(tag) || tag.length !== 2)
567
- refuse(Errors.Invalid.JsonTag);
568
- const [type, data] = tag;
569
- if (type === CodecTag.Bigint && typeof data === "string" && /^-?(0|[1-9]\d*)$/.test(data))
570
- return BigInt(data);
571
- if (type === CodecTag.Bytes && Array.isArray(data) && data.every((v) => Number.isInteger(v) && v >= 0 && v <= 255))
572
- return Uint8Array.from(data);
573
- if (type === CodecTag.Object && Array.isArray(data)) {
574
- if (!data.every((entry) => Array.isArray(entry) && entry.length === 2 && typeof entry[0] === "string"))
575
- refuse(Errors.Invalid.JsonTag);
576
- return Object.fromEntries(data.map(([key, child]) => [key, unpack(child)]));
577
- }
578
- refuse(Errors.Invalid.JsonTag, "Unknown or malformed portable type tag");
579
- }
580
- return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, unpack(child)]));
581
- }
582
- function utf8(text) {
583
- const output = [];
584
- for (const character of text) {
585
- let point = character.codePointAt(0);
586
- if (point >= 55296 && point <= 57343)
587
- point = 65533;
588
- if (point < 128)
589
- output.push(point);
590
- else if (point < 2048)
591
- output.push(192 | point >> 6, 128 | point & 63);
592
- else if (point < 65536)
593
- output.push(224 | point >> 12, 128 | point >> 6 & 63, 128 | point & 63);
594
- else
595
- output.push(240 | point >> 18, 128 | point >> 12 & 63, 128 | point >> 6 & 63, 128 | point & 63);
596
- }
597
- return Uint8Array.from(output);
598
- }
599
- function text(bytes) {
600
- const output = [];
601
- for (let index = 0;index < bytes.length; ) {
602
- const first = bytes[index++];
603
- if (first < 128) {
604
- output.push(String.fromCharCode(first));
605
- continue;
606
- }
607
- const count = first >= 194 && first <= 223 ? 1 : first >= 224 && first <= 239 ? 2 : first >= 240 && first <= 244 ? 3 : -1;
608
- if (count < 0 || index + count > bytes.length)
609
- refuse(Errors.Invalid.Utf8);
610
- let point = first & 127 >> count + 1;
611
- for (let offset = 0;offset < count; offset++) {
612
- const next = bytes[index++];
613
- if ((next & 192) !== 128)
614
- refuse(Errors.Invalid.Utf8);
615
- point = point << 6 | next & 63;
616
- }
617
- if (point < [0, 128, 2048, 65536][count] || point > 1114111 || point >= 55296 && point <= 57343)
618
- refuse(Errors.Invalid.Utf8);
619
- output.push(String.fromCodePoint(point));
620
- }
621
- return output.join("");
622
- }
623
- var jsonCodec = Object.freeze({
624
- id: CodecId.Json,
625
- serialize: (value) => utf8(JSON.stringify(pack(value, new WeakSet))),
626
- deserialize: (bytes) => unpack(JSON.parse(text(bytes)))
627
- });
1
+ import {
2
+ Code2,
3
+ Status2,
4
+ Errors2,
5
+ TembraError2,
6
+ failure
7
+ } from "./chunks/index-c1w7z9hx.js";
8
+ import {
9
+ RpcOp,
10
+ RpcEvent
11
+ } from "./chunks/index-kr4x67wt.js";
12
+ import {
13
+ jsonCodec2
14
+ } from "./chunks/index-sse8aapb.js";
15
+ import {
16
+ encode,
17
+ protect,
18
+ checkSignal
19
+ } from "./chunks/index-kyt9dj0a.js";
20
+ import {
21
+ bindWitReference
22
+ } from "./chunks/index-3fjdfdfd.js";
23
+ import {
24
+ ResourceOwner
25
+ } from "./chunks/index-hfds9mzp.js";
628
26
 
629
27
  // src/infrastructure/rpc/channel.ts
630
28
  function errorValue(error) {
@@ -645,7 +43,7 @@ class Channel {
645
43
  this.transport = transport;
646
44
  this.options = options;
647
45
  this.ended = ended;
648
- this.codec = options.codec ?? jsonCodec;
46
+ this.codec = options.codec ?? jsonCodec2;
649
47
  this.maxFrame = options.maxFrame ?? 1024 * 1024;
650
48
  this.maxPending = options.maxPending ?? 128;
651
49
  this.#detach = transport.listen((frame) => {
@@ -653,10 +51,10 @@ class Channel {
653
51
  return;
654
52
  try {
655
53
  if (frame.length > this.maxFrame)
656
- throw new TembraError(Errors.Exhausted.FrameSize);
54
+ throw new TembraError2(Errors2.Exhausted.FrameSize);
657
55
  const message = this.codec.deserialize(frame);
658
56
  if (!message || typeof message !== "object" || Array.isArray(message))
659
- throw new TembraError(Errors.Invalid.RpcFrame);
57
+ throw new TembraError2(Errors2.Invalid.RpcFrame);
660
58
  receive(message);
661
59
  } catch (error) {
662
60
  this.#report(error);
@@ -671,13 +69,13 @@ class Channel {
671
69
  }
672
70
  async send(message) {
673
71
  if (this.closed)
674
- throw new TembraError(Errors.Gone.Connection);
72
+ throw new TembraError2(Errors2.Gone.Connection);
675
73
  const frame = this.codec.serialize(message);
676
74
  if (frame.length > this.maxFrame)
677
- throw new TembraError(Errors.Exhausted.FrameSize);
75
+ throw new TembraError2(Errors2.Exhausted.FrameSize);
678
76
  await this.transport.send(frame);
679
77
  }
680
- close(error = new TembraError(Errors.Gone.Connection)) {
78
+ close(error = new TembraError2(Errors2.Gone.Connection)) {
681
79
  if (this.closed)
682
80
  return;
683
81
  this.closed = true;
@@ -696,40 +94,6 @@ class Channel {
696
94
  }
697
95
  }
698
96
 
699
- // src/values.ts
700
- var protectedValues = new WeakSet;
701
- function protect(value) {
702
- const visiting = new WeakSet;
703
- function visit(value) {
704
- if (value === null || typeof value !== "object") {
705
- if (["function", "symbol"].includes(typeof value))
706
- refuse(Errors.Invalid.StateValue, "State must contain plain data");
707
- return;
708
- }
709
- if (protectedValues.has(value))
710
- return;
711
- if (visiting.has(value))
712
- refuse(Errors.Invalid.StateCycle, "State cannot contain cycles");
713
- const proto = Object.getPrototypeOf(value);
714
- if (!Array.isArray(value) && proto !== Object.prototype && proto !== null)
715
- refuse(Errors.Invalid.StateValue, "State requires plain objects and arrays");
716
- visiting.add(value);
717
- for (const key of Reflect.ownKeys(value)) {
718
- if (typeof key !== "string")
719
- refuse(Errors.Invalid.StateValue, "State cannot contain symbol properties");
720
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
721
- if (!Object.hasOwn(descriptor, "value"))
722
- refuse(Errors.Invalid.StateValue, "State cannot contain accessors");
723
- visit(descriptor.value);
724
- }
725
- visiting.delete(value);
726
- Object.freeze(value);
727
- protectedValues.add(value);
728
- }
729
- visit(value);
730
- return value;
731
- }
732
-
733
97
  // src/infrastructure/rpc/state.ts
734
98
  class RemoteState {
735
99
  check;
@@ -786,12 +150,72 @@ class RemoteState {
786
150
  }
787
151
  }
788
152
 
153
+ // src/infrastructure/rpc/resources.ts
154
+ function resource(value) {
155
+ if (typeof value !== "object" || value === null)
156
+ throw new TembraError2(Errors2.Invalid.RpcFrame);
157
+ const item = value;
158
+ if (!Number.isSafeInteger(item.reference) || item.reference <= 0 || typeof item.token !== "string" || !/^[a-f0-9]{64}$/.test(item.token) || typeof item.interface !== "string" || typeof item.name !== "string" || typeof item.revision !== "string" || !/^[1-9][0-9]*$/.test(item.revision))
159
+ throw new TembraError2(Errors2.Invalid.RpcFrame);
160
+ return item;
161
+ }
162
+ function resourceBackend(remote, schema) {
163
+ if (remote.resources !== 1 || remote.signature !== schema.signature)
164
+ throw new TembraError2({
165
+ code: Code2.Unsupported,
166
+ reason: "capabilities",
167
+ message: "Matching WIT resource delivery is required"
168
+ });
169
+ return {
170
+ identity: remote.identity,
171
+ run(ctx, operation) {
172
+ if (ctx)
173
+ ctx.check();
174
+ return operation(ctx);
175
+ },
176
+ async invoke(method, _args, capture, ctx) {
177
+ if (!capture.receiver)
178
+ remote.check();
179
+ const receiver = capture.receiver ? resource(capture.receiver.redeem(remote.identity, 0, capture.receiver.nominal)) : undefined;
180
+ const owned = (capture.arguments?.owners ?? []).map((owner) => resource(owner.redeem(remote.identity, 0, owner.nominal)));
181
+ for (const owner of capture.arguments?.owners ?? [])
182
+ owner.take(remote.identity, owner.nominal);
183
+ capture.arguments?.accept();
184
+ try {
185
+ await remote.request({
186
+ reference: receiver?.reference ?? remote.reference,
187
+ method,
188
+ input: capture.input.text,
189
+ capabilities: { signature: schema.signature, receiver: receiver ?? null, owned }
190
+ }, capture, (value) => {
191
+ if (typeof value !== "object" || value === null || !Array.isArray(value.owned))
192
+ throw new TembraError2(Errors2.Invalid.RpcFrame);
193
+ const result = value;
194
+ if (typeof result.output !== "string")
195
+ throw new TembraError2(Errors2.Invalid.RpcFrame);
196
+ const descriptors = result.owned.map(resource);
197
+ if (new Set(descriptors.map((item) => item.reference)).size !== descriptors.length)
198
+ throw new TembraError2(Errors2.Invalid.RpcFrame);
199
+ capture.capabilities = descriptors.map((item) => new ResourceOwner({ interface: item.interface, name: item.name }, remote.identity, 0, item, () => remote.release(item)));
200
+ capture.output = encode(JSON.parse(result.output));
201
+ }, ctx?.signal);
202
+ } catch (error) {
203
+ for (const item of owned)
204
+ remote.release(item);
205
+ throw error;
206
+ }
207
+ }
208
+ };
209
+ }
210
+
789
211
  // src/infrastructure/rpc/client.ts
790
212
  class RemoteHost {
791
213
  channel;
792
214
  #next = 0;
793
215
  #pending = new Map;
794
216
  #states = new Map;
217
+ #releases = [];
218
+ #releaseBytes = 0;
795
219
  constructor(transport, options = {}) {
796
220
  this.channel = new Channel(transport, options, (message) => {
797
221
  if (message.event === RpcEvent.State) {
@@ -803,36 +227,81 @@ class RemoteHost {
803
227
  return;
804
228
  this.#pending.delete(message.id);
805
229
  if (message.error)
806
- pending.reject(new TembraError(message.error));
230
+ pending.reject(new TembraError2(message.error));
807
231
  else
808
232
  pending.resolve(message.ok);
233
+ this.#drainReleases();
809
234
  }, (error) => {
810
235
  for (const pending of this.#pending.values())
811
236
  pending.reject(error);
812
237
  this.#pending.clear();
238
+ for (const queued of this.#releases)
239
+ queued.reject(error);
240
+ this.#releases = [];
241
+ this.#releaseBytes = 0;
813
242
  this.#states.clear();
814
243
  });
815
244
  }
816
245
  request(op, payload, signal) {
817
- return this.#request(op, payload, signal);
246
+ return op === RpcOp.Release ? this.#queueRelease(payload, signal) : this.#request(op, payload, signal);
247
+ }
248
+ async#queueRelease(payload, signal) {
249
+ if (signal)
250
+ checkSignal(signal);
251
+ if (this.channel.closed)
252
+ throw new TembraError2(Errors2.Gone.Connection);
253
+ const bytes = this.channel.codec.serialize({ op: RpcOp.Release, payload }).length;
254
+ if (this.#releaseBytes + bytes > this.channel.maxFrame)
255
+ throw new TembraError2(Errors2.Exhausted.FrameSize);
256
+ return new Promise((resolve, reject) => {
257
+ this.#releases.push({ payload, bytes, signal, resolve, reject });
258
+ this.#releaseBytes += bytes;
259
+ this.#drainReleases();
260
+ });
261
+ }
262
+ #drainReleases() {
263
+ if (this.channel.closed)
264
+ return;
265
+ let pending = 0;
266
+ for (const item of this.#pending.values())
267
+ if (item.control)
268
+ pending++;
269
+ while (pending < this.channel.maxPending && this.#releases.length) {
270
+ const item = this.#releases.shift();
271
+ this.#releaseBytes -= item.bytes;
272
+ pending++;
273
+ this.#request(RpcOp.Release, item.payload, item.signal).then(item.resolve, item.reject).finally(() => this.#drainReleases());
274
+ }
818
275
  }
819
276
  async#request(op, payload, signal, received) {
820
- signal?.throwIfAborted();
821
- if (this.#pending.size >= this.channel.maxPending)
822
- throw new TembraError(Errors.Exhausted.PendingRequests);
277
+ if (signal)
278
+ checkSignal(signal);
279
+ const control = op === RpcOp.Release;
280
+ let pendingCount = 0;
281
+ for (const pending of this.#pending.values())
282
+ if (pending.control === control)
283
+ pendingCount++;
284
+ if (pendingCount >= this.channel.maxPending)
285
+ throw new TembraError2(Errors2.Exhausted.PendingRequests);
823
286
  const id = ++this.#next;
824
287
  if (!Number.isSafeInteger(id))
825
- throw new TembraError(Errors.Exhausted.RequestIds);
288
+ throw new TembraError2(Errors2.Exhausted.RequestIds);
826
289
  let abort;
827
290
  const result = new Promise((resolve, reject) => {
828
291
  const pending = {
292
+ control,
829
293
  resolve: (value) => {
830
294
  try {
831
295
  received?.(value);
296
+ if (op === RpcOp.Call && typeof payload === "object" && payload !== null && "capabilities" in payload && Array.isArray(value?.owned) && value.owned.length > 0) {
297
+ this.channel.send({ op: RpcOp.Accept, payload: { id } }).catch((error) => this.channel.close(error));
298
+ }
832
299
  resolve(value);
833
300
  } catch (error) {
834
301
  if (op === RpcOp.Get)
835
302
  this.#release(value?.reference);
303
+ else if (op === RpcOp.Call)
304
+ this.channel.close(error);
836
305
  reject(error);
837
306
  }
838
307
  },
@@ -842,19 +311,27 @@ class RemoteHost {
842
311
  abort = () => {
843
312
  if (this.#pending.get(id) !== pending)
844
313
  return;
845
- if (op === RpcOp.Get) {
314
+ if (op === RpcOp.Get || op === RpcOp.Call && typeof payload === "object" && payload !== null && "capabilities" in payload) {
846
315
  this.#pending.set(id, {
847
- resolve: (value) => this.#release(value?.reference),
316
+ control,
317
+ resolve: (value) => {
318
+ if (op === RpcOp.Get)
319
+ this.#release(value?.reference);
320
+ else
321
+ this.#releaseResult(value);
322
+ },
848
323
  reject: () => {}
849
324
  });
850
325
  } else {
851
326
  this.#pending.delete(id);
852
327
  }
853
- reject(signal?.reason ?? new TembraError(Errors.Cancelled.Request));
328
+ reject(signal?.reason ?? new TembraError2(Errors2.Cancelled.Request));
854
329
  this.channel.send({ op: RpcOp.Cancel, payload: { id } }).catch(() => {});
855
330
  };
856
331
  signal?.addEventListener("abort", abort, { once: true });
857
332
  this.channel.send({ id, op, payload }).catch((error) => {
333
+ if (op === RpcOp.Get || op === RpcOp.Call && typeof payload === "object" && payload !== null && "capabilities" in payload)
334
+ this.channel.close(error);
858
335
  if (this.#pending.get(id) !== pending)
859
336
  return;
860
337
  this.#pending.delete(id);
@@ -871,11 +348,21 @@ class RemoteHost {
871
348
  #release(reference) {
872
349
  if (!Number.isSafeInteger(reference) || reference <= 0 || this.channel.closed)
873
350
  return;
874
- this.request(RpcOp.Release, { reference }).catch((error) => {
875
- try {
876
- this.channel.options.onError?.(error);
877
- } catch {}
878
- });
351
+ this.request(RpcOp.Release, { reference }).catch((error) => this.channel.close(error));
352
+ }
353
+ #releaseResult(value) {
354
+ try {
355
+ if (typeof value === "object" && value !== null && "owned" in value && Array.isArray(value.owned))
356
+ for (const item of value.owned)
357
+ this.#releaseResource(resource(item));
358
+ } catch (error) {
359
+ this.channel.close(error);
360
+ }
361
+ }
362
+ #releaseResource(item) {
363
+ if (this.channel.closed)
364
+ return;
365
+ this.request(RpcOp.Release, { reference: item.reference, resource: item }).catch((error) => this.channel.close(error));
879
366
  }
880
367
  installedOrbs() {
881
368
  return this.request(RpcOp.Describe, null);
@@ -884,14 +371,14 @@ class RemoteHost {
884
371
  let released = false;
885
372
  const check = () => {
886
373
  if (released)
887
- throw new TembraError(Errors.Released.Reference);
374
+ throw new TembraError2(Errors2.Released.Reference);
888
375
  if (this.channel.closed)
889
- throw new TembraError(Errors.Gone.Connection);
376
+ throw new TembraError2(Errors2.Gone.Connection);
890
377
  };
891
378
  let state;
892
- const acquired = await this.#request(RpcOp.Get, { service, key: typeof key === "string" ? [key] : key }, options.signal, (value) => {
379
+ const acquired = await this.#request(RpcOp.Get, { service, key: typeof key === "string" ? [key] : key, resources: 1 }, options.signal, (value) => {
893
380
  if (!value || !Number.isSafeInteger(value.reference) || value.reference <= 0 || !Array.isArray(value.methods) || !value.methods.every((method) => typeof method === "string"))
894
- throw new TembraError(Errors.Invalid.RpcFrame);
381
+ throw new TembraError2(Errors2.Invalid.RpcFrame);
895
382
  if (Object.hasOwn(value, "state")) {
896
383
  state = new RemoteState(value.state, check, (error) => this.channel.options.onError?.(error));
897
384
  this.#states.set(value.reference, state);
@@ -901,12 +388,12 @@ class RemoteHost {
901
388
  const target = {
902
389
  ready: Promise.resolve(),
903
390
  get status() {
904
- return released ? Status.Released : peer.channel.closed ? Status.Gone : Status.Live;
391
+ return released ? Status2.Released : peer.channel.closed ? Status2.Gone : Status2.Live;
905
392
  },
906
393
  get state() {
907
394
  check();
908
395
  if (!state)
909
- throw new TembraError(Errors.Invalid.State);
396
+ throw new TembraError2(Errors2.Invalid.State);
910
397
  return state;
911
398
  },
912
399
  release: () => {
@@ -914,14 +401,14 @@ class RemoteHost {
914
401
  return;
915
402
  released = true;
916
403
  this.#states.delete(id);
917
- this.request(RpcOp.Release, { reference: id }).catch((error) => this.channel.options.onError?.(error));
404
+ this.#release(id);
918
405
  },
919
406
  opaque() {
920
- throw new TembraError(Errors.Unsupported.RemoteOpaque, "Opaque resources are local to their language environment");
407
+ throw new TembraError2(Errors2.Unsupported.RemoteOpaque, "Opaque resources are local to their language environment");
921
408
  }
922
409
  };
923
410
  const peer = this;
924
- return new Proxy(target, {
411
+ const reference = new Proxy(target, {
925
412
  get: (target, property, receiver) => {
926
413
  if (property === "then")
927
414
  return;
@@ -937,6 +424,16 @@ class RemoteHost {
937
424
  };
938
425
  }
939
426
  });
427
+ bindWitReference(reference, (schema) => resourceBackend({
428
+ identity: this,
429
+ reference: id,
430
+ resources: acquired.resources,
431
+ signature: acquired.signature,
432
+ check,
433
+ request: async (payload, _capture, received, signal) => this.#request(RpcOp.Call, payload, signal, received),
434
+ release: (item) => this.#releaseResource(item)
435
+ }, schema));
436
+ return reference;
940
437
  }
941
438
  close() {
942
439
  this.channel.close();
@@ -973,11 +470,11 @@ function serve(host, transport, options) {
973
470
  }
974
471
  const id = message.id;
975
472
  if (!Number.isSafeInteger(id) || !id || id <= 0 || !message.op) {
976
- channel.close(new TembraError(Errors.Invalid.RpcRequest));
473
+ channel.close(new TembraError2(Errors2.Invalid.RpcRequest));
977
474
  return;
978
475
  }
979
476
  if (pending >= channel.maxPending || requests.has(id)) {
980
- channel.send({ id, error: errorValue(new TembraError(Errors.Exhausted.PendingRequests)) }).catch(() => channel.close());
477
+ channel.send({ id, error: errorValue(new TembraError2(Errors2.Exhausted.PendingRequests)) }).catch(() => channel.close());
981
478
  return;
982
479
  }
983
480
  pending++;
@@ -990,17 +487,17 @@ function serve(host, transport, options) {
990
487
  return host.installedOrbs().map(({ describe, ...info }) => info);
991
488
  case RpcOp.Get: {
992
489
  if (typeof payload?.service !== "string" || !Array.isArray(payload.key) || !payload.key.every((key) => typeof key === "string"))
993
- throw new TembraError(Errors.Invalid.Address);
490
+ throw new TembraError2(Errors2.Invalid.Address);
994
491
  if (options.allow && !options.allow(payload.service, payload.key))
995
- throw new TembraError(Errors.Forbidden.Service);
492
+ throw new TembraError2(Errors2.Forbidden.Service);
996
493
  if (references.size >= channel.maxPending)
997
- throw new TembraError(Errors.Exhausted.RemoteReferences);
494
+ throw new TembraError2(Errors2.Exhausted.RemoteReferences);
998
495
  const reference = await host.get(payload.service, payload.key, {
999
496
  principal: options.principal
1000
497
  });
1001
498
  if (channel.closed || request.cancelled) {
1002
499
  reference.release();
1003
- throw new TembraError(Errors.Gone.Connection);
500
+ throw new TembraError2(Errors2.Gone.Connection);
1004
501
  }
1005
502
  const referenceId = ++next;
1006
503
  const methods = new Set(host.session.handles.reference(reference).methods);
@@ -1040,9 +537,9 @@ function serve(host, transport, options) {
1040
537
  case RpcOp.Call: {
1041
538
  const record = references.get(payload?.reference);
1042
539
  if (!record || typeof payload.method !== "string" || !record.methods.has(payload.method) || !Array.isArray(payload.arguments) || typeof record.reference[payload.method] !== "function")
1043
- throw new TembraError(Errors.Forbidden.Method);
540
+ throw new TembraError2(Errors2.Forbidden.Method);
1044
541
  if (request.cancelled)
1045
- throw new TembraError(Errors.Cancelled.Request);
542
+ throw new TembraError2(Errors2.Cancelled.Request);
1046
543
  return host.root(async (ctx) => {
1047
544
  calls.set(id, ctx);
1048
545
  try {
@@ -1053,7 +550,7 @@ function serve(host, transport, options) {
1053
550
  }, { principal: options.principal });
1054
551
  }
1055
552
  default:
1056
- throw new TembraError(Errors.Invalid.RpcOperation);
553
+ throw new TembraError2(Errors2.Invalid.RpcOperation);
1057
554
  }
1058
555
  })().then(async (ok) => {
1059
556
  await channel.send({ id, ok });