@almadar/runtime 1.0.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.
package/dist/index.js ADDED
@@ -0,0 +1,1556 @@
1
+ import * as fs from 'fs';
2
+ import * as path from 'path';
3
+ import { isEntityReference, parseEntityRef, parseImportedTraitRef, isPageReference, isPageReferenceString, isPageReferenceObject, parsePageRef, OrbitalSchemaSchema } from '@almadar/core';
4
+ import { resolveBinding, evaluate, createMinimalContext, evaluateGuard } from '@almadar/evaluator';
5
+ export { createMinimalContext } from '@almadar/evaluator';
6
+
7
+ var __getOwnPropNames = Object.getOwnPropertyNames;
8
+ var __esm = (fn, res) => function __init() {
9
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
+ };
11
+ var ImportChain, LoaderCache, ExternalOrbitalLoader;
12
+ var init_external_loader = __esm({
13
+ "src/loader/external-loader.ts"() {
14
+ ImportChain = class _ImportChain {
15
+ chain = [];
16
+ /**
17
+ * Try to add a path to the chain.
18
+ * @returns Error message if circular, null if OK
19
+ */
20
+ push(absolutePath) {
21
+ if (this.chain.includes(absolutePath)) {
22
+ const cycle = [...this.chain.slice(this.chain.indexOf(absolutePath)), absolutePath];
23
+ return `Circular import detected: ${cycle.join(" -> ")}`;
24
+ }
25
+ this.chain.push(absolutePath);
26
+ return null;
27
+ }
28
+ /**
29
+ * Remove the last path from the chain.
30
+ */
31
+ pop() {
32
+ this.chain.pop();
33
+ }
34
+ /**
35
+ * Clone the chain for nested loading.
36
+ */
37
+ clone() {
38
+ const newChain = new _ImportChain();
39
+ newChain.chain = [...this.chain];
40
+ return newChain;
41
+ }
42
+ };
43
+ LoaderCache = class {
44
+ cache = /* @__PURE__ */ new Map();
45
+ get(absolutePath) {
46
+ return this.cache.get(absolutePath);
47
+ }
48
+ set(absolutePath, schema) {
49
+ this.cache.set(absolutePath, schema);
50
+ }
51
+ has(absolutePath) {
52
+ return this.cache.has(absolutePath);
53
+ }
54
+ clear() {
55
+ this.cache.clear();
56
+ }
57
+ get size() {
58
+ return this.cache.size;
59
+ }
60
+ };
61
+ ExternalOrbitalLoader = class {
62
+ options;
63
+ cache;
64
+ constructor(options) {
65
+ this.options = {
66
+ stdLibPath: options.stdLibPath ?? "",
67
+ scopedPaths: options.scopedPaths ?? {},
68
+ allowOutsideBasePath: options.allowOutsideBasePath ?? false,
69
+ ...options
70
+ };
71
+ this.cache = new LoaderCache();
72
+ }
73
+ /**
74
+ * Load a schema from an import path.
75
+ *
76
+ * @param importPath - The import path (e.g., "./health.orb", "std/behaviors/game-core")
77
+ * @param fromPath - The path of the file doing the import (for relative resolution)
78
+ * @param chain - Import chain for circular detection
79
+ */
80
+ async load(importPath, fromPath, chain) {
81
+ const importChain = chain ?? new ImportChain();
82
+ const resolveResult = this.resolvePath(importPath, fromPath);
83
+ if (!resolveResult.success) {
84
+ return resolveResult;
85
+ }
86
+ const absolutePath = resolveResult.data;
87
+ const circularError = importChain.push(absolutePath);
88
+ if (circularError) {
89
+ return { success: false, error: circularError };
90
+ }
91
+ try {
92
+ const cached = this.cache.get(absolutePath);
93
+ if (cached) {
94
+ return { success: true, data: cached };
95
+ }
96
+ const loadResult = await this.loadFile(absolutePath);
97
+ if (!loadResult.success) {
98
+ return loadResult;
99
+ }
100
+ const loaded = {
101
+ schema: loadResult.data,
102
+ sourcePath: absolutePath,
103
+ importPath
104
+ };
105
+ this.cache.set(absolutePath, loaded);
106
+ return { success: true, data: loaded };
107
+ } finally {
108
+ importChain.pop();
109
+ }
110
+ }
111
+ /**
112
+ * Load a specific orbital from a schema by name.
113
+ *
114
+ * @param importPath - The import path
115
+ * @param orbitalName - The orbital name (optional, defaults to first orbital)
116
+ * @param fromPath - The path of the file doing the import
117
+ * @param chain - Import chain for circular detection
118
+ */
119
+ async loadOrbital(importPath, orbitalName, fromPath, chain) {
120
+ const schemaResult = await this.load(importPath, fromPath, chain);
121
+ if (!schemaResult.success) {
122
+ return schemaResult;
123
+ }
124
+ const schema = schemaResult.data.schema;
125
+ let orbital;
126
+ if (orbitalName) {
127
+ const found = schema.orbitals.find((o) => o.name === orbitalName);
128
+ if (!found) {
129
+ return {
130
+ success: false,
131
+ error: `Orbital "${orbitalName}" not found in ${importPath}. Available: ${schema.orbitals.map((o) => o.name).join(", ")}`
132
+ };
133
+ }
134
+ orbital = found;
135
+ } else {
136
+ if (schema.orbitals.length === 0) {
137
+ return {
138
+ success: false,
139
+ error: `No orbitals found in ${importPath}`
140
+ };
141
+ }
142
+ orbital = schema.orbitals[0];
143
+ }
144
+ return {
145
+ success: true,
146
+ data: {
147
+ orbital,
148
+ sourcePath: schemaResult.data.sourcePath,
149
+ importPath
150
+ }
151
+ };
152
+ }
153
+ /**
154
+ * Resolve an import path to an absolute filesystem path.
155
+ */
156
+ resolvePath(importPath, fromPath) {
157
+ if (importPath.startsWith("std/")) {
158
+ return this.resolveStdPath(importPath);
159
+ }
160
+ if (importPath.startsWith("@")) {
161
+ return this.resolveScopedPath(importPath);
162
+ }
163
+ if (importPath.startsWith("./") || importPath.startsWith("../")) {
164
+ return this.resolveRelativePath(importPath, fromPath);
165
+ }
166
+ if (path.isAbsolute(importPath)) {
167
+ if (!this.options.allowOutsideBasePath) {
168
+ return {
169
+ success: false,
170
+ error: `Absolute paths not allowed: ${importPath}`
171
+ };
172
+ }
173
+ return { success: true, data: importPath };
174
+ }
175
+ return this.resolveRelativePath(`./${importPath}`, fromPath);
176
+ }
177
+ /**
178
+ * Resolve a standard library path.
179
+ */
180
+ resolveStdPath(importPath) {
181
+ if (!this.options.stdLibPath) {
182
+ return {
183
+ success: false,
184
+ error: `Standard library path not configured. Cannot load: ${importPath}`
185
+ };
186
+ }
187
+ const relativePath = importPath.slice(4);
188
+ let absolutePath = path.join(this.options.stdLibPath, relativePath);
189
+ if (!absolutePath.endsWith(".orb")) {
190
+ absolutePath += ".orb";
191
+ }
192
+ const normalizedPath = path.normalize(absolutePath);
193
+ const normalizedStdLib = path.normalize(this.options.stdLibPath);
194
+ if (!normalizedPath.startsWith(normalizedStdLib)) {
195
+ return {
196
+ success: false,
197
+ error: `Path traversal outside std library: ${importPath}`
198
+ };
199
+ }
200
+ return { success: true, data: absolutePath };
201
+ }
202
+ /**
203
+ * Resolve a scoped package path.
204
+ */
205
+ resolveScopedPath(importPath) {
206
+ const match = importPath.match(/^(@[^/]+)/);
207
+ if (!match) {
208
+ return {
209
+ success: false,
210
+ error: `Invalid scoped package path: ${importPath}`
211
+ };
212
+ }
213
+ const scope = match[1];
214
+ const scopeRoot = this.options.scopedPaths[scope];
215
+ if (!scopeRoot) {
216
+ return {
217
+ success: false,
218
+ error: `Scoped package "${scope}" not configured. Available: ${Object.keys(this.options.scopedPaths).join(", ") || "none"}`
219
+ };
220
+ }
221
+ const relativePath = importPath.slice(scope.length + 1);
222
+ let absolutePath = path.join(scopeRoot, relativePath);
223
+ if (!absolutePath.endsWith(".orb")) {
224
+ absolutePath += ".orb";
225
+ }
226
+ const normalizedPath = path.normalize(absolutePath);
227
+ const normalizedRoot = path.normalize(scopeRoot);
228
+ if (!normalizedPath.startsWith(normalizedRoot)) {
229
+ return {
230
+ success: false,
231
+ error: `Path traversal outside scoped package: ${importPath}`
232
+ };
233
+ }
234
+ return { success: true, data: absolutePath };
235
+ }
236
+ /**
237
+ * Resolve a relative path.
238
+ */
239
+ resolveRelativePath(importPath, fromPath) {
240
+ const baseDir = fromPath ? path.dirname(fromPath) : this.options.basePath;
241
+ let absolutePath = path.resolve(baseDir, importPath);
242
+ if (!absolutePath.endsWith(".orb")) {
243
+ absolutePath += ".orb";
244
+ }
245
+ if (!this.options.allowOutsideBasePath) {
246
+ const normalizedPath = path.normalize(absolutePath);
247
+ const normalizedBase = path.normalize(this.options.basePath);
248
+ if (!normalizedPath.startsWith(normalizedBase)) {
249
+ return {
250
+ success: false,
251
+ error: `Path traversal outside base path: ${importPath}. Base: ${this.options.basePath}`
252
+ };
253
+ }
254
+ }
255
+ return { success: true, data: absolutePath };
256
+ }
257
+ /**
258
+ * Load and parse an .orb file.
259
+ */
260
+ async loadFile(absolutePath) {
261
+ try {
262
+ if (!fs.existsSync(absolutePath)) {
263
+ return {
264
+ success: false,
265
+ error: `File not found: ${absolutePath}`
266
+ };
267
+ }
268
+ const content = await fs.promises.readFile(absolutePath, "utf-8");
269
+ let data;
270
+ try {
271
+ data = JSON.parse(content);
272
+ } catch (e) {
273
+ return {
274
+ success: false,
275
+ error: `Invalid JSON in ${absolutePath}: ${e instanceof Error ? e.message : String(e)}`
276
+ };
277
+ }
278
+ const parseResult = OrbitalSchemaSchema.safeParse(data);
279
+ if (!parseResult.success) {
280
+ const errors = parseResult.error.errors.map((e) => ` - ${e.path.join(".")}: ${e.message}`).join("\n");
281
+ return {
282
+ success: false,
283
+ error: `Invalid schema in ${absolutePath}:
284
+ ${errors}`
285
+ };
286
+ }
287
+ return { success: true, data: parseResult.data };
288
+ } catch (e) {
289
+ return {
290
+ success: false,
291
+ error: `Failed to load ${absolutePath}: ${e instanceof Error ? e.message : String(e)}`
292
+ };
293
+ }
294
+ }
295
+ /**
296
+ * Clear the cache.
297
+ */
298
+ clearCache() {
299
+ this.cache.clear();
300
+ }
301
+ /**
302
+ * Get cache statistics.
303
+ */
304
+ getCacheStats() {
305
+ return { size: this.cache.size };
306
+ }
307
+ };
308
+ }
309
+ });
310
+
311
+ // src/EventBus.ts
312
+ var EventBus = class {
313
+ listeners = /* @__PURE__ */ new Map();
314
+ debug;
315
+ constructor(options = {}) {
316
+ this.debug = options.debug ?? false;
317
+ }
318
+ /**
319
+ * Emit an event to all registered listeners
320
+ */
321
+ emit(type, payload, source) {
322
+ const event = {
323
+ type,
324
+ payload,
325
+ timestamp: Date.now(),
326
+ source
327
+ };
328
+ const listeners = this.listeners.get(type);
329
+ const listenerCount = listeners?.size ?? 0;
330
+ if (this.debug) {
331
+ if (listenerCount > 0) {
332
+ console.log(`[EventBus] Emit: ${type} \u2192 ${listenerCount} listener(s)`, payload);
333
+ } else {
334
+ console.warn(`[EventBus] Emit: ${type} (NO LISTENERS)`, payload);
335
+ }
336
+ }
337
+ if (listeners) {
338
+ const listenersCopy = Array.from(listeners);
339
+ for (const listener of listenersCopy) {
340
+ try {
341
+ listener(event);
342
+ } catch (error) {
343
+ console.error(`[EventBus] Error in listener for '${type}':`, error);
344
+ }
345
+ }
346
+ }
347
+ if (type !== "*") {
348
+ const wildcardListeners = this.listeners.get("*");
349
+ if (wildcardListeners) {
350
+ for (const listener of Array.from(wildcardListeners)) {
351
+ try {
352
+ listener(event);
353
+ } catch (error) {
354
+ console.error(`[EventBus] Error in wildcard listener:`, error);
355
+ }
356
+ }
357
+ }
358
+ }
359
+ }
360
+ /**
361
+ * Subscribe to an event type
362
+ */
363
+ on(type, listener) {
364
+ if (!this.listeners.has(type)) {
365
+ this.listeners.set(type, /* @__PURE__ */ new Set());
366
+ }
367
+ const listeners = this.listeners.get(type);
368
+ listeners.add(listener);
369
+ if (this.debug) {
370
+ console.log(`[EventBus] Subscribed to '${type}', total: ${listeners.size}`);
371
+ }
372
+ return () => {
373
+ listeners.delete(listener);
374
+ if (this.debug) {
375
+ console.log(`[EventBus] Unsubscribed from '${type}', remaining: ${listeners.size}`);
376
+ }
377
+ if (listeners.size === 0) {
378
+ this.listeners.delete(type);
379
+ }
380
+ };
381
+ }
382
+ /**
383
+ * Subscribe to ALL events (wildcard listener)
384
+ * Useful for event tracking, logging, debugging
385
+ */
386
+ onAny(listener) {
387
+ return this.on("*", listener);
388
+ }
389
+ /**
390
+ * Check if there are listeners for an event type
391
+ */
392
+ hasListeners(type) {
393
+ const listeners = this.listeners.get(type);
394
+ return listeners !== void 0 && listeners.size > 0;
395
+ }
396
+ /**
397
+ * Get all registered event types
398
+ */
399
+ getRegisteredEvents() {
400
+ return Array.from(this.listeners.keys());
401
+ }
402
+ /**
403
+ * Clear all listeners
404
+ */
405
+ clear() {
406
+ if (this.debug) {
407
+ console.log(`[EventBus] Clearing all listeners (${this.listeners.size} event types)`);
408
+ }
409
+ this.listeners.clear();
410
+ }
411
+ /**
412
+ * Get listener count for an event type (for testing)
413
+ */
414
+ getListenerCount(type) {
415
+ return this.listeners.get(type)?.size ?? 0;
416
+ }
417
+ };
418
+ var OPERATORS = /* @__PURE__ */ new Set([
419
+ // Comparison
420
+ "=",
421
+ "!=",
422
+ "<",
423
+ ">",
424
+ "<=",
425
+ ">=",
426
+ // Logic
427
+ "and",
428
+ "or",
429
+ "not",
430
+ "if",
431
+ // Math
432
+ "+",
433
+ "-",
434
+ "*",
435
+ "/",
436
+ "%",
437
+ // Array
438
+ "count",
439
+ "first",
440
+ "last",
441
+ "map",
442
+ "filter",
443
+ "find",
444
+ "some",
445
+ "every",
446
+ "reduce",
447
+ // String
448
+ "concat",
449
+ "upper",
450
+ "lower",
451
+ "trim",
452
+ "substring",
453
+ "split",
454
+ "join",
455
+ "str",
456
+ // Effects
457
+ "set",
458
+ "emit",
459
+ "navigate",
460
+ "persist",
461
+ "notify",
462
+ "render-ui",
463
+ "render",
464
+ "spawn",
465
+ "despawn",
466
+ "call-service",
467
+ "do",
468
+ "when",
469
+ "increment",
470
+ "decrement",
471
+ "log"
472
+ ]);
473
+ function interpolateProps(props, ctx) {
474
+ const result = {};
475
+ for (const [key, value] of Object.entries(props)) {
476
+ result[key] = interpolateValue(value, ctx);
477
+ }
478
+ return result;
479
+ }
480
+ function interpolateValue(value, ctx) {
481
+ if (value === null || value === void 0) {
482
+ return value;
483
+ }
484
+ if (typeof value === "string") {
485
+ return interpolateString(value, ctx);
486
+ }
487
+ if (Array.isArray(value)) {
488
+ return interpolateArray(value, ctx);
489
+ }
490
+ if (typeof value === "object") {
491
+ return interpolateProps(value, ctx);
492
+ }
493
+ return value;
494
+ }
495
+ function interpolateString(value, ctx) {
496
+ if (value.startsWith("@") && isPureBinding(value)) {
497
+ return resolveBinding(value, ctx);
498
+ }
499
+ if (value.includes("@")) {
500
+ return interpolateEmbeddedBindings(value, ctx);
501
+ }
502
+ return value;
503
+ }
504
+ function isPureBinding(value) {
505
+ return /^@[\w]+(?:\.[\w]+)*$/.test(value);
506
+ }
507
+ function interpolateEmbeddedBindings(value, ctx) {
508
+ return value.replace(/@[\w]+(?:\.[\w]+)*/g, (match) => {
509
+ const resolved = resolveBinding(match, ctx);
510
+ return resolved !== void 0 ? String(resolved) : match;
511
+ });
512
+ }
513
+ function interpolateArray(value, ctx) {
514
+ if (value.length === 0) {
515
+ return [];
516
+ }
517
+ if (isSExpression(value)) {
518
+ return evaluate(value, ctx);
519
+ }
520
+ return value.map((item) => interpolateValue(item, ctx));
521
+ }
522
+ function isSExpression(value) {
523
+ if (value.length === 0) return false;
524
+ const first = value[0];
525
+ if (typeof first !== "string") return false;
526
+ if (OPERATORS.has(first)) return true;
527
+ if (first.includes("/")) return true;
528
+ if (first === "lambda" || first === "let") return true;
529
+ return false;
530
+ }
531
+ function containsBindings(value) {
532
+ if (typeof value === "string") {
533
+ return value.includes("@");
534
+ }
535
+ if (Array.isArray(value)) {
536
+ return value.some(containsBindings);
537
+ }
538
+ if (value !== null && typeof value === "object") {
539
+ return Object.values(value).some(containsBindings);
540
+ }
541
+ return false;
542
+ }
543
+ function extractBindings(value) {
544
+ const bindings = [];
545
+ function collect(v) {
546
+ if (typeof v === "string") {
547
+ const matches = v.match(/@[\w]+(?:\.[\w]+)*/g);
548
+ if (matches) {
549
+ bindings.push(...matches);
550
+ }
551
+ } else if (Array.isArray(v)) {
552
+ v.forEach(collect);
553
+ } else if (v !== null && typeof v === "object") {
554
+ Object.values(v).forEach(collect);
555
+ }
556
+ }
557
+ collect(value);
558
+ return [...new Set(bindings)];
559
+ }
560
+ function createContextFromBindings(bindings) {
561
+ return createMinimalContext(
562
+ bindings.entity || {},
563
+ bindings.payload || {},
564
+ bindings.state || "idle"
565
+ );
566
+ }
567
+ function findInitialState(trait) {
568
+ if (!trait.states || trait.states.length === 0) {
569
+ console.warn(`[StateMachine] Trait "${trait.name}" has no states defined, using "unknown"`);
570
+ return "unknown";
571
+ }
572
+ const markedInitial = trait.states.find((s) => s.isInitial)?.name;
573
+ const firstState = trait.states[0]?.name;
574
+ return markedInitial || firstState || "unknown";
575
+ }
576
+ function createInitialTraitState(trait) {
577
+ return {
578
+ traitName: trait.name,
579
+ currentState: findInitialState(trait),
580
+ previousState: null,
581
+ lastEvent: null,
582
+ context: {}
583
+ };
584
+ }
585
+ function findTransition(trait, currentState, eventKey) {
586
+ if (!trait.transitions || trait.transitions.length === 0) {
587
+ return void 0;
588
+ }
589
+ return trait.transitions.find((t) => {
590
+ if (Array.isArray(t.from)) {
591
+ return t.from.includes(currentState) && t.event === eventKey;
592
+ }
593
+ return t.from === currentState && t.event === eventKey;
594
+ });
595
+ }
596
+ function normalizeEventKey(eventKey) {
597
+ return eventKey.startsWith("UI:") ? eventKey.slice(3) : eventKey;
598
+ }
599
+ function processEvent(options) {
600
+ const { traitState, trait, eventKey, payload, entityData } = options;
601
+ const normalizedEvent = normalizeEventKey(eventKey);
602
+ const transition = findTransition(trait, traitState.currentState, normalizedEvent);
603
+ if (!transition) {
604
+ return {
605
+ executed: false,
606
+ newState: traitState.currentState,
607
+ previousState: traitState.currentState,
608
+ effects: []
609
+ };
610
+ }
611
+ if (transition.guard) {
612
+ const ctx = createContextFromBindings({
613
+ entity: entityData,
614
+ payload,
615
+ state: traitState.currentState
616
+ });
617
+ try {
618
+ const guardPasses = evaluateGuard(
619
+ transition.guard,
620
+ ctx
621
+ );
622
+ if (!guardPasses) {
623
+ return {
624
+ executed: false,
625
+ newState: traitState.currentState,
626
+ previousState: traitState.currentState,
627
+ effects: [],
628
+ transition: {
629
+ from: traitState.currentState,
630
+ to: transition.to,
631
+ event: normalizedEvent
632
+ },
633
+ guardResult: false
634
+ };
635
+ }
636
+ } catch (error) {
637
+ console.error("[StateMachineCore] Guard evaluation error:", error);
638
+ }
639
+ }
640
+ return {
641
+ executed: true,
642
+ newState: transition.to,
643
+ previousState: traitState.currentState,
644
+ effects: transition.effects || [],
645
+ transition: {
646
+ from: traitState.currentState,
647
+ to: transition.to,
648
+ event: normalizedEvent
649
+ },
650
+ guardResult: transition.guard ? true : void 0
651
+ };
652
+ }
653
+ var StateMachineManager = class {
654
+ traits = /* @__PURE__ */ new Map();
655
+ states = /* @__PURE__ */ new Map();
656
+ constructor(traits = []) {
657
+ for (const trait of traits) {
658
+ this.addTrait(trait);
659
+ }
660
+ }
661
+ /**
662
+ * Add a trait to the manager.
663
+ */
664
+ addTrait(trait) {
665
+ this.traits.set(trait.name, trait);
666
+ this.states.set(trait.name, createInitialTraitState(trait));
667
+ }
668
+ /**
669
+ * Remove a trait from the manager.
670
+ */
671
+ removeTrait(traitName) {
672
+ this.traits.delete(traitName);
673
+ this.states.delete(traitName);
674
+ }
675
+ /**
676
+ * Get current state for a trait.
677
+ */
678
+ getState(traitName) {
679
+ return this.states.get(traitName);
680
+ }
681
+ /**
682
+ * Get all current states.
683
+ */
684
+ getAllStates() {
685
+ return new Map(this.states);
686
+ }
687
+ /**
688
+ * Check if a trait can handle an event from its current state.
689
+ */
690
+ canHandleEvent(traitName, eventKey) {
691
+ const trait = this.traits.get(traitName);
692
+ const state = this.states.get(traitName);
693
+ if (!trait || !state) return false;
694
+ return !!findTransition(trait, state.currentState, normalizeEventKey(eventKey));
695
+ }
696
+ /**
697
+ * Send an event to all traits.
698
+ *
699
+ * @returns Array of transition results (one per trait that had a matching transition)
700
+ */
701
+ sendEvent(eventKey, payload, entityData) {
702
+ const results = [];
703
+ for (const [traitName, trait] of this.traits) {
704
+ const traitState = this.states.get(traitName);
705
+ if (!traitState) continue;
706
+ const result = processEvent({
707
+ traitState,
708
+ trait,
709
+ eventKey,
710
+ payload,
711
+ entityData
712
+ });
713
+ if (result.executed) {
714
+ this.states.set(traitName, {
715
+ ...traitState,
716
+ currentState: result.newState,
717
+ previousState: result.previousState,
718
+ lastEvent: normalizeEventKey(eventKey),
719
+ context: { ...traitState.context, ...payload }
720
+ });
721
+ results.push({ traitName, result });
722
+ }
723
+ }
724
+ return results;
725
+ }
726
+ /**
727
+ * Reset a trait to its initial state.
728
+ */
729
+ resetTrait(traitName) {
730
+ const trait = this.traits.get(traitName);
731
+ if (trait) {
732
+ this.states.set(traitName, createInitialTraitState(trait));
733
+ }
734
+ }
735
+ /**
736
+ * Reset all traits to initial states.
737
+ */
738
+ resetAll() {
739
+ for (const [traitName, trait] of this.traits) {
740
+ this.states.set(traitName, createInitialTraitState(trait));
741
+ }
742
+ }
743
+ };
744
+
745
+ // src/EffectExecutor.ts
746
+ function parseEffect(effect) {
747
+ if (!Array.isArray(effect) || effect.length === 0) {
748
+ return null;
749
+ }
750
+ const [operator, ...args] = effect;
751
+ if (typeof operator !== "string") {
752
+ return null;
753
+ }
754
+ return { operator, args };
755
+ }
756
+ function resolveArgs(args, bindings) {
757
+ const ctx = createContextFromBindings(bindings);
758
+ return args.map((arg) => interpolateValue(arg, ctx));
759
+ }
760
+ var EffectExecutor = class {
761
+ handlers;
762
+ bindings;
763
+ context;
764
+ debug;
765
+ constructor(options) {
766
+ this.handlers = options.handlers;
767
+ this.bindings = options.bindings;
768
+ this.context = options.context;
769
+ this.debug = options.debug ?? false;
770
+ }
771
+ /**
772
+ * Execute a single effect.
773
+ */
774
+ async execute(effect) {
775
+ const parsed = parseEffect(effect);
776
+ if (!parsed) {
777
+ if (this.debug) {
778
+ console.warn("[EffectExecutor] Invalid effect format:", effect);
779
+ }
780
+ return;
781
+ }
782
+ const { operator, args } = parsed;
783
+ const resolvedArgs = resolveArgs(args, this.bindings);
784
+ if (this.debug) {
785
+ console.log("[EffectExecutor] Executing:", operator, resolvedArgs);
786
+ }
787
+ try {
788
+ await this.dispatch(operator, resolvedArgs);
789
+ } catch (error) {
790
+ console.error("[EffectExecutor] Error executing effect:", operator, error);
791
+ throw error;
792
+ }
793
+ }
794
+ /**
795
+ * Execute multiple effects in sequence.
796
+ */
797
+ async executeAll(effects) {
798
+ for (const effect of effects) {
799
+ await this.execute(effect);
800
+ }
801
+ }
802
+ /**
803
+ * Execute multiple effects in parallel.
804
+ */
805
+ async executeParallel(effects) {
806
+ await Promise.all(effects.map((effect) => this.execute(effect)));
807
+ }
808
+ // ==========================================================================
809
+ // Effect Dispatch
810
+ // ==========================================================================
811
+ async dispatch(operator, args) {
812
+ switch (operator) {
813
+ // === Universal Effects ===
814
+ case "emit": {
815
+ const event = args[0];
816
+ const payload = args[1];
817
+ this.handlers.emit(event, payload);
818
+ break;
819
+ }
820
+ case "set": {
821
+ const [entityId, field, value] = args;
822
+ this.handlers.set(entityId, field, value);
823
+ break;
824
+ }
825
+ case "persist": {
826
+ const action = args[0];
827
+ const entityType = args[1];
828
+ const data = args[2];
829
+ await this.handlers.persist(action, entityType, data);
830
+ break;
831
+ }
832
+ case "call-service": {
833
+ const service = args[0];
834
+ const action = args[1];
835
+ const params = args[2];
836
+ await this.handlers.callService(service, action, params);
837
+ break;
838
+ }
839
+ case "fetch": {
840
+ if (this.handlers.fetch) {
841
+ const entityType = args[0];
842
+ const options = args[1];
843
+ await this.handlers.fetch(entityType, options);
844
+ } else {
845
+ this.logUnsupported("fetch");
846
+ }
847
+ break;
848
+ }
849
+ case "spawn": {
850
+ if (this.handlers.spawn) {
851
+ const entityType = args[0];
852
+ const props = args[1];
853
+ this.handlers.spawn(entityType, props);
854
+ } else {
855
+ this.logUnsupported("spawn");
856
+ }
857
+ break;
858
+ }
859
+ case "despawn": {
860
+ if (this.handlers.despawn) {
861
+ const entityId = args[0];
862
+ this.handlers.despawn(entityId);
863
+ } else {
864
+ this.logUnsupported("despawn");
865
+ }
866
+ break;
867
+ }
868
+ case "log": {
869
+ if (this.handlers.log) {
870
+ const message = args[0];
871
+ const level = args[1];
872
+ const data = args[2];
873
+ this.handlers.log(message, level, data);
874
+ } else {
875
+ console.log(args[0], args.slice(1));
876
+ }
877
+ break;
878
+ }
879
+ // === Client-Only Effects ===
880
+ case "render-ui":
881
+ case "render": {
882
+ if (this.handlers.renderUI) {
883
+ const slot = args[0];
884
+ const pattern = args[1];
885
+ const props = args[2];
886
+ const priority = args[3];
887
+ this.handlers.renderUI(slot, pattern, props, priority);
888
+ } else {
889
+ this.logUnsupported("render-ui");
890
+ }
891
+ break;
892
+ }
893
+ case "navigate": {
894
+ if (this.handlers.navigate) {
895
+ const path2 = args[0];
896
+ const params = args[1];
897
+ this.handlers.navigate(path2, params);
898
+ } else {
899
+ this.logUnsupported("navigate");
900
+ }
901
+ break;
902
+ }
903
+ case "notify": {
904
+ if (this.handlers.notify) {
905
+ const message = args[0];
906
+ const type = args[1] || "info";
907
+ this.handlers.notify(message, type);
908
+ } else {
909
+ console.log(`[Notify:${args[1] || "info"}] ${args[0]}`);
910
+ }
911
+ break;
912
+ }
913
+ // === Compound Effects ===
914
+ case "do": {
915
+ const nestedEffects = args;
916
+ for (const nested of nestedEffects) {
917
+ await this.execute(nested);
918
+ }
919
+ break;
920
+ }
921
+ case "when": {
922
+ const condition = args[0];
923
+ const thenEffect = args[1];
924
+ const elseEffect = args[2];
925
+ if (condition) {
926
+ await this.execute(thenEffect);
927
+ } else if (elseEffect) {
928
+ await this.execute(elseEffect);
929
+ }
930
+ break;
931
+ }
932
+ default: {
933
+ if (this.debug) {
934
+ console.warn("[EffectExecutor] Unknown operator:", operator);
935
+ }
936
+ }
937
+ }
938
+ }
939
+ logUnsupported(operator) {
940
+ if (this.debug) {
941
+ console.warn(
942
+ `[EffectExecutor] Effect "${operator}" not supported on this platform`
943
+ );
944
+ }
945
+ }
946
+ };
947
+ function createTestExecutor(overrides = {}) {
948
+ const noopAsync = async () => {
949
+ };
950
+ const noop = () => {
951
+ };
952
+ return new EffectExecutor({
953
+ handlers: {
954
+ emit: overrides.emit ?? noop,
955
+ persist: overrides.persist ?? noopAsync,
956
+ set: overrides.set ?? noop,
957
+ callService: overrides.callService ?? (async () => ({})),
958
+ ...overrides
959
+ },
960
+ bindings: {},
961
+ context: {
962
+ traitName: "TestTrait",
963
+ state: "test",
964
+ transition: "test->test"
965
+ },
966
+ debug: true
967
+ });
968
+ }
969
+
970
+ // src/resolver/reference-resolver.ts
971
+ init_external_loader();
972
+ var ReferenceResolver = class {
973
+ loader;
974
+ options;
975
+ localTraits;
976
+ constructor(options) {
977
+ this.options = options;
978
+ this.loader = options.loader ?? new ExternalOrbitalLoader(options);
979
+ this.localTraits = options.localTraits ?? /* @__PURE__ */ new Map();
980
+ }
981
+ /**
982
+ * Resolve all references in an orbital.
983
+ */
984
+ async resolve(orbital, sourcePath, chain) {
985
+ const errors = [];
986
+ const warnings = [];
987
+ const importChain = chain ?? new ImportChain();
988
+ const importsResult = await this.resolveImports(
989
+ orbital.uses ?? [],
990
+ sourcePath,
991
+ importChain
992
+ );
993
+ if (!importsResult.success) {
994
+ return { success: false, errors: importsResult.errors };
995
+ }
996
+ const imports = importsResult.data;
997
+ const entityResult = this.resolveEntity(orbital.entity, imports);
998
+ if (!entityResult.success) {
999
+ errors.push(...entityResult.errors);
1000
+ }
1001
+ const traitsResult = this.resolveTraits(orbital.traits, imports);
1002
+ if (!traitsResult.success) {
1003
+ errors.push(...traitsResult.errors);
1004
+ }
1005
+ const pagesResult = this.resolvePages(orbital.pages, imports);
1006
+ if (!pagesResult.success) {
1007
+ errors.push(...pagesResult.errors);
1008
+ }
1009
+ if (errors.length > 0) {
1010
+ return { success: false, errors };
1011
+ }
1012
+ if (!entityResult.success || !traitsResult.success || !pagesResult.success) {
1013
+ return { success: false, errors: ["Internal error: unexpected failure state"] };
1014
+ }
1015
+ return {
1016
+ success: true,
1017
+ data: {
1018
+ name: orbital.name,
1019
+ entity: entityResult.data.entity,
1020
+ entitySource: entityResult.data.source,
1021
+ traits: traitsResult.data,
1022
+ pages: pagesResult.data,
1023
+ imports,
1024
+ original: orbital
1025
+ },
1026
+ warnings
1027
+ };
1028
+ }
1029
+ /**
1030
+ * Resolve `uses` declarations to loaded orbitals.
1031
+ */
1032
+ async resolveImports(uses, sourcePath, chain) {
1033
+ const errors = [];
1034
+ const orbitals = /* @__PURE__ */ new Map();
1035
+ if (this.options.skipExternalLoading) {
1036
+ return {
1037
+ success: true,
1038
+ data: { orbitals },
1039
+ warnings: ["External loading skipped"]
1040
+ };
1041
+ }
1042
+ for (const use of uses) {
1043
+ if (orbitals.has(use.as)) {
1044
+ errors.push(`Duplicate import alias: ${use.as}`);
1045
+ continue;
1046
+ }
1047
+ const loadResult = await this.loader.loadOrbital(
1048
+ use.from,
1049
+ void 0,
1050
+ sourcePath,
1051
+ chain
1052
+ );
1053
+ if (!loadResult.success) {
1054
+ errors.push(`Failed to load "${use.from}" as "${use.as}": ${loadResult.error}`);
1055
+ continue;
1056
+ }
1057
+ orbitals.set(use.as, {
1058
+ alias: use.as,
1059
+ from: use.from,
1060
+ orbital: loadResult.data.orbital,
1061
+ sourcePath: loadResult.data.sourcePath
1062
+ });
1063
+ }
1064
+ if (errors.length > 0) {
1065
+ return { success: false, errors };
1066
+ }
1067
+ return { success: true, data: { orbitals }, warnings: [] };
1068
+ }
1069
+ /**
1070
+ * Resolve entity reference.
1071
+ */
1072
+ resolveEntity(entityRef, imports) {
1073
+ if (!isEntityReference(entityRef)) {
1074
+ return {
1075
+ success: true,
1076
+ data: { entity: entityRef },
1077
+ warnings: []
1078
+ };
1079
+ }
1080
+ const parsed = parseEntityRef(entityRef);
1081
+ if (!parsed) {
1082
+ return {
1083
+ success: false,
1084
+ errors: [`Invalid entity reference format: ${entityRef}. Expected "Alias.entity"`]
1085
+ };
1086
+ }
1087
+ const imported = imports.orbitals.get(parsed.alias);
1088
+ if (!imported) {
1089
+ return {
1090
+ success: false,
1091
+ errors: [
1092
+ `Unknown import alias in entity reference: ${parsed.alias}. Available aliases: ${Array.from(imports.orbitals.keys()).join(", ") || "none"}`
1093
+ ]
1094
+ };
1095
+ }
1096
+ const importedEntity = this.getEntityFromOrbital(imported.orbital);
1097
+ if (!importedEntity) {
1098
+ return {
1099
+ success: false,
1100
+ errors: [
1101
+ `Imported orbital "${parsed.alias}" does not have an inline entity. Entity references cannot be chained.`
1102
+ ]
1103
+ };
1104
+ }
1105
+ const persistence = importedEntity.persistence ?? "persistent";
1106
+ return {
1107
+ success: true,
1108
+ data: {
1109
+ entity: importedEntity,
1110
+ source: {
1111
+ alias: parsed.alias,
1112
+ persistence
1113
+ }
1114
+ },
1115
+ warnings: []
1116
+ };
1117
+ }
1118
+ /**
1119
+ * Get the entity from an orbital (handling EntityRef).
1120
+ */
1121
+ getEntityFromOrbital(orbital) {
1122
+ const entityRef = orbital.entity;
1123
+ if (typeof entityRef === "string") {
1124
+ return null;
1125
+ }
1126
+ return entityRef;
1127
+ }
1128
+ /**
1129
+ * Resolve trait references.
1130
+ */
1131
+ resolveTraits(traitRefs, imports) {
1132
+ const errors = [];
1133
+ const resolved = [];
1134
+ for (const traitRef of traitRefs) {
1135
+ const result = this.resolveTraitRef(traitRef, imports);
1136
+ if (!result.success) {
1137
+ errors.push(...result.errors);
1138
+ } else {
1139
+ resolved.push(result.data);
1140
+ }
1141
+ }
1142
+ if (errors.length > 0) {
1143
+ return { success: false, errors };
1144
+ }
1145
+ return { success: true, data: resolved, warnings: [] };
1146
+ }
1147
+ /**
1148
+ * Resolve a single trait reference.
1149
+ */
1150
+ resolveTraitRef(traitRef, imports) {
1151
+ if (typeof traitRef !== "string" && "stateMachine" in traitRef) {
1152
+ return {
1153
+ success: true,
1154
+ data: {
1155
+ trait: traitRef,
1156
+ source: { type: "inline" }
1157
+ },
1158
+ warnings: []
1159
+ };
1160
+ }
1161
+ if (typeof traitRef !== "string" && "ref" in traitRef) {
1162
+ const refObj = traitRef;
1163
+ return this.resolveTraitRefString(refObj.ref, imports, refObj.config, refObj.linkedEntity);
1164
+ }
1165
+ if (typeof traitRef === "string") {
1166
+ return this.resolveTraitRefString(traitRef, imports);
1167
+ }
1168
+ return {
1169
+ success: false,
1170
+ errors: [`Unknown trait reference format: ${JSON.stringify(traitRef)}`]
1171
+ };
1172
+ }
1173
+ /**
1174
+ * Resolve a trait reference string.
1175
+ */
1176
+ resolveTraitRefString(ref, imports, config, linkedEntity) {
1177
+ const parsed = parseImportedTraitRef(ref);
1178
+ if (parsed) {
1179
+ const imported = imports.orbitals.get(parsed.alias);
1180
+ if (!imported) {
1181
+ return {
1182
+ success: false,
1183
+ errors: [
1184
+ `Unknown import alias in trait reference: ${parsed.alias}. Available aliases: ${Array.from(imports.orbitals.keys()).join(", ") || "none"}`
1185
+ ]
1186
+ };
1187
+ }
1188
+ const trait = this.findTraitInOrbital(imported.orbital, parsed.traitName);
1189
+ if (!trait) {
1190
+ return {
1191
+ success: false,
1192
+ errors: [
1193
+ `Trait "${parsed.traitName}" not found in imported orbital "${parsed.alias}". Available traits: ${this.listTraitsInOrbital(imported.orbital).join(", ") || "none"}`
1194
+ ]
1195
+ };
1196
+ }
1197
+ return {
1198
+ success: true,
1199
+ data: {
1200
+ trait,
1201
+ source: { type: "imported", alias: parsed.alias, traitName: parsed.traitName },
1202
+ config,
1203
+ linkedEntity
1204
+ },
1205
+ warnings: []
1206
+ };
1207
+ }
1208
+ const localTrait = this.localTraits.get(ref);
1209
+ if (localTrait) {
1210
+ return {
1211
+ success: true,
1212
+ data: {
1213
+ trait: localTrait,
1214
+ source: { type: "local", name: ref },
1215
+ config,
1216
+ linkedEntity
1217
+ },
1218
+ warnings: []
1219
+ };
1220
+ }
1221
+ return {
1222
+ success: false,
1223
+ errors: [
1224
+ `Trait "${ref}" not found. For imported traits, use format "Alias.traits.TraitName". Local traits available: ${Array.from(this.localTraits.keys()).join(", ") || "none"}`
1225
+ ]
1226
+ };
1227
+ }
1228
+ /**
1229
+ * Find a trait in an orbital by name.
1230
+ */
1231
+ findTraitInOrbital(orbital, traitName) {
1232
+ for (const traitRef of orbital.traits) {
1233
+ if (typeof traitRef !== "string" && "stateMachine" in traitRef) {
1234
+ if (traitRef.name === traitName) {
1235
+ return traitRef;
1236
+ }
1237
+ }
1238
+ if (typeof traitRef !== "string" && "ref" in traitRef) {
1239
+ const refObj = traitRef;
1240
+ if (refObj.ref === traitName || refObj.name === traitName) ;
1241
+ }
1242
+ }
1243
+ return null;
1244
+ }
1245
+ /**
1246
+ * List trait names in an orbital.
1247
+ */
1248
+ listTraitsInOrbital(orbital) {
1249
+ const names = [];
1250
+ for (const traitRef of orbital.traits) {
1251
+ if (typeof traitRef !== "string" && "stateMachine" in traitRef) {
1252
+ names.push(traitRef.name);
1253
+ }
1254
+ }
1255
+ return names;
1256
+ }
1257
+ /**
1258
+ * Resolve page references.
1259
+ */
1260
+ resolvePages(pageRefs, imports) {
1261
+ const errors = [];
1262
+ const resolved = [];
1263
+ for (const pageRef of pageRefs) {
1264
+ const result = this.resolvePageRef(pageRef, imports);
1265
+ if (!result.success) {
1266
+ errors.push(...result.errors);
1267
+ } else {
1268
+ resolved.push(result.data);
1269
+ }
1270
+ }
1271
+ if (errors.length > 0) {
1272
+ return { success: false, errors };
1273
+ }
1274
+ return { success: true, data: resolved, warnings: [] };
1275
+ }
1276
+ /**
1277
+ * Resolve a single page reference.
1278
+ */
1279
+ resolvePageRef(pageRef, imports) {
1280
+ if (!isPageReference(pageRef)) {
1281
+ return {
1282
+ success: true,
1283
+ data: {
1284
+ page: pageRef,
1285
+ source: { type: "inline" },
1286
+ pathOverridden: false
1287
+ },
1288
+ warnings: []
1289
+ };
1290
+ }
1291
+ if (isPageReferenceString(pageRef)) {
1292
+ return this.resolvePageRefString(pageRef, imports);
1293
+ }
1294
+ if (isPageReferenceObject(pageRef)) {
1295
+ return this.resolvePageRefObject(pageRef, imports);
1296
+ }
1297
+ return {
1298
+ success: false,
1299
+ errors: [`Unknown page reference format: ${JSON.stringify(pageRef)}`]
1300
+ };
1301
+ }
1302
+ /**
1303
+ * Resolve a page reference string.
1304
+ */
1305
+ resolvePageRefString(ref, imports) {
1306
+ const parsed = parsePageRef(ref);
1307
+ if (!parsed) {
1308
+ return {
1309
+ success: false,
1310
+ errors: [`Invalid page reference format: ${ref}. Expected "Alias.pages.PageName"`]
1311
+ };
1312
+ }
1313
+ const imported = imports.orbitals.get(parsed.alias);
1314
+ if (!imported) {
1315
+ return {
1316
+ success: false,
1317
+ errors: [
1318
+ `Unknown import alias in page reference: ${parsed.alias}. Available aliases: ${Array.from(imports.orbitals.keys()).join(", ") || "none"}`
1319
+ ]
1320
+ };
1321
+ }
1322
+ const page = this.findPageInOrbital(imported.orbital, parsed.pageName);
1323
+ if (!page) {
1324
+ return {
1325
+ success: false,
1326
+ errors: [
1327
+ `Page "${parsed.pageName}" not found in imported orbital "${parsed.alias}". Available pages: ${this.listPagesInOrbital(imported.orbital).join(", ") || "none"}`
1328
+ ]
1329
+ };
1330
+ }
1331
+ return {
1332
+ success: true,
1333
+ data: {
1334
+ page,
1335
+ source: { type: "imported", alias: parsed.alias, pageName: parsed.pageName },
1336
+ pathOverridden: false
1337
+ },
1338
+ warnings: []
1339
+ };
1340
+ }
1341
+ /**
1342
+ * Resolve a page reference object with optional path override.
1343
+ */
1344
+ resolvePageRefObject(refObj, imports) {
1345
+ const baseResult = this.resolvePageRefString(refObj.ref, imports);
1346
+ if (!baseResult.success) {
1347
+ return baseResult;
1348
+ }
1349
+ const resolved = baseResult.data;
1350
+ if (refObj.path) {
1351
+ const originalPath = resolved.page.path;
1352
+ resolved.page = {
1353
+ ...resolved.page,
1354
+ path: refObj.path
1355
+ };
1356
+ resolved.pathOverridden = true;
1357
+ resolved.originalPath = originalPath;
1358
+ }
1359
+ return {
1360
+ success: true,
1361
+ data: resolved,
1362
+ warnings: baseResult.warnings
1363
+ };
1364
+ }
1365
+ /**
1366
+ * Find a page in an orbital by name.
1367
+ */
1368
+ findPageInOrbital(orbital, pageName) {
1369
+ const pages = orbital.pages;
1370
+ if (!pages) return null;
1371
+ for (const pageRef of pages) {
1372
+ if (typeof pageRef !== "string" && !("ref" in pageRef)) {
1373
+ const page = pageRef;
1374
+ if (page.name === pageName) {
1375
+ return { ...page };
1376
+ }
1377
+ }
1378
+ }
1379
+ return null;
1380
+ }
1381
+ /**
1382
+ * List page names in an orbital.
1383
+ */
1384
+ listPagesInOrbital(orbital) {
1385
+ const pages = orbital.pages;
1386
+ if (!pages) return [];
1387
+ const names = [];
1388
+ for (const pageRef of pages) {
1389
+ if (typeof pageRef !== "string" && !("ref" in pageRef)) {
1390
+ names.push(pageRef.name);
1391
+ }
1392
+ }
1393
+ return names;
1394
+ }
1395
+ /**
1396
+ * Add local traits for resolution.
1397
+ */
1398
+ addLocalTraits(traits) {
1399
+ for (const trait of traits) {
1400
+ this.localTraits.set(trait.name, trait);
1401
+ }
1402
+ }
1403
+ /**
1404
+ * Clear loader cache.
1405
+ */
1406
+ clearCache() {
1407
+ this.loader.clearCache();
1408
+ }
1409
+ };
1410
+ async function resolveSchema(schema, options) {
1411
+ const resolver = new ReferenceResolver(options);
1412
+ const errors = [];
1413
+ const warnings = [];
1414
+ const resolved = [];
1415
+ for (const orbital of schema.orbitals) {
1416
+ const inlineTraits = orbital.traits.filter(
1417
+ (t) => typeof t !== "string" && "stateMachine" in t
1418
+ );
1419
+ resolver.addLocalTraits(inlineTraits);
1420
+ }
1421
+ for (const orbital of schema.orbitals) {
1422
+ const result = await resolver.resolve(orbital);
1423
+ if (!result.success) {
1424
+ errors.push(`Orbital "${orbital.name}": ${result.errors.join(", ")}`);
1425
+ } else {
1426
+ resolved.push(result.data);
1427
+ warnings.push(...result.warnings.map((w) => `Orbital "${orbital.name}": ${w}`));
1428
+ }
1429
+ }
1430
+ if (errors.length > 0) {
1431
+ return { success: false, errors };
1432
+ }
1433
+ return { success: true, data: resolved, warnings };
1434
+ }
1435
+
1436
+ // src/loader/index.ts
1437
+ init_external_loader();
1438
+
1439
+ // src/UsesIntegration.ts
1440
+ async function preprocessSchema(schema, options) {
1441
+ const namespaceEvents = options.namespaceEvents ?? true;
1442
+ const resolveResult = await resolveSchema(schema, options);
1443
+ if (!resolveResult.success) {
1444
+ return { success: false, errors: resolveResult.errors };
1445
+ }
1446
+ const resolved = resolveResult.data;
1447
+ const warnings = resolveResult.warnings;
1448
+ const preprocessedOrbitals = [];
1449
+ const entitySharing = {};
1450
+ const eventNamespaces = {};
1451
+ for (const resolvedOrbital of resolved) {
1452
+ const orbitalName = resolvedOrbital.name;
1453
+ const persistence = resolvedOrbital.entitySource?.persistence ?? resolvedOrbital.entity.persistence ?? "persistent";
1454
+ entitySharing[orbitalName] = {
1455
+ entityName: resolvedOrbital.entity.name,
1456
+ persistence,
1457
+ isShared: persistence !== "runtime",
1458
+ sourceAlias: resolvedOrbital.entitySource?.alias,
1459
+ collectionName: resolvedOrbital.entity.collection
1460
+ };
1461
+ eventNamespaces[orbitalName] = {};
1462
+ for (const resolvedTrait of resolvedOrbital.traits) {
1463
+ const traitName = resolvedTrait.trait.name;
1464
+ const namespace = {
1465
+ emits: {},
1466
+ listens: {}
1467
+ };
1468
+ if (namespaceEvents && resolvedTrait.source.type === "imported") {
1469
+ const emits = resolvedTrait.trait.emits ?? [];
1470
+ for (const emit of emits) {
1471
+ const eventName = typeof emit === "string" ? emit : emit.event;
1472
+ namespace.emits[eventName] = `${orbitalName}.${traitName}.${eventName}`;
1473
+ }
1474
+ const listens = resolvedTrait.trait.listens ?? [];
1475
+ for (const listen of listens) {
1476
+ namespace.listens[listen.event] = listen.event;
1477
+ }
1478
+ }
1479
+ eventNamespaces[orbitalName][traitName] = namespace;
1480
+ }
1481
+ const preprocessedOrbital = {
1482
+ name: orbitalName,
1483
+ description: resolvedOrbital.original.description,
1484
+ visual_prompt: resolvedOrbital.original.visual_prompt,
1485
+ // Resolved entity (always inline now)
1486
+ entity: resolvedOrbital.entity,
1487
+ // Resolved traits (inline definitions)
1488
+ traits: resolvedOrbital.traits.map((rt) => {
1489
+ if (rt.config || rt.linkedEntity) {
1490
+ return {
1491
+ ref: rt.trait.name,
1492
+ config: rt.config,
1493
+ linkedEntity: rt.linkedEntity,
1494
+ // Include the resolved trait definition for runtime
1495
+ _resolved: rt.trait
1496
+ };
1497
+ }
1498
+ return rt.trait;
1499
+ }),
1500
+ // Resolved pages (inline definitions with path overrides applied)
1501
+ pages: resolvedOrbital.pages.map((rp) => rp.page),
1502
+ // Preserve other fields
1503
+ exposes: resolvedOrbital.original.exposes,
1504
+ domainContext: resolvedOrbital.original.domainContext,
1505
+ design: resolvedOrbital.original.design
1506
+ };
1507
+ preprocessedOrbitals.push(preprocessedOrbital);
1508
+ }
1509
+ const preprocessedSchema = {
1510
+ ...schema,
1511
+ orbitals: preprocessedOrbitals
1512
+ };
1513
+ return {
1514
+ success: true,
1515
+ data: {
1516
+ schema: preprocessedSchema,
1517
+ entitySharing,
1518
+ eventNamespaces,
1519
+ warnings
1520
+ }
1521
+ };
1522
+ }
1523
+ function getIsolatedCollectionName(orbitalName, entitySharing) {
1524
+ const info = entitySharing[orbitalName];
1525
+ if (!info) {
1526
+ throw new Error(`Unknown orbital: ${orbitalName}`);
1527
+ }
1528
+ if (info.persistence === "runtime") {
1529
+ return `${orbitalName}_${info.entityName}`;
1530
+ }
1531
+ return info.collectionName || info.entityName.toLowerCase() + "s";
1532
+ }
1533
+ function getNamespacedEvent(orbitalName, traitName, eventName, eventNamespaces) {
1534
+ const orbitalNs = eventNamespaces[orbitalName];
1535
+ if (!orbitalNs) return eventName;
1536
+ const traitNs = orbitalNs[traitName];
1537
+ if (!traitNs) return eventName;
1538
+ return traitNs.emits[eventName] || eventName;
1539
+ }
1540
+ function isNamespacedEvent(eventName) {
1541
+ return eventName.includes(".");
1542
+ }
1543
+ function parseNamespacedEvent(eventName) {
1544
+ const parts = eventName.split(".");
1545
+ if (parts.length === 3) {
1546
+ return { orbital: parts[0], trait: parts[1], event: parts[2] };
1547
+ }
1548
+ if (parts.length === 2) {
1549
+ return { trait: parts[0], event: parts[1] };
1550
+ }
1551
+ return { event: eventName };
1552
+ }
1553
+
1554
+ export { EffectExecutor, EventBus, StateMachineManager, containsBindings, createContextFromBindings, createInitialTraitState, createTestExecutor, extractBindings, findInitialState, findTransition, getIsolatedCollectionName, getNamespacedEvent, interpolateProps, interpolateValue, isNamespacedEvent, normalizeEventKey, parseNamespacedEvent, preprocessSchema, processEvent };
1555
+ //# sourceMappingURL=index.js.map
1556
+ //# sourceMappingURL=index.js.map