@zenithbuild/core 0.6.2 → 1.0.1

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 (87) hide show
  1. package/README.md +20 -19
  2. package/cli/commands/add.ts +2 -2
  3. package/cli/commands/build.ts +2 -3
  4. package/cli/commands/dev.ts +182 -103
  5. package/cli/commands/index.ts +1 -1
  6. package/cli/commands/preview.ts +1 -1
  7. package/cli/commands/remove.ts +2 -2
  8. package/cli/index.ts +1 -1
  9. package/cli/main.ts +1 -1
  10. package/cli/utils/logger.ts +1 -1
  11. package/cli/utils/plugin-manager.ts +1 -1
  12. package/cli/utils/project.ts +4 -4
  13. package/core/components/ErrorPage.zen +218 -0
  14. package/core/components/index.ts +15 -0
  15. package/core/config.ts +1 -0
  16. package/core/index.ts +29 -0
  17. package/dist/compiler-native-frej59m4.node +0 -0
  18. package/dist/core/compiler-native-frej59m4.node +0 -0
  19. package/dist/core/index.js +6293 -0
  20. package/dist/runtime/lifecycle/index.js +1 -0
  21. package/dist/runtime/reactivity/index.js +1 -0
  22. package/dist/zen-build.js +7465 -19128
  23. package/dist/zen-dev.js +7465 -19128
  24. package/dist/zen-preview.js +7465 -19128
  25. package/dist/zenith.js +7465 -19128
  26. package/package.json +21 -22
  27. package/cli/utils/content.ts +0 -112
  28. package/compiler/README.md +0 -380
  29. package/compiler/build-analyzer.ts +0 -122
  30. package/compiler/css/index.ts +0 -317
  31. package/compiler/discovery/componentDiscovery.ts +0 -178
  32. package/compiler/discovery/layouts.ts +0 -70
  33. package/compiler/errors/compilerError.ts +0 -56
  34. package/compiler/finalize/finalizeOutput.ts +0 -192
  35. package/compiler/finalize/generateFinalBundle.ts +0 -82
  36. package/compiler/index.ts +0 -83
  37. package/compiler/ir/types.ts +0 -174
  38. package/compiler/output/types.ts +0 -34
  39. package/compiler/parse/detectMapExpressions.ts +0 -102
  40. package/compiler/parse/importTypes.ts +0 -78
  41. package/compiler/parse/parseImports.ts +0 -309
  42. package/compiler/parse/parseScript.ts +0 -46
  43. package/compiler/parse/parseTemplate.ts +0 -599
  44. package/compiler/parse/parseZenFile.ts +0 -66
  45. package/compiler/parse/scriptAnalysis.ts +0 -91
  46. package/compiler/parse/trackLoopContext.ts +0 -82
  47. package/compiler/runtime/dataExposure.ts +0 -317
  48. package/compiler/runtime/generateDOM.ts +0 -246
  49. package/compiler/runtime/generateHydrationBundle.ts +0 -407
  50. package/compiler/runtime/hydration.ts +0 -309
  51. package/compiler/runtime/navigation.ts +0 -432
  52. package/compiler/runtime/thinRuntime.ts +0 -160
  53. package/compiler/runtime/transformIR.ts +0 -370
  54. package/compiler/runtime/wrapExpression.ts +0 -95
  55. package/compiler/runtime/wrapExpressionWithLoop.ts +0 -83
  56. package/compiler/spa-build.ts +0 -917
  57. package/compiler/ssg-build.ts +0 -422
  58. package/compiler/test/validate-test.ts +0 -104
  59. package/compiler/transform/classifyExpression.ts +0 -444
  60. package/compiler/transform/componentResolver.ts +0 -312
  61. package/compiler/transform/componentScriptTransformer.ts +0 -303
  62. package/compiler/transform/expressionTransformer.ts +0 -385
  63. package/compiler/transform/fragmentLowering.ts +0 -634
  64. package/compiler/transform/generateBindings.ts +0 -47
  65. package/compiler/transform/generateHTML.ts +0 -28
  66. package/compiler/transform/layoutProcessor.ts +0 -132
  67. package/compiler/transform/slotResolver.ts +0 -292
  68. package/compiler/transform/transformNode.ts +0 -126
  69. package/compiler/transform/transformTemplate.ts +0 -38
  70. package/compiler/validate/invariants.ts +0 -292
  71. package/compiler/validate/validateExpressions.ts +0 -168
  72. package/core/config/index.ts +0 -16
  73. package/core/config/loader.ts +0 -69
  74. package/core/config/types.ts +0 -89
  75. package/core/plugins/index.ts +0 -7
  76. package/core/plugins/registry.ts +0 -81
  77. package/dist/cli.js +0 -11665
  78. package/router/manifest.ts +0 -314
  79. package/router/navigation/ZenLink.zen +0 -231
  80. package/router/navigation/index.ts +0 -78
  81. package/router/navigation/zen-link.ts +0 -584
  82. package/router/runtime.ts +0 -458
  83. package/router/types.ts +0 -168
  84. package/runtime/build.ts +0 -17
  85. package/runtime/bundle-generator.ts +0 -1247
  86. package/runtime/client-runtime.ts +0 -549
  87. package/runtime/serve.ts +0 -93
@@ -1,1247 +0,0 @@
1
- /**
2
- * Zenith Bundle Generator
3
- *
4
- * Generates the shared client runtime bundle that gets served as:
5
- * - /assets/bundle.js in production
6
- * - /runtime.js in development
7
- *
8
- * This is a cacheable, versioned file that contains:
9
- * - Reactivity primitives (zenSignal, zenState, zenEffect, etc.)
10
- * - Lifecycle hooks (zenOnMount, zenOnUnmount)
11
- * - Hydration functions (zenithHydrate)
12
- * - Event binding utilities
13
- */
14
-
15
- /**
16
- * Generate the complete client runtime bundle
17
- * This is served as an external JS file, not inlined
18
- */
19
- export function generateBundleJS(): string {
20
- return `/*!
21
- * Zenith Runtime v0.1.0
22
- * Shared client-side runtime for hydration and reactivity
23
- */
24
- (function(global) {
25
- 'use strict';
26
-
27
- // ============================================
28
- // Dependency Tracking System
29
- // ============================================
30
-
31
- let currentEffect = null;
32
- const effectStack = [];
33
- let batchDepth = 0;
34
- const pendingEffects = new Set();
35
-
36
- function pushContext(effect) {
37
- effectStack.push(currentEffect);
38
- currentEffect = effect;
39
- }
40
-
41
- function popContext() {
42
- currentEffect = effectStack.pop() || null;
43
- }
44
-
45
- function trackDependency(subscribers) {
46
- if (currentEffect) {
47
- subscribers.add(currentEffect);
48
- currentEffect.dependencies.add(subscribers);
49
- }
50
- }
51
-
52
- function notifySubscribers(subscribers) {
53
- const effects = [...subscribers];
54
- for (const effect of effects) {
55
- if (batchDepth > 0) {
56
- pendingEffects.add(effect);
57
- } else {
58
- effect.run();
59
- }
60
- }
61
- }
62
-
63
- function cleanupEffect(effect) {
64
- for (const deps of effect.dependencies) {
65
- deps.delete(effect);
66
- }
67
- effect.dependencies.clear();
68
- }
69
-
70
- // ============================================
71
- // zenSignal - Atomic reactive value
72
- // ============================================
73
-
74
- function zenSignal(initialValue) {
75
- let value = initialValue;
76
- const subscribers = new Set();
77
-
78
- function signal(newValue) {
79
- if (arguments.length === 0) {
80
- trackDependency(subscribers);
81
- return value;
82
- }
83
- if (newValue !== value) {
84
- value = newValue;
85
- notifySubscribers(subscribers);
86
- }
87
- return value;
88
- }
89
-
90
- return signal;
91
- }
92
-
93
- // ============================================
94
- // zenState - Deep reactive object with Proxy
95
- // ============================================
96
-
97
- function zenState(initialObj) {
98
- const subscribers = new Map();
99
-
100
- function getSubscribers(path) {
101
- if (!subscribers.has(path)) {
102
- subscribers.set(path, new Set());
103
- }
104
- return subscribers.get(path);
105
- }
106
-
107
- function createProxy(obj, path) {
108
- path = path || '';
109
- if (typeof obj !== 'object' || obj === null) return obj;
110
-
111
- return new Proxy(obj, {
112
- get: function(target, prop) {
113
- const propPath = path ? path + '.' + String(prop) : String(prop);
114
- trackDependency(getSubscribers(propPath));
115
- const value = target[prop];
116
- if (typeof value === 'object' && value !== null) {
117
- return createProxy(value, propPath);
118
- }
119
- return value;
120
- },
121
- set: function(target, prop, value) {
122
- const propPath = path ? path + '.' + String(prop) : String(prop);
123
- target[prop] = value;
124
- notifySubscribers(getSubscribers(propPath));
125
- if (path) {
126
- notifySubscribers(getSubscribers(path));
127
- }
128
- return true;
129
- }
130
- });
131
- }
132
-
133
- return createProxy(initialObj);
134
- }
135
-
136
- // ============================================
137
- // zenEffect - Auto-tracked side effect
138
- // ============================================
139
-
140
- function zenEffect(fn) {
141
- const effect = {
142
- fn: fn,
143
- dependencies: new Set(),
144
- run: function() {
145
- cleanupEffect(this);
146
- pushContext(this);
147
- try {
148
- this.fn();
149
- } finally {
150
- popContext();
151
- }
152
- },
153
- dispose: function() {
154
- cleanupEffect(this);
155
- }
156
- };
157
-
158
- effect.run();
159
- return function() { effect.dispose(); };
160
- }
161
-
162
- // ============================================
163
- // zenMemo - Cached computed value
164
- // ============================================
165
-
166
- function zenMemo(fn) {
167
- let cachedValue;
168
- let dirty = true;
169
- const subscribers = new Set();
170
-
171
- const effect = {
172
- dependencies: new Set(),
173
- run: function() {
174
- dirty = true;
175
- notifySubscribers(subscribers);
176
- }
177
- };
178
-
179
- function compute() {
180
- if (dirty) {
181
- cleanupEffect(effect);
182
- pushContext(effect);
183
- try {
184
- cachedValue = fn();
185
- dirty = false;
186
- } finally {
187
- popContext();
188
- }
189
- }
190
- trackDependency(subscribers);
191
- return cachedValue;
192
- }
193
-
194
- return compute;
195
- }
196
-
197
- // ============================================
198
- // zenRef - Non-reactive mutable container
199
- // ============================================
200
-
201
- function zenRef(initialValue) {
202
- return { current: initialValue !== undefined ? initialValue : null };
203
- }
204
-
205
- // ============================================
206
- // zenBatch - Batch updates
207
- // ============================================
208
-
209
- function zenBatch(fn) {
210
- batchDepth++;
211
- try {
212
- fn();
213
- } finally {
214
- batchDepth--;
215
- if (batchDepth === 0) {
216
- const effects = [...pendingEffects];
217
- pendingEffects.clear();
218
- for (const effect of effects) {
219
- effect.run();
220
- }
221
- }
222
- }
223
- }
224
-
225
- // ============================================
226
- // zenUntrack - Read without tracking
227
- // ============================================
228
-
229
- function zenUntrack(fn) {
230
- const prevEffect = currentEffect;
231
- currentEffect = null;
232
- try {
233
- return fn();
234
- } finally {
235
- currentEffect = prevEffect;
236
- }
237
- }
238
-
239
- // ============================================
240
- // Lifecycle Hooks
241
- // ============================================
242
-
243
- const mountCallbacks = [];
244
- const unmountCallbacks = [];
245
- let isMounted = false;
246
-
247
- function zenOnMount(fn) {
248
- if (isMounted) {
249
- const cleanup = fn();
250
- if (typeof cleanup === 'function') {
251
- unmountCallbacks.push(cleanup);
252
- }
253
- } else {
254
- mountCallbacks.push(fn);
255
- }
256
- }
257
-
258
- function zenOnUnmount(fn) {
259
- unmountCallbacks.push(fn);
260
- }
261
-
262
- function triggerMount() {
263
- isMounted = true;
264
- for (let i = 0; i < mountCallbacks.length; i++) {
265
- try {
266
- const cleanup = mountCallbacks[i]();
267
- if (typeof cleanup === 'function') {
268
- unmountCallbacks.push(cleanup);
269
- }
270
- } catch(e) {
271
- console.error('[Zenith] Mount error:', e);
272
- }
273
- }
274
- mountCallbacks.length = 0;
275
- }
276
-
277
- function triggerUnmount() {
278
- isMounted = false;
279
- for (let i = 0; i < unmountCallbacks.length; i++) {
280
- try { unmountCallbacks[i](); } catch(e) { console.error('[Zenith] Unmount error:', e); }
281
- }
282
- unmountCallbacks.length = 0;
283
- }
284
-
285
- // ============================================
286
- // Component Instance System
287
- // ============================================
288
- // Each component instance gets isolated state, effects, and lifecycles
289
- // Instances are tied to DOM elements via hydration markers
290
-
291
- const componentRegistry = {};
292
-
293
- function createComponentInstance(componentName, rootElement) {
294
- const instanceMountCallbacks = [];
295
- const instanceUnmountCallbacks = [];
296
- const instanceEffects = [];
297
- let instanceMounted = false;
298
-
299
- return {
300
- // DOM reference
301
- root: rootElement,
302
-
303
- // Lifecycle hooks (instance-scoped)
304
- onMount: function(fn) {
305
- if (instanceMounted) {
306
- const cleanup = fn();
307
- if (typeof cleanup === 'function') {
308
- instanceUnmountCallbacks.push(cleanup);
309
- }
310
- } else {
311
- instanceMountCallbacks.push(fn);
312
- }
313
- },
314
- onUnmount: function(fn) {
315
- instanceUnmountCallbacks.push(fn);
316
- },
317
-
318
- // Reactivity (uses global primitives but tracks for cleanup)
319
- signal: function(initial) {
320
- return zenSignal(initial);
321
- },
322
- state: function(initial) {
323
- return zenState(initial);
324
- },
325
- ref: function(initial) {
326
- return zenRef(initial);
327
- },
328
- effect: function(fn) {
329
- const cleanup = zenEffect(fn);
330
- instanceEffects.push(cleanup);
331
- return cleanup;
332
- },
333
- memo: function(fn) {
334
- return zenMemo(fn);
335
- },
336
- batch: function(fn) {
337
- zenBatch(fn);
338
- },
339
- untrack: function(fn) {
340
- return zenUntrack(fn);
341
- },
342
-
343
- // Lifecycle execution
344
- mount: function() {
345
- instanceMounted = true;
346
- for (let i = 0; i < instanceMountCallbacks.length; i++) {
347
- try {
348
- const cleanup = instanceMountCallbacks[i]();
349
- if (typeof cleanup === 'function') {
350
- instanceUnmountCallbacks.push(cleanup);
351
- }
352
- } catch(e) {
353
- console.error('[Zenith] Component mount error:', componentName, e);
354
- }
355
- }
356
- instanceMountCallbacks.length = 0;
357
- },
358
- unmount: function() {
359
- instanceMounted = false;
360
- // Cleanup effects
361
- for (let i = 0; i < instanceEffects.length; i++) {
362
- try {
363
- if (typeof instanceEffects[i] === 'function') instanceEffects[i]();
364
- } catch(e) {
365
- console.error('[Zenith] Effect cleanup error:', e);
366
- }
367
- }
368
- instanceEffects.length = 0;
369
- // Run unmount callbacks
370
- for (let i = 0; i < instanceUnmountCallbacks.length; i++) {
371
- try { instanceUnmountCallbacks[i](); } catch(e) { console.error('[Zenith] Unmount error:', e); }
372
- }
373
- instanceUnmountCallbacks.length = 0;
374
- }
375
- };
376
- }
377
-
378
- function defineComponent(name, factory) {
379
- componentRegistry[name] = factory;
380
- }
381
-
382
- function instantiateComponent(name, props, rootElement) {
383
- const factory = componentRegistry[name];
384
- if (!factory) {
385
- console.warn('[Zenith] Component not found:', name);
386
- return null;
387
- }
388
- return factory(props, rootElement);
389
- }
390
-
391
- /**
392
- * Hydrate components by discovering data-zen-component markers
393
- * This is the ONLY place component instantiation should happen
394
- */
395
- function hydrateComponents(container) {
396
- const componentElements = container.querySelectorAll('[data-zen-component]');
397
-
398
- for (let i = 0; i < componentElements.length; i++) {
399
- const el = componentElements[i];
400
- const componentName = el.getAttribute('data-zen-component');
401
-
402
- // Skip if already hydrated
403
- if (el.__zenith_instance) continue;
404
-
405
- // Parse props from data attribute if present
406
- const propsJson = el.getAttribute('data-zen-props') || '{}';
407
- let props = {};
408
- try {
409
- props = JSON.parse(propsJson);
410
- } catch(e) {
411
- console.warn('[Zenith] Invalid props JSON for', componentName);
412
- }
413
-
414
- // Instantiate component and bind to DOM element
415
- const instance = instantiateComponent(componentName, props, el);
416
-
417
- if (instance) {
418
- el.__zenith_instance = instance;
419
- }
420
- }
421
- }
422
-
423
- // ============================================
424
- // Expression Registry & Hydration
425
- // ============================================
426
-
427
- const expressionRegistry = new Map();
428
-
429
- function registerExpression(id, fn) {
430
- expressionRegistry.set(id, fn);
431
- }
432
-
433
- function getExpression(id) {
434
- return expressionRegistry.get(id);
435
- }
436
-
437
- function updateNode(node, exprId, pageState) {
438
- const expr = getExpression(exprId);
439
- if (!expr) return;
440
-
441
- zenEffect(function() {
442
- const result = expr(pageState);
443
-
444
- if (node.hasAttribute('data-zen-text')) {
445
- // Handle complex text/children results
446
- if (result === null || result === undefined || result === false) {
447
- node.textContent = '';
448
- } else if (typeof result === 'string') {
449
- if (result.trim().startsWith('<') && result.trim().endsWith('>')) {
450
- node.innerHTML = result;
451
- } else {
452
- node.textContent = result;
453
- }
454
- } else if (result instanceof Node) {
455
- node.innerHTML = '';
456
- node.appendChild(result);
457
- } else if (Array.isArray(result)) {
458
- node.innerHTML = '';
459
- const fragment = document.createDocumentFragment();
460
- result.flat(Infinity).forEach(item => {
461
- if (item instanceof Node) fragment.appendChild(item);
462
- else if (item != null && item !== false) fragment.appendChild(document.createTextNode(String(item)));
463
- });
464
- node.appendChild(fragment);
465
- } else {
466
- node.textContent = String(result);
467
- }
468
- } else {
469
- // Attribute update
470
- const attrNames = ['class', 'style', 'src', 'href', 'disabled', 'checked'];
471
- for (const attr of attrNames) {
472
- if (node.hasAttribute('data-zen-attr-' + attr)) {
473
- if (attr === 'class' || attr === 'className') {
474
- node.className = String(result || '');
475
- } else if (attr === 'disabled' || attr === 'checked') {
476
- if (result) node.setAttribute(attr, '');
477
- else node.removeAttribute(attr);
478
- } else {
479
- if (result != null && result !== false) node.setAttribute(attr, String(result));
480
- else node.removeAttribute(attr);
481
- }
482
- }
483
- }
484
- }
485
- });
486
- }
487
-
488
- /**
489
- * Hydrate a page with reactive bindings
490
- * Called after page HTML is in DOM
491
- */
492
- function zenithHydrate(pageState, container) {
493
- container = container || document;
494
-
495
- // Find all text expression placeholders
496
- const textNodes = container.querySelectorAll('[data-zen-text]');
497
- textNodes.forEach(el => updateNode(el, el.getAttribute('data-zen-text'), pageState));
498
-
499
- // Find all attribute expression placeholders
500
- const attrNodes = container.querySelectorAll('[data-zen-attr-class], [data-zen-attr-style], [data-zen-attr-src], [data-zen-attr-href]');
501
- attrNodes.forEach(el => {
502
- const attrMatch = Array.from(el.attributes).find(a => a.name.startsWith('data-zen-attr-'));
503
- if (attrMatch) updateNode(el, attrMatch.value, pageState);
504
- });
505
-
506
- // Wire up event handlers
507
- const eventTypes = ['click', 'change', 'input', 'submit', 'focus', 'blur', 'keyup', 'keydown'];
508
- eventTypes.forEach(eventType => {
509
- const elements = container.querySelectorAll('[data-zen-' + eventType + ']');
510
- elements.forEach(el => {
511
- const handlerName = el.getAttribute('data-zen-' + eventType);
512
- if (handlerName && (global[handlerName] || getExpression(handlerName))) {
513
- el.addEventListener(eventType, function(e) {
514
- const handler = global[handlerName] || getExpression(handlerName);
515
- if (typeof handler === 'function') handler(e, el);
516
- });
517
- }
518
- });
519
- });
520
-
521
- // Trigger mount
522
- triggerMount();
523
- }
524
-
525
- // ============================================
526
- // zenith:content - Content Engine
527
- // ============================================
528
-
529
- const schemaRegistry = new Map();
530
- const builtInEnhancers = {
531
- readTime: (item) => {
532
- const wordsPerMinute = 200;
533
- const text = item.content || '';
534
- const wordCount = text.split(/\\s+/).length;
535
- const minutes = Math.ceil(wordCount / wordsPerMinute);
536
- return Object.assign({}, item, { readTime: minutes + ' min' });
537
- },
538
- wordCount: (item) => {
539
- const text = item.content || '';
540
- const wordCount = text.split(/\\s+/).length;
541
- return Object.assign({}, item, { wordCount: wordCount });
542
- }
543
- };
544
-
545
- async function applyEnhancers(item, enhancers) {
546
- let enrichedItem = Object.assign({}, item);
547
- for (const enhancer of enhancers) {
548
- if (typeof enhancer === 'string') {
549
- const fn = builtInEnhancers[enhancer];
550
- if (fn) enrichedItem = await fn(enrichedItem);
551
- } else if (typeof enhancer === 'function') {
552
- enrichedItem = await enhancer(enrichedItem);
553
- }
554
- }
555
- return enrichedItem;
556
- }
557
-
558
- class ZenCollection {
559
- constructor(items) {
560
- this.items = [...items];
561
- this.filters = [];
562
- this.sortField = null;
563
- this.sortOrder = 'desc';
564
- this.limitCount = null;
565
- this.selectedFields = null;
566
- this.enhancers = [];
567
- this._groupByFolder = false;
568
- }
569
- where(fn) { this.filters.push(fn); return this; }
570
- sortBy(field, order = 'desc') { this.sortField = field; this.sortOrder = order; return this; }
571
- limit(n) { this.limitCount = n; return this; }
572
- fields(f) { this.selectedFields = f; return this; }
573
- enhanceWith(e) { this.enhancers.push(e); return this; }
574
- groupByFolder() { this._groupByFolder = true; return this; }
575
- get() {
576
- let results = [...this.items];
577
- for (const filter of this.filters) results = results.filter(filter);
578
- if (this.sortField) {
579
- results.sort((a, b) => {
580
- const valA = a[this.sortField];
581
- const valB = b[this.sortField];
582
- if (valA < valB) return this.sortOrder === 'asc' ? -1 : 1;
583
- if (valA > valB) return this.sortOrder === 'asc' ? 1 : -1;
584
- return 0;
585
- });
586
- }
587
- if (this.limitCount !== null) results = results.slice(0, this.limitCount);
588
-
589
- // Apply enhancers synchronously if possible
590
- if (this.enhancers.length > 0) {
591
- results = results.map(item => {
592
- let enrichedItem = Object.assign({}, item);
593
- for (const enhancer of this.enhancers) {
594
- if (typeof enhancer === 'string') {
595
- const fn = builtInEnhancers[enhancer];
596
- if (fn) enrichedItem = fn(enrichedItem);
597
- } else if (typeof enhancer === 'function') {
598
- enrichedItem = enhancer(enrichedItem);
599
- }
600
- }
601
- return enrichedItem;
602
- });
603
- }
604
-
605
- if (this.selectedFields) {
606
- results = results.map(item => {
607
- const newItem = {};
608
- this.selectedFields.forEach(f => { newItem[f] = item[f]; });
609
- return newItem;
610
- });
611
- }
612
-
613
- // Group by folder if requested
614
- if (this._groupByFolder) {
615
- const groups = {};
616
- const groupOrder = [];
617
- for (const item of results) {
618
- // Extract folder from slug (e.g., "getting-started/installation" -> "getting-started")
619
- const slug = item.slug || item.id || '';
620
- const parts = slug.split('/');
621
- const folder = parts.length > 1 ? parts[0] : 'root';
622
-
623
- if (!groups[folder]) {
624
- groups[folder] = {
625
- id: folder,
626
- title: folder.split('-').map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(' '),
627
- items: []
628
- };
629
- groupOrder.push(folder);
630
- }
631
- groups[folder].items.push(item);
632
- }
633
- return groupOrder.map(f => groups[f]);
634
- }
635
-
636
- return results;
637
- }
638
- }
639
-
640
- function defineSchema(name, schema) { schemaRegistry.set(name, schema); }
641
-
642
- function zenCollection(collectionName) {
643
- const data = (global.__ZENITH_CONTENT__ && global.__ZENITH_CONTENT__[collectionName]) || [];
644
- return new ZenCollection(data);
645
- }
646
-
647
- // ============================================
648
- // useZenOrder - Documentation ordering & navigation
649
- // ============================================
650
-
651
- function slugify(text) {
652
- return String(text || '')
653
- .toLowerCase()
654
- .replace(/[^\\w\\s-]/g, '')
655
- .replace(/\\s+/g, '-')
656
- .replace(/-+/g, '-')
657
- .trim();
658
- }
659
-
660
- function getDocSlug(doc) {
661
- const slugOrId = String(doc.slug || doc.id || '');
662
- const parts = slugOrId.split('/');
663
- const filename = parts[parts.length - 1];
664
- return filename ? slugify(filename) : slugify(doc.title || 'untitled');
665
- }
666
-
667
- function processRawSections(rawSections) {
668
- const sections = (rawSections || []).map(function(rawSection) {
669
- const sectionSlug = slugify(rawSection.title || rawSection.id || 'section');
670
- const items = (rawSection.items || []).map(function(item) {
671
- return Object.assign({}, item, {
672
- slug: getDocSlug(item),
673
- sectionSlug: sectionSlug,
674
- isIntro: item.intro === true || (item.tags && item.tags.includes && item.tags.includes('intro'))
675
- });
676
- });
677
-
678
- // Sort items: intro first, then order, then alphabetical
679
- items.sort(function(a, b) {
680
- if (a.isIntro && !b.isIntro) return -1;
681
- if (!a.isIntro && b.isIntro) return 1;
682
- if (a.order !== undefined && b.order !== undefined) return a.order - b.order;
683
- if (a.order !== undefined) return -1;
684
- if (b.order !== undefined) return 1;
685
- return (a.title || '').localeCompare(b.title || '');
686
- });
687
-
688
- return {
689
- id: rawSection.id || sectionSlug,
690
- title: rawSection.title || 'Untitled',
691
- slug: sectionSlug,
692
- order: rawSection.order !== undefined ? rawSection.order : (rawSection.meta && rawSection.meta.order),
693
- hasIntro: items.some(function(i) { return i.isIntro; }),
694
- items: items
695
- };
696
- });
697
-
698
- // Sort sections: order → hasIntro → alphabetical
699
- sections.sort(function(a, b) {
700
- if (a.order !== undefined && b.order !== undefined) return a.order - b.order;
701
- if (a.order !== undefined) return -1;
702
- if (b.order !== undefined) return 1;
703
- if (a.hasIntro && !b.hasIntro) return -1;
704
- if (!a.hasIntro && b.hasIntro) return 1;
705
- return a.title.localeCompare(b.title);
706
- });
707
-
708
- return sections;
709
- }
710
-
711
- function createZenOrder(rawSections) {
712
- const sections = processRawSections(rawSections);
713
-
714
- return {
715
- sections: sections,
716
- selectedSection: sections[0] || null,
717
- selectedDoc: sections[0] && sections[0].items[0] || null,
718
-
719
- getSectionBySlug: function(sectionSlug) {
720
- return sections.find(function(s) { return s.slug === sectionSlug; }) || null;
721
- },
722
-
723
- getDocBySlug: function(sectionSlug, docSlug) {
724
- var section = sections.find(function(s) { return s.slug === sectionSlug; });
725
- if (!section) return null;
726
- return section.items.find(function(d) { return d.slug === docSlug; }) || null;
727
- },
728
-
729
- getNextDoc: function(currentDoc) {
730
- if (!currentDoc) return null;
731
- var currentSection = sections.find(function(s) { return s.slug === currentDoc.sectionSlug; });
732
- if (!currentSection) return null;
733
- var idx = currentSection.items.findIndex(function(d) { return d.slug === currentDoc.slug; });
734
- if (idx < currentSection.items.length - 1) return currentSection.items[idx + 1];
735
- var secIdx = sections.findIndex(function(s) { return s.slug === currentSection.slug; });
736
- if (secIdx < sections.length - 1) return sections[secIdx + 1].items[0] || null;
737
- return null;
738
- },
739
-
740
- getPrevDoc: function(currentDoc) {
741
- if (!currentDoc) return null;
742
- var currentSection = sections.find(function(s) { return s.slug === currentDoc.sectionSlug; });
743
- if (!currentSection) return null;
744
- var idx = currentSection.items.findIndex(function(d) { return d.slug === currentDoc.slug; });
745
- if (idx > 0) return currentSection.items[idx - 1];
746
- var secIdx = sections.findIndex(function(s) { return s.slug === currentSection.slug; });
747
- if (secIdx > 0) {
748
- var prev = sections[secIdx - 1];
749
- return prev.items[prev.items.length - 1] || null;
750
- }
751
- return null;
752
- },
753
-
754
- buildDocUrl: function(sectionSlug, docSlug) {
755
- if (!docSlug || docSlug === 'index') return '/documentation/' + sectionSlug;
756
- return '/documentation/' + sectionSlug + '/' + docSlug;
757
- }
758
- };
759
- }
760
-
761
- // Virtual DOM Helper for JSX-style expressions
762
- function h(tag, props, children) {
763
- const el = document.createElement(tag);
764
- if (props) {
765
- for (const [key, value] of Object.entries(props)) {
766
- if (key.startsWith('on') && typeof value === 'function') {
767
- el.addEventListener(key.slice(2).toLowerCase(), value);
768
- } else if (key === 'class' || key === 'className') {
769
- el.className = String(value || '');
770
- } else if (key === 'style' && typeof value === 'object') {
771
- Object.assign(el.style, value);
772
- } else if (value != null && value !== false) {
773
- el.setAttribute(key, String(value));
774
- }
775
- }
776
- }
777
- if (children != null && children !== false) {
778
- // Flatten nested arrays (from .map() calls)
779
- const childrenArray = Array.isArray(children) ? children.flat(Infinity) : [children];
780
- for (const child of childrenArray) {
781
- // Skip null, undefined, and false
782
- if (child == null || child === false) continue;
783
-
784
- if (typeof child === 'string') {
785
- // Check if string looks like HTML
786
- if (child.trim().startsWith('<') && child.trim().endsWith('>')) {
787
- // Render as HTML
788
- const wrapper = document.createElement('div');
789
- wrapper.innerHTML = child;
790
- while (wrapper.firstChild) {
791
- el.appendChild(wrapper.firstChild);
792
- }
793
- } else {
794
- el.appendChild(document.createTextNode(child));
795
- }
796
- } else if (typeof child === 'number') {
797
- el.appendChild(document.createTextNode(String(child)));
798
- } else if (child instanceof Node) {
799
- el.appendChild(child);
800
- } else if (Array.isArray(child)) {
801
- // Handle nested arrays (shouldn't happen after flat() but just in case)
802
- for (const c of child) {
803
- if (c instanceof Node) el.appendChild(c);
804
- else if (c != null && c !== false) el.appendChild(document.createTextNode(String(c)));
805
- }
806
- }
807
- }
808
- }
809
- return el;
810
- }
811
-
812
- // ============================================
813
- // Export to window.__zenith
814
- // ============================================
815
-
816
- global.__zenith = {
817
- // Reactivity primitives
818
- signal: zenSignal,
819
- state: zenState,
820
- effect: zenEffect,
821
- memo: zenMemo,
822
- ref: zenRef,
823
- batch: zenBatch,
824
- untrack: zenUntrack,
825
- // zenith:content
826
- defineSchema: defineSchema,
827
- zenCollection: zenCollection,
828
- // useZenOrder hook
829
- createZenOrder: createZenOrder,
830
- processRawSections: processRawSections,
831
- slugify: slugify,
832
- // Virtual DOM helper for JSX
833
- h: h,
834
- // Lifecycle
835
- onMount: zenOnMount,
836
- onUnmount: zenOnUnmount,
837
- // Internal hooks
838
- triggerMount: triggerMount,
839
- triggerUnmount: triggerUnmount,
840
- // Hydration
841
- hydrate: zenithHydrate,
842
- hydrateComponents: hydrateComponents, // Marker-driven component instantiation
843
- registerExpression: registerExpression,
844
- getExpression: getExpression,
845
- // Component instance system
846
- createInstance: createComponentInstance,
847
- defineComponent: defineComponent,
848
- instantiate: instantiateComponent
849
- };
850
-
851
- // Expose with zen* prefix for direct usage
852
- global.zenSignal = zenSignal;
853
- global.zenState = zenState;
854
- global.zenEffect = zenEffect;
855
- global.zenMemo = zenMemo;
856
- global.zenRef = zenRef;
857
- global.zenBatch = zenBatch;
858
- global.zenUntrack = zenUntrack;
859
- global.zenOnMount = zenOnMount;
860
- global.zenOnUnmount = zenOnUnmount;
861
- global.zenithHydrate = zenithHydrate;
862
-
863
- // Clean aliases
864
- global.signal = zenSignal;
865
- global.state = zenState;
866
- global.effect = zenEffect;
867
- global.memo = zenMemo;
868
- global.ref = zenRef;
869
- global.batch = zenBatch;
870
- global.untrack = zenUntrack;
871
- global.onMount = zenOnMount;
872
- global.onUnmount = zenOnUnmount;
873
-
874
- // useZenOrder hook exports
875
- global.createZenOrder = createZenOrder;
876
- global.processRawSections = processRawSections;
877
- global.slugify = slugify;
878
-
879
- // ============================================
880
- // SPA Router Runtime
881
- // ============================================
882
-
883
- (function() {
884
- 'use strict';
885
-
886
- // Current route state
887
- var currentRoute = {
888
- path: '/',
889
- params: {},
890
- query: {}
891
- };
892
-
893
- // Route listeners
894
- var routeListeners = new Set();
895
-
896
- // Router outlet element
897
- var routerOutlet = null;
898
-
899
- // Page modules registry
900
- var pageModules = {};
901
-
902
- // Route manifest
903
- var routeManifest = [];
904
-
905
- /**
906
- * Parse query string
907
- */
908
- function parseQueryString(search) {
909
- var query = {};
910
- if (!search || search === '?') return query;
911
- var params = new URLSearchParams(search);
912
- params.forEach(function(value, key) { query[key] = value; });
913
- return query;
914
- }
915
-
916
- /**
917
- * Resolve route from pathname
918
- */
919
- function resolveRoute(pathname) {
920
- var normalizedPath = pathname === '' ? '/' : pathname;
921
-
922
- for (var i = 0; i < routeManifest.length; i++) {
923
- var route = routeManifest[i];
924
- var match = route.regex.exec(normalizedPath);
925
- if (match) {
926
- var params = {};
927
- for (var j = 0; j < route.paramNames.length; j++) {
928
- var paramValue = match[j + 1];
929
- if (paramValue !== undefined) {
930
- params[route.paramNames[j]] = decodeURIComponent(paramValue);
931
- }
932
- }
933
- return { record: route, params: params };
934
- }
935
- }
936
- return null;
937
- }
938
-
939
- /**
940
- * Clean up previous page
941
- */
942
- function cleanupPreviousPage() {
943
- // Trigger unmount lifecycle hooks
944
- if (global.__zenith && global.__zenith.triggerUnmount) {
945
- global.__zenith.triggerUnmount();
946
- }
947
-
948
- // Remove previous page styles
949
- var prevStyles = document.querySelectorAll('style[data-zen-page-style]');
950
- prevStyles.forEach(function(s) { s.remove(); });
951
-
952
- // Clean up window properties
953
- if (global.__zenith_cleanup) {
954
- global.__zenith_cleanup.forEach(function(key) {
955
- try { delete global[key]; } catch(e) {}
956
- });
957
- }
958
- global.__zenith_cleanup = [];
959
- }
960
-
961
- /**
962
- * Inject styles
963
- */
964
- function injectStyles(styles) {
965
- styles.forEach(function(content, i) {
966
- var style = document.createElement('style');
967
- style.setAttribute('data-zen-page-style', String(i));
968
- style.textContent = content;
969
- document.head.appendChild(style);
970
- });
971
- }
972
-
973
- /**
974
- * Execute scripts
975
- */
976
- function executeScripts(scripts) {
977
- scripts.forEach(function(content) {
978
- try {
979
- var fn = new Function(content);
980
- fn();
981
- } catch (e) {
982
- console.error('[Zenith Router] Script error:', e);
983
- }
984
- });
985
- }
986
-
987
- /**
988
- * Render page
989
- */
990
- function renderPage(pageModule) {
991
- if (!routerOutlet) {
992
- console.warn('[Zenith Router] No router outlet');
993
- return;
994
- }
995
-
996
- cleanupPreviousPage();
997
- routerOutlet.innerHTML = pageModule.html;
998
- injectStyles(pageModule.styles);
999
- executeScripts(pageModule.scripts);
1000
-
1001
- // Trigger mount lifecycle hooks after scripts are executed
1002
- if (global.__zenith && global.__zenith.triggerMount) {
1003
- global.__zenith.triggerMount();
1004
- }
1005
- }
1006
-
1007
- /**
1008
- * Notify listeners
1009
- */
1010
- function notifyListeners(route, prevRoute) {
1011
- routeListeners.forEach(function(listener) {
1012
- try { listener(route, prevRoute); } catch(e) {}
1013
- });
1014
- }
1015
-
1016
- /**
1017
- * Resolve and render
1018
- */
1019
- function resolveAndRender(path, query, updateHistory, replace) {
1020
- replace = replace || false;
1021
- var prevRoute = Object.assign({}, currentRoute);
1022
- var resolved = resolveRoute(path);
1023
-
1024
- if (resolved) {
1025
- currentRoute = {
1026
- path: path,
1027
- params: resolved.params,
1028
- query: query,
1029
- matched: resolved.record
1030
- };
1031
-
1032
- var pageModule = pageModules[resolved.record.path];
1033
- if (pageModule) {
1034
- renderPage(pageModule);
1035
- }
1036
- } else {
1037
- currentRoute = { path: path, params: {}, query: query, matched: undefined };
1038
- console.warn('[Zenith Router] No route matched:', path);
1039
-
1040
- // Render 404 if available
1041
- if (routerOutlet) {
1042
- routerOutlet.innerHTML = '<div style="padding: 2rem; text-align: center;"><h1>404</h1><p>Page not found</p></div>';
1043
- }
1044
- }
1045
-
1046
- if (updateHistory) {
1047
- var url = path + (Object.keys(query).length ? '?' + new URLSearchParams(query) : '');
1048
- if (replace) {
1049
- history.replaceState(null, '', url);
1050
- } else {
1051
- history.pushState(null, '', url);
1052
- }
1053
- }
1054
-
1055
- notifyListeners(currentRoute, prevRoute);
1056
- global.__zenith_route = currentRoute;
1057
- }
1058
-
1059
- /**
1060
- * Handle popstate
1061
- */
1062
- function handlePopState() {
1063
- resolveAndRender(
1064
- location.pathname,
1065
- parseQueryString(location.search),
1066
- false,
1067
- false
1068
- );
1069
- }
1070
-
1071
- /**
1072
- * Navigate (public API)
1073
- */
1074
- function navigate(to, options) {
1075
- options = options || {};
1076
- var path, query = {};
1077
-
1078
- if (to.includes('?')) {
1079
- var parts = to.split('?');
1080
- path = parts[0];
1081
- query = parseQueryString('?' + parts[1]);
1082
- } else {
1083
- path = to;
1084
- }
1085
-
1086
- if (!path.startsWith('/')) {
1087
- var currentDir = currentRoute.path.split('/').slice(0, -1).join('/');
1088
- path = currentDir + '/' + path;
1089
- }
1090
-
1091
- var normalizedPath = path === '' ? '/' : path;
1092
- var currentPath = currentRoute.path === '' ? '/' : currentRoute.path;
1093
- var isSamePath = normalizedPath === currentPath;
1094
-
1095
- if (isSamePath && JSON.stringify(query) === JSON.stringify(currentRoute.query)) {
1096
- return;
1097
- }
1098
-
1099
- resolveAndRender(path, query, true, options.replace || false);
1100
- }
1101
-
1102
- /**
1103
- * Get current route
1104
- */
1105
- function getRoute() {
1106
- return Object.assign({}, currentRoute);
1107
- }
1108
-
1109
- /**
1110
- * Subscribe to route changes
1111
- */
1112
- function onRouteChange(listener) {
1113
- routeListeners.add(listener);
1114
- return function() { routeListeners.delete(listener); };
1115
- }
1116
-
1117
- /**
1118
- * Check if path is active
1119
- */
1120
- function isActive(path, exact) {
1121
- if (exact) return currentRoute.path === path;
1122
- return currentRoute.path.startsWith(path);
1123
- }
1124
-
1125
- /**
1126
- * Prefetch a route
1127
- */
1128
- var prefetchedRoutes = new Set();
1129
- function prefetch(path) {
1130
- var normalizedPath = path === '' ? '/' : path;
1131
-
1132
- if (prefetchedRoutes.has(normalizedPath)) {
1133
- return Promise.resolve();
1134
- }
1135
- prefetchedRoutes.add(normalizedPath);
1136
-
1137
- var resolved = resolveRoute(normalizedPath);
1138
- if (!resolved) {
1139
- return Promise.resolve();
1140
- }
1141
-
1142
- // In SPA build, all modules are already loaded
1143
- return Promise.resolve();
1144
- }
1145
-
1146
- /**
1147
- * Initialize router
1148
- */
1149
- function initRouter(manifest, modules, outlet) {
1150
- routeManifest = manifest;
1151
- Object.assign(pageModules, modules);
1152
-
1153
- if (outlet) {
1154
- routerOutlet = typeof outlet === 'string'
1155
- ? document.querySelector(outlet)
1156
- : outlet;
1157
- }
1158
-
1159
- window.addEventListener('popstate', handlePopState);
1160
-
1161
- // Initial route resolution
1162
- resolveAndRender(
1163
- location.pathname,
1164
- parseQueryString(location.search),
1165
- false
1166
- );
1167
- }
1168
-
1169
- // Expose router API globally
1170
- global.__zenith_router = {
1171
- navigate: navigate,
1172
- getRoute: getRoute,
1173
- onRouteChange: onRouteChange,
1174
- isActive: isActive,
1175
- prefetch: prefetch,
1176
- initRouter: initRouter
1177
- };
1178
-
1179
- // Also expose navigate directly for convenience
1180
- global.navigate = navigate;
1181
- })();
1182
-
1183
- // ============================================
1184
- // HMR Client (Development Only)
1185
- // ============================================
1186
-
1187
- if (typeof window !== 'undefined' && (location.hostname === 'localhost' || location.hostname === '127.0.0.1')) {
1188
- let socket;
1189
- function connectHMR() {
1190
- const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
1191
- socket = new WebSocket(protocol + '//' + location.host + '/hmr');
1192
-
1193
- socket.onmessage = function(event) {
1194
- try {
1195
- const data = JSON.parse(event.data);
1196
- if (data.type === 'reload') {
1197
- console.log('[Zenith] HMR: Reloading page...');
1198
- location.reload();
1199
- } else if (data.type === 'style-update') {
1200
- console.log('[Zenith] HMR: Updating style ' + data.url);
1201
- const links = document.querySelectorAll('link[rel="stylesheet"]');
1202
- for (let i = 0; i < links.length; i++) {
1203
- const link = links[i];
1204
- const url = new URL(link.href);
1205
- if (url.pathname === data.url) {
1206
- link.href = data.url + '?t=' + Date.now();
1207
- break;
1208
- }
1209
- }
1210
- }
1211
- } catch (e) {
1212
- console.error('[Zenith] HMR Error:', e);
1213
- }
1214
- };
1215
-
1216
- socket.onclose = function() {
1217
- console.log('[Zenith] HMR: Connection closed. Retrying in 2s...');
1218
- setTimeout(connectHMR, 2000);
1219
- };
1220
- }
1221
-
1222
- // Connect unless explicitly disabled
1223
- if (!window.__ZENITH_NO_HMR__) {
1224
- connectHMR();
1225
- }
1226
- }
1227
-
1228
- })(typeof window !== 'undefined' ? window : this);
1229
- `
1230
- }
1231
-
1232
- /**
1233
- * Generate a minified version of the bundle
1234
- * For production builds
1235
- */
1236
- export function generateMinifiedBundleJS(): string {
1237
- // For now, return non-minified
1238
- // TODO: Add minification via terser or similar
1239
- return generateBundleJS()
1240
- }
1241
-
1242
- /**
1243
- * Get bundle version for cache busting
1244
- */
1245
- export function getBundleVersion(): string {
1246
- return '0.1.0'
1247
- }