@syntropika/tembra-sdk 0.1.0 → 0.2.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.
@@ -3,7 +3,7 @@ import type { Environment } from "../runtime/records.ts";
3
3
  import type { Session } from "../runtime/session.ts";
4
4
  import type { Readable, State, StateOptions } from "../state.ts";
5
5
  import { StateBinding } from "../state.ts";
6
- import type { AcquisitionOptions, Completion, DynamicReference, EventSource, ListenerOptions, Resource, ResourceOptions, TaskScope } from "./types.ts";
6
+ import type { AcquisitionOptions, Completion, DynamicReference, EventSource, ListenerOptions, Resource, ResourceOptions, TaskScope, ServiceDefinition, ServiceReference } from "./types.ts";
7
7
  /** Available only during its synchronous factory pass. Issued handles remain usable afterwards. */
8
8
  export declare class Declaration {
9
9
  readonly session: Session;
@@ -21,6 +21,7 @@ export declare class Declaration {
21
21
  /** Declare object state with local validation and versioned migration. */
22
22
  state<T>(initial: T, options?: StateOptions<T>): State<T>;
23
23
  /** Orb factories cannot depend on their own services; object factories may use sibling services. */
24
+ get<const Service extends ServiceDefinition>(service: Service, key: string | readonly string[], options?: AcquisitionOptions): ServiceReference<Service>;
24
25
  get(service: string, key: string | readonly string[], options?: AcquisitionOptions): DynamicReference;
25
26
  /** Declare an owned resource, or access a named host resource. */
26
27
  resource<T>(name: string, options?: ResourceOptions<T>): Resource<T>;
@@ -0,0 +1,7 @@
1
+ import type { ServiceDefinition } from "./types.ts";
2
+ export interface ServiceIdentity {
3
+ readonly orb: string;
4
+ readonly name: string;
5
+ readonly apiVersion: number;
6
+ }
7
+ export declare const serviceIdentities: WeakMap<ServiceDefinition, ServiceIdentity>;
@@ -0,0 +1,8 @@
1
+ import type { AcquisitionOptions, ServiceDefinition } from "./types.ts";
2
+ /** Associate original and captured services only after the whole orb declaration succeeds. */
3
+ export declare function associateServices(orb: string, apiVersion: number, services: readonly (readonly [string, ServiceDefinition, ServiceDefinition])[]): void;
4
+ /** Resolve a declared service without changing the kernel's named acquisition or authority rules. */
5
+ export declare function serviceAcquisition(service: string | ServiceDefinition, options?: AcquisitionOptions): {
6
+ name: string;
7
+ options: AcquisitionOptions;
8
+ };
@@ -2,7 +2,7 @@ import { Lifetime, ReloadStatus, Status } from "../bridge/identifiers.ts";
2
2
  import type { Invocation, KernelOrb, KernelPort } from "../bridge/kernel.ts";
3
3
  import type { Codec } from "../codecs/json.ts";
4
4
  import type { Context } from "../runtime/context.ts";
5
- import type { Readable } from "../state.ts";
5
+ import type { Readable, State } from "../state.ts";
6
6
  import type { Declaration } from "./declaration.ts";
7
7
  export type Completion<T> = T | PromiseLike<T>;
8
8
  export type Handler = (environment: any, context: Context, ...arguments_: any[]) => unknown;
@@ -81,6 +81,20 @@ export interface ReferenceBase<T = unknown> {
81
81
  opaque<R = unknown>(name: string): R;
82
82
  }
83
83
  export type DynamicReference = ReferenceBase<any> & Record<string, any>;
84
+ type EnvironmentState<Environment> = 0 extends 1 & Environment ? unknown : Environment extends State<infer Value> ? Value : Environment extends object ? {
85
+ [Member in keyof Environment]-?: Environment[Member] extends State<infer Value> ? Value : never;
86
+ }[keyof Environment] : never;
87
+ type ServiceState<Service> = Service extends {
88
+ create: (...args: never[]) => infer Environment;
89
+ } ? [EnvironmentState<Environment>] extends [never] ? unknown : EnvironmentState<Environment> : unknown;
90
+ type ArgumentTail<Arguments extends unknown[]> = Arguments extends [] ? [] : Arguments extends [unknown?, ...infer Rest] ? Rest : [];
91
+ type BusinessArguments<Arguments extends unknown[]> = ArgumentTail<ArgumentTail<Arguments>>;
92
+ type CallArguments<Arguments extends unknown[]> = number extends Arguments["length"] ? Arguments | [...Arguments, Context] : [...Arguments, context?: Context];
93
+ type ConsumerMethod<Method> = Method extends (...args: infer Arguments) => infer Result ? (...args: CallArguments<BusinessArguments<Arguments>>) => Promise<Awaited<Result>> : never;
94
+ /** A managed reference inferred from one service's methods and explicitly returned State handles. */
95
+ export type ServiceReference<Service extends ServiceDefinition> = ReferenceBase<ServiceState<Service>> & {
96
+ [Method in Exclude<keyof Service["methods"], keyof ReferenceBase | "then">]: ConsumerMethod<Service["methods"][Method]>;
97
+ };
84
98
  export interface AcquisitionOptions {
85
99
  apiVersion?: number;
86
100
  methods?: readonly string[];
@@ -164,3 +178,4 @@ export interface OrbDescription extends KernelOrb {
164
178
  /** Read metadata without activating orb services. */
165
179
  describe(): Readonly<KernelOrb>;
166
180
  }
181
+ export {};
package/dist/browser.js CHANGED
@@ -348,6 +348,41 @@ function refuse(error, message = error.message) {
348
348
  throw new TembraError(error, message);
349
349
  }
350
350
 
351
+ // src/authoring/service-identities.ts
352
+ var identityKey = Symbol.for("@syntropika/tembra-sdk/service-identities");
353
+ var existing = Object.getOwnPropertyDescriptor(globalThis, identityKey)?.value;
354
+ if (existing !== undefined && !(existing instanceof WeakMap))
355
+ throw new TypeError("The SDK service identity slot must contain a WeakMap");
356
+ var serviceIdentities = existing instanceof WeakMap ? existing : new WeakMap;
357
+ if (existing === undefined)
358
+ Object.defineProperty(globalThis, identityKey, { value: serviceIdentities });
359
+
360
+ // src/authoring/services.ts
361
+ function associateServices(orb, apiVersion, services) {
362
+ const pending = new Map;
363
+ for (const [name, original, captured] of services) {
364
+ const identity = { orb, name, apiVersion };
365
+ for (const definition of [original, captured]) {
366
+ const previous = pending.get(definition) ?? serviceIdentities.get(definition);
367
+ if (previous && (previous.orb !== orb || previous.name !== name || previous.apiVersion !== apiVersion))
368
+ refuse(Errors.Invalid.Service, "A service definition must have one orb, name and API version");
369
+ pending.set(definition, identity);
370
+ }
371
+ }
372
+ for (const [definition, identity] of pending)
373
+ serviceIdentities.set(definition, identity);
374
+ }
375
+ function serviceAcquisition(service, options = {}) {
376
+ if (typeof service === "string")
377
+ return { name: service, options };
378
+ const identity = serviceIdentities.get(service);
379
+ if (!identity)
380
+ refuse(Errors.Invalid.Service, "Declare this service in an orb before acquiring it");
381
+ if (options.apiVersion !== undefined && options.apiVersion !== identity.apiVersion)
382
+ refuse(Errors.Invalid.Service, "The acquisition API version must match the service declaration");
383
+ return { name: identity.name, options: { ...options, apiVersion: identity.apiVersion } };
384
+ }
385
+
351
386
  // src/authoring/orb.ts
352
387
  function orb(definition) {
353
388
  if (!definition.name || !Number.isInteger(definition.apiVersion) || definition.apiVersion <= 0)
@@ -396,13 +431,19 @@ function orb(definition) {
396
431
  typeof contribution === "function" ? contribution : Object.freeze({ ...contribution })
397
432
  ])))
398
433
  ]));
399
- return Object.freeze({
434
+ const captured = Object.freeze({
400
435
  ...definition,
401
436
  services: Object.freeze(services),
402
437
  requires: Object.freeze(requires),
403
438
  hooks: Object.freeze(hooks),
404
439
  contributes: Object.freeze(contributes)
405
440
  });
441
+ associateServices(definition.name, definition.apiVersion, Object.entries(definition.services ?? {}).map(([name, original]) => [
442
+ name,
443
+ original,
444
+ services[name]
445
+ ]));
446
+ return captured;
406
447
  }
407
448
 
408
449
  // src/bridge/protocol.ts
@@ -929,20 +970,24 @@ class Declaration {
929
970
  }
930
971
  get(service, key, options = {}) {
931
972
  this.check();
932
- const requirement = this.session.scopes.requirement(this.environment, service);
973
+ const acquisition = serviceAcquisition(service, options);
974
+ const requirement = this.session.scopes.requirement(this.environment, acquisition.name);
933
975
  const resolved = requirement.service;
976
+ if (typeof service !== "string" && resolved !== acquisition.name)
977
+ refuse(Errors.Invalid.Service, "A typed dependency must resolve its declared service name");
934
978
  if (!this.environment.object && this.environment.orb.definition.services?.[resolved])
935
979
  refuse(Errors.Invalid.DependencyCycle);
936
- const identity = JSON.stringify([resolved, key, options.principal ?? this.principal]);
937
- const existing = this.environment.dependencies.get(identity);
938
- if (existing)
939
- return existing;
940
- const reference = this.session.handles.hold(resolved, key, {
980
+ const admitted = serviceAcquisition(service, {
941
981
  ...options,
942
982
  ...requirement.apiVersion ? { apiVersion: requirement.apiVersion } : {},
943
983
  ...requirement.methods ? { methods: requirement.methods } : {},
944
984
  principal: options.principal ?? this.principal
945
985
  });
986
+ const identity = JSON.stringify([resolved, key, options.principal ?? this.principal]);
987
+ const existing = this.environment.dependencies.get(identity);
988
+ if (existing)
989
+ return existing;
990
+ const reference = this.session.handles.hold(resolved, key, admitted.options);
946
991
  if (this.environment.object) {
947
992
  try {
948
993
  this.session.kernel.command(KernelOp.Dependency, {
@@ -2349,7 +2394,15 @@ class References {
2349
2394
  owned.add(record);
2350
2395
  return object.activation;
2351
2396
  }
2352
- hold(service, key, options = {}, ctx) {
2397
+ hold(definition, key, options = {}, ctx) {
2398
+ let service;
2399
+ if (typeof definition === "string")
2400
+ service = definition;
2401
+ else {
2402
+ const acquisition = serviceAcquisition(definition, options);
2403
+ service = acquisition.name;
2404
+ options = acquisition.options;
2405
+ }
2353
2406
  const session = this.session;
2354
2407
  if (ctx)
2355
2408
  context(ctx, session);
package/dist/embedded.js CHANGED
@@ -1 +1 @@
1
- (()=>{var l=Object.freeze({Invalid:"invalid",Unavailable:"unavailable",Released:"released",Gone:"gone",Expired:"expired",Cancelled:"cancelled",Forbidden:"forbidden",Conflict:"conflict",Unsupported:"unsupported",Closed:"closed",Exhausted:"exhausted"}),p=Object.freeze({ActivationBusy:"activation_busy",Address:"address",AlreadyCommitted:"already_committed",AmbiguousScope:"ambiguous_scope",ApiVersion:"api_version",Arguments:"arguments",AsyncFactory:"async_factory",AsyncState:"async_state",Bigint:"bigint",ByteResult:"byte_result",Call:"call",Callback:"callback",CleanupBusy:"cleanup_busy",Clock:"clock",Codec:"codec",Connection:"connection",Context:"context",Contribution:"contribution",CoordinationLimits:"coordination_limits",Deadline:"deadline",Dependency:"dependency",DependencyCycle:"dependency_cycle",DependencyService:"dependency_service",Disposing:"disposing",Driver:"driver",Duplicate:"duplicate",DuplicateContribution:"duplicate_contribution",DuplicateListener:"duplicate_listener",DuplicateResource:"duplicate_resource",DuplicateService:"duplicate_service",EffectResults:"effect_results",EffectsRunning:"effects_running",EngineEffect:"engine_effect",EventSource:"event_source",ExclusiveDependent:"exclusive_dependent",Executor:"executor",Orb:"orb",OrbGone:"orb_gone",OrbInstalled:"orb_installed",OrbScope:"orb_scope",Factory:"factory",FactoryExpired:"factory_expired",FrameSize:"frame_size",GateBusy:"gate_busy",GateOrb:"gate_orb",GateObject:"gate_object",Hook:"hook",HookDependency:"hook_dependency",Hooks:"hooks",HooksDisabled:"hooks_disabled",Host:"host",HostAddress:"host_address",HostResource:"host_resource",HostResourceReload:"host_resource_reload",Identities:"identities",Implementation:"implementation",Invocation:"invocation",Javascript:"javascript",JsonAccessor:"json_accessor",JsonCycle:"json_cycle",JsonNumber:"json_number",JsonSymbol:"json_symbol",JsonTag:"json_tag",JsonType:"json_type",JsonValue:"json_value",Lifetime:"lifetime",Linger:"linger",ListenerCallback:"listener_callback",LiveConsumer:"live_consumer",LiveReference:"live_reference",LocalValue:"local_value",Memory:"memory",Metadata:"metadata",MetadataSize:"metadata_size",Method:"method",MigrationGate:"migration_gate",MigrationRequired:"migration_required",MigrationValue:"migration_value",MissingHook:"missing_hook",MissingMethod:"missing_method",NativeEffect:"native_effect",NativeMethod:"native_method",NativeObject:"native_object",NativeService:"native_service",Next:"next",NextUsed:"next_used",NotReady:"not_ready",Object:"object",ObjectState:"object_state",ObservationSource:"observation_source",ObservationAdmitted:"observation_admitted",Opaque:"opaque",Operation:"operation",OperationOwner:"operation_owner",Owner:"owner",Payload:"payload",PendingRequests:"pending_requests",PrepareDeadline:"prepare_deadline",Priority:"priority",Program:"program",ProgramPhase:"program_phase",ProgramRunning:"program_running",Reference:"reference",ReloadAborted:"reload_aborted",ReloadDeadline:"reload_deadline",ReloadPreparing:"reload_preparing",ReloadRunning:"reload_running",ReloadTicket:"reload_ticket",RemoteOpaque:"remote_opaque",RemoteReferences:"remote_references",Request:"request",RequestIds:"request_ids",Requires:"requires",Resource:"resource",ResourceDependencies:"resource_dependencies",ResourceDependency:"resource_dependency",ResourceHost:"resource_host",ResourceInFactory:"resource_in_factory",ResourceState:"resource_state",ResourceVersion:"resource_version",Result:"result",RetainedVersions:"retained_versions",RevisionExhausted:"revision_exhausted",Root:"root",Route:"route",RpcFrame:"rpc_frame",RpcOperation:"rpc_operation",RpcRequest:"rpc_request",RustType:"rust_type",Scope:"scope",ScopeClosed:"scope_closed",ScopeOrb:"scope_orb",ScopeOwner:"scope_owner",ScopeResource:"scope_resource",Serialization:"serialization",Service:"service",ServiceGone:"service_gone",State:"state",StateCycle:"state_cycle",StateInitialized:"state_initialized",StateOwner:"state_owner",StateRevision:"state_revision",StateValidation:"state_validation",StateValue:"state_value",StateVersion:"state_version",Subscription:"subscription",SubscriptionBusy:"subscription_busy",SubscriptionIdle:"subscription_idle",SubscriptionQueue:"subscription_queue",SubscriptionSize:"subscription_size",SubscriptionsDisabled:"subscriptions_disabled",Superseded:"superseded",Task:"task",Telemetry:"telemetry",UndeclaredDependency:"undeclared_dependency",UndeclaredService:"undeclared_service",UnknownService:"unknown_service",UpgradeConflict:"upgrade_conflict",Utf8:"utf8",Value:"value",ValueGone:"value_gone",ValuesExhausted:"values_exhausted",Views:"views"}),J=Object.freeze({Referenced:"referenced",Host:"host"}),V=Object.freeze({Loading:"loading",Live:"live",Released:"released",Gone:"gone"}),_=Object.freeze({Prepared:"prepared",Committed:"committed",Aborted:"aborted"}),oe=Object.freeze({Observe:"observe",Transform:"transform",Decide:"decide"});var d=Object.freeze({ContextDerive:"context-derive",ContextValue:"context-value",ContextStats:"context-stats",Allocate:"allocate",ScopeRegister:"scope-register",ScopeExists:"scope-exists",ScopesForOwner:"scopes-for-owner",ScopesForOrb:"scopes-for-orb",ScopeAddResource:"scope-add-resource",ScopeActivate:"scope-activate",ScopesCleanup:"scopes-cleanup",ScopesReloadRegistered:"scopes-reload-registered",ScopesReload:"scopes-reload",ProgramRun:"program-run",ProgramNext:"program-next",ProgramCompleteStep:"program-complete-step",ProgramCommit:"program-commit",ProgramAbort:"program-abort",ProgramForget:"program-forget",Features:"features",Prepare:"prepare",Gate:"gate",GateOrbs:"gate-orbs",Commit:"commit",Abort:"abort",Orbs:"orbs",Orb:"orb",OrbNamed:"orb-named",NextDeadline:"next-deadline",Address:"address",Acquire:"acquire",Ready:"ready",Dependency:"dependency",Undepend:"undepend",Fail:"fail",Status:"status",Release:"release",Forget:"forget",Root:"root",CleanupRoot:"cleanup-root",RootPrincipal:"root-principal",CheckContext:"check-context",CheckRoot:"check-root",EndRoot:"end-root",CancelRoot:"cancel-root",BeginCall:"begin-call",BeginOperation:"begin-operation",BeginHookObservation:"begin-hook-observation",FinishCall:"finish-call",Invocation:"invocation",StateInit:"state-init",Snapshot:"snapshot",StateAdopt:"state-adopt",Task:"task",TaskRoot:"task-root",StopTask:"stop-task",FinishTask:"finish-task",Resource:"resource",ResourceOpened:"resource-opened",ResourceValue:"resource-value",CloseResource:"close-resource",ResourceClosed:"resource-closed",Disposed:"disposed",Tick:"tick",NextWake:"next-wake",NextIdle:"next-idle",Close:"close",FinishClose:"finish-close",Diagnostics:"diagnostics",Drain:"drain",Restrict:"restrict",Contribute:"contribute",ContributionOrdinal:"contribution-ordinal",HookPlan:"hook-plan",Listen:"listen",Subscribe:"subscribe",Enqueue:"enqueue",NextDelivery:"next-delivery",FinishDelivery:"finish-delivery",Unsubscribe:"unsubscribe"}),C=Object.freeze({Execute:"execute",CancelEffects:"cancel-effects",ProgramPrepared:"program-prepared",ProgramComplete:"program-complete",Dispose:"dispose",CloseResource:"close-resource",DropValue:"drop-value",CancelRoot:"cancel-root",CancelTask:"cancel-task",RetireOrb:"retire-orb",State:"state",SubscriptionFailed:"subscription-failed",DetachSubscription:"detach-subscription",Deliver:"deliver"}),E=Object.freeze({Stop:"stop",Open:"open",Close:"close",Restore:"restore",Prepare:"prepare",Validate:"validate",Initialize:"initialize",Migrate:"migrate",Adopt:"adopt",Start:"start",Drop:"drop"}),Me=Object.freeze({Execute:"execute",Wait:"wait",Prepared:"prepared",Complete:"complete",Failed:"failed"}),Ke=Object.freeze({Activate:"activate",Dispose:"dispose",CancelEffect:"cancel-effect",Effect:"effect",Invoke:"invoke",Contribute:"contribute"}),Ue=Object.freeze({Describe:"describe",Get:"get",Release:"release",Call:"call",Cancel:"cancel"}),Le=Object.freeze({State:"state"}),I=Object.freeze({Host:"host",Orb:"orb",Object:"object"}),S=Object.freeze({Declaring:"declaring",Prepared:"prepared",Live:"live",Closed:"closed"}),Ne=Object.freeze({Preparing:"preparing",Commit:"commit",Abort:"abort"}),ne=Object.freeze({Ok:"ok",Error:"error"}),K=Object.freeze({Bigint:"bigint",Bytes:"bytes",Object:"object"}),Se=Object.freeze({Json:"tembra-json/1",MessagePack:"tembra-msgpack/1"});function f(e,t,o){return Object.freeze({code:e,reason:t,message:o})}var c=Object.freeze({Cancelled:Object.freeze({EngineEffect:f(l.Cancelled,p.EngineEffect,"The engine effect was cancelled"),Request:f(l.Cancelled,p.Request,"The request was cancelled"),Resource:f(l.Cancelled,p.Resource,"Resource opening was cancelled"),Root:f(l.Cancelled,p.Root,"The operation was cancelled"),Task:f(l.Cancelled,p.Task,"The task was cancelled")}),Closed:Object.freeze({Host:f(l.Closed,p.Host,"The host is closing")}),Conflict:Object.freeze({AlreadyCommitted:f(l.Conflict,p.AlreadyCommitted,"The replacement is already committed"),Codec:f(l.Conflict,p.Codec,"The Rust and JS host codecs must agree"),PrepareDeadline:f(l.Conflict,p.PrepareDeadline,"The preparation deadline expired"),ReloadRunning:f(l.Conflict,p.ReloadRunning,"A replacement is already running"),ReloadTicket:f(l.Conflict,p.ReloadTicket,"The replacement is no longer prepared")}),Exhausted:Object.freeze({FrameSize:f(l.Exhausted,p.FrameSize,"The frame exceeds the configured size limit"),PendingRequests:f(l.Exhausted,p.PendingRequests,"The pending request limit was reached"),RemoteReferences:f(l.Exhausted,p.RemoteReferences,"The remote reference limit was reached"),RequestIds:f(l.Exhausted,p.RequestIds,"Request identities are exhausted"),SubscriptionQueue:f(l.Exhausted,p.SubscriptionQueue,"The subscription queue is full")}),Expired:Object.freeze({Next:f(l.Expired,p.Next,"Continuation scope has ended")}),Forbidden:Object.freeze({Context:f(l.Forbidden,p.Context,"An issued context from this host is required"),HostResource:f(l.Forbidden,p.HostResource,"The host resource was not declared"),Method:f(l.Forbidden,p.Method,"The method is not allowed by this reference"),ObservationSource:f(l.Forbidden,p.ObservationSource,"Hook observation requires the original physical invocation"),Opaque:f(l.Forbidden,p.Opaque,"The resource is not available as an opaque local value"),Service:f(l.Forbidden,p.Service,"Access to this service is forbidden"),StateOwner:f(l.Forbidden,p.StateOwner,"Only the owning orb may change this state"),UndeclaredDependency:f(l.Forbidden,p.UndeclaredDependency,"The dependency was not declared"),UndeclaredService:f(l.Forbidden,p.UndeclaredService,"The service was not declared as a dependency")}),Gone:Object.freeze({Connection:f(l.Gone,p.Connection,"The connection is closed"),Contribution:f(l.Gone,p.Contribution,"The contribution is no longer available"),Implementation:f(l.Gone,p.Implementation,"The implementation is no longer available"),ListenerCallback:f(l.Gone,p.ListenerCallback,"The listener callback is no longer available"),Reference:f(l.Gone,p.Reference,"The reference is no longer available"),Resource:f(l.Gone,p.Resource,"The resource is no longer available"),Scope:f(l.Gone,p.Scope,"The declaration scope is no longer available"),State:f(l.Gone,p.State,"State owner is gone")}),Invalid:Object.freeze({Address:f(l.Invalid,p.Address,"Invalid address"),AsyncFactory:f(l.Invalid,p.AsyncFactory,"Factories must be synchronous"),AsyncState:f(l.Invalid,p.AsyncState,"State updates and migrations must be synchronous"),CoordinationLimits:f(l.Invalid,p.CoordinationLimits,"Invalid coordination limits"),DependencyCycle:f(l.Invalid,p.DependencyCycle,"Orb factories cannot acquire their own services"),DependencyService:f(l.Invalid,p.DependencyService,"Invalid dependency service"),DuplicateListener:f(l.Invalid,p.DuplicateListener,"Invalid duplicate listener"),DuplicateResource:f(l.Invalid,p.DuplicateResource,"Invalid duplicate resource"),EventSource:f(l.Invalid,p.EventSource,"Invalid event source"),Orb:f(l.Invalid,p.Orb,"An orb needs a name and positive API version"),OrbGone:f(l.Invalid,p.OrbGone,"Invalid orb gone"),OrbInstalled:f(l.Invalid,p.OrbInstalled,"Use reload to replace an installed orb"),Factory:f(l.Invalid,p.Factory,"Invalid factory"),FactoryExpired:f(l.Invalid,p.FactoryExpired,"Declarations must be synchronous"),Hook:f(l.Invalid,p.Hook,"Hooks need a run function"),HookDependency:f(l.Invalid,p.HookDependency,"Invalid hook dependency"),HooksDisabled:f(l.Invalid,p.HooksDisabled,"Invalid hooks disabled"),JsonAccessor:f(l.Invalid,p.JsonAccessor,"Invalid json accessor"),JsonCycle:f(l.Invalid,p.JsonCycle,"Invalid json cycle"),JsonNumber:f(l.Invalid,p.JsonNumber,"Use BigInt for integers outside the safe Number range"),JsonSymbol:f(l.Invalid,p.JsonSymbol,"Invalid json symbol"),JsonTag:f(l.Invalid,p.JsonTag,"Unknown or malformed portable type tag"),JsonType:f(l.Invalid,p.JsonType,"Supply a codec for custom object types"),JsonValue:f(l.Invalid,p.JsonValue,"This JSON codec requires explicit portable values"),Method:f(l.Invalid,p.Method,"Methods must be functions"),NextUsed:f(l.Invalid,p.NextUsed,"Invalid next used"),Priority:f(l.Invalid,p.Priority,"Invalid priority"),Reference:f(l.Invalid,p.Reference,"An issued local reference is required"),Resource:f(l.Invalid,p.Resource,"Invalid resource"),ResourceHost:f(l.Invalid,p.ResourceHost,"Resource dependencies must belong to the same host"),ResourceInFactory:f(l.Invalid,p.ResourceInFactory,"Resources open after declaration"),RpcFrame:f(l.Invalid,p.RpcFrame,"Invalid rpc frame"),RpcOperation:f(l.Invalid,p.RpcOperation,"Invalid rpc operation"),RpcRequest:f(l.Invalid,p.RpcRequest,"Invalid rpc request"),Service:f(l.Invalid,p.Service,"Invalid service"),ServiceGone:f(l.Invalid,p.ServiceGone,"Invalid service gone"),State:f(l.Invalid,p.State,"Service does not expose state"),StateCycle:f(l.Invalid,p.StateCycle,"State cannot contain cycles"),StateValidation:f(l.Invalid,p.StateValidation,"The orb rejected the state candidate"),StateValue:f(l.Invalid,p.StateValue,"State cannot contain accessors"),StateVersion:f(l.Invalid,p.StateVersion,"Invalid state version"),SubscriptionsDisabled:f(l.Invalid,p.SubscriptionsDisabled,"Invalid subscriptions disabled"),SubscriptionSize:f(l.Invalid,p.SubscriptionSize,"A local byte budget requires an explicit sizeOf function"),Task:f(l.Invalid,p.Task,"Invalid task"),Utf8:f(l.Invalid,p.Utf8,"Invalid utf8"),ValueGone:f(l.Invalid,p.ValueGone,"Invalid value gone"),ValuesExhausted:f(l.Invalid,p.ValuesExhausted,"Invalid values exhausted")}),Released:Object.freeze({Reference:f(l.Released,p.Reference,"The reference has been released")}),Unavailable:Object.freeze({Callback:f(l.Unavailable,p.Callback,"A callback failed"),OrbScope:f(l.Unavailable,p.OrbScope,"The orb scope is unavailable"),NotReady:f(l.Unavailable,p.NotReady,"The object is not ready"),Route:f(l.Unavailable,p.Route,"The route is unavailable")}),Unsupported:Object.freeze({EngineEffect:f(l.Unsupported,p.EngineEffect,"The engine effect is not supported by this adapter"),RemoteOpaque:f(l.Unsupported,p.RemoteOpaque,"Opaque resources are local to their language environment"),Telemetry:f(l.Unsupported,p.Telemetry,"Telemetry is disabled in this kernel"),Views:f(l.Unsupported,p.Views,"Reference views are disabled in this kernel")})});var Ae=new Set(Object.values(l));function De(e){return typeof e==="object"&&e!==null&&"code"in e&&Ae.has(e.code)&&"reason"in e&&typeof e.reason==="string"&&"message"in e&&typeof e.message==="string"}class v extends Error{code;reason;constructor(e,t=e.message,o){super(t,o);this.name="TembraError",this.code=e.code,this.reason=e.reason}}function F(e){let t=c.Unavailable.Callback.message;try{if(e instanceof v)return e;if(De(e))return new v(e,e.message,{cause:e});t=String(e instanceof Error?e.message:e)}catch{}return new v(c.Unavailable.Callback,t,{cause:e})}function h(e,t=e.message){throw new v(e,t)}var G="$tembra";function re(e,t){if(typeof e==="bigint")return{[G]:[K.Bigint,e.toString()]};if(e instanceof Uint8Array)return{[G]:[K.Bytes,[...e]]};if(e===null||typeof e==="string"||typeof e==="boolean")return e;if(typeof e==="number"){if(!Number.isFinite(e)||Number.isInteger(e)&&!Number.isSafeInteger(e))h(c.Invalid.JsonNumber,"Use BigInt for integers outside the safe Number range");return e}if(typeof e!=="object")h(c.Invalid.JsonValue,"This JSON codec requires explicit portable values");if(t.has(e))h(c.Invalid.JsonCycle);let o=Object.getPrototypeOf(e);if(!Array.isArray(e)&&o!==Object.prototype&&o!==null)h(c.Invalid.JsonType,"Supply a codec for custom object types");t.add(e);try{if(Array.isArray(e))return Array.from(e,(r)=>re(r,t));let n=Reflect.ownKeys(e).map((r)=>{if(typeof r!=="string")h(c.Invalid.JsonSymbol);let s=Object.getOwnPropertyDescriptor(e,r);if(!Object.hasOwn(s,"value"))h(c.Invalid.JsonAccessor);return[r,re(s.value,t)]});return Object.hasOwn(e,G)?{[G]:[K.Object,n]}:Object.fromEntries(n)}finally{t.delete(e)}}function Y(e){if(e===null||typeof e!=="object"){if(typeof e==="number"&&Number.isInteger(e)&&!Number.isSafeInteger(e))h(c.Invalid.JsonNumber);return e}if(Array.isArray(e))return e.map(Y);if(Object.hasOwn(e,G)){let t=e[G];if(Object.keys(e).length!==1||!Array.isArray(t)||t.length!==2)h(c.Invalid.JsonTag);let[o,n]=t;if(o===K.Bigint&&typeof n==="string"&&/^-?(0|[1-9]\d*)$/.test(n))return BigInt(n);if(o===K.Bytes&&Array.isArray(n)&&n.every((r)=>Number.isInteger(r)&&r>=0&&r<=255))return Uint8Array.from(n);if(o===K.Object&&Array.isArray(n)){if(!n.every((r)=>Array.isArray(r)&&r.length===2&&typeof r[0]==="string"))h(c.Invalid.JsonTag);return Object.fromEntries(n.map(([r,s])=>[r,Y(s)]))}h(c.Invalid.JsonTag,"Unknown or malformed portable type tag")}return Object.fromEntries(Object.entries(e).map(([t,o])=>[t,Y(o)]))}function Ve(e){let t=[];for(let o of e){let n=o.codePointAt(0);if(n>=55296&&n<=57343)n=65533;if(n<128)t.push(n);else if(n<2048)t.push(192|n>>6,128|n&63);else if(n<65536)t.push(224|n>>12,128|n>>6&63,128|n&63);else t.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|n&63)}return Uint8Array.from(t)}function ze(e){let t=[];for(let o=0;o<e.length;){let n=e[o++];if(n<128){t.push(String.fromCharCode(n));continue}let r=n>=194&&n<=223?1:n>=224&&n<=239?2:n>=240&&n<=244?3:-1;if(r<0||o+r>e.length)h(c.Invalid.Utf8);let s=n&127>>r+1;for(let i=0;i<r;i++){let a=e[o++];if((a&192)!==128)h(c.Invalid.Utf8);s=s<<6|a&63}if(s<[0,128,2048,65536][r]||s>1114111||s>=55296&&s<=57343)h(c.Invalid.Utf8);t.push(String.fromCodePoint(s))}return t.join("")}var B=Object.freeze({id:Se.Json,serialize:(e)=>Ve(JSON.stringify(re(e,new WeakSet))),deserialize:(e)=>Y(JSON.parse(ze(e)))});var P=Object.freeze({Text:"text",Integer:"integer",Boolean:"boolean",Opaque:"opaque"});class U{name;version;kind;constructor(e,t,o){this.name=e;this.version=t;this.kind=o;Object.freeze(this)}static text(e,t=1){return new U(e,t,P.Text)}static integer(e,t=1){return new U(e,t,P.Integer)}static boolean(e,t=1){return new U(e,t,P.Boolean)}static opaque(e,t=1){return new U(e,t,P.Opaque)}source(e,t){if(this.kind!==P.Opaque)return;let o=typeof e==="object"&&e!==null?t.session.contextTokens.get(e):void 0;if(!o||o.root!==t.root)throw TypeError("An owner-issued opaque reference from this host and root is required");return o.source}}function se(e,t,o){let n=e.session.kernel.command(d.ContextValue,{root:e.root,context:o,call:e.invocation?.id,key:t});if(!n)return;if(n.kind!==P.Opaque)return n.value;let r=Object.freeze({opaque:!0});return e.session.contextTokens.set(r,{root:e.root,source:n.source}),r}function xe(e,t,o){let n=se(e,t,o);if(!n)throw TypeError("The owner did not issue a reference");return n}function ie(e){if(!e.name||!Number.isInteger(e.apiVersion)||e.apiVersion<=0)h(c.Invalid.Orb,"An orb needs a name and positive API version");let t=Object.fromEntries(Object.entries(e.services??{}).map(([s,i])=>{if(!s||!i.methods||typeof i.methods!=="object")h(c.Invalid.Service);if(i.create&&typeof i.create!=="function")h(c.Invalid.Factory);for(let u of Object.values(i.methods))if(typeof u!=="function")h(c.Invalid.Method,"Methods must be functions");let a={...i,methods:Object.freeze({...i.methods})};return[s,Object.freeze(a)]})),o=Object.fromEntries(Object.entries(e.requires??{}).map(([s,i])=>[s,Object.freeze({...i,...i.methods?{methods:Object.freeze([...i.methods])}:{},...i.hooks?{hooks:Object.freeze([...i.hooks])}:{},...i.services?{services:Object.freeze(Object.fromEntries(Object.entries(i.services).map(([a,u])=>[a,Object.freeze([...u])])))}:{}})])),n=Object.fromEntries(Object.entries(e.hooks??{}).map(([s,i])=>{if(typeof i.run!=="function")h(c.Invalid.Hook,"Hooks need a run function");return[s,Object.freeze({...i,capabilities:Object.freeze([...i.capabilities??[]])})]})),r=Object.fromEntries(Object.entries(e.contributes??{}).map(([s,i])=>[s,Object.freeze(Object.fromEntries(Object.entries(i).map(([a,u])=>[a,typeof u==="function"?u:Object.freeze({...u})])))]));return Object.freeze({...e,services:Object.freeze(t),requires:Object.freeze(o),hooks:Object.freeze(n),contributes:Object.freeze(r)})}class ae{allocate;#e=1;#t=new Map;constructor(e){this.allocate=e}put(e){if(this.#e>4294967295)h(c.Invalid.ValuesExhausted);let t=this.allocate?this.allocate():this.#e++;return this.#t.set(t,e),t}get(e){if(!this.#t.has(e))h(c.Invalid.ValueGone);return this.#t.get(e)}drop(e){this.#t.delete(e)}has(e){return this.#t.has(e)}set(e,t){this.#t.set(e,t)}clear(){this.#t.clear()}get size(){return this.#t.size}}var Ce=new WeakSet;function W(e){let t=new WeakSet;function o(n){if(n===null||typeof n!=="object"){if(["function","symbol"].includes(typeof n))h(c.Invalid.StateValue,"State must contain plain data");return}if(Ce.has(n))return;if(t.has(n))h(c.Invalid.StateCycle,"State cannot contain cycles");let r=Object.getPrototypeOf(n);if(!Array.isArray(n)&&r!==Object.prototype&&r!==null)h(c.Invalid.StateValue,"State requires plain objects and arrays");t.add(n);for(let s of Reflect.ownKeys(n)){if(typeof s!=="string")h(c.Invalid.StateValue,"State cannot contain symbol properties");let i=Object.getOwnPropertyDescriptor(n,s);if(!Object.hasOwn(i,"value"))h(c.Invalid.StateValue,"State cannot contain accessors");o(i.value)}t.delete(n),Object.freeze(n),Ce.add(n)}return o(e),e}class Z{compute;report;check;#e;#t=new Set;#o=new Set;#n=!0;#r;#s;#i;constructor(e,t,o,n){this.compute=e;this.report=o;this.check=n;this.#e=W(e(t))}get value(){return this.check(),this.#e}track(e,t){this.#r=e,this.#i=t;let o=new WeakRef(this);this.#s=()=>o.deref()?.detach(),e?.add(this.#s)}detach(){if(!this.#n)return;if(this.#n=!1,this.#s)this.#r?.delete(this.#s);this.#i?.(),this.#t.clear();for(let e of this.#o)e.deref()?.detach();this.#o.clear()}prepare(e){if(!this.#n)return;try{this.check()}catch{this.detach();return}let t;try{t=W(this.compute(e))}catch(n){this.detach(),this.report(n);return}if(!this.#n)return;let o=[];if(!Object.is(t,this.#e))for(let n of this.#o){let s=n.deref()?.prepare(t);if(s)o.push(s);else this.#o.delete(n)}return{adopt:()=>{if(!this.#n||Object.is(t,this.#e))return()=>{};this.#e=t;let n=o.map((s)=>s.adopt()),r=[...this.#t];return()=>{if(!this.#n)return;for(let s of n)s();for(let s of r)try{s(t)}catch(i){this.report(i)}}}}}select(e){this.check();let t=new Z(e,this.#e,this.report,this.check);this.check();let o=new WeakRef(t);return this.#o.add(o),t.track(this.#r,()=>this.#o.delete(o)),t}subscribe(e){this.check(),this.#t.add(e);try{e(this.#e)}catch(t){this.report(t)}return()=>{this.#t.delete(e)}}}class L{backend;object;closed=!1;#e;#t=new Set;#o=new Set;constructor(e,t,o){this.backend=e;this.object=t;this.#e=arguments.length>=3?o:e.value(e.snapshot(t).value)}check(){if(this.closed)throw new v(c.Gone.State,"State owner is gone")}get value(){return this.check(),this.#e}view(e,t=()=>this.check()){let o=this;return{get value(){return t(),o.value},update(n,r){t(),o.backend.check(n,o.object);let s=o.backend.snapshot(o.object),i=o.backend.value(s.value),a=r(i);if(H(a,e),o.backend.check(n,o.object),Object.is(a,i))return i;let u=o.prepare(a);o.backend.adopt(o.object,n,s.revision,a);let b=o.adopt(u,a);return o.backend.publish(b),a},select:(n)=>(t(),o.select(n,t)),subscribe:(n)=>(t(),o.subscribe(n))}}select(e,t=()=>this.check(),o){t();let n=new Z(e,this.value,(s)=>this.backend.report(s),t);t();let r=new WeakRef(n);return this.#o.add(r),n.track(o,()=>this.#o.delete(r)),n}subscribe(e){this.check(),this.#t.add(e);try{e(this.value)}catch(t){this.backend.report(t)}return()=>{this.#t.delete(e)}}prepare(e){let t=[];for(let o of this.#o){let r=o.deref()?.prepare(e);if(r)t.push(r);else this.#o.delete(o)}return t}adopt(e,t){this.#e=t;let o=e.map((r)=>r.adopt()),n=[...this.#t];return()=>{for(let r of o)r();for(let r of n)try{r(t)}catch(s){this.backend.report(s)}}}close(){this.closed=!0,this.#e=void 0,this.#t.clear();for(let e of this.#o)e.deref()?.detach();this.#o.clear()}}function H(e,t){if(e&&typeof e.then==="function")h(c.Invalid.AsyncState,"State updates and migrations must be synchronous");let o=W(e),n=t.validate?.(o);if(n!==void 0&&n!==!0)h(c.Invalid.StateValidation,"Orb rejected the candidate state");return o}class M{session;environment;constructor(e,t){this.session=e;this.environment=t}check(){if(this.environment.phase!==S.Declaring)h(c.Invalid.FactoryExpired,"Declarations must be synchronous")}get principal(){return this.session.principalFor(this.environment.object?.id??0)}get orb(){return this.environment.orb.scope?.value}get key(){return this.environment.object?.address.key??["main"]}state(e,t={}){this.check();let o=this.environment,n=o.object;if(!n||o.state)h(c.Invalid.State,"An object declares exactly one state");let r=t.version??1;if(!Number.isInteger(r)||r<=0)h(c.Invalid.StateVersion);let s=n.binding;if(!s&&n.live)s=new L(this.session,n.id,H(e,t));if(!s){let a=H(e,t),u=this.session.values.put(a);try{this.session.kernel.command(d.StateInit,{object:n.id,value:u,version:r})}catch(b){throw this.session.values.drop(u),b}n.binding=s=new L(this.session,n.id)}let i=s.view(t);return o.state={initial:e,options:t,binding:s},i}get(e,t,o={}){this.check();let n=this.session.scopes.requirement(this.environment,e),r=n.service;if(!this.environment.object&&this.environment.orb.definition.services?.[r])h(c.Invalid.DependencyCycle);let s=JSON.stringify([r,t,o.principal??this.principal]),i=this.environment.dependencies.get(s);if(i)return i;let a=this.session.handles.hold(r,t,{...o,...n.apiVersion?{apiVersion:n.apiVersion}:{},...n.methods?{methods:n.methods}:{},principal:o.principal??this.principal});if(this.environment.object)try{this.session.kernel.command(d.Dependency,{object:this.environment.object.id,reference:this.session.handles.reference(a).id})}catch(u){throw a.release(),u}return this.environment.dependencies.set(s,a),a}resource(e,t){if(this.check(),!t)return this.session.scopes.hostResource(e);if(this.environment.resources.has(e))h(c.Invalid.DuplicateResource,e);let o=this.session.resources.declare(this.environment,e,t);return this.environment.resources.set(e,o),o.handle}task(e){if(this.check(),typeof e!=="function")h(c.Invalid.Task);this.environment.tasks.push({start:e})}on(e,t,o,n={}){if(this.check(),!this.session.kernel.features.subscriptions)h(c.Invalid.SubscriptionsDisabled);if(n.maxBytes!==void 0&&!n.sizeOf)h(c.Invalid.SubscriptionSize,"A local byte budget requires an explicit sizeOf function");if(!e||this.environment.listeners.some((r)=>r.name===e))h(c.Invalid.DuplicateListener,e);this.environment.listeners.push({name:e,source:t,handle:o,options:n})}hook(e){if(this.check(),!this.session.kernel.features.hooks)h(c.Invalid.HooksDisabled);if(!this.environment.orb.definition.hooks?.[e])h(c.Invalid.Hook,e);let t=this.session.kernel.command(d.Allocate);return{run:(o,n)=>this.session.orbs.runHook(this.environment,e,o,n),observe:(o,n)=>this.session.orbs.observe(this.environment,e,t,o,n)}}}function Te(e,t,o){return{get value(){return t(),e.value},select(n){return t(),e.select(n,t,o)},subscribe(n){t();let r=e.subscribe((a)=>{try{t()}catch{return}n(a)}),s=!0,i=()=>{if(!s)return;s=!1,o.delete(i),r()};o.add(i);try{t()}catch{i()}return i}}}class ce{port;features;constructor(e){this.port=e;this.features=this.command(d.Features)}command(e,t={}){let o=JSON.parse(this.port.request(JSON.stringify({...t,op:e})));if(o.error)throw new v(o.error);return o.ok}}class de{capacity;sampleEvery;#e=[];#t=0;constructor(e=256,t=1){this.capacity=e;this.sampleEvery=t;if(!Number.isInteger(e)||e<=0||!Number.isInteger(t)||t<=0)throw RangeError("Invalid telemetry limits")}sample(){return this.#t++%this.sampleEvery===0}record(e){if(this.#e.length===this.capacity)this.#e.shift();this.#e.push(e)}drain(){return this.#e.splice(0)}}class le{session;tasks=new Map;listeners=new Map;#e=new WeakMap;constructor(e){this.session=e}prepare(e,t){for(let o of e.listeners){let n=typeof o.source==="function"?o.source():o.source;if(!n||typeof n.subscribe!=="function")h(c.Invalid.EventSource);let r=this.session.kernel.command(d.Listen,{scope:e.id,previous:t?.id,name:o.name,source:this.identity(n),sizing:o.options.sizeOf?this.identity(o.options.sizeOf):0,operation:this.session.kernel.command(d.Allocate),maxPending:o.options.maxPending??64,...o.options.maxBytes?{maxBytes:o.options.maxBytes}:{},coalesce:"select"in n}),s=this.listeners.get(r);if(s){o.running=s;continue}let i={id:r,definition:o,environment:e,stopped:!1,detach(){}};o.running=i,this.listeners.set(r,i);try{if(i.detach=n.subscribe((a)=>{if(i.stopped)return;let u=this.session.values.put(a);try{let b=o.options.sizeOf?.(a)??0;if(!Number.isSafeInteger(b)||b<0||b>4294967295)throw new v(c.Invalid.SubscriptionSize);this.session.kernel.command(d.Enqueue,{subscription:r,payload:u,bytes:b})}catch(b){this.session.values.drop(u),this.session.report(b),this.failed(r)}this.session.lifecycle.flush()}),i.stopped)i.detach()}catch(a){throw this.stopListener(i),a}}}start(e){e.phase=S.Live;for(let t of e.listeners){let o=t.running;o.environment=e,o.definition=t}for(let t of e.tasks)this.startTask(e,t)}startTask(e,t){if(t.running||e.phase!==S.Live||this.session.closing)return;let o=this.session.kernel.command(d.Task,{owner:e.owner}),n=new AbortController,r=this.session.kernel.command(d.Allocate),s={id:o,controller:n,done:Promise.resolve()};t.running=s,this.tasks.set(o,s),s.done=this.session.track(Promise.resolve().then(async()=>{try{await t.start({signal:n.signal,root:(i)=>{let a=this.session.kernel.command(d.TaskRoot,{task:o,principal:this.session.principalFor(e.object?.id??0)});return this.session.calls.root(()=>this.session.calls.owned(e,r,i,a),!1,a)}})}catch(i){if(!n.signal.aborted)this.session.report(i)}finally{this.session.kernel.command(d.Tick,{now:this.session.now()}),this.session.kernel.command(d.FinishTask,{task:o}),this.tasks.delete(o),delete t.running,this.session.lifecycle.flush()}}))}identity(e){let t=this.#e.get(e);if(t===void 0)t=this.session.kernel.command(d.Allocate),this.#e.set(e,t);return t}deliver(e,t,o){let n=this.listeners.get(e),r=Promise.resolve().then(async()=>{try{if(!n)throw new v(c.Gone.ListenerCallback);await this.session.calls.owned(n.environment,o,(s)=>n.definition.handle(s,this.session.values.get(t)))}catch(s){this.session.report(s)}finally{this.session.kernel.command(d.FinishDelivery,{subscription:e}),this.session.lifecycle.flush()}});if(n)n.done=r;this.session.track(r)}detach(e){let t=this.listeners.get(e);if(t)this.stopListener(t)}cancel(e){this.tasks.get(e)?.controller.abort(new v(c.Cancelled.Task))}failed(e){let t=this.listeners.get(e);if(!t)return;this.session.report(new v(c.Exhausted.SubscriptionQueue)),this.stopListener(t)}stopListener(e){if(e.stopped)return;e.stopped=!0;try{e.detach()}catch(t){this.session.report(t)}this.session.kernel.command(d.Unsubscribe,{subscription:e.id}),this.listeners.delete(e.id),this.session.lifecycle.flush()}async stop(e){for(let t of e.tasks)if(t.running)this.session.kernel.command(d.StopTask,{task:t.running.id});this.session.lifecycle.flush(),await Promise.all(e.tasks.map((t)=>t.running?.done)),await Promise.all(e.listeners.map((t)=>t.running?.done))}}var ee=new WeakMap;class A{session;root;invocation;frame;constructor(e,t,o,n=0){this.session=e;this.root=t;this.invocation=o;this.frame=n;ee.set(this,this)}with(e,t){let o=e.source(t,this),n=this.session.kernel.command(d.ContextDerive,{root:this.root,context:this.frame,call:this.invocation?.id,key:e,...e.kind===P.Opaque?{source:o}:{value:t}});return new A(this.session,this.root,this.invocation,n)}value(e){return se(this,e,this.frame)}exportValues(e){let t={};for(let o of e){if(o.kind===P.Opaque)throw TypeError("Local opaque references cannot be exported");let n=this.value(o);if(n!==void 0)t[`${o.name}@${o.version}`]=n}return t}get principal(){return this.session.kernel.command(d.RootPrincipal,{root:this.root})}get signal(){return this.session.calls.signal(this.root)}check(){this.session.kernel.command(d.CheckContext,{root:this.root,call:this.invocation?.id})}cancel(){this.session.kernel.command(d.CancelRoot,{root:this.root}),this.session.lifecycle.flush()}get(e,t,o={}){return this.check(),this.session.handles.get(e,t,o,this)}resource(e){return this.check(),this.session.scopes.hostResource(e)}}function pe(e,t){if(typeof e!=="object"||e===null||ee.get(e)?.session!==t)throw new v(c.Forbidden.Context,"An issued context from this host is required");return ee.get(e)}function z(e,t){let o=pe(e,t);return o.check(),o}function je(e){return typeof e==="object"&&e!==null&&ee.has(e)}class ue{session;constructor(e){this.session=e}signal(e){let t=this.session,o=t.controllers.get(e);if(!o){o=new AbortController;try{t.kernel.command(d.CheckRoot,{root:e})}catch(n){if(!(n instanceof v)||n.code!==l.Cancelled)throw n;o.abort(n)}t.controllers.set(e,o)}return o.signal}releaseRoot(e){for(let t of this.session.rootReferences.get(e)??[])this.session.handles.release(t);this.session.rootReferences.delete(e),this.session.controllers.delete(e)}async root(e,t=!1,o,n=this.session.principal){let r=this.session,s=o??r.kernel.command(t?d.CleanupRoot:d.Root,{principal:n}),i=new A(r,s);try{return await e(i)}finally{if(this.releaseRoot(s),r.options.native?.rootEnded?.(s),!r.lifecycle.closedDiagnostics)r.kernel.command(d.EndRoot,{root:s});r.controllers.delete(s),r.lifecycle.flush()}}async invoke(e,t,o,n){let r=this.session;if(z(n,r),e.released)throw new v(c.Released.Reference);await e.ready;let s=r.options.native?.admit?.(e.id,t,n),i;if(s)i=s.call;else n.check(),i=r.kernel.command(d.BeginCall,{reference:e.id,root:n.root,context:n.frame||void 0,method:t});let a=new A(r,n.root,i,n.frame),u=r.track((async()=>{let b=r.telemetry?.sample(),m=b?r.now():0,k=ne.Ok;try{let y=r.options.native;if(y&&(s?.native??y.hasOrb(i.orb)))return await y.invoke(i,o,a);let w=r.objects.get(i.object)?.versions.get(i.orb),x=w?.orb.definition.services?.[e.address.service]?.methods[t];if(!w||!x)throw new v(c.Gone.Implementation);return await x(w.value,a,...o)}catch(y){throw k=ne.Error,y}finally{if(b)r.telemetry.record({service:e.address.service,method:t,root:i.root,codeVersion:i.codeVersion,duration:r.now()-m,outcome:k});r.lifecycle.finishCall(i.id)}})());return this.observe(u,n.signal)}async owned(e,t,o,n){let r=this.session,s=async(i)=>{let a=r.kernel.command(d.BeginOperation,{orb:e.orb.info.id,root:i.root,context:i.frame||void 0,operation:t,...e.object?{object:e.object.id}:{}});try{return await o(new A(r,i.root,a,i.frame))}finally{r.kernel.command(d.FinishCall,{call:a.id}),r.lifecycle.flush()}};return n===void 0?this.root(s,!1,void 0,r.principalFor(e.object?.id??0)):s(typeof n==="number"?new A(r,n):n)}async observe(e,t){if(t.aborted)throw t.reason;let o,n=new Promise((r,s)=>{o=()=>s(t.reason??new v(c.Cancelled.Root)),t.addEventListener("abort",o,{once:!0})});try{return await Promise.race([e,n])}finally{t.removeEventListener("abort",o)}}}class fe{session;records=new Map;operations=new Map;#e=new Map;#t=new Map;constructor(e){this.session=e}declarations(e){let t=e.map((s)=>ie(s)),o=this.session.kernel.command(d.Orbs),n=(s)=>t.find((i)=>i.name===s),r=t.map((s)=>{if(!this.session.kernel.features.views&&Object.values(s.services??{}).some((a)=>a.access))throw new v(c.Unsupported.Views);let i=Object.entries(s.requires??{}).map(([a,u])=>{let b=u.orb??a,m=n(b),k=o.find((w)=>w.name===b),y=m?Object.keys(m.services??{}):k?.services.map((w)=>w.name)??[],g=y.includes(a)?a:y.length===1?y[0]:void 0;if(u.methods&&!g)h(c.Invalid.DependencyService,`Use explicit services for ${b}`);return{orb:b,apiVersion:u.apiVersion,services:u.services??(u.methods?{[g]:u.methods}:{}),hooks:u.hooks??[]}});for(let[a,u]of Object.entries(s.contributes??{})){let b=s.requires?.[a];if(!b)h(c.Invalid.HookDependency,a);for(let[m,k]of Object.entries(u)){if(!b.hooks?.includes(m))h(c.Invalid.HookDependency,m);let y=typeof k==="function"?0:k.priority??0;if(!Number.isInteger(y)||y<-2147483648||y>2147483647)h(c.Invalid.Priority)}}return{name:s.name,apiVersion:s.apiVersion,requires:i,hooks:Object.keys(s.hooks??{}),services:Object.entries(s.services??{}).map(([a,u])=>({name:a,methods:Object.keys(u.methods),lifetime:u.lifetime??J.Referenced,linger:u.linger??0}))}});return{definitions:t,metadata:r}}async install(e){let t=this.session.kernel.command(d.Orbs);if(e.some((s)=>t.some((i)=>i.name===s.name)))h(c.Invalid.OrbInstalled,"Use reload to replace an installed orb");let o=this.declarations(e),n=this.session.kernel.command(d.Prepare,{orbs:o.metadata});this.session.kernel.command(d.Commit,{ticket:n.id});let r=n.orbs.map((s)=>({info:s,definition:o.definitions.find((i)=>i.name===s.name)}));for(let s of r)this.records.set(s.info.id,s);for(let s of r)this.registerContributions(s);await Promise.all(r.map((s)=>this.ready(s)));for(let s of r)for(let i of s.info.services.filter((a)=>a.lifetime===J.Host))(await this.session.handles.get(i.name,"main",{principal:"host"})).release();this.session.lifecycle.flush()}scope(e){if(e.scope)return e.scope;let t=this.session.scopes.environment({kind:I.Orb,id:e.info.owner},e);e.scope=t;try{let o=e.definition.create?.(new M(this.session,t))??{};if(o&&typeof o.then==="function")h(c.Invalid.AsyncFactory);t.value=o}finally{t.phase=S.Prepared,this.session.programs.register(t)}return t}ready(e){if(e.scope?.phase===S.Live)return Promise.resolve();let t=this.#e.get(e.info.id);if(!t){t=(async()=>{try{if(await this.session.scopes.readyHostScope(),e.scope?.phase===S.Closed)delete e.scope;let n=this.scope(e);await this.session.programs.activate(n.id)}catch(n){if(e.scope)await this.session.programs.cleanup([e.scope]),delete e.scope;throw n}})(),this.#e.set(e.info.id,t);let o=()=>{if(this.#e.get(e.info.id)===t)this.#e.delete(e.info.id)};t.then(o,o)}return t}registerContributions(e){for(let[t,o]of Object.entries(e.definition.contributes??{})){let r=e.definition.requires[t].orb??t;for(let[s,i]of Object.entries(o)){let a=this.session.kernel.command(d.Allocate),u=JSON.stringify([e.info.name,r,s]);if(!this.#t.has(u))this.#t.set(u,this.session.kernel.command(d.ContributionOrdinal));this.operations.set(a,{orb:e,handler:typeof i==="function"?i:i.handle}),this.session.kernel.command(d.Contribute,{orb:e.info.id,target:r,hook:s,operation:a,priority:typeof i==="function"?0:i.priority??0,ordinal:this.#t.get(u)})}}}async runHook(e,t,o,n){o=z(o,this.session);let r=e.orb.definition.hooks?.[t];if(!r)h(c.Invalid.Hook,t);let i=this.session.kernel.command(d.HookPlan,{root:o.root,target:e.orb.info.name,hook:t}).map((a)=>async(u,b,m)=>this.runContribution(a,u,b,m));return r.run(o,n,i)}async observe(e,t,o,n,r){n=pe(n,this.session);let s=e.orb.definition.hooks?.[t];if(!s)h(c.Invalid.Hook,t);if(!n.invocation)throw new v(c.Forbidden.ObservationSource);let i=this.session.kernel.command(d.BeginHookObservation,{source:n.invocation.id,orb:e.orb.info.id,operation:o,...e.object?{object:e.object.id}:{},hook:t});await this.session.track(this.session.calls.root(async()=>{try{let a=new A(this.session,i.invocation.root,i.invocation),u=i.plan.map((b)=>async(m,k,y)=>this.runContribution(b,m,k,y));await s.run(a,r,u)}finally{this.session.lifecycle.finishCall(i.invocation.id)}},!1,i.invocation.root))}async runContribution(e,t,o,n){t=z(t,this.session);let r=this.operations.get(e);if(!r){let i=this.session.options.native;if(i?.hasContribution?.(e)&&i.contribute)return i.contribute(e,t,o);throw new v(c.Gone.Contribution)}let s=r.orb.scope;if(!s)throw new v(c.Unavailable.OrbScope);return this.session.calls.owned(s,e,(i)=>r.handler(i,o,n),t)}retire(e){let t=this.session.kernel.command(d.ScopesForOrb,{orb:e}),o=this.session.programs.cleanupScopes(t);this.session.track(o.then(()=>{for(let[n,r]of this.operations)if(r.orb.info.id===e)this.operations.delete(n);this.records.delete(e),this.#e.delete(e)}),!0)}}class me{session;constructor(e){this.session=e}get closedDiagnostics(){return this.#r}#e;#t=!1;#o;#n;#r;flush(e){if(this.#t)return;this.#t=!0;try{for(;;){let t=e??this.session.kernel.command(d.Drain);if(e=void 0,!t.length)break;for(let o of t)try{this.action(o)}catch(n){this.session.report(n)}}}finally{this.#t=!1,this.scheduleLinger()}}finishCall(e){let t=this.session;if(!this.#t&&t.options.native?.finish){let o=t.options.native.finish(e,t.now());if(!o.actions.length){this.scheduleLinger(o.deadline);return}this.flush(o.actions);return}t.kernel.command(d.Tick,{now:t.now()}),t.kernel.command(d.FinishCall,{call:e}),this.flush()}action(e){let t=this.session;if(t.options.native?.notify?.(e)&&!(e.type===C.ProgramComplete&&t.programs.pending(e.id)))return;switch(e.type){case C.Execute:case C.CancelEffects:case C.ProgramPrepared:case C.ProgramComplete:t.programs.dispatch(e);break;case C.DropValue:t.values.drop(e.id),t.options.native?.dropValue?.(e.id);break;case C.CancelRoot:t.controllers.get(e.id)?.abort(new v(c.Cancelled.Root));break;case C.CancelTask:t.activities.cancel(e.id);break;case C.Deliver:t.activities.deliver(e.id,e.payload,e.operation);break;case C.DetachSubscription:t.activities.detach(e.id);break;case C.SubscriptionFailed:t.activities.failed(e.id);break;case C.Dispose:t.track(this.dispose(e.id),!0);break;case C.CloseResource:break;case C.RetireOrb:t.handles.retire(e.id),t.orbs.retire(e.id);break;case C.State:{let n=t.objects.get(e.id);if(!n?.binding)break;let r=t.snapshot(e.id);if(!t.values.has(r.value)){let s=t.value(r.value);t.publish(n.binding.adopt(n.binding.prepare(s),s))}break}}}async dispose(e){let t=this.session,o=t.objects.get(e);if(!o){await t.options.native?.dispose(e),t.kernel.command(d.Disposed,{object:e}),this.flush();return}return o.disposing??=(async()=>{let n=[];await o.activation.catch(()=>{});let r=t.kernel.command(d.ScopesForOwner,{owner:{kind:I.Object,id:e}});try{await t.programs.cleanupScopes(r)}catch(s){n.push(s)}try{if(t.options.native?.hasOrb(o.orb))await t.options.native.dispose(e)}catch(s){n.push(s)}if(o.binding?.close(),t.kernel.command(d.Disposed,{object:e}),t.objects.delete(e),this.flush(),n.length)throw AggregateError(n,"Object cleanup failed")})(),o.disposing}scheduleLinger(e){let t=this.session;if(t.closing)return;let o=(e===void 0?t.kernel.command(d.NextDeadline):e)??void 0;if(o===this.#n)return;if(this.#o!==void 0)clearTimeout(this.#o);if(this.#o=void 0,this.#n=o,o===void 0)return;this.#o=setTimeout(()=>{if(this.#n!==o)return;this.#o=void 0,this.#n=void 0,t.kernel.command(d.Tick,{now:t.now()}),this.flush()},Math.max(0,o-t.now())),this.#o.unref?.()}diagnostics(){let e=this.session;if(this.#r)return this.#r;return{...e.kernel.command(d.Diagnostics),values:e.values.size,pendingJobs:e.jobs.size}}close(){let e=this.session;return this.#e??=(async()=>{e.closing=!0,clearTimeout(this.#o),this.#o=void 0,this.#n=void 0,e.kernel.command(d.Close),await e.replacements.cancel(),this.flush();for(;;){await e.options.native?.settled?.(),this.flush();let t=[...e.jobs];if(!t.length)break;await Promise.allSettled(t),this.flush()}if(e.kernel.command(d.FinishClose),e.values.clear(),e.handles.clear(),e.orbs.records.clear(),e.scopes.clear(),this.#r=this.diagnostics(),e.kernel.port.free?.(),e.cleanupErrors.length)throw AggregateError(e.cleanupErrors,"Host cleanup failed")})(),this.#e}}function Q(){let e,t,o=new Promise((n,r)=>{e=n,t=r});return o.catch(()=>{}),{promise:o,resolve:e,reject:t}}function Ee(e,t){return e.slice(0,t).replace(/[\uD800-\uDFFF]/gu,"�")}class he{session;scopes=new Map;#e=new Map;constructor(e){this.session=e}register(e){let t=e.owner.kind===I.Host?void 0:e.object?e.orb.scope:this.session.hostScope;this.session.kernel.command(d.ScopeRegister,{scope:e.id,owner:e.owner,orb:e.orb.info.id,parents:t?[t.id]:[],dependencies:[...e.dependencies.values()].map((o)=>this.session.handles.reference(o).id),resources:[...e.resources.values()].map((o)=>o.id),stateVersion:e.state?.options.version??(e.state?1:void 0),migrate:Boolean(e.state?.options.migrate)})}activate(e){return this.run(this.session.kernel.command(d.ScopeActivate,{scope:e}))}cleanup(e){let t=e.map((o)=>o.id).filter((o)=>this.session.kernel.command(d.ScopeExists,{scope:o}));return this.cleanupScopes(t)}cleanupScopes(e){return e.length?this.run(this.session.kernel.command(d.ScopesCleanup,{scopes:e})):Promise.resolve()}pending(e){return this.#e.has(e)}run(e){let t=this.#e.get(e);if(t)return t.promise;let o=Q();this.#e.set(e,o);try{this.session.kernel.command(d.ProgramRun,{program:e}),this.session.lifecycle.flush()}catch(n){this.#e.delete(e),o.reject(n)}return o.promise}dispatch(e){if(e.type===C.Execute)this.session.track(Promise.allSettled(e.effects.map((t)=>this.execute(t))).then((t)=>{let o=Math.max(0,Math.min(2048,Math.floor((1048448-t.length*96)/(12*t.length)))),n=t.map((r)=>{if(r.status==="fulfilled")return{value:r.value??null};try{let{code:s,reason:i,message:a}=F(r.reason);if(!Object.values(l).includes(s)||typeof i!=="string"||typeof a!=="string")return{error:c.Unavailable.Callback};return{error:{code:s,reason:Ee(i,o),message:Ee(a,o)}}}catch{return{error:c.Unavailable.Callback}}});this.session.kernel.command(d.ProgramCompleteStep,{program:e.id,results:n}),this.session.lifecycle.flush()}));else if(e.type===C.CancelEffects)for(let t of e.effects){if(t.type!==E.Open&&t.type!==E.Restore)continue;let o=this.session.resources.find(t.resource);if(o)o.controller.abort(new v(c.Cancelled.EngineEffect));else if(this.session.options.native?.cancelEffect){let n=this.session.options.native.cancelEffect.bind(this.session.options.native);this.session.track(Promise.resolve().then(()=>n(t))).catch((r)=>this.session.report(r))}}else{let t=this.#e.get(e.id);if(this.#e.delete(e.id),e.error){let o=new v(e.error);if(t)t.reject(o);else this.session.cleanupErrors.push(o),this.session.report(o)}else t?.resolve()}}resource(e){let t=this.session.resources.find(e);if(t)return t;throw new v(c.Gone.Resource)}async execute(e){let t=e.scope===void 0?void 0:this.scopes.get(e.scope);if(e.scope!==void 0&&!t&&this.session.options.native)return this.session.options.native.effect(e);if((e.type===E.Close||e.type===E.Open)&&!this.session.resources.find(e.resource)&&this.session.options.native)return this.session.options.native.effect(e);switch(e.type){case E.Open:await this.resource(e.resource).start();break;case E.Close:await this.session.resources.close(this.resource(e.resource));break;case E.Restore:await this.session.resources.reopen(this.resource(e.previous),e.resource);break;case E.Stop:if(t)await this.session.activities.stop(t);break;case E.Prepare:{if(!t)throw new v(c.Gone.Scope);this.session.activities.prepare(t,e.previous?this.scopes.get(e.previous):void 0);break}case E.Validate:H(this.session.value(e.value),t.state.options);break;case E.Initialize:return this.candidate(t,t.state.initial);case E.Migrate:{let o=t.state;return this.candidate(t,o.options.migrate(this.session.value(e.value),e.version))}case E.Adopt:{let o=new Map;for(let n of e.replacements){if(!n.next)continue;let r=this.scopes.get(n.next);for(let[s,i]of r.resourceDeclarations??[])s.options=i;if(delete r.resourceDeclarations,o.set(r.orb.info.id,r.orb),r.object){if(r.state)r.object.binding=r.state.binding;r.object.orb=r.orb.info.id,r.object.versions.set(r.orb.info.id,r)}}for(let n of o.values())this.session.orbs.records.set(n.info.id,n),this.session.orbs.registerContributions(n);for(let n of e.replacements){let r=n.next?this.scopes.get(n.next):void 0;if(r?.object)this.session.handles.refreshReferences(r.object,r.orb)}for(let n of e.replacements)if(n.next)this.scopes.get(n.next)?.state?.publish?.();break}case E.Start:if(t){if(this.session.activities.start(t),t.object)t.object.live=!0}break;case E.Drop:{if(!t)break;for(let o of t.dependencies.values())this.session.handles.revoke(this.session.handles.reference(o).id);t.dependencies.clear();for(let o of t.resources.values())this.session.resources.closedRecords.delete(o.id);if(t.phase=S.Closed,t.object)t.object.versions.delete(t.orb.info.id);this.scopes.delete(t.id);break}default:throw new v(c.Unsupported.EngineEffect,e.type)}}candidate(e,t){let o=e.state,n=H(t,o.options),r=this.session.values.put(n);return o.publish=()=>this.session.publish(o.binding.adopt(o.binding.prepare(n),n)),r}}var Ie=new WeakMap,be=typeof FinalizationRegistry>"u"?void 0:new FinalizationRegistry((e)=>e.session.deref()?.handles.release(e.id));class ve{session;constructor(e){this.session=e}#e=new Map;#t=new Map;activateAcquired(e,t,o=[]){let n=this.session,r=n.objects.get(e.object);if(!r){let m=Q();r={id:e.object,address:t,orb:e.orb,versions:new Map,activation:m.promise},n.objects.set(r.id,r);let k=r;n.track(n.scopes.activate(k,e).then(m.resolve,(y)=>{k.error=y;try{n.kernel.command(d.Fail,{object:k.id})}catch{}m.reject(y),n.lifecycle.flush()}))}if(!this.claimExists(e.reference))return r.activation;let i=this.orbMetadata(r.orb).services.find((m)=>m.name===t.service)?.methods??[],a={id:e.reference,object:e.object,address:t,methods:new Set(i),requiredMethods:new Set(o),stateCleanups:new Set,ready:r.activation,released:!1,nativeOwned:!0},u=n.orbs.records.get(r.orb)?.definition.services?.[t.service]?.access;try{this.referenceMethods(a,i,u)}catch(m){if(n.kernel.features.views&&this.claimExists(a.id))n.kernel.command(d.Restrict,{reference:a.id,methods:[]});throw m}n.references.set(a.id,a);let b=this.#t.get(a.object);if(!b)this.#t.set(a.object,b=new Set);return b.add(a),r.activation}hold(e,t,o={},n){let r=this.session;if(n)z(n,r);r.kernel.command(d.Tick,{now:r.now()});let s={service:e,key:typeof t==="string"?[t]:[...t],principal:o.principal??n?.principal??r.principal},i=r.kernel.command(d.Acquire,{...s,apiVersion:o.apiVersion??0,methods:o.methods??[]}),a=r.objects.get(i.object);if(!a){let R=Q();a={id:i.object,address:s,orb:i.orb,versions:new Map,activation:R.promise},r.objects.set(a.id,a);let T=a;queueMicrotask(()=>{r.track(r.scopes.activate(T,i).then(R.resolve,(D)=>{T.error=D;try{r.kernel.command(d.Fail,{object:T.id})}catch{}R.reject(D),r.lifecycle.flush()}))})}let u=this.orbMetadata(i.orb),b=new Set(u.services.find((R)=>R.name===e)?.methods??[]),m={id:i.reference,object:i.object,address:s,methods:b,requiredMethods:new Set(o.methods??[]),stateCleanups:new Set,ready:a.activation,released:!1,...n?{context:n}:{}},k=r.options.native?.access?.(i.orb,e,s.principal),y=k?()=>({methods:k}):r.orbs.records.get(i.orb)?.definition.services?.[e]?.access;try{this.referenceMethods(m,b,y)}catch(R){throw r.kernel.command(d.Release,{reference:m.id}),r.kernel.command(d.Forget,{reference:m.id}),r.lifecycle.flush(),R}r.references.set(m.id,m);let g=this.#t.get(m.object);if(!g)g=new Set,this.#t.set(m.object,g);if(g.add(m),n){let R=r.rootReferences.get(n.root);if(!R)R=new Set,r.rootReferences.set(n.root,R);R.add(m.id)}let w=()=>{if(m.released)throw new v(c.Released.Reference);if(r.closing)throw new v(c.Gone.Reference);let R=r.objects.get(m.object);if(!R||R.disposing||R.error)throw new v(c.Gone.Reference);if(!R.live)throw new v(c.Unavailable.NotReady)},x={get ready(){return m.ready},get status(){return m.released?V.Released:j.closing?V.Gone:j.kernel.command(d.Status,{reference:m.id})},get state(){w();let R=j.objects.get(m.object)?.binding;if(!R)h(c.Invalid.State,"Service does not expose state");return Te(R,w,m.stateCleanups)},release:()=>this.release(m.id),opaque:(R)=>{w();let T=r.objects.get(m.object),D=T.versions.get(T.orb)?.resources.get(R);if(!D?.options.opaque)throw new v(c.Forbidden.Opaque,R);return D.handle.value}},j=r,q=new Proxy(x,{get:(R,T,D)=>{if(T==="then")return;if(Object.hasOwn(R,T))return Reflect.get(R,T,D);if(typeof T!=="string")return;if(!m.methods.has(T))return;return(...X)=>{let te=m.context;if(je(X.at(-1)))te=X.pop();return te?r.calls.invoke(m,T,X,z(te,r)):r.calls.root((Pe)=>r.calls.invoke(m,T,X,Pe),!1,void 0,m.address.principal)}}});return Ie.set(q,{session:r,record:m}),be?.register(q,{session:new WeakRef(r),id:m.id},m),q}async get(e,t,o={},n){let r=this.hold(e,t,o,n);try{return await r.ready,r}catch(s){throw r.release(),s}}reference(e){let t=typeof e==="object"&&e!==null?Ie.get(e):void 0;if(!t||t.session!==this.session)h(c.Invalid.Reference,"An issued local reference is required");return t.record}orbMetadata(e){let t=this.session.orbs.records.get(e)?.info;if(t)return t;let o=this.#e.get(e);if(!o)o=this.session.kernel.command(d.Orb,{id:e}),this.#e.set(e,o);return o}referenceMethods(e,t,o,n=!1){let r=this.session;if(o&&!r.kernel.features.views)throw new v(c.Unsupported.Views);let s=o?new Set(o(e.address.principal).methods):void 0,i=new Set([...t].filter((a)=>(!e.requiredMethods.size||e.requiredMethods.has(a))&&(!s||s.has(a))));if(o||n&&r.kernel.features.views)r.kernel.command(d.Restrict,{reference:e.id,methods:[...i]});e.methods=i}refreshReferences(e,t){let o=this.session,n=t.definition.services?.[e.address.service];if(!n)return;let r=Object.keys(n.methods);for(let s of this.#t.get(e.id)??[]){if(s.released)continue;if(s.nativeOwned&&!this.claimExists(s.id)){this.revoke(s.id);continue}try{this.referenceMethods(s,r,n.access,!0)}catch(i){if(s.methods.clear(),!s.released&&o.kernel.features.views)o.kernel.command(d.Restrict,{reference:s.id,methods:[]});o.report(i)}}}claimExists(e){try{let t=this.session.kernel.command(d.Status,{reference:e});return t!==V.Released&&t!==V.Gone}catch(t){if(t instanceof v&&(t.code===l.Gone||t.code===l.Released))return!1;throw t}}forget(e){for(let o of e.stateCleanups)o();e.stateCleanups.clear(),this.session.references.delete(e.id);let t=this.#t.get(e.object);if(t?.delete(e),!t?.size)this.#t.delete(e.object)}release(e){let t=this.session,o=t.references.get(e);if(!o||o.released)return;if(o.released=!0,be?.unregister(o),t.lifecycle.closedDiagnostics){this.forget(o);return}t.kernel.command(d.Tick,{now:t.now()}),t.kernel.command(d.Release,{reference:e}),t.kernel.command(d.Forget,{reference:e}),this.forget(o),t.lifecycle.flush()}revoke(e){let t=this.session.references.get(e);if(!t)return;t.released=!0,be?.unregister(t),this.forget(t)}retire(e){this.#e.delete(e)}clear(){for(let e of this.session.references.values())this.forget(e);this.session.references.clear(),this.#t.clear(),this.#e.clear()}}class ye{session;#e;#t;#o;constructor(e){this.session=e}async replace(e,t={},o=[]){return(await this.prepare(e,t,o)).commit()}prepare(e,t={},o=[]){if(this.session.closing)return Promise.reject(new v(c.Closed.Host));if(this.#e)return Promise.reject(new v(c.Conflict.ReloadRunning));let n=this.capture(e,t,o);return this.#e=n,n.catch(()=>{if(this.#e===n)this.#e=void 0}),n}async cancel(){if(this.#o?.status===_.Prepared)return this.#o.abort();if(this.#t!==void 0){this.session.kernel.command(d.ProgramAbort,{program:this.#t});let e=this.session.programs.run(this.#t);this.session.lifecycle.flush(),await e.catch(()=>{})}await this.#e?.catch(()=>{return})}async capture(e,t,o){let n=this.session,r=n.orbs.declarations(e),s=n.kernel.command(d.Prepare,{orbs:r.metadata,remove:o}),i=new Map(r.definitions.map((g)=>[g.name,g])),a=s.orbs.map((g)=>({info:g,definition:i.get(g.name),ticket:s.id})),u=new Map(a.map((g)=>[g.info.id,g])),b;try{for(let g of a)n.orbs.scope(g);for(let g of s.objects){let w=n.objects.get(g);if(!w)continue;let x=s.providers[w.address.service],j=x===void 0?void 0:u.get(x);if(j)n.scopes.createEnvironment(w,j)}for(let g of a)g.ticket=void 0;if(b=n.kernel.command(d.ScopesReloadRegistered,{ticket:s.id,deadline:t.deadline??5000,now:n.now()}),this.#t=b,await n.programs.run(b),n.closing)await n.programs.run(b)}catch(g){if(this.#t=void 0,b===void 0){n.kernel.command(d.Abort,{ticket:s.id});let w=s.orbs.flatMap((x)=>n.kernel.command(d.ScopesForOrb,{orb:x.id}));await n.programs.cleanupScopes(w)}throw g}this.#t=void 0;let m=b,k={codeVersion:s.codeVersion,orbs:a.map((g)=>g.info.name)},y=_.Prepared;return this.#o={report:k,get status(){return y},commit:async()=>{if(y!==_.Prepared)throw new v(c.Conflict.ReloadTicket);this.#o=void 0;try{n.kernel.command(d.ProgramCommit,{program:m})}catch(g){throw n.kernel.command(d.ProgramAbort,{program:m}),await n.programs.run(m).catch(()=>{}),y=_.Aborted,this.#e=void 0,g}return y=_.Committed,this.#e=void 0,await n.programs.run(m),k},abort:async()=>{if(y===_.Aborted)return;if(y!==_.Prepared)throw new v(c.Conflict.AlreadyCommitted);y=_.Aborted,this.#o=void 0,this.#e=void 0,n.kernel.command(d.ProgramAbort,{program:m});try{await n.programs.run(m)}catch(g){if(!(g instanceof v)||g.reason!==p.ReloadAborted)throw g}}}}}var _e=new WeakMap;class ge{session;records=new Map;closedRecords=new Map;constructor(e){this.session=e}find(e){return this.records.get(e)??this.closedRecords.get(e)}dependencyIds(e){let t=[];for(let o of e.deps??[]){let n=typeof o==="object"&&o!==null?_e.get(o):void 0;if(n){if(n.session!==this.session)h(c.Invalid.ResourceHost,"Resource dependencies must belong to the same host");t.push(n.id)}else this.session.handles.reference(o)}return t}register(e,t,o){return this.session.kernel.command(d.Resource,{owner:e.owner,name:t,version:o.version??1,exclusive:o.exclusive??!1,dependencies:this.dependencyIds(o)}).id}redeclare(e,t){for(let o of t.resources.values())this.records.delete(o.id),this.closedRecords.delete(o.id),o.reset(this.register(e,o.name,o.options)),o.dependencies=this.dependencyIds(o.options),this.records.set(o.id,o),e.resources.set(o.name,o)}declare(e,t,o){if(!t||typeof o.open!=="function")h(c.Invalid.Resource);let n=this.register(e,t,o),r=this.records.get(n);if(r)return(e.resourceDeclarations??=new Map).set(r,o),r;let s=new AbortController,i=Object.freeze({get value(){if(e.phase===S.Declaring)h(c.Invalid.ResourceInFactory,"Resources open after declaration");let u=a.session.kernel.command(d.ResourceValue,{resource:a.id});return a.session.value(u)},version:o.version??1}),a={id:n,name:t,options:o,handle:i,dependencies:this.dependencyIds(o),controller:s,session:this.session,reset:(u)=>{a.id=u,a.controller=new AbortController,delete a.value,delete a.closed,delete a.started},start:()=>(a.started??=(async()=>{let u=a.options,b=await u.open(a.controller.signal),m=this.session.values.put(b);try{this.session.kernel.command(d.ResourceOpened,{resource:a.id,value:m})}catch(k){if(this.session.values.drop(m),u.close)await this.session.calls.root((y)=>u.close(b,y),!0);throw k}a.value=m})(),a.started.catch(()=>{}),a.started)};return _e.set(i,a),this.records.set(n,a),a}async close(e){return e.closed??=(async()=>{e.controller.abort(new v(c.Cancelled.Resource)),await e.started?.catch(()=>{});try{if(e.value!==void 0&&e.options.close){let t=this.session.value(e.value);await this.session.calls.root((o)=>e.options.close(t,o),!0)}}finally{this.session.kernel.command(d.ResourceClosed,{resource:e.id}),this.records.delete(e.id),this.closedRecords.set(e.id,e),this.session.lifecycle.flush()}})(),e.closed}async reopen(e,t){this.closedRecords.delete(e.id),e.reset(t),this.records.set(t,e),await e.start()}}class ke{session;constructor(e){this.session=e}#e=new Map;#t=new Set;#o;environment(e,t,o){let n={id:this.session.kernel.command(d.Allocate),owner:e,orb:t,...o?{object:o}:{},phase:S.Declaring,value:{},dependencies:new Map,resources:new Map,tasks:[],listeners:[]};return this.session.programs.scopes.set(n.id,n),n}async activate(e,t){let o=this.session;if(o.options.native?.hasOrb(t.orb)){await o.options.native.activate(e.id,t.orb,e.address.service,e.address.key,e.address.principal);let n=o.kernel.command(d.ScopesForOwner,{owner:{kind:I.Object,id:e.id}});await Promise.all(n.map((r)=>o.programs.activate(r)));try{o.snapshot(e.id),e.binding=new L(o,e.id)}catch{}}else{let n=o.orbs.records.get(t.orb);if(!n)h(c.Invalid.OrbGone);await o.orbs.ready(n);let r=this.createEnvironment(e,n);e.versions.set(n.info.id,r),await this.session.programs.activate(r.id)}if(o.kernel.command(d.Status,{reference:t.reference})===V.Loading)o.kernel.command(d.Ready,{object:e.id});e.live=!0,o.lifecycle.flush()}createEnvironment(e,t){let o=t.definition.services?.[e.address.service];if(!o)h(c.Invalid.ServiceGone);let n=this.environment({kind:I.Object,id:e.id},t,e);try{let r=o.create?.(new M(this.session,n))??{};if(r&&typeof r.then==="function")h(c.Invalid.AsyncFactory,"Factories must be synchronous");return n.value=r,n}finally{n.phase=S.Prepared,this.session.programs.register(n)}}readyHostScope(){let e=this.session;if(e.closing)return Promise.reject(new v(c.Closed.Host));if(this.#o)return this.#o;let t=(async()=>{if(e.hostScope.phase===S.Closed)e.hostScope=await this.redeclareHostScope(e.hostScope);await this.session.programs.activate(e.hostScope.id);while(this.#t.size){let n=this.#t.values().next().value;if(n.phase===S.Closed||[...n.resources.values()].some((r)=>e.resources.dependencyIds(r.options).some((s,i)=>s!==r.dependencies[i]))){let r=n;n=await this.redeclareHostScope(r),this.#t.delete(r),this.#t.add(n)}await this.session.programs.activate(n.id),this.#t.delete(n)}})();this.#o=t;let o=()=>{if(this.#o===t)this.#o=void 0};return t.then(o,o),t}async redeclareHostScope(e){let t=this.session;await t.programs.cleanup([e]);let o=this.environment({kind:I.Host},e.orb);return t.resources.redeclare(o,e),o.phase=S.Prepared,t.programs.register(o),o}requirement(e,t){if(e.orb.definition.services?.[t])return{service:t,apiVersion:e.orb.info.apiVersion};for(let[n,r]of Object.entries(e.orb.definition.requires??{})){let s;try{s=this.session.kernel.command(d.OrbNamed,{name:r.orb??n,ticket:e.orb.ticket})}catch(u){if(u instanceof v&&u.code===l.Gone&&u.reason===p.Orb)continue;throw u}let i=n===t?s.services.find((u)=>u.name===n)??(s.services.length===1?s.services[0]:void 0):s.services.find((u)=>u.name===t);if(!i)continue;let a=r.services?.[i.name]??r.methods;if(!a)throw new v(c.Forbidden.UndeclaredService,t);return{service:i.name,apiVersion:r.apiVersion,methods:a}}throw new v(c.Forbidden.UndeclaredDependency,t)}hostResource(e){let t=this.#e.get(e);if(!t)throw new v(c.Forbidden.HostResource,e);return t.handle}resource(e,t){let o=this.session;if(o.closing)throw new v(c.Closed.Host);if(this.#e.has(e))h(c.Invalid.DuplicateResource);let n=this.environment({kind:I.Host},o.hostScope.orb);try{let r=new M(o,n).resource(e,t);return this.#e.set(e,n.resources.get(e)),n.phase=S.Prepared,o.programs.register(n),this.#t.add(n),o.track(this.readyHostScope()).catch((s)=>o.report(s)),r}catch(r){throw o.programs.scopes.delete(n.id),r}}registerHost(e){for(let[t,o]of e.resources)this.#e.set(t,o)}clear(){this.#e.clear(),this.#t.clear()}}class we{options;contextTokens=new WeakMap;calls=new ue(this);handles=new ve(this);scopes=new ke(this);lifecycle=new me(this);kernel;values;resources=new ge(this);activities=new le(this);orbs=new fe(this);replacements=new ye(this);programs=new he(this);objects=new Map;references=new Map;rootReferences=new Map;controllers=new Map;jobs=new Set;cleanupErrors=[];hostScope;codec;name;principal;errors=[];now;telemetry;closing=!1;#e=!1;#t=[];constructor(e){this.options=e;if(this.kernel=new ce(e.kernel),e.telemetry&&!this.kernel.features.telemetry)throw new v(c.Unsupported.Telemetry);this.telemetry=e.telemetry?new de(e.telemetry.capacity,e.telemetry.sampleEvery):void 0,this.values=new ae(()=>this.kernel.command(d.Allocate)),this.codec=e.serialization??B,this.name=e.name??"host",this.principal=e.principal??"host";let t=e.now??(()=>performance.now()),o=e.clockOrigin??t();this.now=()=>Math.floor(t()-o);let n={info:{id:0,owner:0,name:"$host",apiVersion:1,codeVersion:1,services:[],hooks:[],requires:[]},definition:{name:"$host",apiVersion:1}};this.hostScope=this.scopes.environment({kind:I.Host},n);for(let[r,s]of Object.entries(e.resources??{}))new M(this,this.hostScope).resource(r,s);this.scopes.registerHost(this.hostScope),this.hostScope.phase=S.Prepared,this.programs.register(this.hostScope)}principalFor(e){return this.objects.get(e)?.address.principal??this.principal}snapshot(e){return this.kernel.command(d.Snapshot,{object:e})}value(e){if(this.values.has(e))return this.values.get(e);if(!this.options.native)h(c.Invalid.ValueGone);let t=this.options.native.value(e);return this.values.set(e,t),t}check(e,t){let o=z(e,this);if(!o.invocation||o.invocation.object!==t)throw new v(c.Forbidden.StateOwner);return o.invocation}adopt(e,t,o,n){let r=this.check(t,e),s=this.values.put(n);try{return this.kernel.command(d.StateAdopt,{call:r.id,object:e,revision:o,value:s})}catch(i){throw this.values.drop(s),i}finally{this.lifecycle.flush()}}publish(e){if(this.#t.push(e),this.#e)return;this.#e=!0;try{while(this.#t.length)this.#t.shift()()}finally{this.#e=!1}}report(e){let t=F(e);if(this.errors.length===64)this.errors.shift();this.errors.push(t);try{this.options.onError?.(t)}catch{}}track(e,t=!1){return this.jobs.add(e),e.then(()=>{this.jobs.delete(e)},(o)=>{if(this.jobs.delete(e),t)this.cleanupErrors.push(o),this.report(o)}),e}}class Re{session;constructor(e){this.session=new we(e)}get name(){return this.session.name}get features(){return this.session.kernel.features}install(e){return this.session.orbs.install(Array.isArray(e)?e:[e])}async load(e){if(!this.session.options.load)throw Error("This host has no module loader");await this.install(await this.session.options.load(e))}reload(e,t){return this.session.replacements.replace(e,t)}prepare(e,t){return this.session.replacements.prepare(e,t)}remove(e,t){return this.session.replacements.replace([],t,e)}hold(e,t,o){return this.session.handles.hold(e,t,o)}get(e,t,o){return this.session.handles.get(e,t,o)}root(e,t={}){return this.session.calls.root(e,!1,void 0,t.principal)}resource(e,t){return this.session.scopes.resource(e,t)}diagnostics(){return this.session.lifecycle.diagnostics()}errors(){return this.session.errors.splice(0)}traces(){return this.session.telemetry?.drain()??[]}installedOrbs(){return this.session.kernel.command(d.Orbs).map((e)=>{let t=this.session.orbs.records.get(e.id)?.definition,o=Object.freeze({...e,hookCapabilities:Object.fromEntries(e.hooks.map((n)=>[n,t?.hooks?.[n]?.capabilities??[]]))});return Object.freeze({...e,describe:()=>o})})}close(){return this.session.lifecycle.close()}}var O=Deno.core.ops,N=globalThis;N.queueMicrotask??=(e)=>Promise.resolve().then(e);N.performance??={now:()=>O.op_tembra_now()};N.AbortController??=class{signal={aborted:!1,reason:void 0,listeners:new Set,addEventListener(e,t){this.listeners.add(t)},removeEventListener(e,t){this.listeners.delete(t)},throwIfAborted(){if(this.aborted)throw this.reason}};abort(e=Error("Aborted")){if(this.signal.aborted)return;this.signal.aborted=!0,this.signal.reason=e;for(let t of[...this.signal.listeners])t();this.signal.listeners.clear()}};var qe=0,Oe=new Set;N.setTimeout??=(e,t=0,...o)=>{let n=++qe;return Oe.add(n),O.op_tembra_sleep(n,Math.max(0,Math.min(2147483647,t))).then(()=>{if(Oe.delete(n))e(...o)}),n};N.clearTimeout??=(e)=>{if(Oe.delete(e))O.op_tembra_clear_timer(e)};function Fe(e={}){let t=e.serialization??B;if(t.id!==O.op_tembra_codec())throw new v(c.Conflict.Codec,"The Rust and JS host codecs must agree");function o(a){let u=t.deserialize(a);if(u.error)throw new v(u.error);return u.ok}let n=O.op_tembra_driver_enabled?.()??!1,r=new Map;N.__tembraDeliver=(a)=>{for(let[u,b,m]of a){let k=r.get(u);if(!k)throw Error("unknown native completion");r.delete(u);try{if(!m)throw Error(b);k.resolve(o(b))}catch(y){k.reject(y)}}};function s(a,u){let b=O.op_tembra_submit(a,u);return new Promise((m,k)=>r.set(b,{resolve:m,reject:k}))}let i=new Re({...e,clockOrigin:0,kernel:{request:(a)=>O.op_tembra_kernel(a)},native:{...n?{admit:(a,u,b)=>{let m=JSON.parse(O.op_tembra_admit(JSON.stringify({reference:a,method:u,root:b.root,context:b.frame,parent:b.invocation?.id})));if(m.error)throw new v(m.error);return m.ok},finish:(a,u)=>{let b=JSON.parse(O.op_tembra_finish(a,String(u)));if(b.error)throw new v(b.error);return b.ok}}:{},rootEnded:(a)=>O.op_tembra_end_context(a),access:(a,u,b)=>JSON.parse(O.op_tembra_access(a,u,b))??void 0,settled:()=>O.op_tembra_settled(),notify:(a)=>O.op_tembra_notify(JSON.stringify(a)),hasContribution:(a)=>O.op_tembra_has_contribution?.(a)??!1,contribute:async(a,u,b)=>o(await O.op_tembra_native("contribute",t.serialize({operation:a,root:u.root,frame:u.frame,...b===void 0?{}:{input:b}}))).value,hasOrb:(a)=>O.op_tembra_has_orb(a),activate:async(a,u,b)=>{o(await O.op_tembra_native("activate",t.serialize({object:a,orb:u,service:b})))},invoke:async(a,u)=>n?s("invoke",t.serialize({invocation:a,arguments:u})):o(await O.op_tembra_native("invoke",t.serialize({invocation:a,arguments:u}))),dispose:async(a)=>{o(await O.op_tembra_native("dispose",t.serialize({object:a})))},effect:async(a)=>o(await O.op_tembra_native("effect",t.serialize(a))),cancelEffect:async(a)=>{o(await O.op_tembra_native("cancel-effect",t.serialize(a)))},value:(a)=>o(O.op_tembra_value(a)),dropValue:(a)=>O.op_tembra_drop_value(a)}});if(O.op_tembra_callback_next)(async()=>{for(;;){let a=O.op_tembra_callback_next();Deno.core.unrefOpPromise(a);let u=await a;if(!u.length)return;let b=new DataView(u.buffer,u.byteOffset,9),m=b.getUint8(0),k=b.getUint32(1,!0)+b.getUint32(5,!0)*4294967296;if(m!==0){if(m===2)i.session.calls.releaseRoot(k);if(m===3)i.session.handles.revoke(k);i.session.lifecycle.flush();continue}let y;try{y=t.deserialize(u.subarray(9))}catch(g){let{code:w,reason:x,message:j}=F(g);O.op_tembra_callback_error(k,JSON.stringify({code:w,reason:x,message:j}),!0);continue}i.session.track((async()=>{let g;try{let w;if(y.kind==="activate")await i.session.handles.activateAcquired(y.acquired,y.address,y.methods),w=null;else{let x=y.call,j=i.session.kernel.command(d.Invocation,{call:x}),q=new A(i.session,j.root,j,y.frame);if(y.kind==="invoke"){let R=i.session.objects.get(j.object),T=R?.versions.get(j.orb),D=T?.orb.definition.services?.[R.address.service]?.methods[j.method];if(!D||!T)throw new v(c.Gone.Implementation);w=await D(T.value,q,...y.input)}else w=await i.session.orbs.runContribution(y.operation,q,y.input)}g=w===void 0?{}:{value:w}}catch(w){let x=F(w);g={error:{code:x.code,reason:x.reason,message:x.message}}}try{O.op_tembra_callback_complete(k,t.serialize(g))}catch(w){let{code:x,reason:j,message:q}=F(w);O.op_tembra_callback_error(k,JSON.stringify({code:x,reason:j,message:q}),!1)}})(),!0)}})();return i}N.Tembra=Object.freeze({ContextKey:U,ContextKind:P,opaqueFrom:xe,createHost:Fe,jsonCodec:B,Code:l,Reason:p,Lifetime:J,Status:V,ReloadStatus:_,HookCapability:oe,Errors:c});})();
1
+ (()=>{var l=Object.freeze({Invalid:"invalid",Unavailable:"unavailable",Released:"released",Gone:"gone",Expired:"expired",Cancelled:"cancelled",Forbidden:"forbidden",Conflict:"conflict",Unsupported:"unsupported",Closed:"closed",Exhausted:"exhausted"}),u=Object.freeze({ActivationBusy:"activation_busy",Address:"address",AlreadyCommitted:"already_committed",AmbiguousScope:"ambiguous_scope",ApiVersion:"api_version",Arguments:"arguments",AsyncFactory:"async_factory",AsyncState:"async_state",Bigint:"bigint",ByteResult:"byte_result",Call:"call",Callback:"callback",CleanupBusy:"cleanup_busy",Clock:"clock",Codec:"codec",Connection:"connection",Context:"context",Contribution:"contribution",CoordinationLimits:"coordination_limits",Deadline:"deadline",Dependency:"dependency",DependencyCycle:"dependency_cycle",DependencyService:"dependency_service",Disposing:"disposing",Driver:"driver",Duplicate:"duplicate",DuplicateContribution:"duplicate_contribution",DuplicateListener:"duplicate_listener",DuplicateResource:"duplicate_resource",DuplicateService:"duplicate_service",EffectResults:"effect_results",EffectsRunning:"effects_running",EngineEffect:"engine_effect",EventSource:"event_source",ExclusiveDependent:"exclusive_dependent",Executor:"executor",Orb:"orb",OrbGone:"orb_gone",OrbInstalled:"orb_installed",OrbScope:"orb_scope",Factory:"factory",FactoryExpired:"factory_expired",FrameSize:"frame_size",GateBusy:"gate_busy",GateOrb:"gate_orb",GateObject:"gate_object",Hook:"hook",HookDependency:"hook_dependency",Hooks:"hooks",HooksDisabled:"hooks_disabled",Host:"host",HostAddress:"host_address",HostResource:"host_resource",HostResourceReload:"host_resource_reload",Identities:"identities",Implementation:"implementation",Invocation:"invocation",Javascript:"javascript",JsonAccessor:"json_accessor",JsonCycle:"json_cycle",JsonNumber:"json_number",JsonSymbol:"json_symbol",JsonTag:"json_tag",JsonType:"json_type",JsonValue:"json_value",Lifetime:"lifetime",Linger:"linger",ListenerCallback:"listener_callback",LiveConsumer:"live_consumer",LiveReference:"live_reference",LocalValue:"local_value",Memory:"memory",Metadata:"metadata",MetadataSize:"metadata_size",Method:"method",MigrationGate:"migration_gate",MigrationRequired:"migration_required",MigrationValue:"migration_value",MissingHook:"missing_hook",MissingMethod:"missing_method",NativeEffect:"native_effect",NativeMethod:"native_method",NativeObject:"native_object",NativeService:"native_service",Next:"next",NextUsed:"next_used",NotReady:"not_ready",Object:"object",ObjectState:"object_state",ObservationSource:"observation_source",ObservationAdmitted:"observation_admitted",Opaque:"opaque",Operation:"operation",OperationOwner:"operation_owner",Owner:"owner",Payload:"payload",PendingRequests:"pending_requests",PrepareDeadline:"prepare_deadline",Priority:"priority",Program:"program",ProgramPhase:"program_phase",ProgramRunning:"program_running",Reference:"reference",ReloadAborted:"reload_aborted",ReloadDeadline:"reload_deadline",ReloadPreparing:"reload_preparing",ReloadRunning:"reload_running",ReloadTicket:"reload_ticket",RemoteOpaque:"remote_opaque",RemoteReferences:"remote_references",Request:"request",RequestIds:"request_ids",Requires:"requires",Resource:"resource",ResourceDependencies:"resource_dependencies",ResourceDependency:"resource_dependency",ResourceHost:"resource_host",ResourceInFactory:"resource_in_factory",ResourceState:"resource_state",ResourceVersion:"resource_version",Result:"result",RetainedVersions:"retained_versions",RevisionExhausted:"revision_exhausted",Root:"root",Route:"route",RpcFrame:"rpc_frame",RpcOperation:"rpc_operation",RpcRequest:"rpc_request",RustType:"rust_type",Scope:"scope",ScopeClosed:"scope_closed",ScopeOrb:"scope_orb",ScopeOwner:"scope_owner",ScopeResource:"scope_resource",Serialization:"serialization",Service:"service",ServiceGone:"service_gone",State:"state",StateCycle:"state_cycle",StateInitialized:"state_initialized",StateOwner:"state_owner",StateRevision:"state_revision",StateValidation:"state_validation",StateValue:"state_value",StateVersion:"state_version",Subscription:"subscription",SubscriptionBusy:"subscription_busy",SubscriptionIdle:"subscription_idle",SubscriptionQueue:"subscription_queue",SubscriptionSize:"subscription_size",SubscriptionsDisabled:"subscriptions_disabled",Superseded:"superseded",Task:"task",Telemetry:"telemetry",UndeclaredDependency:"undeclared_dependency",UndeclaredService:"undeclared_service",UnknownService:"unknown_service",UpgradeConflict:"upgrade_conflict",Utf8:"utf8",Value:"value",ValueGone:"value_gone",ValuesExhausted:"values_exhausted",Views:"views"}),G=Object.freeze({Referenced:"referenced",Host:"host"}),_=Object.freeze({Loading:"loading",Live:"live",Released:"released",Gone:"gone"}),D=Object.freeze({Prepared:"prepared",Committed:"committed",Aborted:"aborted"}),ie=Object.freeze({Observe:"observe",Transform:"transform",Decide:"decide"});var d=Object.freeze({ContextDerive:"context-derive",ContextValue:"context-value",ContextStats:"context-stats",Allocate:"allocate",ScopeRegister:"scope-register",ScopeExists:"scope-exists",ScopesForOwner:"scopes-for-owner",ScopesForOrb:"scopes-for-orb",ScopeAddResource:"scope-add-resource",ScopeActivate:"scope-activate",ScopesCleanup:"scopes-cleanup",ScopesReloadRegistered:"scopes-reload-registered",ScopesReload:"scopes-reload",ProgramRun:"program-run",ProgramNext:"program-next",ProgramCompleteStep:"program-complete-step",ProgramCommit:"program-commit",ProgramAbort:"program-abort",ProgramForget:"program-forget",Features:"features",Prepare:"prepare",Gate:"gate",GateOrbs:"gate-orbs",Commit:"commit",Abort:"abort",Orbs:"orbs",Orb:"orb",OrbNamed:"orb-named",NextDeadline:"next-deadline",Address:"address",Acquire:"acquire",Ready:"ready",Dependency:"dependency",Undepend:"undepend",Fail:"fail",Status:"status",Release:"release",Forget:"forget",Root:"root",CleanupRoot:"cleanup-root",RootPrincipal:"root-principal",CheckContext:"check-context",CheckRoot:"check-root",EndRoot:"end-root",CancelRoot:"cancel-root",BeginCall:"begin-call",BeginOperation:"begin-operation",BeginHookObservation:"begin-hook-observation",FinishCall:"finish-call",Invocation:"invocation",StateInit:"state-init",Snapshot:"snapshot",StateAdopt:"state-adopt",Task:"task",TaskRoot:"task-root",StopTask:"stop-task",FinishTask:"finish-task",Resource:"resource",ResourceOpened:"resource-opened",ResourceValue:"resource-value",CloseResource:"close-resource",ResourceClosed:"resource-closed",Disposed:"disposed",Tick:"tick",NextWake:"next-wake",NextIdle:"next-idle",Close:"close",FinishClose:"finish-close",Diagnostics:"diagnostics",Drain:"drain",Restrict:"restrict",Contribute:"contribute",ContributionOrdinal:"contribution-ordinal",HookPlan:"hook-plan",Listen:"listen",Subscribe:"subscribe",Enqueue:"enqueue",NextDelivery:"next-delivery",FinishDelivery:"finish-delivery",Unsubscribe:"unsubscribe"}),C=Object.freeze({Execute:"execute",CancelEffects:"cancel-effects",ProgramPrepared:"program-prepared",ProgramComplete:"program-complete",Dispose:"dispose",CloseResource:"close-resource",DropValue:"drop-value",CancelRoot:"cancel-root",CancelTask:"cancel-task",RetireOrb:"retire-orb",State:"state",SubscriptionFailed:"subscription-failed",DetachSubscription:"detach-subscription",Deliver:"deliver"}),j=Object.freeze({Stop:"stop",Open:"open",Close:"close",Restore:"restore",Prepare:"prepare",Validate:"validate",Initialize:"initialize",Migrate:"migrate",Adopt:"adopt",Start:"start",Drop:"drop"}),Ge=Object.freeze({Execute:"execute",Wait:"wait",Prepared:"prepared",Complete:"complete",Failed:"failed"}),Be=Object.freeze({Activate:"activate",Dispose:"dispose",CancelEffect:"cancel-effect",Effect:"effect",Invoke:"invoke",Contribute:"contribute"}),We=Object.freeze({Describe:"describe",Get:"get",Release:"release",Call:"call",Cancel:"cancel"}),$e=Object.freeze({State:"state"}),I=Object.freeze({Host:"host",Orb:"orb",Object:"object"}),S=Object.freeze({Declaring:"declaring",Prepared:"prepared",Live:"live",Closed:"closed"}),Qe=Object.freeze({Preparing:"preparing",Commit:"commit",Abort:"abort"}),ae=Object.freeze({Ok:"ok",Error:"error"}),K=Object.freeze({Bigint:"bigint",Bytes:"bytes",Object:"object"}),je=Object.freeze({Json:"tembra-json/1",MessagePack:"tembra-msgpack/1"});function f(e,t,n){return Object.freeze({code:e,reason:t,message:n})}var c=Object.freeze({Cancelled:Object.freeze({EngineEffect:f(l.Cancelled,u.EngineEffect,"The engine effect was cancelled"),Request:f(l.Cancelled,u.Request,"The request was cancelled"),Resource:f(l.Cancelled,u.Resource,"Resource opening was cancelled"),Root:f(l.Cancelled,u.Root,"The operation was cancelled"),Task:f(l.Cancelled,u.Task,"The task was cancelled")}),Closed:Object.freeze({Host:f(l.Closed,u.Host,"The host is closing")}),Conflict:Object.freeze({AlreadyCommitted:f(l.Conflict,u.AlreadyCommitted,"The replacement is already committed"),Codec:f(l.Conflict,u.Codec,"The Rust and JS host codecs must agree"),PrepareDeadline:f(l.Conflict,u.PrepareDeadline,"The preparation deadline expired"),ReloadRunning:f(l.Conflict,u.ReloadRunning,"A replacement is already running"),ReloadTicket:f(l.Conflict,u.ReloadTicket,"The replacement is no longer prepared")}),Exhausted:Object.freeze({FrameSize:f(l.Exhausted,u.FrameSize,"The frame exceeds the configured size limit"),PendingRequests:f(l.Exhausted,u.PendingRequests,"The pending request limit was reached"),RemoteReferences:f(l.Exhausted,u.RemoteReferences,"The remote reference limit was reached"),RequestIds:f(l.Exhausted,u.RequestIds,"Request identities are exhausted"),SubscriptionQueue:f(l.Exhausted,u.SubscriptionQueue,"The subscription queue is full")}),Expired:Object.freeze({Next:f(l.Expired,u.Next,"Continuation scope has ended")}),Forbidden:Object.freeze({Context:f(l.Forbidden,u.Context,"An issued context from this host is required"),HostResource:f(l.Forbidden,u.HostResource,"The host resource was not declared"),Method:f(l.Forbidden,u.Method,"The method is not allowed by this reference"),ObservationSource:f(l.Forbidden,u.ObservationSource,"Hook observation requires the original physical invocation"),Opaque:f(l.Forbidden,u.Opaque,"The resource is not available as an opaque local value"),Service:f(l.Forbidden,u.Service,"Access to this service is forbidden"),StateOwner:f(l.Forbidden,u.StateOwner,"Only the owning orb may change this state"),UndeclaredDependency:f(l.Forbidden,u.UndeclaredDependency,"The dependency was not declared"),UndeclaredService:f(l.Forbidden,u.UndeclaredService,"The service was not declared as a dependency")}),Gone:Object.freeze({Connection:f(l.Gone,u.Connection,"The connection is closed"),Contribution:f(l.Gone,u.Contribution,"The contribution is no longer available"),Implementation:f(l.Gone,u.Implementation,"The implementation is no longer available"),ListenerCallback:f(l.Gone,u.ListenerCallback,"The listener callback is no longer available"),Reference:f(l.Gone,u.Reference,"The reference is no longer available"),Resource:f(l.Gone,u.Resource,"The resource is no longer available"),Scope:f(l.Gone,u.Scope,"The declaration scope is no longer available"),State:f(l.Gone,u.State,"State owner is gone")}),Invalid:Object.freeze({Address:f(l.Invalid,u.Address,"Invalid address"),AsyncFactory:f(l.Invalid,u.AsyncFactory,"Factories must be synchronous"),AsyncState:f(l.Invalid,u.AsyncState,"State updates and migrations must be synchronous"),CoordinationLimits:f(l.Invalid,u.CoordinationLimits,"Invalid coordination limits"),DependencyCycle:f(l.Invalid,u.DependencyCycle,"Orb factories cannot acquire their own services"),DependencyService:f(l.Invalid,u.DependencyService,"Invalid dependency service"),DuplicateListener:f(l.Invalid,u.DuplicateListener,"Invalid duplicate listener"),DuplicateResource:f(l.Invalid,u.DuplicateResource,"Invalid duplicate resource"),EventSource:f(l.Invalid,u.EventSource,"Invalid event source"),Orb:f(l.Invalid,u.Orb,"An orb needs a name and positive API version"),OrbGone:f(l.Invalid,u.OrbGone,"Invalid orb gone"),OrbInstalled:f(l.Invalid,u.OrbInstalled,"Use reload to replace an installed orb"),Factory:f(l.Invalid,u.Factory,"Invalid factory"),FactoryExpired:f(l.Invalid,u.FactoryExpired,"Declarations must be synchronous"),Hook:f(l.Invalid,u.Hook,"Hooks need a run function"),HookDependency:f(l.Invalid,u.HookDependency,"Invalid hook dependency"),HooksDisabled:f(l.Invalid,u.HooksDisabled,"Invalid hooks disabled"),JsonAccessor:f(l.Invalid,u.JsonAccessor,"Invalid json accessor"),JsonCycle:f(l.Invalid,u.JsonCycle,"Invalid json cycle"),JsonNumber:f(l.Invalid,u.JsonNumber,"Use BigInt for integers outside the safe Number range"),JsonSymbol:f(l.Invalid,u.JsonSymbol,"Invalid json symbol"),JsonTag:f(l.Invalid,u.JsonTag,"Unknown or malformed portable type tag"),JsonType:f(l.Invalid,u.JsonType,"Supply a codec for custom object types"),JsonValue:f(l.Invalid,u.JsonValue,"This JSON codec requires explicit portable values"),Method:f(l.Invalid,u.Method,"Methods must be functions"),NextUsed:f(l.Invalid,u.NextUsed,"Invalid next used"),Priority:f(l.Invalid,u.Priority,"Invalid priority"),Reference:f(l.Invalid,u.Reference,"An issued local reference is required"),Resource:f(l.Invalid,u.Resource,"Invalid resource"),ResourceHost:f(l.Invalid,u.ResourceHost,"Resource dependencies must belong to the same host"),ResourceInFactory:f(l.Invalid,u.ResourceInFactory,"Resources open after declaration"),RpcFrame:f(l.Invalid,u.RpcFrame,"Invalid rpc frame"),RpcOperation:f(l.Invalid,u.RpcOperation,"Invalid rpc operation"),RpcRequest:f(l.Invalid,u.RpcRequest,"Invalid rpc request"),Service:f(l.Invalid,u.Service,"Invalid service"),ServiceGone:f(l.Invalid,u.ServiceGone,"Invalid service gone"),State:f(l.Invalid,u.State,"Service does not expose state"),StateCycle:f(l.Invalid,u.StateCycle,"State cannot contain cycles"),StateValidation:f(l.Invalid,u.StateValidation,"The orb rejected the state candidate"),StateValue:f(l.Invalid,u.StateValue,"State cannot contain accessors"),StateVersion:f(l.Invalid,u.StateVersion,"Invalid state version"),SubscriptionsDisabled:f(l.Invalid,u.SubscriptionsDisabled,"Invalid subscriptions disabled"),SubscriptionSize:f(l.Invalid,u.SubscriptionSize,"A local byte budget requires an explicit sizeOf function"),Task:f(l.Invalid,u.Task,"Invalid task"),Utf8:f(l.Invalid,u.Utf8,"Invalid utf8"),ValueGone:f(l.Invalid,u.ValueGone,"Invalid value gone"),ValuesExhausted:f(l.Invalid,u.ValuesExhausted,"Invalid values exhausted")}),Released:Object.freeze({Reference:f(l.Released,u.Reference,"The reference has been released")}),Unavailable:Object.freeze({Callback:f(l.Unavailable,u.Callback,"A callback failed"),OrbScope:f(l.Unavailable,u.OrbScope,"The orb scope is unavailable"),NotReady:f(l.Unavailable,u.NotReady,"The object is not ready"),Route:f(l.Unavailable,u.Route,"The route is unavailable")}),Unsupported:Object.freeze({EngineEffect:f(l.Unsupported,u.EngineEffect,"The engine effect is not supported by this adapter"),RemoteOpaque:f(l.Unsupported,u.RemoteOpaque,"Opaque resources are local to their language environment"),Telemetry:f(l.Unsupported,u.Telemetry,"Telemetry is disabled in this kernel"),Views:f(l.Unsupported,u.Views,"Reference views are disabled in this kernel")})});var He=new Set(Object.values(l));function Me(e){return typeof e==="object"&&e!==null&&"code"in e&&He.has(e.code)&&"reason"in e&&typeof e.reason==="string"&&"message"in e&&typeof e.message==="string"}class b extends Error{code;reason;constructor(e,t=e.message,n){super(t,n);this.name="TembraError",this.code=e.code,this.reason=e.reason}}function z(e){let t=c.Unavailable.Callback.message;try{if(e instanceof b)return e;if(Me(e))return new b(e,e.message,{cause:e});t=String(e instanceof Error?e.message:e)}catch{}return new b(c.Unavailable.Callback,t,{cause:e})}function h(e,t=e.message){throw new b(e,t)}var B="$tembra";function ce(e,t){if(typeof e==="bigint")return{[B]:[K.Bigint,e.toString()]};if(e instanceof Uint8Array)return{[B]:[K.Bytes,[...e]]};if(e===null||typeof e==="string"||typeof e==="boolean")return e;if(typeof e==="number"){if(!Number.isFinite(e)||Number.isInteger(e)&&!Number.isSafeInteger(e))h(c.Invalid.JsonNumber,"Use BigInt for integers outside the safe Number range");return e}if(typeof e!=="object")h(c.Invalid.JsonValue,"This JSON codec requires explicit portable values");if(t.has(e))h(c.Invalid.JsonCycle);let n=Object.getPrototypeOf(e);if(!Array.isArray(e)&&n!==Object.prototype&&n!==null)h(c.Invalid.JsonType,"Supply a codec for custom object types");t.add(e);try{if(Array.isArray(e))return Array.from(e,(r)=>ce(r,t));let o=Reflect.ownKeys(e).map((r)=>{if(typeof r!=="string")h(c.Invalid.JsonSymbol);let s=Object.getOwnPropertyDescriptor(e,r);if(!Object.hasOwn(s,"value"))h(c.Invalid.JsonAccessor);return[r,ce(s.value,t)]});return Object.hasOwn(e,B)?{[B]:[K.Object,o]}:Object.fromEntries(o)}finally{t.delete(e)}}function ne(e){if(e===null||typeof e!=="object"){if(typeof e==="number"&&Number.isInteger(e)&&!Number.isSafeInteger(e))h(c.Invalid.JsonNumber);return e}if(Array.isArray(e))return e.map(ne);if(Object.hasOwn(e,B)){let t=e[B];if(Object.keys(e).length!==1||!Array.isArray(t)||t.length!==2)h(c.Invalid.JsonTag);let[n,o]=t;if(n===K.Bigint&&typeof o==="string"&&/^-?(0|[1-9]\d*)$/.test(o))return BigInt(o);if(n===K.Bytes&&Array.isArray(o)&&o.every((r)=>Number.isInteger(r)&&r>=0&&r<=255))return Uint8Array.from(o);if(n===K.Object&&Array.isArray(o)){if(!o.every((r)=>Array.isArray(r)&&r.length===2&&typeof r[0]==="string"))h(c.Invalid.JsonTag);return Object.fromEntries(o.map(([r,s])=>[r,ne(s)]))}h(c.Invalid.JsonTag,"Unknown or malformed portable type tag")}return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,ne(n)]))}function Ke(e){let t=[];for(let n of e){let o=n.codePointAt(0);if(o>=55296&&o<=57343)o=65533;if(o<128)t.push(o);else if(o<2048)t.push(192|o>>6,128|o&63);else if(o<65536)t.push(224|o>>12,128|o>>6&63,128|o&63);else t.push(240|o>>18,128|o>>12&63,128|o>>6&63,128|o&63)}return Uint8Array.from(t)}function Ue(e){let t=[];for(let n=0;n<e.length;){let o=e[n++];if(o<128){t.push(String.fromCharCode(o));continue}let r=o>=194&&o<=223?1:o>=224&&o<=239?2:o>=240&&o<=244?3:-1;if(r<0||n+r>e.length)h(c.Invalid.Utf8);let s=o&127>>r+1;for(let a=0;a<r;a++){let i=e[n++];if((i&192)!==128)h(c.Invalid.Utf8);s=s<<6|i&63}if(s<[0,128,2048,65536][r]||s>1114111||s>=55296&&s<=57343)h(c.Invalid.Utf8);t.push(String.fromCodePoint(s))}return t.join("")}var W=Object.freeze({id:je.Json,serialize:(e)=>Ke(JSON.stringify(ce(e,new WeakSet))),deserialize:(e)=>ne(JSON.parse(Ue(e)))});var P=Object.freeze({Text:"text",Integer:"integer",Boolean:"boolean",Opaque:"opaque"});class U{name;version;kind;constructor(e,t,n){this.name=e;this.version=t;this.kind=n;Object.freeze(this)}static text(e,t=1){return new U(e,t,P.Text)}static integer(e,t=1){return new U(e,t,P.Integer)}static boolean(e,t=1){return new U(e,t,P.Boolean)}static opaque(e,t=1){return new U(e,t,P.Opaque)}source(e,t){if(this.kind!==P.Opaque)return;let n=typeof e==="object"&&e!==null?t.session.contextTokens.get(e):void 0;if(!n||n.root!==t.root)throw TypeError("An owner-issued opaque reference from this host and root is required");return n.source}}function de(e,t,n){let o=e.session.kernel.command(d.ContextValue,{root:e.root,context:n,call:e.invocation?.id,key:t});if(!o)return;if(o.kind!==P.Opaque)return o.value;let r=Object.freeze({opaque:!0});return e.session.contextTokens.set(r,{root:e.root,source:o.source}),r}function Ee(e,t,n){let o=de(e,t,n);if(!o)throw TypeError("The owner did not issue a reference");return o}var Ie=Symbol.for("@syntropika/tembra-sdk/service-identities"),Q=Object.getOwnPropertyDescriptor(globalThis,Ie)?.value;if(Q!==void 0&&!(Q instanceof WeakMap))throw TypeError("The SDK service identity slot must contain a WeakMap");var X=Q instanceof WeakMap?Q:new WeakMap;if(Q===void 0)Object.defineProperty(globalThis,Ie,{value:X});function De(e,t,n){let o=new Map;for(let[r,s,a]of n){let i={orb:e,name:r,apiVersion:t};for(let p of[s,a]){let m=o.get(p)??X.get(p);if(m&&(m.orb!==e||m.name!==r||m.apiVersion!==t))h(c.Invalid.Service,"A service definition must have one orb, name and API version");o.set(p,i)}}for(let[r,s]of o)X.set(r,s)}function Y(e,t={}){if(typeof e==="string")return{name:e,options:t};let n=X.get(e);if(!n)h(c.Invalid.Service,"Declare this service in an orb before acquiring it");if(t.apiVersion!==void 0&&t.apiVersion!==n.apiVersion)h(c.Invalid.Service,"The acquisition API version must match the service declaration");return{name:n.name,options:{...t,apiVersion:n.apiVersion}}}function le(e){if(!e.name||!Number.isInteger(e.apiVersion)||e.apiVersion<=0)h(c.Invalid.Orb,"An orb needs a name and positive API version");let t=Object.fromEntries(Object.entries(e.services??{}).map(([a,i])=>{if(!a||!i.methods||typeof i.methods!=="object")h(c.Invalid.Service);if(i.create&&typeof i.create!=="function")h(c.Invalid.Factory);for(let m of Object.values(i.methods))if(typeof m!=="function")h(c.Invalid.Method,"Methods must be functions");let p={...i,methods:Object.freeze({...i.methods})};return[a,Object.freeze(p)]})),n=Object.fromEntries(Object.entries(e.requires??{}).map(([a,i])=>[a,Object.freeze({...i,...i.methods?{methods:Object.freeze([...i.methods])}:{},...i.hooks?{hooks:Object.freeze([...i.hooks])}:{},...i.services?{services:Object.freeze(Object.fromEntries(Object.entries(i.services).map(([p,m])=>[p,Object.freeze([...m])])))}:{}})])),o=Object.fromEntries(Object.entries(e.hooks??{}).map(([a,i])=>{if(typeof i.run!=="function")h(c.Invalid.Hook,"Hooks need a run function");return[a,Object.freeze({...i,capabilities:Object.freeze([...i.capabilities??[]])})]})),r=Object.fromEntries(Object.entries(e.contributes??{}).map(([a,i])=>[a,Object.freeze(Object.fromEntries(Object.entries(i).map(([p,m])=>[p,typeof m==="function"?m:Object.freeze({...m})])))])),s=Object.freeze({...e,services:Object.freeze(t),requires:Object.freeze(n),hooks:Object.freeze(o),contributes:Object.freeze(r)});return De(e.name,e.apiVersion,Object.entries(e.services??{}).map(([a,i])=>[a,i,t[a]])),s}class pe{allocate;#e=1;#t=new Map;constructor(e){this.allocate=e}put(e){if(this.#e>4294967295)h(c.Invalid.ValuesExhausted);let t=this.allocate?this.allocate():this.#e++;return this.#t.set(t,e),t}get(e){if(!this.#t.has(e))h(c.Invalid.ValueGone);return this.#t.get(e)}drop(e){this.#t.delete(e)}has(e){return this.#t.has(e)}set(e,t){this.#t.set(e,t)}clear(){this.#t.clear()}get size(){return this.#t.size}}var Pe=new WeakSet;function Z(e){let t=new WeakSet;function n(o){if(o===null||typeof o!=="object"){if(["function","symbol"].includes(typeof o))h(c.Invalid.StateValue,"State must contain plain data");return}if(Pe.has(o))return;if(t.has(o))h(c.Invalid.StateCycle,"State cannot contain cycles");let r=Object.getPrototypeOf(o);if(!Array.isArray(o)&&r!==Object.prototype&&r!==null)h(c.Invalid.StateValue,"State requires plain objects and arrays");t.add(o);for(let s of Reflect.ownKeys(o)){if(typeof s!=="string")h(c.Invalid.StateValue,"State cannot contain symbol properties");let a=Object.getOwnPropertyDescriptor(o,s);if(!Object.hasOwn(a,"value"))h(c.Invalid.StateValue,"State cannot contain accessors");n(a.value)}t.delete(o),Object.freeze(o),Pe.add(o)}return n(e),e}class oe{compute;report;check;#e;#t=new Set;#n=new Set;#o=!0;#r;#s;#i;constructor(e,t,n,o){this.compute=e;this.report=n;this.check=o;this.#e=Z(e(t))}get value(){return this.check(),this.#e}track(e,t){this.#r=e,this.#i=t;let n=new WeakRef(this);this.#s=()=>n.deref()?.detach(),e?.add(this.#s)}detach(){if(!this.#o)return;if(this.#o=!1,this.#s)this.#r?.delete(this.#s);this.#i?.(),this.#t.clear();for(let e of this.#n)e.deref()?.detach();this.#n.clear()}prepare(e){if(!this.#o)return;try{this.check()}catch{this.detach();return}let t;try{t=Z(this.compute(e))}catch(o){this.detach(),this.report(o);return}if(!this.#o)return;let n=[];if(!Object.is(t,this.#e))for(let o of this.#n){let s=o.deref()?.prepare(t);if(s)n.push(s);else this.#n.delete(o)}return{adopt:()=>{if(!this.#o||Object.is(t,this.#e))return()=>{};this.#e=t;let o=n.map((s)=>s.adopt()),r=[...this.#t];return()=>{if(!this.#o)return;for(let s of o)s();for(let s of r)try{s(t)}catch(a){this.report(a)}}}}}select(e){this.check();let t=new oe(e,this.#e,this.report,this.check);this.check();let n=new WeakRef(t);return this.#n.add(n),t.track(this.#r,()=>this.#n.delete(n)),t}subscribe(e){this.check(),this.#t.add(e);try{e(this.#e)}catch(t){this.report(t)}return()=>{this.#t.delete(e)}}}class L{backend;object;closed=!1;#e;#t=new Set;#n=new Set;constructor(e,t,n){this.backend=e;this.object=t;this.#e=arguments.length>=3?n:e.value(e.snapshot(t).value)}check(){if(this.closed)throw new b(c.Gone.State,"State owner is gone")}get value(){return this.check(),this.#e}view(e,t=()=>this.check()){let n=this;return{get value(){return t(),n.value},update(o,r){t(),n.backend.check(o,n.object);let s=n.backend.snapshot(n.object),a=n.backend.value(s.value),i=r(a);if(F(i,e),n.backend.check(o,n.object),Object.is(i,a))return a;let p=n.prepare(i);n.backend.adopt(n.object,o,s.revision,i);let m=n.adopt(p,i);return n.backend.publish(m),i},select:(o)=>(t(),n.select(o,t)),subscribe:(o)=>(t(),n.subscribe(o))}}select(e,t=()=>this.check(),n){t();let o=new oe(e,this.value,(s)=>this.backend.report(s),t);t();let r=new WeakRef(o);return this.#n.add(r),o.track(n,()=>this.#n.delete(r)),o}subscribe(e){this.check(),this.#t.add(e);try{e(this.value)}catch(t){this.backend.report(t)}return()=>{this.#t.delete(e)}}prepare(e){let t=[];for(let n of this.#n){let r=n.deref()?.prepare(e);if(r)t.push(r);else this.#n.delete(n)}return t}adopt(e,t){this.#e=t;let n=e.map((r)=>r.adopt()),o=[...this.#t];return()=>{for(let r of n)r();for(let r of o)try{r(t)}catch(s){this.backend.report(s)}}}close(){this.closed=!0,this.#e=void 0,this.#t.clear();for(let e of this.#n)e.deref()?.detach();this.#n.clear()}}function F(e,t){if(e&&typeof e.then==="function")h(c.Invalid.AsyncState,"State updates and migrations must be synchronous");let n=Z(e),o=t.validate?.(n);if(o!==void 0&&o!==!0)h(c.Invalid.StateValidation,"Orb rejected the candidate state");return n}class H{session;environment;constructor(e,t){this.session=e;this.environment=t}check(){if(this.environment.phase!==S.Declaring)h(c.Invalid.FactoryExpired,"Declarations must be synchronous")}get principal(){return this.session.principalFor(this.environment.object?.id??0)}get orb(){return this.environment.orb.scope?.value}get key(){return this.environment.object?.address.key??["main"]}state(e,t={}){this.check();let n=this.environment,o=n.object;if(!o||n.state)h(c.Invalid.State,"An object declares exactly one state");let r=t.version??1;if(!Number.isInteger(r)||r<=0)h(c.Invalid.StateVersion);let s=o.binding;if(!s&&o.live)s=new L(this.session,o.id,F(e,t));if(!s){let i=F(e,t),p=this.session.values.put(i);try{this.session.kernel.command(d.StateInit,{object:o.id,value:p,version:r})}catch(m){throw this.session.values.drop(p),m}o.binding=s=new L(this.session,o.id)}let a=s.view(t);return n.state={initial:e,options:t,binding:s},a}get(e,t,n={}){this.check();let o=Y(e,n),r=this.session.scopes.requirement(this.environment,o.name),s=r.service;if(typeof e!=="string"&&s!==o.name)h(c.Invalid.Service,"A typed dependency must resolve its declared service name");if(!this.environment.object&&this.environment.orb.definition.services?.[s])h(c.Invalid.DependencyCycle);let a=Y(e,{...n,...r.apiVersion?{apiVersion:r.apiVersion}:{},...r.methods?{methods:r.methods}:{},principal:n.principal??this.principal}),i=JSON.stringify([s,t,n.principal??this.principal]),p=this.environment.dependencies.get(i);if(p)return p;let m=this.session.handles.hold(s,t,a.options);if(this.environment.object)try{this.session.kernel.command(d.Dependency,{object:this.environment.object.id,reference:this.session.handles.reference(m).id})}catch(y){throw m.release(),y}return this.environment.dependencies.set(i,m),m}resource(e,t){if(this.check(),!t)return this.session.scopes.hostResource(e);if(this.environment.resources.has(e))h(c.Invalid.DuplicateResource,e);let n=this.session.resources.declare(this.environment,e,t);return this.environment.resources.set(e,n),n.handle}task(e){if(this.check(),typeof e!=="function")h(c.Invalid.Task);this.environment.tasks.push({start:e})}on(e,t,n,o={}){if(this.check(),!this.session.kernel.features.subscriptions)h(c.Invalid.SubscriptionsDisabled);if(o.maxBytes!==void 0&&!o.sizeOf)h(c.Invalid.SubscriptionSize,"A local byte budget requires an explicit sizeOf function");if(!e||this.environment.listeners.some((r)=>r.name===e))h(c.Invalid.DuplicateListener,e);this.environment.listeners.push({name:e,source:t,handle:n,options:o})}hook(e){if(this.check(),!this.session.kernel.features.hooks)h(c.Invalid.HooksDisabled);if(!this.environment.orb.definition.hooks?.[e])h(c.Invalid.Hook,e);let t=this.session.kernel.command(d.Allocate);return{run:(n,o)=>this.session.orbs.runHook(this.environment,e,n,o),observe:(n,o)=>this.session.orbs.observe(this.environment,e,t,n,o)}}}function Ae(e,t,n){return{get value(){return t(),e.value},select(o){return t(),e.select(o,t,n)},subscribe(o){t();let r=e.subscribe((i)=>{try{t()}catch{return}o(i)}),s=!0,a=()=>{if(!s)return;s=!1,n.delete(a),r()};n.add(a);try{t()}catch{a()}return a}}}class ue{port;features;constructor(e){this.port=e;this.features=this.command(d.Features)}command(e,t={}){let n=JSON.parse(this.port.request(JSON.stringify({...t,op:e})));if(n.error)throw new b(n.error);return n.ok}}class fe{capacity;sampleEvery;#e=[];#t=0;constructor(e=256,t=1){this.capacity=e;this.sampleEvery=t;if(!Number.isInteger(e)||e<=0||!Number.isInteger(t)||t<=0)throw RangeError("Invalid telemetry limits")}sample(){return this.#t++%this.sampleEvery===0}record(e){if(this.#e.length===this.capacity)this.#e.shift();this.#e.push(e)}drain(){return this.#e.splice(0)}}class me{session;tasks=new Map;listeners=new Map;#e=new WeakMap;constructor(e){this.session=e}prepare(e,t){for(let n of e.listeners){let o=typeof n.source==="function"?n.source():n.source;if(!o||typeof o.subscribe!=="function")h(c.Invalid.EventSource);let r=this.session.kernel.command(d.Listen,{scope:e.id,previous:t?.id,name:n.name,source:this.identity(o),sizing:n.options.sizeOf?this.identity(n.options.sizeOf):0,operation:this.session.kernel.command(d.Allocate),maxPending:n.options.maxPending??64,...n.options.maxBytes?{maxBytes:n.options.maxBytes}:{},coalesce:"select"in o}),s=this.listeners.get(r);if(s){n.running=s;continue}let a={id:r,definition:n,environment:e,stopped:!1,detach(){}};n.running=a,this.listeners.set(r,a);try{if(a.detach=o.subscribe((i)=>{if(a.stopped)return;let p=this.session.values.put(i);try{let m=n.options.sizeOf?.(i)??0;if(!Number.isSafeInteger(m)||m<0||m>4294967295)throw new b(c.Invalid.SubscriptionSize);this.session.kernel.command(d.Enqueue,{subscription:r,payload:p,bytes:m})}catch(m){this.session.values.drop(p),this.session.report(m),this.failed(r)}this.session.lifecycle.flush()}),a.stopped)a.detach()}catch(i){throw this.stopListener(a),i}}}start(e){e.phase=S.Live;for(let t of e.listeners){let n=t.running;n.environment=e,n.definition=t}for(let t of e.tasks)this.startTask(e,t)}startTask(e,t){if(t.running||e.phase!==S.Live||this.session.closing)return;let n=this.session.kernel.command(d.Task,{owner:e.owner}),o=new AbortController,r=this.session.kernel.command(d.Allocate),s={id:n,controller:o,done:Promise.resolve()};t.running=s,this.tasks.set(n,s),s.done=this.session.track(Promise.resolve().then(async()=>{try{await t.start({signal:o.signal,root:(a)=>{let i=this.session.kernel.command(d.TaskRoot,{task:n,principal:this.session.principalFor(e.object?.id??0)});return this.session.calls.root(()=>this.session.calls.owned(e,r,a,i),!1,i)}})}catch(a){if(!o.signal.aborted)this.session.report(a)}finally{this.session.kernel.command(d.Tick,{now:this.session.now()}),this.session.kernel.command(d.FinishTask,{task:n}),this.tasks.delete(n),delete t.running,this.session.lifecycle.flush()}}))}identity(e){let t=this.#e.get(e);if(t===void 0)t=this.session.kernel.command(d.Allocate),this.#e.set(e,t);return t}deliver(e,t,n){let o=this.listeners.get(e),r=Promise.resolve().then(async()=>{try{if(!o)throw new b(c.Gone.ListenerCallback);await this.session.calls.owned(o.environment,n,(s)=>o.definition.handle(s,this.session.values.get(t)))}catch(s){this.session.report(s)}finally{this.session.kernel.command(d.FinishDelivery,{subscription:e}),this.session.lifecycle.flush()}});if(o)o.done=r;this.session.track(r)}detach(e){let t=this.listeners.get(e);if(t)this.stopListener(t)}cancel(e){this.tasks.get(e)?.controller.abort(new b(c.Cancelled.Task))}failed(e){let t=this.listeners.get(e);if(!t)return;this.session.report(new b(c.Exhausted.SubscriptionQueue)),this.stopListener(t)}stopListener(e){if(e.stopped)return;e.stopped=!0;try{e.detach()}catch(t){this.session.report(t)}this.session.kernel.command(d.Unsubscribe,{subscription:e.id}),this.listeners.delete(e.id),this.session.lifecycle.flush()}async stop(e){for(let t of e.tasks)if(t.running)this.session.kernel.command(d.StopTask,{task:t.running.id});this.session.lifecycle.flush(),await Promise.all(e.tasks.map((t)=>t.running?.done)),await Promise.all(e.listeners.map((t)=>t.running?.done))}}var re=new WeakMap;class A{session;root;invocation;frame;constructor(e,t,n,o=0){this.session=e;this.root=t;this.invocation=n;this.frame=o;re.set(this,this)}with(e,t){let n=e.source(t,this),o=this.session.kernel.command(d.ContextDerive,{root:this.root,context:this.frame,call:this.invocation?.id,key:e,...e.kind===P.Opaque?{source:n}:{value:t}});return new A(this.session,this.root,this.invocation,o)}value(e){return de(this,e,this.frame)}exportValues(e){let t={};for(let n of e){if(n.kind===P.Opaque)throw TypeError("Local opaque references cannot be exported");let o=this.value(n);if(o!==void 0)t[`${n.name}@${n.version}`]=o}return t}get principal(){return this.session.kernel.command(d.RootPrincipal,{root:this.root})}get signal(){return this.session.calls.signal(this.root)}check(){this.session.kernel.command(d.CheckContext,{root:this.root,call:this.invocation?.id})}cancel(){this.session.kernel.command(d.CancelRoot,{root:this.root}),this.session.lifecycle.flush()}get(e,t,n={}){return this.check(),this.session.handles.get(e,t,n,this)}resource(e){return this.check(),this.session.scopes.hostResource(e)}}function he(e,t){if(typeof e!=="object"||e===null||re.get(e)?.session!==t)throw new b(c.Forbidden.Context,"An issued context from this host is required");return re.get(e)}function V(e,t){let n=he(e,t);return n.check(),n}function _e(e){return typeof e==="object"&&e!==null&&re.has(e)}class be{session;constructor(e){this.session=e}signal(e){let t=this.session,n=t.controllers.get(e);if(!n){n=new AbortController;try{t.kernel.command(d.CheckRoot,{root:e})}catch(o){if(!(o instanceof b)||o.code!==l.Cancelled)throw o;n.abort(o)}t.controllers.set(e,n)}return n.signal}releaseRoot(e){for(let t of this.session.rootReferences.get(e)??[])this.session.handles.release(t);this.session.rootReferences.delete(e),this.session.controllers.delete(e)}async root(e,t=!1,n,o=this.session.principal){let r=this.session,s=n??r.kernel.command(t?d.CleanupRoot:d.Root,{principal:o}),a=new A(r,s);try{return await e(a)}finally{if(this.releaseRoot(s),r.options.native?.rootEnded?.(s),!r.lifecycle.closedDiagnostics)r.kernel.command(d.EndRoot,{root:s});r.controllers.delete(s),r.lifecycle.flush()}}async invoke(e,t,n,o){let r=this.session;if(V(o,r),e.released)throw new b(c.Released.Reference);await e.ready;let s=r.options.native?.admit?.(e.id,t,o),a;if(s)a=s.call;else o.check(),a=r.kernel.command(d.BeginCall,{reference:e.id,root:o.root,context:o.frame||void 0,method:t});let i=new A(r,o.root,a,o.frame),p=r.track((async()=>{let m=r.telemetry?.sample(),y=m?r.now():0,v=ae.Ok;try{let g=r.options.native;if(g&&(s?.native??g.hasOrb(a.orb)))return await g.invoke(a,n,i);let R=r.objects.get(a.object)?.versions.get(a.orb),x=R?.orb.definition.services?.[e.address.service]?.methods[t];if(!R||!x)throw new b(c.Gone.Implementation);return await x(R.value,i,...n)}catch(g){throw v=ae.Error,g}finally{if(m)r.telemetry.record({service:e.address.service,method:t,root:a.root,codeVersion:a.codeVersion,duration:r.now()-y,outcome:v});r.lifecycle.finishCall(a.id)}})());return this.observe(p,o.signal)}async owned(e,t,n,o){let r=this.session,s=async(a)=>{let i=r.kernel.command(d.BeginOperation,{orb:e.orb.info.id,root:a.root,context:a.frame||void 0,operation:t,...e.object?{object:e.object.id}:{}});try{return await n(new A(r,a.root,i,a.frame))}finally{r.kernel.command(d.FinishCall,{call:i.id}),r.lifecycle.flush()}};return o===void 0?this.root(s,!1,void 0,r.principalFor(e.object?.id??0)):s(typeof o==="number"?new A(r,o):o)}async observe(e,t){if(t.aborted)throw t.reason;let n,o=new Promise((r,s)=>{n=()=>s(t.reason??new b(c.Cancelled.Root)),t.addEventListener("abort",n,{once:!0})});try{return await Promise.race([e,o])}finally{t.removeEventListener("abort",n)}}}class ve{session;records=new Map;operations=new Map;#e=new Map;#t=new Map;constructor(e){this.session=e}declarations(e){let t=e.map((s)=>le(s)),n=this.session.kernel.command(d.Orbs),o=(s)=>t.find((a)=>a.name===s),r=t.map((s)=>{if(!this.session.kernel.features.views&&Object.values(s.services??{}).some((i)=>i.access))throw new b(c.Unsupported.Views);let a=Object.entries(s.requires??{}).map(([i,p])=>{let m=p.orb??i,y=o(m),v=n.find((R)=>R.name===m),g=y?Object.keys(y.services??{}):v?.services.map((R)=>R.name)??[],k=g.includes(i)?i:g.length===1?g[0]:void 0;if(p.methods&&!k)h(c.Invalid.DependencyService,`Use explicit services for ${m}`);return{orb:m,apiVersion:p.apiVersion,services:p.services??(p.methods?{[k]:p.methods}:{}),hooks:p.hooks??[]}});for(let[i,p]of Object.entries(s.contributes??{})){let m=s.requires?.[i];if(!m)h(c.Invalid.HookDependency,i);for(let[y,v]of Object.entries(p)){if(!m.hooks?.includes(y))h(c.Invalid.HookDependency,y);let g=typeof v==="function"?0:v.priority??0;if(!Number.isInteger(g)||g<-2147483648||g>2147483647)h(c.Invalid.Priority)}}return{name:s.name,apiVersion:s.apiVersion,requires:a,hooks:Object.keys(s.hooks??{}),services:Object.entries(s.services??{}).map(([i,p])=>({name:i,methods:Object.keys(p.methods),lifetime:p.lifetime??G.Referenced,linger:p.linger??0}))}});return{definitions:t,metadata:r}}async install(e){let t=this.session.kernel.command(d.Orbs);if(e.some((s)=>t.some((a)=>a.name===s.name)))h(c.Invalid.OrbInstalled,"Use reload to replace an installed orb");let n=this.declarations(e),o=this.session.kernel.command(d.Prepare,{orbs:n.metadata});this.session.kernel.command(d.Commit,{ticket:o.id});let r=o.orbs.map((s)=>({info:s,definition:n.definitions.find((a)=>a.name===s.name)}));for(let s of r)this.records.set(s.info.id,s);for(let s of r)this.registerContributions(s);await Promise.all(r.map((s)=>this.ready(s)));for(let s of r)for(let a of s.info.services.filter((i)=>i.lifetime===G.Host))(await this.session.handles.get(a.name,"main",{principal:"host"})).release();this.session.lifecycle.flush()}scope(e){if(e.scope)return e.scope;let t=this.session.scopes.environment({kind:I.Orb,id:e.info.owner},e);e.scope=t;try{let n=e.definition.create?.(new H(this.session,t))??{};if(n&&typeof n.then==="function")h(c.Invalid.AsyncFactory);t.value=n}finally{t.phase=S.Prepared,this.session.programs.register(t)}return t}ready(e){if(e.scope?.phase===S.Live)return Promise.resolve();let t=this.#e.get(e.info.id);if(!t){t=(async()=>{try{if(await this.session.scopes.readyHostScope(),e.scope?.phase===S.Closed)delete e.scope;let o=this.scope(e);await this.session.programs.activate(o.id)}catch(o){if(e.scope)await this.session.programs.cleanup([e.scope]),delete e.scope;throw o}})(),this.#e.set(e.info.id,t);let n=()=>{if(this.#e.get(e.info.id)===t)this.#e.delete(e.info.id)};t.then(n,n)}return t}registerContributions(e){for(let[t,n]of Object.entries(e.definition.contributes??{})){let r=e.definition.requires[t].orb??t;for(let[s,a]of Object.entries(n)){let i=this.session.kernel.command(d.Allocate),p=JSON.stringify([e.info.name,r,s]);if(!this.#t.has(p))this.#t.set(p,this.session.kernel.command(d.ContributionOrdinal));this.operations.set(i,{orb:e,handler:typeof a==="function"?a:a.handle}),this.session.kernel.command(d.Contribute,{orb:e.info.id,target:r,hook:s,operation:i,priority:typeof a==="function"?0:a.priority??0,ordinal:this.#t.get(p)})}}}async runHook(e,t,n,o){n=V(n,this.session);let r=e.orb.definition.hooks?.[t];if(!r)h(c.Invalid.Hook,t);let a=this.session.kernel.command(d.HookPlan,{root:n.root,target:e.orb.info.name,hook:t}).map((i)=>async(p,m,y)=>this.runContribution(i,p,m,y));return r.run(n,o,a)}async observe(e,t,n,o,r){o=he(o,this.session);let s=e.orb.definition.hooks?.[t];if(!s)h(c.Invalid.Hook,t);if(!o.invocation)throw new b(c.Forbidden.ObservationSource);let a=this.session.kernel.command(d.BeginHookObservation,{source:o.invocation.id,orb:e.orb.info.id,operation:n,...e.object?{object:e.object.id}:{},hook:t});await this.session.track(this.session.calls.root(async()=>{try{let i=new A(this.session,a.invocation.root,a.invocation),p=a.plan.map((m)=>async(y,v,g)=>this.runContribution(m,y,v,g));await s.run(i,r,p)}finally{this.session.lifecycle.finishCall(a.invocation.id)}},!1,a.invocation.root))}async runContribution(e,t,n,o){t=V(t,this.session);let r=this.operations.get(e);if(!r){let a=this.session.options.native;if(a?.hasContribution?.(e)&&a.contribute)return a.contribute(e,t,n);throw new b(c.Gone.Contribution)}let s=r.orb.scope;if(!s)throw new b(c.Unavailable.OrbScope);return this.session.calls.owned(s,e,(a)=>r.handler(a,n,o),t)}retire(e){let t=this.session.kernel.command(d.ScopesForOrb,{orb:e}),n=this.session.programs.cleanupScopes(t);this.session.track(n.then(()=>{for(let[o,r]of this.operations)if(r.orb.info.id===e)this.operations.delete(o);this.records.delete(e),this.#e.delete(e)}),!0)}}class ye{session;constructor(e){this.session=e}get closedDiagnostics(){return this.#r}#e;#t=!1;#n;#o;#r;flush(e){if(this.#t)return;this.#t=!0;try{for(;;){let t=e??this.session.kernel.command(d.Drain);if(e=void 0,!t.length)break;for(let n of t)try{this.action(n)}catch(o){this.session.report(o)}}}finally{this.#t=!1,this.scheduleLinger()}}finishCall(e){let t=this.session;if(!this.#t&&t.options.native?.finish){let n=t.options.native.finish(e,t.now());if(!n.actions.length){this.scheduleLinger(n.deadline);return}this.flush(n.actions);return}t.kernel.command(d.Tick,{now:t.now()}),t.kernel.command(d.FinishCall,{call:e}),this.flush()}action(e){let t=this.session;if(t.options.native?.notify?.(e)&&!(e.type===C.ProgramComplete&&t.programs.pending(e.id)))return;switch(e.type){case C.Execute:case C.CancelEffects:case C.ProgramPrepared:case C.ProgramComplete:t.programs.dispatch(e);break;case C.DropValue:t.values.drop(e.id),t.options.native?.dropValue?.(e.id);break;case C.CancelRoot:t.controllers.get(e.id)?.abort(new b(c.Cancelled.Root));break;case C.CancelTask:t.activities.cancel(e.id);break;case C.Deliver:t.activities.deliver(e.id,e.payload,e.operation);break;case C.DetachSubscription:t.activities.detach(e.id);break;case C.SubscriptionFailed:t.activities.failed(e.id);break;case C.Dispose:t.track(this.dispose(e.id),!0);break;case C.CloseResource:break;case C.RetireOrb:t.handles.retire(e.id),t.orbs.retire(e.id);break;case C.State:{let o=t.objects.get(e.id);if(!o?.binding)break;let r=t.snapshot(e.id);if(!t.values.has(r.value)){let s=t.value(r.value);t.publish(o.binding.adopt(o.binding.prepare(s),s))}break}}}async dispose(e){let t=this.session,n=t.objects.get(e);if(!n){await t.options.native?.dispose(e),t.kernel.command(d.Disposed,{object:e}),this.flush();return}return n.disposing??=(async()=>{let o=[];await n.activation.catch(()=>{});let r=t.kernel.command(d.ScopesForOwner,{owner:{kind:I.Object,id:e}});try{await t.programs.cleanupScopes(r)}catch(s){o.push(s)}try{if(t.options.native?.hasOrb(n.orb))await t.options.native.dispose(e)}catch(s){o.push(s)}if(n.binding?.close(),t.kernel.command(d.Disposed,{object:e}),t.objects.delete(e),this.flush(),o.length)throw AggregateError(o,"Object cleanup failed")})(),n.disposing}scheduleLinger(e){let t=this.session;if(t.closing)return;let n=(e===void 0?t.kernel.command(d.NextDeadline):e)??void 0;if(n===this.#o)return;if(this.#n!==void 0)clearTimeout(this.#n);if(this.#n=void 0,this.#o=n,n===void 0)return;this.#n=setTimeout(()=>{if(this.#o!==n)return;this.#n=void 0,this.#o=void 0,t.kernel.command(d.Tick,{now:t.now()}),this.flush()},Math.max(0,n-t.now())),this.#n.unref?.()}diagnostics(){let e=this.session;if(this.#r)return this.#r;return{...e.kernel.command(d.Diagnostics),values:e.values.size,pendingJobs:e.jobs.size}}close(){let e=this.session;return this.#e??=(async()=>{e.closing=!0,clearTimeout(this.#n),this.#n=void 0,this.#o=void 0,e.kernel.command(d.Close),await e.replacements.cancel(),this.flush();for(;;){await e.options.native?.settled?.(),this.flush();let t=[...e.jobs];if(!t.length)break;await Promise.allSettled(t),this.flush()}if(e.kernel.command(d.FinishClose),e.values.clear(),e.handles.clear(),e.orbs.records.clear(),e.scopes.clear(),this.#r=this.diagnostics(),e.kernel.port.free?.(),e.cleanupErrors.length)throw AggregateError(e.cleanupErrors,"Host cleanup failed")})(),this.#e}}function ee(){let e,t,n=new Promise((o,r)=>{e=o,t=r});return n.catch(()=>{}),{promise:n,resolve:e,reject:t}}function Ve(e,t){return e.slice(0,t).replace(/[\uD800-\uDFFF]/gu,"�")}class ge{session;scopes=new Map;#e=new Map;constructor(e){this.session=e}register(e){let t=e.owner.kind===I.Host?void 0:e.object?e.orb.scope:this.session.hostScope;this.session.kernel.command(d.ScopeRegister,{scope:e.id,owner:e.owner,orb:e.orb.info.id,parents:t?[t.id]:[],dependencies:[...e.dependencies.values()].map((n)=>this.session.handles.reference(n).id),resources:[...e.resources.values()].map((n)=>n.id),stateVersion:e.state?.options.version??(e.state?1:void 0),migrate:Boolean(e.state?.options.migrate)})}activate(e){return this.run(this.session.kernel.command(d.ScopeActivate,{scope:e}))}cleanup(e){let t=e.map((n)=>n.id).filter((n)=>this.session.kernel.command(d.ScopeExists,{scope:n}));return this.cleanupScopes(t)}cleanupScopes(e){return e.length?this.run(this.session.kernel.command(d.ScopesCleanup,{scopes:e})):Promise.resolve()}pending(e){return this.#e.has(e)}run(e){let t=this.#e.get(e);if(t)return t.promise;let n=ee();this.#e.set(e,n);try{this.session.kernel.command(d.ProgramRun,{program:e}),this.session.lifecycle.flush()}catch(o){this.#e.delete(e),n.reject(o)}return n.promise}dispatch(e){if(e.type===C.Execute)this.session.track(Promise.allSettled(e.effects.map((t)=>this.execute(t))).then((t)=>{let n=Math.max(0,Math.min(2048,Math.floor((1048448-t.length*96)/(12*t.length)))),o=t.map((r)=>{if(r.status==="fulfilled")return{value:r.value??null};try{let{code:s,reason:a,message:i}=z(r.reason);if(!Object.values(l).includes(s)||typeof a!=="string"||typeof i!=="string")return{error:c.Unavailable.Callback};return{error:{code:s,reason:Ve(a,n),message:Ve(i,n)}}}catch{return{error:c.Unavailable.Callback}}});this.session.kernel.command(d.ProgramCompleteStep,{program:e.id,results:o}),this.session.lifecycle.flush()}));else if(e.type===C.CancelEffects)for(let t of e.effects){if(t.type!==j.Open&&t.type!==j.Restore)continue;let n=this.session.resources.find(t.resource);if(n)n.controller.abort(new b(c.Cancelled.EngineEffect));else if(this.session.options.native?.cancelEffect){let o=this.session.options.native.cancelEffect.bind(this.session.options.native);this.session.track(Promise.resolve().then(()=>o(t))).catch((r)=>this.session.report(r))}}else{let t=this.#e.get(e.id);if(this.#e.delete(e.id),e.error){let n=new b(e.error);if(t)t.reject(n);else this.session.cleanupErrors.push(n),this.session.report(n)}else t?.resolve()}}resource(e){let t=this.session.resources.find(e);if(t)return t;throw new b(c.Gone.Resource)}async execute(e){let t=e.scope===void 0?void 0:this.scopes.get(e.scope);if(e.scope!==void 0&&!t&&this.session.options.native)return this.session.options.native.effect(e);if((e.type===j.Close||e.type===j.Open)&&!this.session.resources.find(e.resource)&&this.session.options.native)return this.session.options.native.effect(e);switch(e.type){case j.Open:await this.resource(e.resource).start();break;case j.Close:await this.session.resources.close(this.resource(e.resource));break;case j.Restore:await this.session.resources.reopen(this.resource(e.previous),e.resource);break;case j.Stop:if(t)await this.session.activities.stop(t);break;case j.Prepare:{if(!t)throw new b(c.Gone.Scope);this.session.activities.prepare(t,e.previous?this.scopes.get(e.previous):void 0);break}case j.Validate:F(this.session.value(e.value),t.state.options);break;case j.Initialize:return this.candidate(t,t.state.initial);case j.Migrate:{let n=t.state;return this.candidate(t,n.options.migrate(this.session.value(e.value),e.version))}case j.Adopt:{let n=new Map;for(let o of e.replacements){if(!o.next)continue;let r=this.scopes.get(o.next);for(let[s,a]of r.resourceDeclarations??[])s.options=a;if(delete r.resourceDeclarations,n.set(r.orb.info.id,r.orb),r.object){if(r.state)r.object.binding=r.state.binding;r.object.orb=r.orb.info.id,r.object.versions.set(r.orb.info.id,r)}}for(let o of n.values())this.session.orbs.records.set(o.info.id,o),this.session.orbs.registerContributions(o);for(let o of e.replacements){let r=o.next?this.scopes.get(o.next):void 0;if(r?.object)this.session.handles.refreshReferences(r.object,r.orb)}for(let o of e.replacements)if(o.next)this.scopes.get(o.next)?.state?.publish?.();break}case j.Start:if(t){if(this.session.activities.start(t),t.object)t.object.live=!0}break;case j.Drop:{if(!t)break;for(let n of t.dependencies.values())this.session.handles.revoke(this.session.handles.reference(n).id);t.dependencies.clear();for(let n of t.resources.values())this.session.resources.closedRecords.delete(n.id);if(t.phase=S.Closed,t.object)t.object.versions.delete(t.orb.info.id);this.scopes.delete(t.id);break}default:throw new b(c.Unsupported.EngineEffect,e.type)}}candidate(e,t){let n=e.state,o=F(t,n.options),r=this.session.values.put(o);return n.publish=()=>this.session.publish(n.binding.adopt(n.binding.prepare(o),o)),r}}var qe=new WeakMap,ke=typeof FinalizationRegistry>"u"?void 0:new FinalizationRegistry((e)=>e.session.deref()?.handles.release(e.id));class we{session;constructor(e){this.session=e}#e=new Map;#t=new Map;activateAcquired(e,t,n=[]){let o=this.session,r=o.objects.get(e.object);if(!r){let y=ee();r={id:e.object,address:t,orb:e.orb,versions:new Map,activation:y.promise},o.objects.set(r.id,r);let v=r;o.track(o.scopes.activate(v,e).then(y.resolve,(g)=>{v.error=g;try{o.kernel.command(d.Fail,{object:v.id})}catch{}y.reject(g),o.lifecycle.flush()}))}if(!this.claimExists(e.reference))return r.activation;let a=this.orbMetadata(r.orb).services.find((y)=>y.name===t.service)?.methods??[],i={id:e.reference,object:e.object,address:t,methods:new Set(a),requiredMethods:new Set(n),stateCleanups:new Set,ready:r.activation,released:!1,nativeOwned:!0},p=o.orbs.records.get(r.orb)?.definition.services?.[t.service]?.access;try{this.referenceMethods(i,a,p)}catch(y){if(o.kernel.features.views&&this.claimExists(i.id))o.kernel.command(d.Restrict,{reference:i.id,methods:[]});throw y}o.references.set(i.id,i);let m=this.#t.get(i.object);if(!m)this.#t.set(i.object,m=new Set);return m.add(i),r.activation}hold(e,t,n={},o){let r;if(typeof e==="string")r=e;else{let w=Y(e,n);r=w.name,n=w.options}let s=this.session;if(o)V(o,s);s.kernel.command(d.Tick,{now:s.now()});let a={service:r,key:typeof t==="string"?[t]:[...t],principal:n.principal??o?.principal??s.principal},i=s.kernel.command(d.Acquire,{...a,apiVersion:n.apiVersion??0,methods:n.methods??[]}),p=s.objects.get(i.object);if(!p){let w=ee();p={id:i.object,address:a,orb:i.orb,versions:new Map,activation:w.promise},s.objects.set(p.id,p);let T=p;queueMicrotask(()=>{s.track(s.scopes.activate(T,i).then(w.resolve,(M)=>{T.error=M;try{s.kernel.command(d.Fail,{object:T.id})}catch{}w.reject(M),s.lifecycle.flush()}))})}let m=this.orbMetadata(i.orb),y=new Set(m.services.find((w)=>w.name===r)?.methods??[]),v={id:i.reference,object:i.object,address:a,methods:y,requiredMethods:new Set(n.methods??[]),stateCleanups:new Set,ready:p.activation,released:!1,...o?{context:o}:{}},g=s.options.native?.access?.(i.orb,r,a.principal),k=g?()=>({methods:g}):s.orbs.records.get(i.orb)?.definition.services?.[r]?.access;try{this.referenceMethods(v,y,k)}catch(w){throw s.kernel.command(d.Release,{reference:v.id}),s.kernel.command(d.Forget,{reference:v.id}),s.lifecycle.flush(),w}s.references.set(v.id,v);let R=this.#t.get(v.object);if(!R)R=new Set,this.#t.set(v.object,R);if(R.add(v),o){let w=s.rootReferences.get(o.root);if(!w)w=new Set,s.rootReferences.set(o.root,w);w.add(v.id)}let x=()=>{if(v.released)throw new b(c.Released.Reference);if(s.closing)throw new b(c.Gone.Reference);let w=s.objects.get(v.object);if(!w||w.disposing||w.error)throw new b(c.Gone.Reference);if(!w.live)throw new b(c.Unavailable.NotReady)},E={get ready(){return v.ready},get status(){return v.released?_.Released:q.closing?_.Gone:q.kernel.command(d.Status,{reference:v.id})},get state(){x();let w=q.objects.get(v.object)?.binding;if(!w)h(c.Invalid.State,"Service does not expose state");return Ae(w,x,v.stateCleanups)},release:()=>this.release(v.id),opaque:(w)=>{x();let T=s.objects.get(v.object),M=T.versions.get(T.orb)?.resources.get(w);if(!M?.options.opaque)throw new b(c.Forbidden.Opaque,w);return M.handle.value}},q=s,J=new Proxy(E,{get:(w,T,M)=>{if(T==="then")return;if(Object.hasOwn(w,T))return Reflect.get(w,T,M);if(typeof T!=="string")return;if(!v.methods.has(T))return;return(...te)=>{let se=v.context;if(_e(te.at(-1)))se=te.pop();return se?s.calls.invoke(v,T,te,V(se,s)):s.calls.root((Fe)=>s.calls.invoke(v,T,te,Fe),!1,void 0,v.address.principal)}}});return qe.set(J,{session:s,record:v}),ke?.register(J,{session:new WeakRef(s),id:v.id},v),J}async get(e,t,n={},o){let r=this.hold(e,t,n,o);try{return await r.ready,r}catch(s){throw r.release(),s}}reference(e){let t=typeof e==="object"&&e!==null?qe.get(e):void 0;if(!t||t.session!==this.session)h(c.Invalid.Reference,"An issued local reference is required");return t.record}orbMetadata(e){let t=this.session.orbs.records.get(e)?.info;if(t)return t;let n=this.#e.get(e);if(!n)n=this.session.kernel.command(d.Orb,{id:e}),this.#e.set(e,n);return n}referenceMethods(e,t,n,o=!1){let r=this.session;if(n&&!r.kernel.features.views)throw new b(c.Unsupported.Views);let s=n?new Set(n(e.address.principal).methods):void 0,a=new Set([...t].filter((i)=>(!e.requiredMethods.size||e.requiredMethods.has(i))&&(!s||s.has(i))));if(n||o&&r.kernel.features.views)r.kernel.command(d.Restrict,{reference:e.id,methods:[...a]});e.methods=a}refreshReferences(e,t){let n=this.session,o=t.definition.services?.[e.address.service];if(!o)return;let r=Object.keys(o.methods);for(let s of this.#t.get(e.id)??[]){if(s.released)continue;if(s.nativeOwned&&!this.claimExists(s.id)){this.revoke(s.id);continue}try{this.referenceMethods(s,r,o.access,!0)}catch(a){if(s.methods.clear(),!s.released&&n.kernel.features.views)n.kernel.command(d.Restrict,{reference:s.id,methods:[]});n.report(a)}}}claimExists(e){try{let t=this.session.kernel.command(d.Status,{reference:e});return t!==_.Released&&t!==_.Gone}catch(t){if(t instanceof b&&(t.code===l.Gone||t.code===l.Released))return!1;throw t}}forget(e){for(let n of e.stateCleanups)n();e.stateCleanups.clear(),this.session.references.delete(e.id);let t=this.#t.get(e.object);if(t?.delete(e),!t?.size)this.#t.delete(e.object)}release(e){let t=this.session,n=t.references.get(e);if(!n||n.released)return;if(n.released=!0,ke?.unregister(n),t.lifecycle.closedDiagnostics){this.forget(n);return}t.kernel.command(d.Tick,{now:t.now()}),t.kernel.command(d.Release,{reference:e}),t.kernel.command(d.Forget,{reference:e}),this.forget(n),t.lifecycle.flush()}revoke(e){let t=this.session.references.get(e);if(!t)return;t.released=!0,ke?.unregister(t),this.forget(t)}retire(e){this.#e.delete(e)}clear(){for(let e of this.session.references.values())this.forget(e);this.session.references.clear(),this.#t.clear(),this.#e.clear()}}class Re{session;#e;#t;#n;constructor(e){this.session=e}async replace(e,t={},n=[]){return(await this.prepare(e,t,n)).commit()}prepare(e,t={},n=[]){if(this.session.closing)return Promise.reject(new b(c.Closed.Host));if(this.#e)return Promise.reject(new b(c.Conflict.ReloadRunning));let o=this.capture(e,t,n);return this.#e=o,o.catch(()=>{if(this.#e===o)this.#e=void 0}),o}async cancel(){if(this.#n?.status===D.Prepared)return this.#n.abort();if(this.#t!==void 0){this.session.kernel.command(d.ProgramAbort,{program:this.#t});let e=this.session.programs.run(this.#t);this.session.lifecycle.flush(),await e.catch(()=>{})}await this.#e?.catch(()=>{return})}async capture(e,t,n){let o=this.session,r=o.orbs.declarations(e),s=o.kernel.command(d.Prepare,{orbs:r.metadata,remove:n}),a=new Map(r.definitions.map((k)=>[k.name,k])),i=s.orbs.map((k)=>({info:k,definition:a.get(k.name),ticket:s.id})),p=new Map(i.map((k)=>[k.info.id,k])),m;try{for(let k of i)o.orbs.scope(k);for(let k of s.objects){let R=o.objects.get(k);if(!R)continue;let x=s.providers[R.address.service],E=x===void 0?void 0:p.get(x);if(E)o.scopes.createEnvironment(R,E)}for(let k of i)k.ticket=void 0;if(m=o.kernel.command(d.ScopesReloadRegistered,{ticket:s.id,deadline:t.deadline??5000,now:o.now()}),this.#t=m,await o.programs.run(m),o.closing)await o.programs.run(m)}catch(k){if(this.#t=void 0,m===void 0){o.kernel.command(d.Abort,{ticket:s.id});let R=s.orbs.flatMap((x)=>o.kernel.command(d.ScopesForOrb,{orb:x.id}));await o.programs.cleanupScopes(R)}throw k}this.#t=void 0;let y=m,v={codeVersion:s.codeVersion,orbs:i.map((k)=>k.info.name)},g=D.Prepared;return this.#n={report:v,get status(){return g},commit:async()=>{if(g!==D.Prepared)throw new b(c.Conflict.ReloadTicket);this.#n=void 0;try{o.kernel.command(d.ProgramCommit,{program:y})}catch(k){throw o.kernel.command(d.ProgramAbort,{program:y}),await o.programs.run(y).catch(()=>{}),g=D.Aborted,this.#e=void 0,k}return g=D.Committed,this.#e=void 0,await o.programs.run(y),v},abort:async()=>{if(g===D.Aborted)return;if(g!==D.Prepared)throw new b(c.Conflict.AlreadyCommitted);g=D.Aborted,this.#n=void 0,this.#e=void 0,o.kernel.command(d.ProgramAbort,{program:y});try{await o.programs.run(y)}catch(k){if(!(k instanceof b)||k.reason!==u.ReloadAborted)throw k}}}}}var ze=new WeakMap;class Oe{session;records=new Map;closedRecords=new Map;constructor(e){this.session=e}find(e){return this.records.get(e)??this.closedRecords.get(e)}dependencyIds(e){let t=[];for(let n of e.deps??[]){let o=typeof n==="object"&&n!==null?ze.get(n):void 0;if(o){if(o.session!==this.session)h(c.Invalid.ResourceHost,"Resource dependencies must belong to the same host");t.push(o.id)}else this.session.handles.reference(n)}return t}register(e,t,n){return this.session.kernel.command(d.Resource,{owner:e.owner,name:t,version:n.version??1,exclusive:n.exclusive??!1,dependencies:this.dependencyIds(n)}).id}redeclare(e,t){for(let n of t.resources.values())this.records.delete(n.id),this.closedRecords.delete(n.id),n.reset(this.register(e,n.name,n.options)),n.dependencies=this.dependencyIds(n.options),this.records.set(n.id,n),e.resources.set(n.name,n)}declare(e,t,n){if(!t||typeof n.open!=="function")h(c.Invalid.Resource);let o=this.register(e,t,n),r=this.records.get(o);if(r)return(e.resourceDeclarations??=new Map).set(r,n),r;let s=new AbortController,a=Object.freeze({get value(){if(e.phase===S.Declaring)h(c.Invalid.ResourceInFactory,"Resources open after declaration");let p=i.session.kernel.command(d.ResourceValue,{resource:i.id});return i.session.value(p)},version:n.version??1}),i={id:o,name:t,options:n,handle:a,dependencies:this.dependencyIds(n),controller:s,session:this.session,reset:(p)=>{i.id=p,i.controller=new AbortController,delete i.value,delete i.closed,delete i.started},start:()=>(i.started??=(async()=>{let p=i.options,m=await p.open(i.controller.signal),y=this.session.values.put(m);try{this.session.kernel.command(d.ResourceOpened,{resource:i.id,value:y})}catch(v){if(this.session.values.drop(y),p.close)await this.session.calls.root((g)=>p.close(m,g),!0);throw v}i.value=y})(),i.started.catch(()=>{}),i.started)};return ze.set(a,i),this.records.set(o,i),i}async close(e){return e.closed??=(async()=>{e.controller.abort(new b(c.Cancelled.Resource)),await e.started?.catch(()=>{});try{if(e.value!==void 0&&e.options.close){let t=this.session.value(e.value);await this.session.calls.root((n)=>e.options.close(t,n),!0)}}finally{this.session.kernel.command(d.ResourceClosed,{resource:e.id}),this.records.delete(e.id),this.closedRecords.set(e.id,e),this.session.lifecycle.flush()}})(),e.closed}async reopen(e,t){this.closedRecords.delete(e.id),e.reset(t),this.records.set(t,e),await e.start()}}class Se{session;constructor(e){this.session=e}#e=new Map;#t=new Set;#n;environment(e,t,n){let o={id:this.session.kernel.command(d.Allocate),owner:e,orb:t,...n?{object:n}:{},phase:S.Declaring,value:{},dependencies:new Map,resources:new Map,tasks:[],listeners:[]};return this.session.programs.scopes.set(o.id,o),o}async activate(e,t){let n=this.session;if(n.options.native?.hasOrb(t.orb)){await n.options.native.activate(e.id,t.orb,e.address.service,e.address.key,e.address.principal);let o=n.kernel.command(d.ScopesForOwner,{owner:{kind:I.Object,id:e.id}});await Promise.all(o.map((r)=>n.programs.activate(r)));try{n.snapshot(e.id),e.binding=new L(n,e.id)}catch{}}else{let o=n.orbs.records.get(t.orb);if(!o)h(c.Invalid.OrbGone);await n.orbs.ready(o);let r=this.createEnvironment(e,o);e.versions.set(o.info.id,r),await this.session.programs.activate(r.id)}if(n.kernel.command(d.Status,{reference:t.reference})===_.Loading)n.kernel.command(d.Ready,{object:e.id});e.live=!0,n.lifecycle.flush()}createEnvironment(e,t){let n=t.definition.services?.[e.address.service];if(!n)h(c.Invalid.ServiceGone);let o=this.environment({kind:I.Object,id:e.id},t,e);try{let r=n.create?.(new H(this.session,o))??{};if(r&&typeof r.then==="function")h(c.Invalid.AsyncFactory,"Factories must be synchronous");return o.value=r,o}finally{o.phase=S.Prepared,this.session.programs.register(o)}}readyHostScope(){let e=this.session;if(e.closing)return Promise.reject(new b(c.Closed.Host));if(this.#n)return this.#n;let t=(async()=>{if(e.hostScope.phase===S.Closed)e.hostScope=await this.redeclareHostScope(e.hostScope);await this.session.programs.activate(e.hostScope.id);while(this.#t.size){let o=this.#t.values().next().value;if(o.phase===S.Closed||[...o.resources.values()].some((r)=>e.resources.dependencyIds(r.options).some((s,a)=>s!==r.dependencies[a]))){let r=o;o=await this.redeclareHostScope(r),this.#t.delete(r),this.#t.add(o)}await this.session.programs.activate(o.id),this.#t.delete(o)}})();this.#n=t;let n=()=>{if(this.#n===t)this.#n=void 0};return t.then(n,n),t}async redeclareHostScope(e){let t=this.session;await t.programs.cleanup([e]);let n=this.environment({kind:I.Host},e.orb);return t.resources.redeclare(n,e),n.phase=S.Prepared,t.programs.register(n),n}requirement(e,t){if(e.orb.definition.services?.[t])return{service:t,apiVersion:e.orb.info.apiVersion};for(let[o,r]of Object.entries(e.orb.definition.requires??{})){let s;try{s=this.session.kernel.command(d.OrbNamed,{name:r.orb??o,ticket:e.orb.ticket})}catch(p){if(p instanceof b&&p.code===l.Gone&&p.reason===u.Orb)continue;throw p}let a=o===t?s.services.find((p)=>p.name===o)??(s.services.length===1?s.services[0]:void 0):s.services.find((p)=>p.name===t);if(!a)continue;let i=r.services?.[a.name]??r.methods;if(!i)throw new b(c.Forbidden.UndeclaredService,t);return{service:a.name,apiVersion:r.apiVersion,methods:i}}throw new b(c.Forbidden.UndeclaredDependency,t)}hostResource(e){let t=this.#e.get(e);if(!t)throw new b(c.Forbidden.HostResource,e);return t.handle}resource(e,t){let n=this.session;if(n.closing)throw new b(c.Closed.Host);if(this.#e.has(e))h(c.Invalid.DuplicateResource);let o=this.environment({kind:I.Host},n.hostScope.orb);try{let r=new H(n,o).resource(e,t);return this.#e.set(e,o.resources.get(e)),o.phase=S.Prepared,n.programs.register(o),this.#t.add(o),n.track(this.readyHostScope()).catch((s)=>n.report(s)),r}catch(r){throw n.programs.scopes.delete(o.id),r}}registerHost(e){for(let[t,n]of e.resources)this.#e.set(t,n)}clear(){this.#e.clear(),this.#t.clear()}}class xe{options;contextTokens=new WeakMap;calls=new be(this);handles=new we(this);scopes=new Se(this);lifecycle=new ye(this);kernel;values;resources=new Oe(this);activities=new me(this);orbs=new ve(this);replacements=new Re(this);programs=new ge(this);objects=new Map;references=new Map;rootReferences=new Map;controllers=new Map;jobs=new Set;cleanupErrors=[];hostScope;codec;name;principal;errors=[];now;telemetry;closing=!1;#e=!1;#t=[];constructor(e){this.options=e;if(this.kernel=new ue(e.kernel),e.telemetry&&!this.kernel.features.telemetry)throw new b(c.Unsupported.Telemetry);this.telemetry=e.telemetry?new fe(e.telemetry.capacity,e.telemetry.sampleEvery):void 0,this.values=new pe(()=>this.kernel.command(d.Allocate)),this.codec=e.serialization??W,this.name=e.name??"host",this.principal=e.principal??"host";let t=e.now??(()=>performance.now()),n=e.clockOrigin??t();this.now=()=>Math.floor(t()-n);let o={info:{id:0,owner:0,name:"$host",apiVersion:1,codeVersion:1,services:[],hooks:[],requires:[]},definition:{name:"$host",apiVersion:1}};this.hostScope=this.scopes.environment({kind:I.Host},o);for(let[r,s]of Object.entries(e.resources??{}))new H(this,this.hostScope).resource(r,s);this.scopes.registerHost(this.hostScope),this.hostScope.phase=S.Prepared,this.programs.register(this.hostScope)}principalFor(e){return this.objects.get(e)?.address.principal??this.principal}snapshot(e){return this.kernel.command(d.Snapshot,{object:e})}value(e){if(this.values.has(e))return this.values.get(e);if(!this.options.native)h(c.Invalid.ValueGone);let t=this.options.native.value(e);return this.values.set(e,t),t}check(e,t){let n=V(e,this);if(!n.invocation||n.invocation.object!==t)throw new b(c.Forbidden.StateOwner);return n.invocation}adopt(e,t,n,o){let r=this.check(t,e),s=this.values.put(o);try{return this.kernel.command(d.StateAdopt,{call:r.id,object:e,revision:n,value:s})}catch(a){throw this.values.drop(s),a}finally{this.lifecycle.flush()}}publish(e){if(this.#t.push(e),this.#e)return;this.#e=!0;try{while(this.#t.length)this.#t.shift()()}finally{this.#e=!1}}report(e){let t=z(e);if(this.errors.length===64)this.errors.shift();this.errors.push(t);try{this.options.onError?.(t)}catch{}}track(e,t=!1){return this.jobs.add(e),e.then(()=>{this.jobs.delete(e)},(n)=>{if(this.jobs.delete(e),t)this.cleanupErrors.push(n),this.report(n)}),e}}class Ce{session;constructor(e){this.session=new xe(e)}get name(){return this.session.name}get features(){return this.session.kernel.features}install(e){return this.session.orbs.install(Array.isArray(e)?e:[e])}async load(e){if(!this.session.options.load)throw Error("This host has no module loader");await this.install(await this.session.options.load(e))}reload(e,t){return this.session.replacements.replace(e,t)}prepare(e,t){return this.session.replacements.prepare(e,t)}remove(e,t){return this.session.replacements.replace([],t,e)}hold(e,t,n){return this.session.handles.hold(e,t,n)}get(e,t,n){return this.session.handles.get(e,t,n)}root(e,t={}){return this.session.calls.root(e,!1,void 0,t.principal)}resource(e,t){return this.session.scopes.resource(e,t)}diagnostics(){return this.session.lifecycle.diagnostics()}errors(){return this.session.errors.splice(0)}traces(){return this.session.telemetry?.drain()??[]}installedOrbs(){return this.session.kernel.command(d.Orbs).map((e)=>{let t=this.session.orbs.records.get(e.id)?.definition,n=Object.freeze({...e,hookCapabilities:Object.fromEntries(e.hooks.map((o)=>[o,t?.hooks?.[o]?.capabilities??[]]))});return Object.freeze({...e,describe:()=>n})})}close(){return this.session.lifecycle.close()}}var O=Deno.core.ops,N=globalThis;N.queueMicrotask??=(e)=>Promise.resolve().then(e);N.performance??={now:()=>O.op_tembra_now()};N.AbortController??=class{signal={aborted:!1,reason:void 0,listeners:new Set,addEventListener(e,t){this.listeners.add(t)},removeEventListener(e,t){this.listeners.delete(t)},throwIfAborted(){if(this.aborted)throw this.reason}};abort(e=Error("Aborted")){if(this.signal.aborted)return;this.signal.aborted=!0,this.signal.reason=e;for(let t of[...this.signal.listeners])t();this.signal.listeners.clear()}};var Le=0,Te=new Set;N.setTimeout??=(e,t=0,...n)=>{let o=++Le;return Te.add(o),O.op_tembra_sleep(o,Math.max(0,Math.min(2147483647,t))).then(()=>{if(Te.delete(o))e(...n)}),o};N.clearTimeout??=(e)=>{if(Te.delete(e))O.op_tembra_clear_timer(e)};function Ne(e={}){let t=e.serialization??W;if(t.id!==O.op_tembra_codec())throw new b(c.Conflict.Codec,"The Rust and JS host codecs must agree");function n(i){let p=t.deserialize(i);if(p.error)throw new b(p.error);return p.ok}let o=O.op_tembra_driver_enabled?.()??!1,r=new Map;N.__tembraDeliver=(i)=>{for(let[p,m,y]of i){let v=r.get(p);if(!v)throw Error("unknown native completion");r.delete(p);try{if(!y)throw Error(m);v.resolve(n(m))}catch(g){v.reject(g)}}};function s(i,p){let m=O.op_tembra_submit(i,p);return new Promise((y,v)=>r.set(m,{resolve:y,reject:v}))}let a=new Ce({...e,clockOrigin:0,kernel:{request:(i)=>O.op_tembra_kernel(i)},native:{...o?{admit:(i,p,m)=>{let y=JSON.parse(O.op_tembra_admit(JSON.stringify({reference:i,method:p,root:m.root,context:m.frame,parent:m.invocation?.id})));if(y.error)throw new b(y.error);return y.ok},finish:(i,p)=>{let m=JSON.parse(O.op_tembra_finish(i,String(p)));if(m.error)throw new b(m.error);return m.ok}}:{},rootEnded:(i)=>O.op_tembra_end_context(i),access:(i,p,m)=>JSON.parse(O.op_tembra_access(i,p,m))??void 0,settled:()=>O.op_tembra_settled(),notify:(i)=>O.op_tembra_notify(JSON.stringify(i)),hasContribution:(i)=>O.op_tembra_has_contribution?.(i)??!1,contribute:async(i,p,m)=>n(await O.op_tembra_native("contribute",t.serialize({operation:i,root:p.root,frame:p.frame,...m===void 0?{}:{input:m}}))).value,hasOrb:(i)=>O.op_tembra_has_orb(i),activate:async(i,p,m)=>{n(await O.op_tembra_native("activate",t.serialize({object:i,orb:p,service:m})))},invoke:async(i,p)=>o?s("invoke",t.serialize({invocation:i,arguments:p})):n(await O.op_tembra_native("invoke",t.serialize({invocation:i,arguments:p}))),dispose:async(i)=>{n(await O.op_tembra_native("dispose",t.serialize({object:i})))},effect:async(i)=>n(await O.op_tembra_native("effect",t.serialize(i))),cancelEffect:async(i)=>{n(await O.op_tembra_native("cancel-effect",t.serialize(i)))},value:(i)=>n(O.op_tembra_value(i)),dropValue:(i)=>O.op_tembra_drop_value(i)}});if(O.op_tembra_callback_next)(async()=>{for(;;){let i=O.op_tembra_callback_next();Deno.core.unrefOpPromise(i);let p=await i;if(!p.length)return;let m=new DataView(p.buffer,p.byteOffset,9),y=m.getUint8(0),v=m.getUint32(1,!0)+m.getUint32(5,!0)*4294967296;if(y!==0){if(y===2)a.session.calls.releaseRoot(v);if(y===3)a.session.handles.revoke(v);a.session.lifecycle.flush();continue}let g;try{g=t.deserialize(p.subarray(9))}catch(k){let{code:R,reason:x,message:E}=z(k);O.op_tembra_callback_error(v,JSON.stringify({code:R,reason:x,message:E}),!0);continue}a.session.track((async()=>{let k;try{let R;if(g.kind==="activate")await a.session.handles.activateAcquired(g.acquired,g.address,g.methods),R=null;else{let x=g.call,E=a.session.kernel.command(d.Invocation,{call:x}),q=new A(a.session,E.root,E,g.frame);if(g.kind==="invoke"){let J=a.session.objects.get(E.object),w=J?.versions.get(E.orb),T=w?.orb.definition.services?.[J.address.service]?.methods[E.method];if(!T||!w)throw new b(c.Gone.Implementation);R=await T(w.value,q,...g.input)}else R=await a.session.orbs.runContribution(g.operation,q,g.input)}k=R===void 0?{}:{value:R}}catch(R){let x=z(R);k={error:{code:x.code,reason:x.reason,message:x.message}}}try{O.op_tembra_callback_complete(v,t.serialize(k))}catch(R){let{code:x,reason:E,message:q}=z(R);O.op_tembra_callback_error(v,JSON.stringify({code:x,reason:E,message:q}),!1)}})(),!0)}})();return a}N.Tembra=Object.freeze({ContextKey:U,ContextKind:P,opaqueFrom:Ee,createHost:Ne,jsonCodec:W,Code:l,Reason:u,Lifetime:G,Status:_,ReloadStatus:D,HookCapability:ie,Errors:c});})();
package/dist/host.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { orb } from "./authoring/orb.ts";
2
- import type { AcquisitionOptions, Completion, OrbDefinition, HostOptions, ReloadOptions, ResourceOptions } from "./authoring/types.ts";
2
+ import type { AcquisitionOptions, Completion, OrbDefinition, HostOptions, ReloadOptions, ResourceOptions, DynamicReference, ServiceDefinition, ServiceReference } from "./authoring/types.ts";
3
3
  import { Context } from "./runtime/context.ts";
4
4
  import { Session } from "./runtime/session.ts";
5
5
  /** The application facade. Platform entrypoints provide its metadata kernel and module loader. */
@@ -22,9 +22,11 @@ export declare class Host {
22
22
  /** Remove named orbs through the replacement lifecycle. */
23
23
  remove(names: readonly string[], options?: ReloadOptions): Promise<import("./index.ts").ReloadReport>;
24
24
  /** Acquire a reference before its asynchronous activation completes. */
25
- hold(service: string, key: string | readonly string[], options?: AcquisitionOptions): import("./index.ts").DynamicReference;
25
+ hold<const Service extends ServiceDefinition>(service: Service, key: string | readonly string[], options?: AcquisitionOptions): ServiceReference<Service>;
26
+ hold(service: string, key: string | readonly string[], options?: AcquisitionOptions): DynamicReference;
26
27
  /** Acquire a reference and wait for activation. */
27
- get(service: string, key: string | readonly string[], options?: AcquisitionOptions): Promise<import("./index.ts").DynamicReference>;
28
+ get<const Service extends ServiceDefinition>(service: Service, key: string | readonly string[], options?: AcquisitionOptions): Promise<ServiceReference<Service>>;
29
+ get(service: string, key: string | readonly string[], options?: AcquisitionOptions): Promise<DynamicReference>;
28
30
  /** Run an operation with one principal and bounded context lifetime. */
29
31
  root<T>(operation: (context: Context) => Completion<T>, options?: {
30
32
  principal?: string;