@zenithbuild/bundler 1.3.16 → 1.3.18

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 (54) hide show
  1. package/dist/build-analyzer.d.ts +45 -0
  2. package/dist/build-analyzer.d.ts.map +1 -0
  3. package/dist/build-analyzer.js +88 -0
  4. package/dist/build-analyzer.js.map +1 -0
  5. package/dist/bundle-generator.d.ts +19 -0
  6. package/dist/bundle-generator.d.ts.map +1 -0
  7. package/dist/bundle-generator.js +838 -0
  8. package/dist/bundle-generator.js.map +1 -0
  9. package/dist/bundler.d.ts +32 -0
  10. package/dist/bundler.d.ts.map +1 -0
  11. package/dist/bundler.js +87 -0
  12. package/dist/bundler.js.map +1 -0
  13. package/dist/css.d.ts +60 -0
  14. package/dist/css.d.ts.map +1 -0
  15. package/dist/css.js +229 -0
  16. package/dist/css.js.map +1 -0
  17. package/dist/discovery/componentDiscovery.d.ts +42 -0
  18. package/dist/discovery/componentDiscovery.d.ts.map +1 -0
  19. package/dist/discovery/componentDiscovery.js +67 -0
  20. package/dist/discovery/componentDiscovery.js.map +1 -0
  21. package/dist/discovery/layouts.d.ts +15 -0
  22. package/dist/discovery/layouts.d.ts.map +1 -0
  23. package/dist/discovery/layouts.js +37 -0
  24. package/dist/discovery/layouts.js.map +1 -0
  25. package/dist/generateFinalBundle.d.ts +25 -0
  26. package/dist/generateFinalBundle.d.ts.map +1 -0
  27. package/dist/generateFinalBundle.js +69 -0
  28. package/dist/generateFinalBundle.js.map +1 -0
  29. package/dist/index.d.ts +12 -0
  30. package/dist/index.d.ts.map +1 -0
  31. package/dist/index.js +12 -0
  32. package/dist/index.js.map +1 -0
  33. package/dist/runtime-generator.d.ts +5 -0
  34. package/dist/runtime-generator.d.ts.map +1 -0
  35. package/dist/runtime-generator.js +21 -0
  36. package/dist/runtime-generator.js.map +1 -0
  37. package/dist/spa-build.d.ts +27 -0
  38. package/dist/spa-build.d.ts.map +1 -0
  39. package/dist/spa-build.js +862 -0
  40. package/dist/spa-build.js.map +1 -0
  41. package/dist/ssg-build.d.ts +32 -0
  42. package/dist/ssg-build.d.ts.map +1 -0
  43. package/dist/ssg-build.js +429 -0
  44. package/dist/ssg-build.js.map +1 -0
  45. package/dist/types.d.ts +6 -0
  46. package/dist/types.d.ts.map +1 -0
  47. package/dist/types.js +2 -0
  48. package/dist/types.js.map +1 -0
  49. package/package.json +11 -7
  50. package/src/discovery/componentDiscovery.ts +98 -0
  51. package/src/discovery/layouts.ts +50 -0
  52. package/src/index.ts +4 -0
  53. package/src/spa-build.ts +931 -0
  54. package/src/ssg-build.ts +549 -0
@@ -0,0 +1,862 @@
1
+ /**
2
+ * Zenith SPA Build System
3
+ *
4
+ * Builds all pages into a single index.html with:
5
+ * - Route manifest
6
+ * - Compiled page modules (inlined)
7
+ * - Runtime router
8
+ * - Shell HTML with router outlet
9
+ */
10
+ import fs from "fs";
11
+ import path from "path";
12
+ // Import new compiler
13
+ import { compile } from "@zenithbuild/compiler";
14
+ import { discoverComponents } from "./discovery/componentDiscovery";
15
+ import { discoverLayouts } from "./discovery/layouts";
16
+ import { discoverPages, generateRouteDefinition, routePathToRegex } from "@zenithbuild/router/manifest";
17
+ /**
18
+ * Compile a single page file
19
+ */
20
+ async function compilePage(pagePath, pagesDir, baseDir = process.cwd()) {
21
+ try {
22
+ const srcDir = path.dirname(pagesDir);
23
+ const layoutsDir = path.join(srcDir, 'layouts');
24
+ const componentsDir = path.join(srcDir, 'components');
25
+ const layouts = discoverLayouts(layoutsDir);
26
+ const components = new Map([...layouts]);
27
+ if (fs.existsSync(componentsDir)) {
28
+ const discovered = discoverComponents(componentsDir);
29
+ for (const [k, v] of discovered) {
30
+ components.set(k, v);
31
+ }
32
+ }
33
+ const source = fs.readFileSync(pagePath, 'utf-8');
34
+ // Use new unified compiler pipeline
35
+ const result = await compile(source, pagePath, {
36
+ components
37
+ });
38
+ if (!result.finalized) {
39
+ throw new Error(`Compilation failed: No finalized output`);
40
+ }
41
+ // Extract compiled output
42
+ const html = result.finalized.html;
43
+ const js = result.finalized.js;
44
+ const styles = result.finalized.styles;
45
+ // Convert JS bundle to scripts array (for compatibility)
46
+ const scripts = js ? [js] : [];
47
+ // Generate route definition
48
+ const routeDef = generateRouteDefinition(pagePath, pagesDir);
49
+ const regex = routePathToRegex(routeDef.path);
50
+ return {
51
+ routePath: routeDef.path,
52
+ filePath: pagePath,
53
+ html,
54
+ scripts,
55
+ styles,
56
+ score: routeDef.score,
57
+ paramNames: routeDef.paramNames,
58
+ regex
59
+ };
60
+ }
61
+ catch (error) {
62
+ console.error(`[Zenith Build] Compilation failed for ${pagePath}:`, error.message);
63
+ throw error;
64
+ }
65
+ }
66
+ /**
67
+ * Generate the runtime router code (inlined into the bundle)
68
+ */
69
+ function generateRuntimeRouterCode() {
70
+ return `
71
+ // ============================================
72
+ // Zenith Runtime Router
73
+ // ============================================
74
+
75
+ (function() {
76
+ 'use strict';
77
+
78
+ // Current route state
79
+ let currentRoute = {
80
+ path: '/',
81
+ params: {},
82
+ query: {}
83
+ };
84
+
85
+ // Route listeners
86
+ const routeListeners = new Set();
87
+
88
+ // Router outlet element
89
+ let routerOutlet = null;
90
+
91
+ // Page modules registry
92
+ const pageModules = {};
93
+
94
+ // Route manifest
95
+ let routeManifest = [];
96
+
97
+ /**
98
+ * Parse query string
99
+ */
100
+ function parseQueryString(search) {
101
+ const query = {};
102
+ if (!search || search === '?') return query;
103
+ const params = new URLSearchParams(search);
104
+ params.forEach((value, key) => { query[key] = value; });
105
+ return query;
106
+ }
107
+
108
+ /**
109
+ * Resolve route from pathname
110
+ */
111
+ function resolveRoute(pathname) {
112
+ const normalizedPath = pathname === '' ? '/' : pathname;
113
+
114
+ for (const route of routeManifest) {
115
+ const match = route.regex.exec(normalizedPath);
116
+ if (match) {
117
+ const params = {};
118
+ for (let i = 0; i < route.paramNames.length; i++) {
119
+ const paramValue = match[i + 1];
120
+ if (paramValue !== undefined) {
121
+ params[route.paramNames[i]] = decodeURIComponent(paramValue);
122
+ }
123
+ }
124
+ return { record: route, params };
125
+ }
126
+ }
127
+ return null;
128
+ }
129
+
130
+ /**
131
+ * Clean up previous page
132
+ */
133
+ function cleanupPreviousPage() {
134
+ // Trigger unmount lifecycle hooks
135
+ if (window.__zenith && window.__zenith.triggerUnmount) {
136
+ window.__zenith.triggerUnmount();
137
+ }
138
+
139
+ // Remove previous page styles
140
+ document.querySelectorAll('style[data-zen-page-style]').forEach(s => s.remove());
141
+
142
+ // Clean up window properties (state variables, functions)
143
+ // This is important for proper state isolation between pages
144
+ if (window.__zenith_cleanup) {
145
+ window.__zenith_cleanup.forEach(key => {
146
+ try { delete window[key]; } catch(e) {}
147
+ });
148
+ }
149
+ window.__zenith_cleanup = [];
150
+ }
151
+
152
+ /**
153
+ * Inject styles
154
+ */
155
+ function injectStyles(styles) {
156
+ if (!styles) return;
157
+ const style = document.createElement('style');
158
+ style.setAttribute('data-zen-page-style', '0');
159
+ style.textContent = styles;
160
+ document.head.appendChild(style);
161
+ }
162
+
163
+ /**
164
+ * Execute scripts
165
+ */
166
+ function executeScripts(scripts) {
167
+ scripts.forEach(content => {
168
+ try {
169
+ const fn = new Function(content);
170
+ fn();
171
+ } catch (e) {
172
+ console.error('[Zenith Router] Script error:', e);
173
+ }
174
+ });
175
+ }
176
+
177
+ /**
178
+ * Render page
179
+ */
180
+ function renderPage(pageModule) {
181
+ if (!routerOutlet) {
182
+ console.warn('[Zenith Router] No router outlet');
183
+ return;
184
+ }
185
+
186
+ cleanupPreviousPage();
187
+ routerOutlet.innerHTML = pageModule.html;
188
+ injectStyles(pageModule.styles);
189
+ executeScripts(pageModule.scripts);
190
+
191
+ // Trigger mount lifecycle hooks after scripts are executed
192
+ if (window.__zenith && window.__zenith.triggerMount) {
193
+ window.__zenith.triggerMount();
194
+ }
195
+ }
196
+
197
+ /**
198
+ * Notify listeners
199
+ */
200
+ function notifyListeners(route, prevRoute) {
201
+ routeListeners.forEach(listener => {
202
+ try { listener(route, prevRoute); } catch(e) {}
203
+ });
204
+ }
205
+
206
+ /**
207
+ * Resolve and render
208
+ */
209
+ function resolveAndRender(path, query, updateHistory, replace) {
210
+ replace = replace || false;
211
+ const prevRoute = { ...currentRoute };
212
+ const resolved = resolveRoute(path);
213
+
214
+ if (resolved) {
215
+ currentRoute = {
216
+ path,
217
+ params: resolved.params,
218
+ query,
219
+ matched: resolved.record
220
+ };
221
+
222
+ const pageModule = pageModules[resolved.record.path];
223
+ if (pageModule) {
224
+ renderPage(pageModule);
225
+ }
226
+ } else {
227
+ currentRoute = { path, params: {}, query, matched: undefined };
228
+ console.warn('[Zenith Router] No route matched:', path);
229
+
230
+ // Render 404 if available, otherwise show message
231
+ if (routerOutlet) {
232
+ routerOutlet.innerHTML = '<div style="padding: 2rem; text-align: center;"><h1>404</h1><p>Page not found</p></div>';
233
+ }
234
+ }
235
+
236
+ if (updateHistory) {
237
+ const url = path + (Object.keys(query).length ? '?' + new URLSearchParams(query) : '');
238
+ if (replace) {
239
+ window.history.replaceState(null, '', url);
240
+ } else {
241
+ window.history.pushState(null, '', url);
242
+ }
243
+ }
244
+
245
+ notifyListeners(currentRoute, prevRoute);
246
+ window.__zenith_route = currentRoute;
247
+ }
248
+
249
+ /**
250
+ * Handle popstate
251
+ */
252
+ function handlePopState() {
253
+ // Don't update history on popstate - browser already changed it
254
+ resolveAndRender(
255
+ window.location.pathname,
256
+ parseQueryString(window.location.search),
257
+ false,
258
+ false
259
+ );
260
+ }
261
+
262
+ /**
263
+ * Navigate (public API)
264
+ */
265
+ function navigate(to, options) {
266
+ options = options || {};
267
+ let path, query = {};
268
+
269
+ if (to.includes('?')) {
270
+ const parts = to.split('?');
271
+ path = parts[0];
272
+ query = parseQueryString('?' + parts[1]);
273
+ } else {
274
+ path = to;
275
+ }
276
+
277
+ if (!path.startsWith('/')) {
278
+ const currentDir = currentRoute.path.split('/').slice(0, -1).join('/');
279
+ path = currentDir + '/' + path;
280
+ }
281
+
282
+ // Normalize path for comparison
283
+ const normalizedPath = path === '' ? '/' : path;
284
+ const currentPath = currentRoute.path === '' ? '/' : currentRoute.path;
285
+
286
+ // Check if we're already on this path
287
+ const isSamePath = normalizedPath === currentPath;
288
+
289
+ // If same path and same query, don't navigate (idempotent)
290
+ if (isSamePath && JSON.stringify(query) === JSON.stringify(currentRoute.query)) {
291
+ return;
292
+ }
293
+
294
+ // Resolve and render with replace option if specified
295
+ resolveAndRender(path, query, true, options.replace || false);
296
+ }
297
+
298
+ /**
299
+ * Get current route
300
+ */
301
+ function getRoute() {
302
+ return { ...currentRoute };
303
+ }
304
+
305
+ /**
306
+ * Subscribe to route changes
307
+ */
308
+ function onRouteChange(listener) {
309
+ routeListeners.add(listener);
310
+ return () => routeListeners.delete(listener);
311
+ }
312
+
313
+ /**
314
+ * Check if path is active
315
+ */
316
+ function isActive(path, exact) {
317
+ if (exact) return currentRoute.path === path;
318
+ return currentRoute.path.startsWith(path);
319
+ }
320
+
321
+ /**
322
+ * Prefetch a route (preload page module)
323
+ */
324
+ const prefetchedRoutes = new Set();
325
+ function prefetch(path) {
326
+ const normalizedPath = path === '' ? '/' : path;
327
+ console.log('[Zenith Router] Prefetch requested for:', normalizedPath);
328
+
329
+ if (prefetchedRoutes.has(normalizedPath)) {
330
+ console.log('[Zenith Router] Route already prefetched:', normalizedPath);
331
+ return Promise.resolve();
332
+ }
333
+ prefetchedRoutes.add(normalizedPath);
334
+
335
+ // Find matching route
336
+ const resolved = resolveRoute(normalizedPath);
337
+ if (!resolved) {
338
+ console.warn('[Zenith Router] Prefetch: No route found for:', normalizedPath);
339
+ return Promise.resolve();
340
+ }
341
+
342
+ console.log('[Zenith Router] Prefetch: Route resolved:', resolved.record.path);
343
+
344
+ // Preload the module if it exists
345
+ if (pageModules[resolved.record.path]) {
346
+ console.log('[Zenith Router] Prefetch: Module already loaded:', resolved.record.path);
347
+ // Module already loaded
348
+ return Promise.resolve();
349
+ }
350
+
351
+ console.log('[Zenith Router] Prefetch: Module not yet loaded (all modules are pre-loaded in SPA build)');
352
+ // In SPA build, all modules are already loaded, so this is a no-op
353
+ // Could prefetch here if we had a way to load modules dynamically
354
+ return Promise.resolve();
355
+ }
356
+
357
+ /**
358
+ * Initialize router
359
+ */
360
+ function initRouter(manifest, modules, outlet) {
361
+ routeManifest = manifest;
362
+ Object.assign(pageModules, modules);
363
+
364
+ if (outlet) {
365
+ routerOutlet = typeof outlet === 'string'
366
+ ? document.querySelector(outlet)
367
+ : outlet;
368
+ }
369
+
370
+ window.addEventListener('popstate', handlePopState);
371
+
372
+ // Initial route resolution
373
+ resolveAndRender(
374
+ window.location.pathname,
375
+ parseQueryString(window.location.search),
376
+ false
377
+ );
378
+ }
379
+
380
+ // Expose router API globally
381
+ window.__zenith_router = {
382
+ navigate,
383
+ getRoute,
384
+ onRouteChange,
385
+ isActive,
386
+ prefetch,
387
+ initRouter
388
+ };
389
+
390
+ // Also expose navigate directly for convenience
391
+ window.navigate = navigate;
392
+
393
+ })();
394
+ `;
395
+ }
396
+ /**
397
+ * Generate the Zen primitives runtime code
398
+ * This makes zen* primitives available globally for auto-imports
399
+ */
400
+ function generateZenPrimitivesRuntime() {
401
+ return `
402
+ // ============================================
403
+ // Zenith Reactivity Primitives Runtime
404
+ // ============================================
405
+ // Auto-imported zen* primitives are resolved from window.__zenith
406
+
407
+ (function() {
408
+ 'use strict';
409
+
410
+ // ============================================
411
+ // Dependency Tracking System
412
+ // ============================================
413
+
414
+ let currentEffect = null;
415
+ const effectStack = [];
416
+ let batchDepth = 0;
417
+ const pendingEffects = new Set();
418
+
419
+ function pushContext(effect) {
420
+ effectStack.push(currentEffect);
421
+ currentEffect = effect;
422
+ }
423
+
424
+ function popContext() {
425
+ currentEffect = effectStack.pop() || null;
426
+ }
427
+
428
+ function trackDependency(subscribers) {
429
+ if (currentEffect) {
430
+ subscribers.add(currentEffect);
431
+ currentEffect.dependencies.add(subscribers);
432
+ }
433
+ }
434
+
435
+ function notifySubscribers(subscribers) {
436
+ const effects = [...subscribers];
437
+ for (const effect of effects) {
438
+ if (batchDepth > 0) {
439
+ pendingEffects.add(effect);
440
+ } else {
441
+ effect.run();
442
+ }
443
+ }
444
+ }
445
+
446
+ function cleanupEffect(effect) {
447
+ for (const deps of effect.dependencies) {
448
+ deps.delete(effect);
449
+ }
450
+ effect.dependencies.clear();
451
+ }
452
+
453
+ // ============================================
454
+ // zenSignal - Atomic reactive value
455
+ // ============================================
456
+
457
+ function zenSignal(initialValue) {
458
+ let value = initialValue;
459
+ const subscribers = new Set();
460
+
461
+ function signal(newValue) {
462
+ if (arguments.length === 0) {
463
+ trackDependency(subscribers);
464
+ return value;
465
+ }
466
+ if (newValue !== value) {
467
+ value = newValue;
468
+ notifySubscribers(subscribers);
469
+ // Bridge to Phase 5 Hydration: Trigger global update
470
+ if (typeof window !== 'undefined' && window.__zenith_update && window.__ZENITH_STATE__) {
471
+ window.__zenith_update(window.__ZENITH_STATE__);
472
+ }
473
+ }
474
+ return value;
475
+ }
476
+
477
+ // Add .value property for Vue/Ref-like usage
478
+ Object.defineProperty(signal, 'value', {
479
+ get() {
480
+ return signal();
481
+ },
482
+ set(newValue) {
483
+ signal(newValue);
484
+ }
485
+ });
486
+
487
+ return signal;
488
+ }
489
+
490
+ // ============================================
491
+ // zenState - Deep reactive object
492
+ // ============================================
493
+
494
+ function zenState(initialObj) {
495
+ const subscribers = new Map(); // path -> Set of effects
496
+
497
+ function getSubscribers(path) {
498
+ if (!subscribers.has(path)) {
499
+ subscribers.set(path, new Set());
500
+ }
501
+ return subscribers.get(path);
502
+ }
503
+
504
+ function createProxy(obj, path = '') {
505
+ if (typeof obj !== 'object' || obj === null) return obj;
506
+
507
+ return new Proxy(obj, {
508
+ get(target, prop) {
509
+ const propPath = path ? path + '.' + String(prop) : String(prop);
510
+ trackDependency(getSubscribers(propPath));
511
+ const value = target[prop];
512
+ if (typeof value === 'object' && value !== null) {
513
+ return createProxy(value, propPath);
514
+ }
515
+ return value;
516
+ },
517
+ set(target, prop, value) {
518
+ const propPath = path ? path + '.' + String(prop) : String(prop);
519
+ target[prop] = value;
520
+ notifySubscribers(getSubscribers(propPath));
521
+ // Also notify parent path for nested updates
522
+ if (path) {
523
+ notifySubscribers(getSubscribers(path));
524
+ }
525
+ return true;
526
+ }
527
+ });
528
+ }
529
+
530
+ return createProxy(initialObj);
531
+ }
532
+
533
+ // ============================================
534
+ // zenEffect - Auto-tracked side effect
535
+ // ============================================
536
+
537
+ function zenEffect(fn) {
538
+ const effect = {
539
+ fn,
540
+ dependencies: new Set(),
541
+ run() {
542
+ cleanupEffect(this);
543
+ pushContext(this);
544
+ try {
545
+ this.fn();
546
+ } finally {
547
+ popContext();
548
+ }
549
+ },
550
+ dispose() {
551
+ cleanupEffect(this);
552
+ }
553
+ };
554
+
555
+ effect.run();
556
+ return () => effect.dispose();
557
+ }
558
+
559
+ // ============================================
560
+ // zenMemo - Cached computed value
561
+ // ============================================
562
+
563
+ function zenMemo(fn) {
564
+ let cachedValue;
565
+ let dirty = true;
566
+ const subscribers = new Set();
567
+
568
+ const effect = {
569
+ dependencies: new Set(),
570
+ run() {
571
+ dirty = true;
572
+ notifySubscribers(subscribers);
573
+ }
574
+ };
575
+
576
+ function compute() {
577
+ if (dirty) {
578
+ cleanupEffect(effect);
579
+ pushContext(effect);
580
+ try {
581
+ cachedValue = fn();
582
+ dirty = false;
583
+ } finally {
584
+ popContext();
585
+ }
586
+ }
587
+ trackDependency(subscribers);
588
+ return cachedValue;
589
+ }
590
+
591
+ return compute;
592
+ }
593
+
594
+ // ============================================
595
+ // zenRef - Non-reactive mutable container
596
+ // ============================================
597
+
598
+ function zenRef(initialValue) {
599
+ return { current: initialValue !== undefined ? initialValue : null };
600
+ }
601
+
602
+ // ============================================
603
+ // zenBatch - Batch updates
604
+ // ============================================
605
+
606
+ function zenBatch(fn) {
607
+ batchDepth++;
608
+ try {
609
+ fn();
610
+ } finally {
611
+ batchDepth--;
612
+ if (batchDepth === 0) {
613
+ const effects = [...pendingEffects];
614
+ pendingEffects.clear();
615
+ for (const effect of effects) {
616
+ effect.run();
617
+ }
618
+ }
619
+ }
620
+ }
621
+
622
+ // ============================================
623
+ // zenUntrack - Read without tracking
624
+ // ============================================
625
+
626
+ function zenUntrack(fn) {
627
+ const prevEffect = currentEffect;
628
+ currentEffect = null;
629
+ try {
630
+ return fn();
631
+ } finally {
632
+ currentEffect = prevEffect;
633
+ }
634
+ }
635
+
636
+ // ============================================
637
+ // Lifecycle Hooks
638
+ // ============================================
639
+
640
+ const mountCallbacks = [];
641
+ const unmountCallbacks = [];
642
+ let isMounted = false;
643
+
644
+ function zenOnMount(fn) {
645
+ if (isMounted) {
646
+ // Already mounted, run immediately
647
+ const cleanup = fn();
648
+ if (typeof cleanup === 'function') {
649
+ unmountCallbacks.push(cleanup);
650
+ }
651
+ } else {
652
+ mountCallbacks.push(fn);
653
+ }
654
+ }
655
+
656
+ function zenOnUnmount(fn) {
657
+ unmountCallbacks.push(fn);
658
+ }
659
+
660
+ // Called by router when page mounts
661
+ function triggerMount() {
662
+ isMounted = true;
663
+ for (const cb of mountCallbacks) {
664
+ const cleanup = cb();
665
+ if (typeof cleanup === 'function') {
666
+ unmountCallbacks.push(cleanup);
667
+ }
668
+ }
669
+ mountCallbacks.length = 0;
670
+ }
671
+
672
+ // Called by router when page unmounts
673
+ function triggerUnmount() {
674
+ isMounted = false;
675
+ for (const cb of unmountCallbacks) {
676
+ try { cb(); } catch(e) { console.error('[Zenith] Unmount error:', e); }
677
+ }
678
+ unmountCallbacks.length = 0;
679
+ }
680
+
681
+ // ============================================
682
+ // Export to window.__zenith
683
+ // ============================================
684
+
685
+ window.__zenith = Object.assign(window.__zenith || {}, {
686
+ // Reactivity primitives
687
+ signal: zenSignal,
688
+ state: zenState,
689
+ effect: zenEffect,
690
+ memo: zenMemo,
691
+ ref: zenRef,
692
+ batch: zenBatch,
693
+ untrack: zenUntrack,
694
+ // Lifecycle
695
+ onMount: zenOnMount,
696
+ onUnmount: zenOnUnmount,
697
+ // Internal hooks for router
698
+ triggerMount,
699
+ triggerUnmount
700
+ });
701
+
702
+ // Also expose with zen* prefix for direct usage
703
+ window.zenSignal = zenSignal;
704
+ window.zenState = zenState;
705
+ window.zenEffect = zenEffect;
706
+ window.zenMemo = zenMemo;
707
+ window.zenRef = zenRef;
708
+ window.zenBatch = zenBatch;
709
+ window.zenUntrack = zenUntrack;
710
+ window.zenOnMount = zenOnMount;
711
+ window.zenOnUnmount = zenOnUnmount;
712
+
713
+ // Clean aliases
714
+ window.signal = zenSignal;
715
+ window.state = zenState;
716
+ window.effect = zenEffect;
717
+ window.memo = zenMemo;
718
+ window.ref = zenRef;
719
+ window.batch = zenBatch;
720
+ window.untrack = zenUntrack;
721
+ window.onMount = zenOnMount;
722
+ window.onUnmount = zenOnUnmount;
723
+
724
+ })();
725
+ `;
726
+ }
727
+ /**
728
+ * Generate the HTML shell
729
+ */
730
+ function generateHTMLShell(pages, layoutStyles) {
731
+ // Collect all global styles (from layouts)
732
+ const globalStyles = layoutStyles.join("\n");
733
+ // Generate route manifest JavaScript
734
+ const manifestJS = pages.map(page => ({
735
+ path: page.routePath,
736
+ regex: page.regex.toString(),
737
+ paramNames: page.paramNames,
738
+ score: page.score,
739
+ filePath: page.filePath
740
+ }));
741
+ // Generate page modules JavaScript
742
+ const modulesJS = pages.map(page => {
743
+ const escapedHtml = JSON.stringify(page.html);
744
+ const escapedScripts = JSON.stringify(page.scripts);
745
+ const escapedStyles = JSON.stringify(page.styles);
746
+ return `${JSON.stringify(page.routePath)}: {
747
+ html: ${escapedHtml},
748
+ scripts: ${escapedScripts},
749
+ styles: ${escapedStyles}
750
+ }`;
751
+ }).join(",\n ");
752
+ // Generate manifest with actual RegExp objects
753
+ const manifestCode = `[
754
+ ${pages.map(page => `{
755
+ path: ${JSON.stringify(page.routePath)},
756
+ regex: ${page.regex.toString()},
757
+ paramNames: ${JSON.stringify(page.paramNames)},
758
+ score: ${page.score}
759
+ }`).join(",\n ")}
760
+ ]`;
761
+ return `<!DOCTYPE html>
762
+ <html lang="en">
763
+ <head>
764
+ <meta charset="UTF-8">
765
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
766
+ <title>Zenith App</title>
767
+ <link rel="icon" type="image/x-icon" href="./favicon.ico">
768
+ <style>
769
+ /* Global/Layout Styles */
770
+ ${globalStyles}
771
+ </style>
772
+ </head>
773
+ <body>
774
+ <!-- Router Outlet -->
775
+ <div id="app"></div>
776
+
777
+ <!-- Zenith Primitives Runtime -->
778
+ <script>
779
+ ${generateZenPrimitivesRuntime()}
780
+ </script>
781
+
782
+ <!-- Zenith Runtime Router -->
783
+ <script>
784
+ ${generateRuntimeRouterCode()}
785
+ </script>
786
+
787
+ <!-- Route Manifest & Page Modules -->
788
+ <script>
789
+ (function() {
790
+ // Route manifest (sorted by score, highest first)
791
+ const manifest = ${manifestCode};
792
+
793
+ // Page modules keyed by route path
794
+ const modules = {
795
+ ${modulesJS}
796
+ };
797
+
798
+ // Initialize router when DOM is ready
799
+ if (document.readyState === 'loading') {
800
+ document.addEventListener('DOMContentLoaded', function() {
801
+ window.__zenith_router.initRouter(manifest, modules, '#app');
802
+ });
803
+ } else {
804
+ window.__zenith_router.initRouter(manifest, modules, '#app');
805
+ }
806
+ })();
807
+ </script>
808
+ </body>
809
+ </html>`;
810
+ }
811
+ /**
812
+ * Build SPA from pages directory
813
+ */
814
+ export async function buildSPA(options) {
815
+ const { pagesDir, outDir, baseDir } = options;
816
+ // Clean output directory
817
+ if (fs.existsSync(outDir)) {
818
+ fs.rmSync(outDir, { recursive: true, force: true });
819
+ }
820
+ fs.mkdirSync(outDir, { recursive: true });
821
+ // Discover all pages
822
+ const pageFiles = discoverPages(pagesDir);
823
+ if (pageFiles.length === 0) {
824
+ console.warn("[Zenith Build] No pages found in", pagesDir);
825
+ return;
826
+ }
827
+ // Compile all pages
828
+ const compiledPages = [];
829
+ const layoutStyles = [];
830
+ for (const pageFile of pageFiles) {
831
+ try {
832
+ const compiled = await compilePage(pageFile, pagesDir);
833
+ compiledPages.push(compiled);
834
+ }
835
+ catch (error) {
836
+ console.error(`[Zenith Build] Error compiling ${pageFile}:`, error);
837
+ throw error;
838
+ }
839
+ }
840
+ // Sort pages by score (highest first)
841
+ compiledPages.sort((a, b) => b.score - a.score);
842
+ // Extract layout styles (they should be global)
843
+ // For now, we'll include any styles from the first page that uses a layout
844
+ // TODO: Better layout handling
845
+ // Generate HTML shell
846
+ const htmlShell = generateHTMLShell(compiledPages, layoutStyles);
847
+ // Write index.html
848
+ fs.writeFileSync(path.join(outDir, "index.html"), htmlShell);
849
+ // Copy favicon if it exists
850
+ const faviconPath = path.join(path.dirname(pagesDir), "favicon.ico");
851
+ if (fs.existsSync(faviconPath)) {
852
+ fs.copyFileSync(faviconPath, path.join(outDir, "favicon.ico"));
853
+ }
854
+ // Log route manifest
855
+ }
856
+ /**
857
+ * Watch mode for development (future)
858
+ */
859
+ export function watchSPA(_options) {
860
+ // TODO: Implement file watching
861
+ }
862
+ //# sourceMappingURL=spa-build.js.map