@hypen-space/core 0.4.37 → 0.4.38

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/README.md +13 -14
  2. package/dist/app.js +289 -227
  3. package/dist/app.js.map +5 -5
  4. package/dist/components/builtin.js +289 -227
  5. package/dist/components/builtin.js.map +5 -5
  6. package/dist/context.js +60 -64
  7. package/dist/context.js.map +2 -2
  8. package/dist/datasource.js +80 -0
  9. package/dist/datasource.js.map +10 -0
  10. package/dist/disposable.js +60 -63
  11. package/dist/disposable.js.map +2 -2
  12. package/dist/events.js +60 -63
  13. package/dist/events.js.map +2 -2
  14. package/dist/hypen.js +78 -0
  15. package/dist/hypen.js.map +10 -0
  16. package/dist/index.browser.d.ts +2 -1
  17. package/dist/index.browser.js +303 -244
  18. package/dist/index.browser.js.map +6 -7
  19. package/dist/index.d.ts +0 -3
  20. package/dist/index.js +492 -180
  21. package/dist/index.js.map +6 -6
  22. package/dist/logger.js +60 -64
  23. package/dist/logger.js.map +2 -2
  24. package/dist/remote/client.js +243 -158
  25. package/dist/remote/client.js.map +6 -6
  26. package/dist/remote/index.d.ts +6 -5
  27. package/dist/remote/index.js +241 -1986
  28. package/dist/remote/index.js.map +6 -13
  29. package/dist/remote/session.js +151 -0
  30. package/dist/remote/session.js.map +10 -0
  31. package/dist/renderer.js +60 -63
  32. package/dist/renderer.js.map +2 -2
  33. package/dist/result.js +220 -0
  34. package/dist/result.js.map +10 -0
  35. package/dist/retry.js +329 -0
  36. package/dist/retry.js.map +11 -0
  37. package/dist/router.js +62 -70
  38. package/dist/router.js.map +2 -2
  39. package/dist/state.js +3 -8
  40. package/dist/state.js.map +2 -2
  41. package/package.json +11 -56
  42. package/src/index.browser.ts +5 -4
  43. package/src/index.ts +10 -23
  44. package/src/remote/index.ts +9 -5
  45. package/dist/discovery.d.ts +0 -90
  46. package/dist/discovery.js +0 -1334
  47. package/dist/discovery.js.map +0 -15
  48. package/dist/engine.browser.d.ts +0 -116
  49. package/dist/engine.browser.js +0 -479
  50. package/dist/engine.browser.js.map +0 -12
  51. package/dist/engine.d.ts +0 -107
  52. package/dist/engine.js +0 -543
  53. package/dist/engine.js.map +0 -12
  54. package/dist/loader.d.ts +0 -51
  55. package/dist/loader.js +0 -292
  56. package/dist/loader.js.map +0 -11
  57. package/dist/plugin.d.ts +0 -39
  58. package/dist/plugin.js +0 -685
  59. package/dist/plugin.js.map +0 -12
  60. package/dist/remote/server.d.ts +0 -188
  61. package/dist/remote/server.js +0 -2270
  62. package/dist/remote/server.js.map +0 -19
  63. package/src/discovery.ts +0 -527
  64. package/src/engine.browser.ts +0 -302
  65. package/src/engine.ts +0 -282
  66. package/src/loader.ts +0 -136
  67. package/src/plugin.ts +0 -220
  68. package/src/remote/server.ts +0 -879
  69. package/wasm-browser/README.md +0 -594
  70. package/wasm-browser/hypen_engine.d.ts +0 -389
  71. package/wasm-browser/hypen_engine.js +0 -1070
  72. package/wasm-browser/hypen_engine_bg.wasm +0 -0
  73. package/wasm-browser/hypen_engine_bg.wasm.d.ts +0 -37
  74. package/wasm-browser/package.json +0 -24
  75. package/wasm-node/README.md +0 -594
  76. package/wasm-node/hypen_engine.d.ts +0 -327
  77. package/wasm-node/hypen_engine.js +0 -979
  78. package/wasm-node/hypen_engine_bg.wasm +0 -0
  79. package/wasm-node/hypen_engine_bg.wasm.d.ts +0 -37
  80. package/wasm-node/package.json +0 -22
@@ -1,2270 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __returnValue = (v) => v;
3
- function __exportSetter(name, newValue) {
4
- this[name] = __returnValue.bind(null, newValue);
5
- }
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, {
9
- get: all[name],
10
- enumerable: true,
11
- configurable: true,
12
- set: __exportSetter.bind(all, name)
13
- });
14
- };
15
- var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
16
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
17
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
18
- }) : x)(function(x) {
19
- if (typeof require !== "undefined")
20
- return require.apply(this, arguments);
21
- throw Error('Dynamic require of "' + x + '" is not supported');
22
- });
23
-
24
- // src/state.ts
25
- function deepClone(obj) {
26
- if (obj === null || typeof obj !== "object") {
27
- return obj;
28
- }
29
- if (typeof obj === "function") {
30
- return obj;
31
- }
32
- if (typeof obj.__getSnapshot === "function") {
33
- return obj.__getSnapshot();
34
- }
35
- if (obj instanceof WeakMap || obj instanceof WeakSet) {
36
- return obj;
37
- }
38
- const visited = new WeakMap;
39
- function cloneInternal(value) {
40
- if (value === null || typeof value !== "object") {
41
- return value;
42
- }
43
- if (typeof value === "function") {
44
- return value;
45
- }
46
- if (visited.has(value)) {
47
- return visited.get(value);
48
- }
49
- if (value instanceof WeakMap || value instanceof WeakSet) {
50
- return value;
51
- }
52
- if (value instanceof Date || value instanceof RegExp || value instanceof Map || value instanceof Set || ArrayBuffer.isView(value) || value instanceof ArrayBuffer) {
53
- try {
54
- return structuredClone(value);
55
- } catch {}
56
- }
57
- if (Array.isArray(value)) {
58
- const arrClone = [];
59
- visited.set(value, arrClone);
60
- for (let i = 0;i < value.length; i++) {
61
- arrClone[i] = cloneInternal(value[i]);
62
- }
63
- return arrClone;
64
- }
65
- const objClone = {};
66
- visited.set(value, objClone);
67
- for (const key in value) {
68
- if (Object.prototype.hasOwnProperty.call(value, key)) {
69
- objClone[key] = cloneInternal(value[key]);
70
- }
71
- }
72
- const symbolKeys = Object.getOwnPropertySymbols(value);
73
- for (const sym of symbolKeys) {
74
- objClone[sym] = cloneInternal(value[sym]);
75
- }
76
- return objClone;
77
- }
78
- return cloneInternal(obj);
79
- }
80
- function diffState(oldState, newState, basePath = "") {
81
- const paths = [];
82
- const newValues = {};
83
- function diff(oldVal, newVal, path) {
84
- if (oldVal === newVal)
85
- return;
86
- if (typeof oldVal !== "object" || typeof newVal !== "object" || oldVal === null || newVal === null) {
87
- if (oldVal !== newVal) {
88
- paths.push(path);
89
- newValues[path] = newVal;
90
- }
91
- return;
92
- }
93
- if (Array.isArray(oldVal) || Array.isArray(newVal)) {
94
- if (!Array.isArray(oldVal) || !Array.isArray(newVal) || oldVal.length !== newVal.length) {
95
- paths.push(path);
96
- newValues[path] = newVal;
97
- return;
98
- }
99
- for (let i = 0;i < newVal.length; i++) {
100
- const itemPath = path ? `${path}.${i}` : `${i}`;
101
- diff(oldVal[i], newVal[i], itemPath);
102
- }
103
- return;
104
- }
105
- const oldKeys = new Set(Object.keys(oldVal));
106
- const newKeys = new Set(Object.keys(newVal));
107
- for (const key of newKeys) {
108
- const propPath = path ? `${path}.${key}` : key;
109
- if (!oldKeys.has(key)) {
110
- paths.push(propPath);
111
- newValues[propPath] = newVal[key];
112
- } else {
113
- diff(oldVal[key], newVal[key], propPath);
114
- }
115
- }
116
- for (const key of oldKeys) {
117
- if (!newKeys.has(key)) {
118
- const propPath = path ? `${path}.${key}` : key;
119
- paths.push(propPath);
120
- newValues[propPath] = undefined;
121
- }
122
- }
123
- }
124
- diff(oldState, newState, basePath);
125
- return { paths, newValues };
126
- }
127
- function createObservableState(initialState, options) {
128
- const opts = options || { onChange: () => {} };
129
- if (initialState === null || initialState === undefined) {
130
- initialState = {};
131
- }
132
- if (initialState instanceof Number || initialState instanceof String || initialState instanceof Boolean) {
133
- throw new TypeError("Cannot create observable state from primitive wrapper objects (Number, String, Boolean). " + "Use plain primitives or regular objects instead.");
134
- }
135
- initialState = deepClone(initialState);
136
- let lastSnapshot = deepClone(initialState);
137
- const pathPrefix = opts.pathPrefix || "";
138
- let batchDepth = 0;
139
- let pendingChange = null;
140
- function notifyChange() {
141
- if (batchDepth > 0)
142
- return;
143
- const change = diffState(lastSnapshot, state, pathPrefix);
144
- if (change.paths.length > 0) {
145
- lastSnapshot = deepClone(state);
146
- if (pendingChange) {
147
- change.paths.push(...pendingChange.paths);
148
- Object.assign(change.newValues, pendingChange.newValues);
149
- pendingChange = null;
150
- }
151
- opts.onChange(change);
152
- }
153
- }
154
- let notificationPending = false;
155
- function scheduleBatch() {
156
- if (batchDepth === 0) {
157
- if (!notificationPending) {
158
- notificationPending = true;
159
- queueMicrotask(() => {
160
- notificationPending = false;
161
- if (batchDepth === 0) {
162
- notifyChange();
163
- } else {}
164
- });
165
- }
166
- } else {
167
- pendingChange = pendingChange || { paths: [], newValues: {} };
168
- }
169
- }
170
- const proxyCache = new WeakMap;
171
- function createProxy(target, basePath) {
172
- const cached = proxyCache.get(target);
173
- if (cached)
174
- return cached;
175
- const proxy = new Proxy(target, {
176
- get(obj, prop) {
177
- if (prop === IS_PROXY)
178
- return true;
179
- if (prop === RAW_TARGET)
180
- return obj;
181
- if (prop === "__beginBatch") {
182
- return () => {
183
- batchDepth++;
184
- };
185
- }
186
- if (prop === "__endBatch") {
187
- return () => {
188
- batchDepth--;
189
- if (batchDepth === 0) {
190
- notifyChange();
191
- }
192
- };
193
- }
194
- if (prop === "__getSnapshot") {
195
- return () => deepClone(obj);
196
- }
197
- const value = obj[prop];
198
- if (value && typeof value === "object") {
199
- if (value[IS_PROXY]) {
200
- return value;
201
- }
202
- if (value instanceof Date || value instanceof RegExp || value instanceof Map || value instanceof Set || value instanceof WeakMap || value instanceof WeakSet) {
203
- return value;
204
- }
205
- const cachedNested = proxyCache.get(value);
206
- if (cachedNested) {
207
- return cachedNested;
208
- }
209
- const nestedProxy = createProxy(value, basePath ? `${basePath}.${String(prop)}` : String(prop));
210
- return nestedProxy;
211
- }
212
- return value;
213
- },
214
- set(obj, prop, value) {
215
- const oldValue = obj[prop];
216
- if (value && typeof value === "object" && value[IS_PROXY]) {
217
- value = value[RAW_TARGET];
218
- }
219
- obj[prop] = value;
220
- if (oldValue !== value) {
221
- scheduleBatch();
222
- }
223
- return true;
224
- },
225
- deleteProperty(obj, prop) {
226
- const existed = Object.prototype.hasOwnProperty.call(obj, prop);
227
- const result = delete obj[prop];
228
- if (existed) {
229
- scheduleBatch();
230
- }
231
- return result;
232
- }
233
- });
234
- proxyCache.set(target, proxy);
235
- return proxy;
236
- }
237
- const state = createProxy(initialState, pathPrefix);
238
- return state;
239
- }
240
- function batchStateUpdates(state, fn) {
241
- const s = state;
242
- if (s.__beginBatch && s.__endBatch) {
243
- s.__beginBatch();
244
- try {
245
- fn();
246
- } finally {
247
- s.__endBatch();
248
- }
249
- } else {
250
- fn();
251
- }
252
- }
253
- function getStateSnapshot(state) {
254
- const s = state;
255
- if (s.__getSnapshot) {
256
- return s.__getSnapshot();
257
- }
258
- return deepClone(state);
259
- }
260
- function isStateProxy(value) {
261
- return value !== null && typeof value === "object" && value[IS_PROXY] === true;
262
- }
263
- function unwrapProxy(value) {
264
- if (value !== null && typeof value === "object" && value[IS_PROXY]) {
265
- return value[RAW_TARGET];
266
- }
267
- return value;
268
- }
269
- var IS_PROXY, RAW_TARGET;
270
- var init_state = __esm(() => {
271
- IS_PROXY = Symbol.for("hypen.isProxy");
272
- RAW_TARGET = Symbol.for("hypen.rawTarget");
273
- });
274
-
275
- // src/logger.ts
276
- function isProduction() {
277
- if (typeof process !== "undefined" && process.env) {
278
- return false;
279
- }
280
- return false;
281
- }
282
- function setLogLevel(level) {
283
- config.level = level;
284
- }
285
- function getLogLevel() {
286
- return config.level;
287
- }
288
- function configureLogger(options) {
289
- config = { ...config, ...options };
290
- }
291
- function enableLogging() {
292
- config.level = "debug";
293
- }
294
- function disableLogging() {
295
- config.level = "none";
296
- }
297
- function setDebugMode(enabled) {
298
- config.level = enabled ? "debug" : "error";
299
- }
300
- function isDebugMode() {
301
- return config.level === "debug";
302
- }
303
- function shouldLog(level) {
304
- return LOG_LEVEL_ORDER[level] >= LOG_LEVEL_ORDER[config.level];
305
- }
306
- function formatTag(tag, level) {
307
- const timestamp = config.timestamps ? `${new Date().toISOString()} ` : "";
308
- if (config.colors && level !== "none") {
309
- const color = LOG_LEVEL_COLORS[level];
310
- return `${timestamp}${color}[${tag}]${RESET_COLOR}`;
311
- }
312
- return `${timestamp}[${tag}]`;
313
- }
314
-
315
- class Logger {
316
- tag;
317
- constructor(tag) {
318
- this.tag = tag;
319
- }
320
- debug(...args) {
321
- if (!shouldLog("debug"))
322
- return;
323
- if (config.handler) {
324
- config.handler.debug(this.tag, ...args);
325
- } else {
326
- console.log(formatTag(this.tag, "debug"), ...args);
327
- }
328
- }
329
- info(...args) {
330
- if (!shouldLog("info"))
331
- return;
332
- if (config.handler) {
333
- config.handler.info(this.tag, ...args);
334
- } else {
335
- console.info(formatTag(this.tag, "info"), ...args);
336
- }
337
- }
338
- warn(...args) {
339
- if (!shouldLog("warn"))
340
- return;
341
- if (config.handler) {
342
- config.handler.warn(this.tag, ...args);
343
- } else {
344
- console.warn(formatTag(this.tag, "warn"), ...args);
345
- }
346
- }
347
- error(...args) {
348
- if (!shouldLog("error"))
349
- return;
350
- if (config.handler) {
351
- config.handler.error(this.tag, ...args);
352
- } else {
353
- console.error(formatTag(this.tag, "error"), ...args);
354
- }
355
- }
356
- time(label, fn) {
357
- if (!shouldLog("debug")) {
358
- return fn();
359
- }
360
- const start = performance.now();
361
- try {
362
- return fn();
363
- } finally {
364
- const duration = performance.now() - start;
365
- this.debug(`${label}: ${duration.toFixed(2)}ms`);
366
- }
367
- }
368
- async timeAsync(label, fn) {
369
- if (!shouldLog("debug")) {
370
- return fn();
371
- }
372
- const start = performance.now();
373
- try {
374
- return await fn();
375
- } finally {
376
- const duration = performance.now() - start;
377
- this.debug(`${label}: ${duration.toFixed(2)}ms`);
378
- }
379
- }
380
- child(subTag) {
381
- return new Logger(`${this.tag}:${subTag}`);
382
- }
383
- debugIf(condition, ...args) {
384
- if (condition)
385
- this.debug(...args);
386
- }
387
- warnIf(condition, ...args) {
388
- if (condition)
389
- this.warn(...args);
390
- }
391
- errorIf(condition, ...args) {
392
- if (condition)
393
- this.error(...args);
394
- }
395
- loggedOnce = new Set;
396
- warnOnce(key, ...args) {
397
- if (this.loggedOnce.has(key))
398
- return;
399
- this.loggedOnce.add(key);
400
- this.warn(...args);
401
- }
402
- debugOnce(key, ...args) {
403
- if (this.loggedOnce.has(key))
404
- return;
405
- this.loggedOnce.add(key);
406
- this.debug(...args);
407
- }
408
- }
409
- function createLogger(tag) {
410
- return new Logger(tag);
411
- }
412
- var LOG_LEVEL_ORDER, LOG_LEVEL_COLORS, RESET_COLOR = "\x1B[0m", config, logger, log, frameworkLoggers;
413
- var init_logger = __esm(() => {
414
- LOG_LEVEL_ORDER = {
415
- debug: 0,
416
- info: 1,
417
- warn: 2,
418
- error: 3,
419
- none: 4
420
- };
421
- LOG_LEVEL_COLORS = {
422
- debug: "\x1B[36m",
423
- info: "\x1B[32m",
424
- warn: "\x1B[33m",
425
- error: "\x1B[31m"
426
- };
427
- config = {
428
- level: isProduction() ? "error" : "info",
429
- colors: true,
430
- timestamps: false
431
- };
432
- logger = createLogger("Hypen");
433
- log = {
434
- debug: (tag, ...args) => {
435
- if (!shouldLog("debug"))
436
- return;
437
- console.log(formatTag(tag, "debug"), ...args);
438
- },
439
- info: (tag, ...args) => {
440
- if (!shouldLog("info"))
441
- return;
442
- console.info(formatTag(tag, "info"), ...args);
443
- },
444
- warn: (tag, ...args) => {
445
- if (!shouldLog("warn"))
446
- return;
447
- console.warn(formatTag(tag, "warn"), ...args);
448
- },
449
- error: (tag, ...args) => {
450
- if (!shouldLog("error"))
451
- return;
452
- console.error(formatTag(tag, "error"), ...args);
453
- }
454
- };
455
- frameworkLoggers = {
456
- hypen: createLogger("Hypen"),
457
- engine: createLogger("Engine"),
458
- router: createLogger("Router"),
459
- state: createLogger("State"),
460
- events: createLogger("Events"),
461
- remote: createLogger("Remote"),
462
- renderer: createLogger("Renderer"),
463
- module: createLogger("Module"),
464
- lifecycle: createLogger("Lifecycle"),
465
- loader: createLogger("Loader"),
466
- context: createLogger("Context"),
467
- discovery: createLogger("Discovery"),
468
- plugin: createLogger("Plugin"),
469
- canvas: createLogger("Canvas"),
470
- debug: createLogger("Debug")
471
- };
472
- });
473
-
474
- // src/result.ts
475
- function Ok(value) {
476
- return { ok: true, value };
477
- }
478
- function Err(error) {
479
- return { ok: false, error };
480
- }
481
- function classifyEngineError(err) {
482
- const message = err instanceof Error ? err.message : String(err);
483
- if (message.startsWith("Parse error:")) {
484
- return new ParseError(message);
485
- }
486
- if (message.startsWith("Invalid state:") || message.startsWith("Invalid state patch:")) {
487
- return new StateError(message);
488
- }
489
- if (message.startsWith("Parent node not found:")) {
490
- return new RenderError(message);
491
- }
492
- return new RenderError(message);
493
- }
494
- var HypenError, ActionError, ConnectionError, StateError, ParseError, RenderError;
495
- var init_result = __esm(() => {
496
- HypenError = class HypenError extends Error {
497
- code;
498
- context;
499
- cause;
500
- constructor(code, message, options) {
501
- super(message);
502
- this.name = "HypenError";
503
- this.code = code;
504
- this.context = options?.context;
505
- this.cause = options?.cause;
506
- Object.setPrototypeOf(this, new.target.prototype);
507
- }
508
- };
509
- ActionError = class ActionError extends HypenError {
510
- actionName;
511
- constructor(actionName, cause) {
512
- super("ACTION_ERROR", `Action handler "${actionName}" failed: ${cause instanceof Error ? cause.message : String(cause)}`, {
513
- context: { actionName },
514
- cause: cause instanceof Error ? cause : undefined
515
- });
516
- this.name = "ActionError";
517
- this.actionName = actionName;
518
- }
519
- };
520
- ConnectionError = class ConnectionError extends HypenError {
521
- url;
522
- attempt;
523
- constructor(url, cause, attempt) {
524
- super("CONNECTION_ERROR", `Connection to "${url}" failed${attempt ? ` (attempt ${attempt})` : ""}: ${cause instanceof Error ? cause.message : String(cause)}`, {
525
- context: { url, attempt },
526
- cause: cause instanceof Error ? cause : undefined
527
- });
528
- this.name = "ConnectionError";
529
- this.url = url;
530
- this.attempt = attempt;
531
- }
532
- };
533
- StateError = class StateError extends HypenError {
534
- path;
535
- constructor(message, path, cause) {
536
- super("STATE_ERROR", message, {
537
- context: { path },
538
- cause: cause instanceof Error ? cause : undefined
539
- });
540
- this.name = "StateError";
541
- this.path = path;
542
- }
543
- };
544
- ParseError = class ParseError extends HypenError {
545
- source;
546
- constructor(message, source, cause) {
547
- super("PARSE_ERROR", message, {
548
- context: { source },
549
- cause: cause instanceof Error ? cause : undefined
550
- });
551
- this.name = "ParseError";
552
- this.source = source;
553
- }
554
- };
555
- RenderError = class RenderError extends HypenError {
556
- constructor(message, cause) {
557
- super("RENDER_ERROR", message, {
558
- cause: cause instanceof Error ? cause : undefined
559
- });
560
- this.name = "RenderError";
561
- }
562
- };
563
- });
564
-
565
- // src/datasource.ts
566
- class DataSourceManager {
567
- plugins = new Map;
568
- configs = new Map;
569
- state = new Map;
570
- engine;
571
- constructor(engine) {
572
- this.engine = engine;
573
- }
574
- async use(plugin, config2) {
575
- const { name } = plugin;
576
- this.state.set(name, {});
577
- this.plugins.set(name, plugin);
578
- this.configs.set(name, config2);
579
- await plugin.connect(config2, (change) => {
580
- const current = this.state.get(name) ?? {};
581
- for (const path of change.paths) {
582
- if (path in change.values) {
583
- current[path] = change.values[path];
584
- }
585
- }
586
- this.state.set(name, current);
587
- this.engine.setContext(name, current);
588
- });
589
- }
590
- get(name) {
591
- return this.plugins.get(name);
592
- }
593
- has(name) {
594
- return this.plugins.has(name);
595
- }
596
- getNames() {
597
- return Array.from(this.plugins.keys());
598
- }
599
- getStatus(name) {
600
- return this.plugins.get(name)?.status;
601
- }
602
- async remove(name) {
603
- const plugin = this.plugins.get(name);
604
- if (plugin) {
605
- await plugin.disconnect();
606
- this.plugins.delete(name);
607
- this.configs.delete(name);
608
- this.state.delete(name);
609
- this.engine.removeContext(name);
610
- }
611
- }
612
- async disconnectAll() {
613
- const names = Array.from(this.plugins.keys());
614
- await Promise.all(names.map((name) => this.remove(name)));
615
- }
616
- }
617
-
618
- // src/app.ts
619
- var exports_app = {};
620
- __export(exports_app, {
621
- app: () => app,
622
- HypenModuleInstance: () => HypenModuleInstance,
623
- HypenAppBuilder: () => HypenAppBuilder,
624
- HypenApp: () => HypenApp
625
- });
626
-
627
- class HypenAppBuilder {
628
- initialState;
629
- options;
630
- createdHandler;
631
- actionHandlers = new Map;
632
- destroyedHandler;
633
- disconnectHandler;
634
- reconnectHandler;
635
- expireHandler;
636
- errorHandler;
637
- template;
638
- _registry;
639
- dataSourceEntries = [];
640
- constructor(initialState, options, registry) {
641
- this.initialState = initialState;
642
- this.options = options || {};
643
- this._registry = registry;
644
- }
645
- onCreated(fn) {
646
- this.createdHandler = fn;
647
- return this;
648
- }
649
- onAction(name, fn) {
650
- this.actionHandlers.set(name, fn);
651
- return this;
652
- }
653
- onDestroyed(fn) {
654
- this.destroyedHandler = fn;
655
- return this;
656
- }
657
- onDisconnect(fn) {
658
- this.disconnectHandler = fn;
659
- return this;
660
- }
661
- onReconnect(fn) {
662
- this.reconnectHandler = fn;
663
- return this;
664
- }
665
- onExpire(fn) {
666
- this.expireHandler = fn;
667
- return this;
668
- }
669
- onError(fn) {
670
- this.errorHandler = fn;
671
- return this;
672
- }
673
- useDataSource(plugin, config2) {
674
- this.dataSourceEntries.push({ plugin, config: config2 });
675
- return this;
676
- }
677
- ui(template) {
678
- this.template = template;
679
- return this.build();
680
- }
681
- uiFile(path) {
682
- const fs = (() => ({}));
683
- this.template = fs.readFileSync(path, "utf-8").trim();
684
- return this.build();
685
- }
686
- build() {
687
- const stateKeys = this.initialState !== null && typeof this.initialState === "object" ? Object.keys(this.initialState) : [];
688
- const definition = {
689
- name: this.options.name,
690
- actions: Array.from(this.actionHandlers.keys()),
691
- stateKeys,
692
- persist: this.options.persist,
693
- version: this.options.version,
694
- initialState: this.initialState,
695
- template: this.template,
696
- dataSources: this.dataSourceEntries.length > 0 ? this.dataSourceEntries : undefined,
697
- handlers: {
698
- onCreated: this.createdHandler,
699
- onAction: this.actionHandlers,
700
- onDestroyed: this.destroyedHandler,
701
- onDisconnect: this.disconnectHandler,
702
- onReconnect: this.reconnectHandler,
703
- onExpire: this.expireHandler,
704
- onError: this.errorHandler
705
- }
706
- };
707
- if (this.options.name && this._registry) {
708
- this._registry.set(this.options.name, definition);
709
- }
710
- return definition;
711
- }
712
- }
713
-
714
- class HypenApp {
715
- _registry = new Map;
716
- defineState(initial, options) {
717
- return new HypenAppBuilder(initial, options, this._registry);
718
- }
719
- module(name) {
720
- const registry = this._registry;
721
- return {
722
- defineState: (initial, options) => {
723
- return new HypenAppBuilder(initial, { ...options, name }, registry);
724
- }
725
- };
726
- }
727
- get(name) {
728
- return this._registry.get(name);
729
- }
730
- has(name) {
731
- return this._registry.has(name);
732
- }
733
- get components() {
734
- return this._registry;
735
- }
736
- getNames() {
737
- return Array.from(this._registry.keys());
738
- }
739
- get size() {
740
- return this._registry.size;
741
- }
742
- unregister(name) {
743
- this._registry.delete(name);
744
- }
745
- clear() {
746
- this._registry.clear();
747
- }
748
- }
749
-
750
- class HypenModuleInstance {
751
- engine;
752
- definition;
753
- state;
754
- isDestroyed = false;
755
- router;
756
- globalContext;
757
- stateChangeCallbacks = [];
758
- dataSourceManager;
759
- dataSourceAccessor = {};
760
- constructor(engine, definition, router, globalContext) {
761
- this.engine = engine;
762
- this.definition = definition;
763
- this.router = router ?? null;
764
- this.globalContext = globalContext;
765
- const statePrefix = (definition.name || "").toLowerCase();
766
- this.state = createObservableState(definition.initialState, {
767
- onChange: (change) => {
768
- this.engine.notifyStateChange(change.paths, change.newValues);
769
- this.stateChangeCallbacks.forEach((cb) => cb());
770
- },
771
- pathPrefix: statePrefix || undefined
772
- });
773
- const snapshot = getStateSnapshot(this.state);
774
- const prefixedState = statePrefix ? { [statePrefix]: snapshot } : snapshot;
775
- this.engine.setModule(definition.name || "AnonymousModule", definition.actions, definition.stateKeys, prefixedState);
776
- for (const [actionName, handler] of definition.handlers.onAction) {
777
- log2.debug(`Registering action handler: ${actionName} for module ${definition.name}`);
778
- this.engine.onAction(actionName, async (action) => {
779
- log2.debug(`Action handler fired: ${actionName}`, action);
780
- const actionCtx = {
781
- name: action.name,
782
- payload: action.payload,
783
- sender: action.sender
784
- };
785
- const context = this.globalContext ? this.createGlobalContextAPI() : undefined;
786
- const result = await this.executeAction(actionName, handler, {
787
- action: actionCtx,
788
- state: this.state,
789
- context,
790
- dataSources: this.dataSourceAccessor
791
- });
792
- if (!result.ok) {
793
- const shouldRethrow = await this.handleError(result.error, { actionName });
794
- if (shouldRethrow) {
795
- throw result.error;
796
- }
797
- } else {
798
- log2.debug(`Action handler completed: ${actionName}`);
799
- }
800
- });
801
- }
802
- this.engine.onAction("__hypen_bind", (action) => {
803
- const payload = action.payload;
804
- if (!payload?.path)
805
- return;
806
- const segments = payload.path.split(".");
807
- let target = this.state;
808
- for (let i = 0;i < segments.length - 1; i++) {
809
- const seg = segments[i];
810
- target = target?.[seg];
811
- if (target == null)
812
- return;
813
- }
814
- const lastSeg = segments[segments.length - 1];
815
- target[lastSeg] = payload.value;
816
- });
817
- this.callCreatedHandler();
818
- }
819
- createGlobalContextAPI() {
820
- if (!this.globalContext) {
821
- throw new Error("Global context not available");
822
- }
823
- const ctx = this.globalContext;
824
- const api = {
825
- getModule: (id) => ctx.getModule(id),
826
- hasModule: (id) => ctx.hasModule(id),
827
- getModuleIds: () => ctx.getModuleIds(),
828
- getGlobalState: () => ctx.getGlobalState(),
829
- emit: (event, payload) => ctx.emit(event, payload),
830
- on: (event, handler) => ctx.on(event, handler),
831
- router: this.router
832
- };
833
- const ctxRecord = ctx;
834
- if (ctxRecord.__hypenEngine) {
835
- api.__hypenEngine = ctxRecord.__hypenEngine;
836
- }
837
- return api;
838
- }
839
- async executeAction(actionName, handler, ctx) {
840
- try {
841
- const result = handler(ctx);
842
- await result;
843
- return Ok(undefined);
844
- } catch (e) {
845
- return Err(new ActionError(actionName, e));
846
- }
847
- }
848
- async handleError(error, context) {
849
- const errorCtx = {
850
- error,
851
- state: this.state,
852
- actionName: context.actionName,
853
- lifecycle: context.lifecycle
854
- };
855
- if (this.definition.handlers.onError) {
856
- try {
857
- const result = await this.definition.handlers.onError(errorCtx);
858
- if (result && typeof result === "object") {
859
- if ("handled" in result && result.handled) {
860
- return false;
861
- }
862
- if ("rethrow" in result && result.rethrow) {
863
- return true;
864
- }
865
- }
866
- } catch (handlerError) {
867
- log2.error("Error in onError handler:", handlerError);
868
- }
869
- }
870
- if (this.globalContext) {
871
- const eventContext = context.actionName ? `action:${context.actionName}` : context.lifecycle ? `lifecycle:${context.lifecycle}` : "unknown";
872
- this.globalContext.emit("error", {
873
- message: error.message,
874
- error,
875
- context: eventContext
876
- });
877
- }
878
- log2.error(`${context.actionName ? `Action "${context.actionName}"` : `Lifecycle "${context.lifecycle}"`} error:`, error);
879
- return false;
880
- }
881
- async callCreatedHandler() {
882
- if (this.definition.dataSources?.length) {
883
- const dsEngine = this.engine;
884
- this.dataSourceManager = new DataSourceManager(dsEngine);
885
- for (const { plugin, config: config2 } of this.definition.dataSources) {
886
- try {
887
- await this.dataSourceManager.use(plugin, config2);
888
- this.dataSourceAccessor[plugin.name] = new Proxy(plugin, {
889
- get(target, prop) {
890
- if (typeof prop === "string" && !(prop in target)) {
891
- return (...args) => target.call(prop, ...args);
892
- }
893
- return target[prop];
894
- }
895
- });
896
- } catch (e) {
897
- log2.error(`Failed to connect data source "${plugin.name}":`, e);
898
- }
899
- }
900
- }
901
- if (this.definition.handlers.onCreated) {
902
- const context = this.globalContext ? this.createGlobalContextAPI() : undefined;
903
- try {
904
- await this.definition.handlers.onCreated(this.state, context);
905
- } catch (e) {
906
- const error = e instanceof HypenError ? e : new ActionError("onCreated", e);
907
- const shouldRethrow = await this.handleError(error, { lifecycle: "created" });
908
- if (shouldRethrow) {
909
- throw error;
910
- }
911
- }
912
- }
913
- }
914
- onStateChange(callback) {
915
- this.stateChangeCallbacks.push(callback);
916
- }
917
- async destroy() {
918
- if (this.isDestroyed)
919
- return;
920
- if (this.dataSourceManager) {
921
- try {
922
- await this.dataSourceManager.disconnectAll();
923
- } catch (e) {
924
- log2.error("Error disconnecting data sources:", e);
925
- }
926
- this.dataSourceManager = undefined;
927
- this.dataSourceAccessor = {};
928
- }
929
- if (this.definition.handlers.onDestroyed) {
930
- try {
931
- await this.definition.handlers.onDestroyed(this.state);
932
- } catch (e) {
933
- const error = e instanceof HypenError ? e : new ActionError("onDestroyed", e);
934
- const shouldRethrow = await this.handleError(error, { lifecycle: "destroyed" });
935
- if (shouldRethrow) {
936
- throw error;
937
- }
938
- }
939
- }
940
- this.isDestroyed = true;
941
- }
942
- getState() {
943
- return getStateSnapshot(this.state);
944
- }
945
- getLiveState() {
946
- return this.state;
947
- }
948
- updateState(patch) {
949
- Object.assign(this.state, patch);
950
- }
951
- }
952
- var log2, app;
953
- var init_app = __esm(() => {
954
- init_result();
955
- init_state();
956
- init_logger();
957
- log2 = createLogger("ModuleInstance");
958
- app = new HypenApp;
959
- });
960
-
961
- // node:path
962
- var exports_path = {};
963
- __export(exports_path, {
964
- sep: () => sep,
965
- resolve: () => resolve,
966
- relative: () => relative,
967
- posix: () => posix,
968
- parse: () => parse,
969
- normalize: () => normalize,
970
- join: () => join,
971
- isAbsolute: () => isAbsolute,
972
- format: () => format,
973
- extname: () => extname,
974
- dirname: () => dirname,
975
- delimiter: () => delimiter,
976
- default: () => path_default,
977
- basename: () => basename,
978
- _makeLong: () => _makeLong
979
- });
980
- function assertPath(path) {
981
- if (typeof path !== "string")
982
- throw TypeError("Path must be a string. Received " + JSON.stringify(path));
983
- }
984
- function normalizeStringPosix(path, allowAboveRoot) {
985
- var res = "", lastSegmentLength = 0, lastSlash = -1, dots = 0, code;
986
- for (var i = 0;i <= path.length; ++i) {
987
- if (i < path.length)
988
- code = path.charCodeAt(i);
989
- else if (code === 47)
990
- break;
991
- else
992
- code = 47;
993
- if (code === 47) {
994
- if (lastSlash === i - 1 || dots === 1)
995
- ;
996
- else if (lastSlash !== i - 1 && dots === 2) {
997
- if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== 46 || res.charCodeAt(res.length - 2) !== 46) {
998
- if (res.length > 2) {
999
- var lastSlashIndex = res.lastIndexOf("/");
1000
- if (lastSlashIndex !== res.length - 1) {
1001
- if (lastSlashIndex === -1)
1002
- res = "", lastSegmentLength = 0;
1003
- else
1004
- res = res.slice(0, lastSlashIndex), lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
1005
- lastSlash = i, dots = 0;
1006
- continue;
1007
- }
1008
- } else if (res.length === 2 || res.length === 1) {
1009
- res = "", lastSegmentLength = 0, lastSlash = i, dots = 0;
1010
- continue;
1011
- }
1012
- }
1013
- if (allowAboveRoot) {
1014
- if (res.length > 0)
1015
- res += "/..";
1016
- else
1017
- res = "..";
1018
- lastSegmentLength = 2;
1019
- }
1020
- } else {
1021
- if (res.length > 0)
1022
- res += "/" + path.slice(lastSlash + 1, i);
1023
- else
1024
- res = path.slice(lastSlash + 1, i);
1025
- lastSegmentLength = i - lastSlash - 1;
1026
- }
1027
- lastSlash = i, dots = 0;
1028
- } else if (code === 46 && dots !== -1)
1029
- ++dots;
1030
- else
1031
- dots = -1;
1032
- }
1033
- return res;
1034
- }
1035
- function _format(sep, pathObject) {
1036
- var dir = pathObject.dir || pathObject.root, base = pathObject.base || (pathObject.name || "") + (pathObject.ext || "");
1037
- if (!dir)
1038
- return base;
1039
- if (dir === pathObject.root)
1040
- return dir + base;
1041
- return dir + sep + base;
1042
- }
1043
- function resolve() {
1044
- var resolvedPath = "", resolvedAbsolute = false, cwd;
1045
- for (var i = arguments.length - 1;i >= -1 && !resolvedAbsolute; i--) {
1046
- var path;
1047
- if (i >= 0)
1048
- path = arguments[i];
1049
- else {
1050
- if (cwd === undefined)
1051
- cwd = process.cwd();
1052
- path = cwd;
1053
- }
1054
- if (assertPath(path), path.length === 0)
1055
- continue;
1056
- resolvedPath = path + "/" + resolvedPath, resolvedAbsolute = path.charCodeAt(0) === 47;
1057
- }
1058
- if (resolvedPath = normalizeStringPosix(resolvedPath, !resolvedAbsolute), resolvedAbsolute)
1059
- if (resolvedPath.length > 0)
1060
- return "/" + resolvedPath;
1061
- else
1062
- return "/";
1063
- else if (resolvedPath.length > 0)
1064
- return resolvedPath;
1065
- else
1066
- return ".";
1067
- }
1068
- function normalize(path) {
1069
- if (assertPath(path), path.length === 0)
1070
- return ".";
1071
- var isAbsolute = path.charCodeAt(0) === 47, trailingSeparator = path.charCodeAt(path.length - 1) === 47;
1072
- if (path = normalizeStringPosix(path, !isAbsolute), path.length === 0 && !isAbsolute)
1073
- path = ".";
1074
- if (path.length > 0 && trailingSeparator)
1075
- path += "/";
1076
- if (isAbsolute)
1077
- return "/" + path;
1078
- return path;
1079
- }
1080
- function isAbsolute(path) {
1081
- return assertPath(path), path.length > 0 && path.charCodeAt(0) === 47;
1082
- }
1083
- function join() {
1084
- if (arguments.length === 0)
1085
- return ".";
1086
- var joined;
1087
- for (var i = 0;i < arguments.length; ++i) {
1088
- var arg = arguments[i];
1089
- if (assertPath(arg), arg.length > 0)
1090
- if (joined === undefined)
1091
- joined = arg;
1092
- else
1093
- joined += "/" + arg;
1094
- }
1095
- if (joined === undefined)
1096
- return ".";
1097
- return normalize(joined);
1098
- }
1099
- function relative(from, to) {
1100
- if (assertPath(from), assertPath(to), from === to)
1101
- return "";
1102
- if (from = resolve(from), to = resolve(to), from === to)
1103
- return "";
1104
- var fromStart = 1;
1105
- for (;fromStart < from.length; ++fromStart)
1106
- if (from.charCodeAt(fromStart) !== 47)
1107
- break;
1108
- var fromEnd = from.length, fromLen = fromEnd - fromStart, toStart = 1;
1109
- for (;toStart < to.length; ++toStart)
1110
- if (to.charCodeAt(toStart) !== 47)
1111
- break;
1112
- var toEnd = to.length, toLen = toEnd - toStart, length = fromLen < toLen ? fromLen : toLen, lastCommonSep = -1, i = 0;
1113
- for (;i <= length; ++i) {
1114
- if (i === length) {
1115
- if (toLen > length) {
1116
- if (to.charCodeAt(toStart + i) === 47)
1117
- return to.slice(toStart + i + 1);
1118
- else if (i === 0)
1119
- return to.slice(toStart + i);
1120
- } else if (fromLen > length) {
1121
- if (from.charCodeAt(fromStart + i) === 47)
1122
- lastCommonSep = i;
1123
- else if (i === 0)
1124
- lastCommonSep = 0;
1125
- }
1126
- break;
1127
- }
1128
- var fromCode = from.charCodeAt(fromStart + i), toCode = to.charCodeAt(toStart + i);
1129
- if (fromCode !== toCode)
1130
- break;
1131
- else if (fromCode === 47)
1132
- lastCommonSep = i;
1133
- }
1134
- var out = "";
1135
- for (i = fromStart + lastCommonSep + 1;i <= fromEnd; ++i)
1136
- if (i === fromEnd || from.charCodeAt(i) === 47)
1137
- if (out.length === 0)
1138
- out += "..";
1139
- else
1140
- out += "/..";
1141
- if (out.length > 0)
1142
- return out + to.slice(toStart + lastCommonSep);
1143
- else {
1144
- if (toStart += lastCommonSep, to.charCodeAt(toStart) === 47)
1145
- ++toStart;
1146
- return to.slice(toStart);
1147
- }
1148
- }
1149
- function _makeLong(path) {
1150
- return path;
1151
- }
1152
- function dirname(path) {
1153
- if (assertPath(path), path.length === 0)
1154
- return ".";
1155
- var code = path.charCodeAt(0), hasRoot = code === 47, end = -1, matchedSlash = true;
1156
- for (var i = path.length - 1;i >= 1; --i)
1157
- if (code = path.charCodeAt(i), code === 47) {
1158
- if (!matchedSlash) {
1159
- end = i;
1160
- break;
1161
- }
1162
- } else
1163
- matchedSlash = false;
1164
- if (end === -1)
1165
- return hasRoot ? "/" : ".";
1166
- if (hasRoot && end === 1)
1167
- return "//";
1168
- return path.slice(0, end);
1169
- }
1170
- function basename(path, ext) {
1171
- if (ext !== undefined && typeof ext !== "string")
1172
- throw TypeError('"ext" argument must be a string');
1173
- assertPath(path);
1174
- var start = 0, end = -1, matchedSlash = true, i;
1175
- if (ext !== undefined && ext.length > 0 && ext.length <= path.length) {
1176
- if (ext.length === path.length && ext === path)
1177
- return "";
1178
- var extIdx = ext.length - 1, firstNonSlashEnd = -1;
1179
- for (i = path.length - 1;i >= 0; --i) {
1180
- var code = path.charCodeAt(i);
1181
- if (code === 47) {
1182
- if (!matchedSlash) {
1183
- start = i + 1;
1184
- break;
1185
- }
1186
- } else {
1187
- if (firstNonSlashEnd === -1)
1188
- matchedSlash = false, firstNonSlashEnd = i + 1;
1189
- if (extIdx >= 0)
1190
- if (code === ext.charCodeAt(extIdx)) {
1191
- if (--extIdx === -1)
1192
- end = i;
1193
- } else
1194
- extIdx = -1, end = firstNonSlashEnd;
1195
- }
1196
- }
1197
- if (start === end)
1198
- end = firstNonSlashEnd;
1199
- else if (end === -1)
1200
- end = path.length;
1201
- return path.slice(start, end);
1202
- } else {
1203
- for (i = path.length - 1;i >= 0; --i)
1204
- if (path.charCodeAt(i) === 47) {
1205
- if (!matchedSlash) {
1206
- start = i + 1;
1207
- break;
1208
- }
1209
- } else if (end === -1)
1210
- matchedSlash = false, end = i + 1;
1211
- if (end === -1)
1212
- return "";
1213
- return path.slice(start, end);
1214
- }
1215
- }
1216
- function extname(path) {
1217
- assertPath(path);
1218
- var startDot = -1, startPart = 0, end = -1, matchedSlash = true, preDotState = 0;
1219
- for (var i = path.length - 1;i >= 0; --i) {
1220
- var code = path.charCodeAt(i);
1221
- if (code === 47) {
1222
- if (!matchedSlash) {
1223
- startPart = i + 1;
1224
- break;
1225
- }
1226
- continue;
1227
- }
1228
- if (end === -1)
1229
- matchedSlash = false, end = i + 1;
1230
- if (code === 46) {
1231
- if (startDot === -1)
1232
- startDot = i;
1233
- else if (preDotState !== 1)
1234
- preDotState = 1;
1235
- } else if (startDot !== -1)
1236
- preDotState = -1;
1237
- }
1238
- if (startDot === -1 || end === -1 || preDotState === 0 || preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)
1239
- return "";
1240
- return path.slice(startDot, end);
1241
- }
1242
- function format(pathObject) {
1243
- if (pathObject === null || typeof pathObject !== "object")
1244
- throw TypeError('The "pathObject" argument must be of type Object. Received type ' + typeof pathObject);
1245
- return _format("/", pathObject);
1246
- }
1247
- function parse(path) {
1248
- assertPath(path);
1249
- var ret = { root: "", dir: "", base: "", ext: "", name: "" };
1250
- if (path.length === 0)
1251
- return ret;
1252
- var code = path.charCodeAt(0), isAbsolute2 = code === 47, start;
1253
- if (isAbsolute2)
1254
- ret.root = "/", start = 1;
1255
- else
1256
- start = 0;
1257
- var startDot = -1, startPart = 0, end = -1, matchedSlash = true, i = path.length - 1, preDotState = 0;
1258
- for (;i >= start; --i) {
1259
- if (code = path.charCodeAt(i), code === 47) {
1260
- if (!matchedSlash) {
1261
- startPart = i + 1;
1262
- break;
1263
- }
1264
- continue;
1265
- }
1266
- if (end === -1)
1267
- matchedSlash = false, end = i + 1;
1268
- if (code === 46) {
1269
- if (startDot === -1)
1270
- startDot = i;
1271
- else if (preDotState !== 1)
1272
- preDotState = 1;
1273
- } else if (startDot !== -1)
1274
- preDotState = -1;
1275
- }
1276
- if (startDot === -1 || end === -1 || preDotState === 0 || preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
1277
- if (end !== -1)
1278
- if (startPart === 0 && isAbsolute2)
1279
- ret.base = ret.name = path.slice(1, end);
1280
- else
1281
- ret.base = ret.name = path.slice(startPart, end);
1282
- } else {
1283
- if (startPart === 0 && isAbsolute2)
1284
- ret.name = path.slice(1, startDot), ret.base = path.slice(1, end);
1285
- else
1286
- ret.name = path.slice(startPart, startDot), ret.base = path.slice(startPart, end);
1287
- ret.ext = path.slice(startDot, end);
1288
- }
1289
- if (startPart > 0)
1290
- ret.dir = path.slice(0, startPart - 1);
1291
- else if (isAbsolute2)
1292
- ret.dir = "/";
1293
- return ret;
1294
- }
1295
- var sep = "/", delimiter = ":", posix, path_default;
1296
- var init_path = __esm(() => {
1297
- posix = ((p) => (p.posix = p, p))({ resolve, normalize, isAbsolute, join, relative, _makeLong, dirname, basename, extname, format, parse, sep, delimiter, win32: null, posix: null });
1298
- path_default = posix;
1299
- });
1300
-
1301
- // src/engine.ts
1302
- init_logger();
1303
- init_result();
1304
- import { WasmEngine } from "../wasm-node/hypen_engine.js";
1305
- var log3 = frameworkLoggers.engine;
1306
- function unwrapForWasm(value) {
1307
- if (value === null || typeof value !== "object") {
1308
- return value;
1309
- }
1310
- if (typeof value.__getSnapshot === "function") {
1311
- return value.__getSnapshot();
1312
- }
1313
- try {
1314
- return structuredClone(value);
1315
- } catch {
1316
- return JSON.parse(JSON.stringify(value));
1317
- }
1318
- }
1319
-
1320
- class Engine {
1321
- wasmEngine = null;
1322
- initialized = false;
1323
- async init() {
1324
- if (this.initialized)
1325
- return;
1326
- this.wasmEngine = new WasmEngine;
1327
- this.initialized = true;
1328
- }
1329
- ensureInitialized() {
1330
- if (!this.wasmEngine) {
1331
- throw new Error("Engine not initialized. Call init() first.");
1332
- }
1333
- return this.wasmEngine;
1334
- }
1335
- setRenderCallback(callback) {
1336
- const engine = this.ensureInitialized();
1337
- engine.setRenderCallback((patches) => {
1338
- callback(patches);
1339
- });
1340
- }
1341
- setComponentResolver(resolver) {
1342
- const engine = this.ensureInitialized();
1343
- engine.setComponentResolver((componentName, contextPath) => {
1344
- const result = resolver(componentName, contextPath);
1345
- return result;
1346
- });
1347
- }
1348
- renderSource(source) {
1349
- const engine = this.ensureInitialized();
1350
- try {
1351
- engine.renderSource(source);
1352
- } catch (err) {
1353
- throw classifyEngineError(err);
1354
- }
1355
- }
1356
- renderLazyComponent(source) {
1357
- const engine = this.ensureInitialized();
1358
- engine.renderLazyComponent(source);
1359
- }
1360
- renderInto(source, parentNodeId, state) {
1361
- const engine = this.ensureInitialized();
1362
- try {
1363
- engine.renderInto(source, parentNodeId, unwrapForWasm(state));
1364
- } catch (err) {
1365
- throw classifyEngineError(err);
1366
- }
1367
- }
1368
- notifyStateChange(paths, values) {
1369
- const engine = this.ensureInitialized();
1370
- if (paths.length === 0) {
1371
- return;
1372
- }
1373
- try {
1374
- engine.updateStateSparse(paths, unwrapForWasm(values));
1375
- } catch (err) {
1376
- throw classifyEngineError(err);
1377
- }
1378
- log3.debug("State changed (sparse):", paths);
1379
- }
1380
- notifyStateChangeFull(paths, currentState) {
1381
- const engine = this.ensureInitialized();
1382
- engine.updateState(unwrapForWasm(currentState));
1383
- if (paths.length > 0) {
1384
- log3.debug("State changed (full):", paths);
1385
- }
1386
- }
1387
- updateState(statePatch) {
1388
- const engine = this.ensureInitialized();
1389
- engine.updateState(unwrapForWasm(statePatch));
1390
- }
1391
- dispatchAction(name, payload) {
1392
- const engine = this.ensureInitialized();
1393
- try {
1394
- engine.dispatchAction(name, payload ?? null);
1395
- } catch (err) {
1396
- throw classifyEngineError(err);
1397
- }
1398
- }
1399
- _onErrorHandler;
1400
- setOnError(handler) {
1401
- this._onErrorHandler = handler;
1402
- }
1403
- onAction(actionName, handler) {
1404
- const engine = this.ensureInitialized();
1405
- const handleError = (err) => {
1406
- log3.error("Action handler error:", err);
1407
- if (this._onErrorHandler) {
1408
- this._onErrorHandler(err instanceof Error ? err : new Error(String(err)));
1409
- }
1410
- };
1411
- engine.onAction(actionName, (action) => {
1412
- try {
1413
- const result = handler(action);
1414
- if (result && typeof result.catch === "function") {
1415
- result.catch(handleError);
1416
- }
1417
- } catch (err) {
1418
- handleError(err);
1419
- }
1420
- });
1421
- }
1422
- setModule(name, actions, stateKeys, initialState) {
1423
- const engine = this.ensureInitialized();
1424
- engine.setModule(name, actions, stateKeys, initialState);
1425
- }
1426
- getRevision() {
1427
- const engine = this.ensureInitialized();
1428
- return Number(engine.getRevision());
1429
- }
1430
- clearTree() {
1431
- const engine = this.ensureInitialized();
1432
- engine.clearTree();
1433
- }
1434
- debugParseComponent(source) {
1435
- const engine = this.ensureInitialized();
1436
- return engine.debugParseComponent(source);
1437
- }
1438
- setContext(name, data) {
1439
- const engine = this.ensureInitialized();
1440
- try {
1441
- engine.setContext(name, unwrapForWasm(data));
1442
- } catch (err) {
1443
- throw classifyEngineError(err);
1444
- }
1445
- log3.debug(`Data source "${name}" context set`);
1446
- }
1447
- removeContext(name) {
1448
- const engine = this.ensureInitialized();
1449
- engine.removeContext(name);
1450
- }
1451
- }
1452
-
1453
- // src/remote/server.ts
1454
- init_app();
1455
-
1456
- // src/remote/session.ts
1457
- class SessionManager {
1458
- activeSessions = new Map;
1459
- pendingSessions = new Map;
1460
- sessionConnections = new Map;
1461
- config;
1462
- constructor(config2 = {}) {
1463
- this.config = {
1464
- ttl: config2.ttl ?? 3600,
1465
- concurrent: config2.concurrent ?? "kick-old",
1466
- generateId: config2.generateId ?? (() => crypto.randomUUID())
1467
- };
1468
- }
1469
- getTtl() {
1470
- return this.config.ttl;
1471
- }
1472
- getConcurrentPolicy() {
1473
- return this.config.concurrent;
1474
- }
1475
- createSession(props) {
1476
- const now = new Date;
1477
- const session = {
1478
- id: this.config.generateId(),
1479
- ttl: this.config.ttl,
1480
- createdAt: now,
1481
- lastConnectedAt: now,
1482
- props
1483
- };
1484
- this.activeSessions.set(session.id, session);
1485
- return session;
1486
- }
1487
- getActiveSession(id) {
1488
- return this.activeSessions.get(id) ?? null;
1489
- }
1490
- getPendingSession(id) {
1491
- return this.pendingSessions.get(id) ?? null;
1492
- }
1493
- hasSession(id) {
1494
- return this.activeSessions.has(id) || this.pendingSessions.has(id);
1495
- }
1496
- suspendSession(sessionId, savedState, onExpire) {
1497
- const session = this.activeSessions.get(sessionId);
1498
- if (!session)
1499
- return;
1500
- this.activeSessions.delete(sessionId);
1501
- const expiryTimer = setTimeout(async () => {
1502
- const pending = this.pendingSessions.get(sessionId);
1503
- if (pending) {
1504
- this.pendingSessions.delete(sessionId);
1505
- await onExpire(pending.session);
1506
- }
1507
- }, session.ttl * 1000);
1508
- this.pendingSessions.set(sessionId, {
1509
- session,
1510
- savedState,
1511
- expiryTimer
1512
- });
1513
- }
1514
- resumeSession(sessionId) {
1515
- const pending = this.pendingSessions.get(sessionId);
1516
- if (!pending)
1517
- return null;
1518
- clearTimeout(pending.expiryTimer);
1519
- this.pendingSessions.delete(sessionId);
1520
- pending.session.lastConnectedAt = new Date;
1521
- this.activeSessions.set(sessionId, pending.session);
1522
- return {
1523
- session: pending.session,
1524
- savedState: pending.savedState
1525
- };
1526
- }
1527
- destroySession(sessionId) {
1528
- this.activeSessions.delete(sessionId);
1529
- const pending = this.pendingSessions.get(sessionId);
1530
- if (pending) {
1531
- clearTimeout(pending.expiryTimer);
1532
- this.pendingSessions.delete(sessionId);
1533
- }
1534
- this.sessionConnections.delete(sessionId);
1535
- }
1536
- trackConnection(sessionId, ws) {
1537
- let connections = this.sessionConnections.get(sessionId);
1538
- if (!connections) {
1539
- connections = new Set;
1540
- this.sessionConnections.set(sessionId, connections);
1541
- }
1542
- connections.add(ws);
1543
- }
1544
- untrackConnection(sessionId, ws) {
1545
- const connections = this.sessionConnections.get(sessionId);
1546
- if (connections) {
1547
- connections.delete(ws);
1548
- if (connections.size === 0) {
1549
- this.sessionConnections.delete(sessionId);
1550
- }
1551
- }
1552
- }
1553
- getConnections(sessionId) {
1554
- return this.sessionConnections.get(sessionId);
1555
- }
1556
- getConnectionCount(sessionId) {
1557
- return this.sessionConnections.get(sessionId)?.size ?? 0;
1558
- }
1559
- getStats() {
1560
- let totalConnections = 0;
1561
- for (const connections of this.sessionConnections.values()) {
1562
- totalConnections += connections.size;
1563
- }
1564
- return {
1565
- activeSessions: this.activeSessions.size,
1566
- pendingSessions: this.pendingSessions.size,
1567
- totalConnections
1568
- };
1569
- }
1570
- destroy() {
1571
- for (const pending of this.pendingSessions.values()) {
1572
- clearTimeout(pending.expiryTimer);
1573
- }
1574
- this.activeSessions.clear();
1575
- this.pendingSessions.clear();
1576
- this.sessionConnections.clear();
1577
- }
1578
- }
1579
-
1580
- // src/remote/server.ts
1581
- init_logger();
1582
-
1583
- // src/discovery.ts
1584
- init_path();
1585
- init_logger();
1586
- var {existsSync, readdirSync, readFileSync, watch} = (() => ({}));
1587
- async function discoverComponents(baseDir, options = {}) {
1588
- const {
1589
- patterns = ["single-file", "folder", "sibling", "index"],
1590
- recursive = true,
1591
- debug = false
1592
- } = options;
1593
- const log4 = debug ? (...args) => frameworkLoggers.discovery.debug(...args) : () => {};
1594
- const resolvedDir = resolve(baseDir);
1595
- const components = [];
1596
- const seen = new Set;
1597
- log4("Scanning directory:", resolvedDir);
1598
- log4("Patterns:", patterns);
1599
- const addTwoFileComponent = (name, hypenPath, modulePath) => {
1600
- if (seen.has(name)) {
1601
- log4(`Skipping duplicate: ${name}`);
1602
- return;
1603
- }
1604
- seen.add(name);
1605
- const templateRaw = readFileSync(hypenPath, "utf-8");
1606
- const template = templateRaw.trim();
1607
- components.push({
1608
- name,
1609
- hypenPath,
1610
- modulePath,
1611
- template,
1612
- hasModule: modulePath !== null,
1613
- isSingleFile: false
1614
- });
1615
- log4(`Found: ${name} (two-file, ${modulePath ? "with module" : "stateless"})`);
1616
- };
1617
- const addSingleFileComponent = (name, modulePath, template) => {
1618
- if (seen.has(name)) {
1619
- log4(`Skipping duplicate: ${name}`);
1620
- return;
1621
- }
1622
- seen.add(name);
1623
- components.push({
1624
- name,
1625
- hypenPath: null,
1626
- modulePath,
1627
- template,
1628
- hasModule: true,
1629
- isSingleFile: true
1630
- });
1631
- log4(`Found: ${name} (single-file with inline template)`);
1632
- };
1633
- const scanForFolderComponents = (dir) => {
1634
- if (!existsSync(dir))
1635
- return;
1636
- const entries = readdirSync(dir, { withFileTypes: true });
1637
- for (const entry of entries) {
1638
- if (!entry.isDirectory())
1639
- continue;
1640
- const folderPath = join(dir, entry.name);
1641
- const componentName = entry.name;
1642
- if (patterns.includes("folder")) {
1643
- const hypenPath = join(folderPath, "component.hypen");
1644
- if (existsSync(hypenPath)) {
1645
- const modulePath = join(folderPath, "component.ts");
1646
- addTwoFileComponent(componentName, hypenPath, existsSync(modulePath) ? modulePath : null);
1647
- continue;
1648
- }
1649
- }
1650
- if (patterns.includes("index")) {
1651
- const hypenPath = join(folderPath, "index.hypen");
1652
- if (existsSync(hypenPath)) {
1653
- const modulePath = join(folderPath, "index.ts");
1654
- addTwoFileComponent(componentName, hypenPath, existsSync(modulePath) ? modulePath : null);
1655
- continue;
1656
- }
1657
- }
1658
- if (recursive) {
1659
- scanForFolderComponents(folderPath);
1660
- }
1661
- }
1662
- };
1663
- const scanForSiblingComponents = (dir) => {
1664
- if (!existsSync(dir))
1665
- return;
1666
- const entries = readdirSync(dir, { withFileTypes: true });
1667
- for (const entry of entries) {
1668
- if (entry.isDirectory()) {
1669
- if (recursive) {
1670
- scanForSiblingComponents(join(dir, entry.name));
1671
- }
1672
- continue;
1673
- }
1674
- if (!entry.name.endsWith(".hypen"))
1675
- continue;
1676
- const hypenPath = join(dir, entry.name);
1677
- const baseName = basename(entry.name, ".hypen");
1678
- if (baseName === "component" || baseName === "index")
1679
- continue;
1680
- const modulePath = join(dir, `${baseName}.ts`);
1681
- addTwoFileComponent(baseName, hypenPath, existsSync(modulePath) ? modulePath : null);
1682
- }
1683
- };
1684
- const scanForSingleFileComponents = async (dir) => {
1685
- if (!existsSync(dir))
1686
- return;
1687
- const entries = readdirSync(dir, { withFileTypes: true });
1688
- for (const entry of entries) {
1689
- if (entry.isDirectory()) {
1690
- if (recursive) {
1691
- await scanForSingleFileComponents(join(dir, entry.name));
1692
- }
1693
- continue;
1694
- }
1695
- if (!entry.name.endsWith(".ts"))
1696
- continue;
1697
- if (entry.name.startsWith(".") || entry.name.includes(".test.") || entry.name.includes(".spec."))
1698
- continue;
1699
- const baseName = basename(entry.name, ".ts");
1700
- if (baseName === "component" || baseName === "index")
1701
- continue;
1702
- const hypenPath = join(dir, `${baseName}.hypen`);
1703
- if (existsSync(hypenPath))
1704
- continue;
1705
- const modulePath = join(dir, entry.name);
1706
- const content = readFileSync(modulePath, "utf-8");
1707
- if (content.includes(".ui(") || content.includes(".ui(hypen")) {
1708
- try {
1709
- const moduleExport = await import(modulePath);
1710
- const module = moduleExport.default;
1711
- if (module && typeof module === "object" && module.template) {
1712
- addSingleFileComponent(baseName, modulePath, module.template);
1713
- } else if (module && typeof module === "object") {
1714
- frameworkLoggers.discovery.warn(`Skipping "${entry.name}": has .ui() pattern but module has no .template property. Did you forget to call .ui(hypen\`...\`)?`);
1715
- }
1716
- } catch (e) {
1717
- log4(`Failed to import potential single-file component: ${entry.name}`, e);
1718
- }
1719
- }
1720
- }
1721
- };
1722
- if (patterns.includes("folder") || patterns.includes("index")) {
1723
- scanForFolderComponents(resolvedDir);
1724
- }
1725
- if (patterns.includes("sibling")) {
1726
- scanForSiblingComponents(resolvedDir);
1727
- }
1728
- if (patterns.includes("single-file")) {
1729
- await scanForSingleFileComponents(resolvedDir);
1730
- }
1731
- log4(`Discovered ${components.length} components`);
1732
- return components;
1733
- }
1734
- async function loadDiscoveredComponents(components) {
1735
- const { app: app2 } = await Promise.resolve().then(() => (init_app(), exports_app));
1736
- const loaded = new Map;
1737
- for (const component of components) {
1738
- let module;
1739
- let template = component.template;
1740
- if (component.modulePath) {
1741
- const moduleExport = await import(component.modulePath);
1742
- module = moduleExport.default;
1743
- if (component.isSingleFile && module.template) {
1744
- template = module.template;
1745
- }
1746
- } else {
1747
- module = app2.defineState({}).build();
1748
- }
1749
- loaded.set(component.name, {
1750
- name: component.name,
1751
- module,
1752
- template
1753
- });
1754
- }
1755
- return loaded;
1756
- }
1757
-
1758
- // src/remote/server.ts
1759
- var log4 = frameworkLoggers.remote;
1760
-
1761
- class RemoteServer {
1762
- _module = null;
1763
- _moduleName = "App";
1764
- _ui = "";
1765
- _sourceDir = null;
1766
- _discoveredComponents = new Map;
1767
- _config = {};
1768
- _sessionConfig = {};
1769
- _onConnectionCallbacks = [];
1770
- _onDisconnectionCallbacks = [];
1771
- clients = new Map;
1772
- nextClientId = 1;
1773
- server = null;
1774
- sessionManager = null;
1775
- _syncActions = false;
1776
- module(name, module) {
1777
- this._moduleName = name;
1778
- this._module = module;
1779
- return this;
1780
- }
1781
- ui(dsl) {
1782
- this._ui = dsl;
1783
- return this;
1784
- }
1785
- source(dir) {
1786
- this._sourceDir = dir;
1787
- return this;
1788
- }
1789
- config(config2) {
1790
- this._config = { ...this._config, ...config2 };
1791
- return this;
1792
- }
1793
- session(config2) {
1794
- this._sessionConfig = config2;
1795
- return this;
1796
- }
1797
- syncActions() {
1798
- this._syncActions = true;
1799
- return this;
1800
- }
1801
- onConnection(callback) {
1802
- this._onConnectionCallbacks.push(callback);
1803
- return this;
1804
- }
1805
- onDisconnection(callback) {
1806
- this._onDisconnectionCallbacks.push(callback);
1807
- return this;
1808
- }
1809
- async listen(port) {
1810
- if (!this._module) {
1811
- throw new Error("Module not set. Call .module() before .listen()");
1812
- }
1813
- if (this._sourceDir) {
1814
- await this.discoverFromSource();
1815
- }
1816
- if (!this._ui) {
1817
- throw new Error("UI not set. Call .ui() or .source() before .listen()");
1818
- }
1819
- this.sessionManager = new SessionManager(this._sessionConfig);
1820
- const finalPort = port ?? this._config.port ?? 3000;
1821
- const hostname = this._config.hostname ?? "0.0.0.0";
1822
- this.server = Bun.serve({
1823
- port: finalPort,
1824
- hostname,
1825
- websocket: {
1826
- open: (ws) => this.handleOpen(ws),
1827
- message: (ws, message) => this.handleMessage(ws, message),
1828
- close: (ws) => this.handleClose(ws)
1829
- },
1830
- fetch: (req, server) => {
1831
- const url = new URL(req.url);
1832
- if (server.upgrade(req, { data: undefined })) {
1833
- return;
1834
- }
1835
- if (url.pathname === "/health") {
1836
- return new Response("OK", { status: 200 });
1837
- }
1838
- if (url.pathname === "/stats") {
1839
- const stats = this.sessionManager?.getStats() ?? {
1840
- activeSessions: 0,
1841
- pendingSessions: 0,
1842
- totalConnections: 0
1843
- };
1844
- return new Response(JSON.stringify(stats), {
1845
- headers: { "Content-Type": "application/json" }
1846
- });
1847
- }
1848
- return new Response("Hypen Remote Server", { status: 200 });
1849
- }
1850
- });
1851
- log4.info(`Hypen app streaming on ws://${hostname}:${finalPort}`);
1852
- return this;
1853
- }
1854
- stop() {
1855
- if (this.server) {
1856
- this.server.stop();
1857
- this.server = null;
1858
- }
1859
- if (this.sessionManager) {
1860
- this.sessionManager.destroy();
1861
- this.sessionManager = null;
1862
- }
1863
- }
1864
- get url() {
1865
- if (!this.server)
1866
- return null;
1867
- const hostname = this._config.hostname ?? "localhost";
1868
- const port = this._config.port ?? 3000;
1869
- return `ws://${hostname}:${port}`;
1870
- }
1871
- async discoverFromSource() {
1872
- const dir = this._sourceDir;
1873
- log4.info(`Discovering components from ${dir}...`);
1874
- const discovered = await discoverComponents(dir);
1875
- const loaded = await loadDiscoveredComponents(discovered);
1876
- for (const [name, { module, template }] of loaded) {
1877
- this._discoveredComponents.set(name, { template, module });
1878
- }
1879
- log4.info(`Discovered ${this._discoveredComponents.size} components: ${Array.from(this._discoveredComponents.keys()).join(", ")}`);
1880
- if (!this._ui) {
1881
- const entry = this._discoveredComponents.get(this._moduleName);
1882
- if (entry) {
1883
- this._ui = entry.template;
1884
- }
1885
- }
1886
- }
1887
- setupComponentResolver(engine) {
1888
- if (this._discoveredComponents.size === 0)
1889
- return;
1890
- engine.setComponentResolver((componentName, _contextPath) => {
1891
- const comp = this._discoveredComponents.get(componentName);
1892
- if (!comp) {
1893
- log4.warn(`Component "${componentName}" not found. Available: ${Array.from(this._discoveredComponents.keys()).join(", ") || "(none)"}`);
1894
- return null;
1895
- }
1896
- return {
1897
- source: comp.template,
1898
- path: componentName
1899
- };
1900
- });
1901
- }
1902
- handleOpen(ws) {
1903
- try {
1904
- const clientId = `client_${this.nextClientId++}`;
1905
- const connectedAt = new Date;
1906
- const engine = new Engine;
1907
- engine.init().catch((err) => log4.error("Engine init failed:", err));
1908
- this.setupComponentResolver(engine);
1909
- const moduleInstance = new HypenModuleInstance(engine, this._module);
1910
- log4.info(`Client ${clientId} connected, engine initialized`);
1911
- const clientData = {
1912
- id: clientId,
1913
- engine,
1914
- moduleInstance,
1915
- revision: 0,
1916
- connectedAt,
1917
- sessionId: "",
1918
- helloReceived: false,
1919
- stateSubscribed: false
1920
- };
1921
- this.clients.set(ws, clientData);
1922
- clientData.helloTimeout = setTimeout(() => {
1923
- if (!clientData.helloReceived) {
1924
- this.initializeSession(ws, clientData, undefined, undefined).catch((err) => log4.error("Error initializing legacy session:", err));
1925
- }
1926
- }, 1000);
1927
- } catch (error) {
1928
- log4.error("Error handling WebSocket open:", error);
1929
- ws.close(1011, "Internal server error");
1930
- }
1931
- }
1932
- async initializeSession(ws, clientData, requestedSessionId, props) {
1933
- if (clientData.helloReceived)
1934
- return;
1935
- clientData.helloReceived = true;
1936
- log4.info(`Initializing session for ${clientData.id} (sessionId: ${requestedSessionId ?? "new"})`);
1937
- if (clientData.helloTimeout) {
1938
- clearTimeout(clientData.helloTimeout);
1939
- clientData.helloTimeout = undefined;
1940
- }
1941
- let session;
1942
- let isNew = true;
1943
- let isRestored = false;
1944
- let restoredState = null;
1945
- if (requestedSessionId && this.sessionManager) {
1946
- const resumed = this.sessionManager.resumeSession(requestedSessionId);
1947
- if (resumed) {
1948
- session = resumed.session;
1949
- restoredState = resumed.savedState;
1950
- isNew = false;
1951
- isRestored = true;
1952
- await this.triggerReconnect(clientData, session, restoredState);
1953
- } else {
1954
- const activeSession = this.sessionManager.getActiveSession(requestedSessionId);
1955
- if (activeSession) {
1956
- const handled = await this.handleConcurrentConnection(ws, clientData, activeSession, props);
1957
- if (!handled)
1958
- return;
1959
- session = activeSession;
1960
- isNew = false;
1961
- } else {
1962
- session = this.sessionManager.createSession(props);
1963
- }
1964
- }
1965
- } else if (this.sessionManager) {
1966
- session = this.sessionManager.createSession(props);
1967
- } else {
1968
- session = {
1969
- id: crypto.randomUUID(),
1970
- ttl: 3600,
1971
- createdAt: new Date,
1972
- lastConnectedAt: new Date,
1973
- props
1974
- };
1975
- }
1976
- clientData.sessionId = session.id;
1977
- this.sessionManager?.trackConnection(session.id, ws);
1978
- const sessionAck = {
1979
- type: "sessionAck",
1980
- sessionId: session.id,
1981
- isNew,
1982
- isRestored
1983
- };
1984
- ws.send(JSON.stringify(sessionAck));
1985
- log4.info(`Sent sessionAck to ${clientData.id} (session: ${session.id})`);
1986
- const initialPatches = [];
1987
- clientData.engine.setRenderCallback((patches) => {
1988
- initialPatches.push(...patches);
1989
- });
1990
- try {
1991
- clientData.engine.renderSource(this._ui);
1992
- } catch (renderError) {
1993
- log4.error(`Failed to render UI for ${clientData.id}:`, renderError);
1994
- ws.close(1011, "Render failed");
1995
- return;
1996
- }
1997
- this.setupRenderCallback(ws, clientData);
1998
- const initialMessage = {
1999
- type: "initialTree",
2000
- module: this._moduleName,
2001
- state: clientData.moduleInstance.getState(),
2002
- patches: initialPatches,
2003
- revision: 0
2004
- };
2005
- try {
2006
- ws.send(JSON.stringify(initialMessage));
2007
- } catch (sendError) {
2008
- log4.error(`Failed to send initialTree to ${clientData.id}:`, sendError);
2009
- return;
2010
- }
2011
- log4.info(`Sent initialTree to ${clientData.id} (${initialPatches.length} patches)`);
2012
- const client = {
2013
- id: clientData.id,
2014
- socket: ws,
2015
- connectedAt: clientData.connectedAt
2016
- };
2017
- this._onConnectionCallbacks.forEach((cb) => cb(client));
2018
- }
2019
- setupRenderCallback(ws, clientData) {
2020
- clientData.engine.setRenderCallback((patches) => {
2021
- const data = this.clients.get(ws);
2022
- if (!data)
2023
- return;
2024
- data.revision++;
2025
- const patchMessage = {
2026
- type: "patch",
2027
- module: this._moduleName,
2028
- patches,
2029
- revision: data.revision
2030
- };
2031
- ws.send(JSON.stringify(patchMessage));
2032
- if (data.stateSubscribed) {
2033
- const stateMessage = {
2034
- type: "stateUpdate",
2035
- module: this._moduleName,
2036
- state: data.moduleInstance.getState(),
2037
- revision: data.revision
2038
- };
2039
- ws.send(JSON.stringify(stateMessage));
2040
- }
2041
- if (this.sessionManager?.getConcurrentPolicy() === "allow-multiple" && data.sessionId) {
2042
- const connections = this.sessionManager.getConnections(data.sessionId);
2043
- if (connections) {
2044
- for (const conn of connections) {
2045
- if (conn !== ws) {
2046
- const otherWs = conn;
2047
- const otherData = this.clients.get(otherWs);
2048
- otherWs.send(JSON.stringify(patchMessage));
2049
- if (otherData?.stateSubscribed) {
2050
- const stateMessage = {
2051
- type: "stateUpdate",
2052
- module: this._moduleName,
2053
- state: data.moduleInstance.getState(),
2054
- revision: data.revision
2055
- };
2056
- otherWs.send(JSON.stringify(stateMessage));
2057
- }
2058
- }
2059
- }
2060
- }
2061
- }
2062
- });
2063
- }
2064
- async handleConcurrentConnection(ws, clientData, existingSession, props) {
2065
- const policy = this.sessionManager?.getConcurrentPolicy() ?? "kick-old";
2066
- switch (policy) {
2067
- case "kick-old": {
2068
- const existingConnections = this.sessionManager?.getConnections(existingSession.id);
2069
- if (existingConnections) {
2070
- for (const conn of existingConnections) {
2071
- const oldWs = conn;
2072
- const expiredMsg = {
2073
- type: "sessionExpired",
2074
- sessionId: existingSession.id,
2075
- reason: "kicked"
2076
- };
2077
- oldWs.send(JSON.stringify(expiredMsg));
2078
- oldWs.close(1000, "Session taken by new connection");
2079
- }
2080
- }
2081
- return true;
2082
- }
2083
- case "reject-new": {
2084
- const expiredMsg = {
2085
- type: "sessionExpired",
2086
- sessionId: existingSession.id,
2087
- reason: "kicked"
2088
- };
2089
- ws.send(JSON.stringify(expiredMsg));
2090
- ws.close(1000, "Session already active");
2091
- return false;
2092
- }
2093
- case "allow-multiple": {
2094
- return true;
2095
- }
2096
- default:
2097
- return true;
2098
- }
2099
- }
2100
- async triggerReconnect(clientData, session, savedState) {
2101
- const handler = this._module?.handlers.onReconnect;
2102
- if (!handler)
2103
- return;
2104
- let restored = false;
2105
- const restore = (state) => {
2106
- if (state === null || typeof state !== "object") {
2107
- log4.warn("restore() called with non-object state, ignoring:", typeof state);
2108
- return;
2109
- }
2110
- restored = true;
2111
- clientData.moduleInstance.updateState(state);
2112
- };
2113
- await handler({ session, restore });
2114
- }
2115
- handleMessage(ws, message) {
2116
- try {
2117
- const clientData = this.clients.get(ws);
2118
- if (!clientData)
2119
- return;
2120
- const msg = JSON.parse(message.toString());
2121
- switch (msg.type) {
2122
- case "hello": {
2123
- const helloMsg = msg;
2124
- this.initializeSession(ws, clientData, helloMsg.sessionId, helloMsg.props).catch((err) => log4.error("Error initializing session from hello:", err));
2125
- break;
2126
- }
2127
- case "dispatchAction": {
2128
- const actionMsg = msg;
2129
- clientData.engine.dispatchAction(actionMsg.action, actionMsg.payload);
2130
- if (this._syncActions) {
2131
- for (const [otherWs, otherClient] of this.clients) {
2132
- if (otherWs === ws || !otherClient.helloReceived)
2133
- continue;
2134
- otherClient.engine.dispatchAction(actionMsg.action, actionMsg.payload);
2135
- }
2136
- }
2137
- break;
2138
- }
2139
- case "updateState": {
2140
- const stateMsg = msg;
2141
- clientData.moduleInstance.updateState(stateMsg.state);
2142
- if (this._syncActions) {
2143
- for (const [otherWs, otherClient] of this.clients) {
2144
- if (otherWs === ws || !otherClient.helloReceived)
2145
- continue;
2146
- otherClient.moduleInstance.updateState(stateMsg.state);
2147
- }
2148
- }
2149
- break;
2150
- }
2151
- case "subscribeState": {
2152
- clientData.stateSubscribed = true;
2153
- log4.info(`Client ${clientData.id} subscribed to state updates`);
2154
- break;
2155
- }
2156
- default:
2157
- break;
2158
- }
2159
- } catch (error) {
2160
- log4.error("Error handling WebSocket message:", error);
2161
- }
2162
- }
2163
- async handleClose(ws) {
2164
- const clientData = this.clients.get(ws);
2165
- if (!clientData)
2166
- return;
2167
- if (clientData.helloTimeout) {
2168
- clearTimeout(clientData.helloTimeout);
2169
- }
2170
- const currentState = clientData.moduleInstance.getState();
2171
- if (clientData.sessionId && this._module?.handlers.onDisconnect) {
2172
- const session = this.sessionManager?.getActiveSession(clientData.sessionId);
2173
- if (session) {
2174
- await this._module.handlers.onDisconnect({
2175
- state: currentState,
2176
- session
2177
- });
2178
- }
2179
- }
2180
- if (clientData.sessionId && this.sessionManager) {
2181
- this.sessionManager.untrackConnection(clientData.sessionId, ws);
2182
- if (this.sessionManager.getConnectionCount(clientData.sessionId) === 0) {
2183
- const session = this.sessionManager.getActiveSession(clientData.sessionId);
2184
- if (session) {
2185
- this.sessionManager.suspendSession(clientData.sessionId, currentState, async (expiredSession) => {
2186
- if (this._module?.handlers.onExpire) {
2187
- await this._module.handlers.onExpire({ session: expiredSession });
2188
- }
2189
- });
2190
- }
2191
- }
2192
- }
2193
- await clientData.moduleInstance.destroy();
2194
- this.clients.delete(ws);
2195
- const client = {
2196
- id: clientData.id,
2197
- socket: ws,
2198
- connectedAt: clientData.connectedAt
2199
- };
2200
- this._onDisconnectionCallbacks.forEach((cb) => cb(client));
2201
- }
2202
- async reload() {
2203
- if (this._sourceDir) {
2204
- this._ui = "";
2205
- await this.discoverFromSource();
2206
- }
2207
- if (!this._ui) {
2208
- log4.warn("Reload skipped: no UI template available");
2209
- return;
2210
- }
2211
- for (const [ws, clientData] of this.clients) {
2212
- if (!clientData.helloReceived)
2213
- continue;
2214
- this.setupComponentResolver(clientData.engine);
2215
- try {
2216
- clientData.engine.renderSource(this._ui);
2217
- log4.info(`Hot-reloaded client ${clientData.id}`);
2218
- } catch (e) {
2219
- log4.error(`Failed to hot-reload client ${clientData.id}:`, e);
2220
- }
2221
- }
2222
- }
2223
- getClientCount() {
2224
- return this.clients.size;
2225
- }
2226
- getSessionStats() {
2227
- return this.sessionManager?.getStats() ?? {
2228
- activeSessions: 0,
2229
- pendingSessions: 0,
2230
- totalConnections: 0
2231
- };
2232
- }
2233
- broadcast(message) {
2234
- const json = JSON.stringify(message);
2235
- this.clients.forEach((_, ws) => {
2236
- ws.send(json);
2237
- });
2238
- }
2239
- }
2240
- async function serve(options) {
2241
- const server = new RemoteServer().module(options.moduleName ?? "App", options.module);
2242
- if (options.source) {
2243
- server.source(options.source);
2244
- }
2245
- if (options.ui) {
2246
- server.ui(options.ui);
2247
- }
2248
- if (options.port || options.hostname) {
2249
- server.config({
2250
- port: options.port,
2251
- hostname: options.hostname
2252
- });
2253
- }
2254
- if (options.session) {
2255
- server.session(options.session);
2256
- }
2257
- if (options.onConnection) {
2258
- server.onConnection(options.onConnection);
2259
- }
2260
- if (options.onDisconnection) {
2261
- server.onDisconnection(options.onDisconnection);
2262
- }
2263
- return server.listen(options.port);
2264
- }
2265
- export {
2266
- serve,
2267
- RemoteServer
2268
- };
2269
-
2270
- //# debugId=23B2AD6EC2DA1C3B64756E2164756E21