@zenithbuild/core 0.4.7 → 0.5.0-beta.2.2

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 (110) hide show
  1. package/CORE_CONTRACT.md +143 -0
  2. package/README.md +11 -31
  3. package/bin/zenith.js +68 -0
  4. package/package.json +41 -53
  5. package/src/config.js +134 -0
  6. package/src/core-template.js +30 -0
  7. package/src/errors.js +54 -0
  8. package/src/guards.js +61 -0
  9. package/src/hash.js +52 -0
  10. package/src/index.js +26 -0
  11. package/src/ir/index.js +1 -0
  12. package/src/order.js +69 -0
  13. package/src/path.js +131 -0
  14. package/src/schema.js +28 -0
  15. package/src/version.js +67 -0
  16. package/bin/zen-build.ts +0 -2
  17. package/bin/zen-dev.ts +0 -2
  18. package/bin/zen-preview.ts +0 -2
  19. package/bin/zenith.ts +0 -2
  20. package/cli/commands/add.ts +0 -37
  21. package/cli/commands/build.ts +0 -37
  22. package/cli/commands/create.ts +0 -702
  23. package/cli/commands/dev.ts +0 -335
  24. package/cli/commands/index.ts +0 -112
  25. package/cli/commands/preview.ts +0 -62
  26. package/cli/commands/remove.ts +0 -33
  27. package/cli/index.ts +0 -10
  28. package/cli/main.ts +0 -101
  29. package/cli/utils/branding.ts +0 -178
  30. package/cli/utils/content.ts +0 -112
  31. package/cli/utils/logger.ts +0 -46
  32. package/cli/utils/plugin-manager.ts +0 -114
  33. package/cli/utils/project.ts +0 -77
  34. package/compiler/README.md +0 -380
  35. package/compiler/build-analyzer.ts +0 -122
  36. package/compiler/css/index.ts +0 -317
  37. package/compiler/discovery/componentDiscovery.ts +0 -178
  38. package/compiler/discovery/layouts.ts +0 -70
  39. package/compiler/errors/compilerError.ts +0 -56
  40. package/compiler/finalize/finalizeOutput.ts +0 -192
  41. package/compiler/finalize/generateFinalBundle.ts +0 -82
  42. package/compiler/index.ts +0 -82
  43. package/compiler/ir/types.ts +0 -162
  44. package/compiler/output/types.ts +0 -34
  45. package/compiler/parse/detectMapExpressions.ts +0 -102
  46. package/compiler/parse/parseScript.ts +0 -46
  47. package/compiler/parse/parseTemplate.ts +0 -599
  48. package/compiler/parse/parseZenFile.ts +0 -66
  49. package/compiler/parse/scriptAnalysis.ts +0 -91
  50. package/compiler/parse/trackLoopContext.ts +0 -82
  51. package/compiler/runtime/dataExposure.ts +0 -317
  52. package/compiler/runtime/generateDOM.ts +0 -246
  53. package/compiler/runtime/generateHydrationBundle.ts +0 -407
  54. package/compiler/runtime/hydration.ts +0 -309
  55. package/compiler/runtime/navigation.ts +0 -432
  56. package/compiler/runtime/thinRuntime.ts +0 -160
  57. package/compiler/runtime/transformIR.ts +0 -363
  58. package/compiler/runtime/wrapExpression.ts +0 -95
  59. package/compiler/runtime/wrapExpressionWithLoop.ts +0 -83
  60. package/compiler/spa-build.ts +0 -917
  61. package/compiler/ssg-build.ts +0 -422
  62. package/compiler/test/validate-test.ts +0 -104
  63. package/compiler/transform/classifyExpression.ts +0 -444
  64. package/compiler/transform/componentResolver.ts +0 -312
  65. package/compiler/transform/componentScriptTransformer.ts +0 -147
  66. package/compiler/transform/expressionTransformer.ts +0 -385
  67. package/compiler/transform/fragmentLowering.ts +0 -634
  68. package/compiler/transform/generateBindings.ts +0 -47
  69. package/compiler/transform/generateHTML.ts +0 -28
  70. package/compiler/transform/layoutProcessor.ts +0 -132
  71. package/compiler/transform/slotResolver.ts +0 -292
  72. package/compiler/transform/transformNode.ts +0 -126
  73. package/compiler/transform/transformTemplate.ts +0 -38
  74. package/compiler/validate/invariants.ts +0 -292
  75. package/compiler/validate/validateExpressions.ts +0 -168
  76. package/core/config/index.ts +0 -16
  77. package/core/config/loader.ts +0 -69
  78. package/core/config/types.ts +0 -89
  79. package/core/index.ts +0 -135
  80. package/core/lifecycle/index.ts +0 -49
  81. package/core/lifecycle/zen-mount.ts +0 -182
  82. package/core/lifecycle/zen-unmount.ts +0 -88
  83. package/core/plugins/index.ts +0 -7
  84. package/core/plugins/registry.ts +0 -81
  85. package/core/reactivity/index.ts +0 -54
  86. package/core/reactivity/tracking.ts +0 -167
  87. package/core/reactivity/zen-batch.ts +0 -57
  88. package/core/reactivity/zen-effect.ts +0 -139
  89. package/core/reactivity/zen-memo.ts +0 -146
  90. package/core/reactivity/zen-ref.ts +0 -52
  91. package/core/reactivity/zen-signal.ts +0 -121
  92. package/core/reactivity/zen-state.ts +0 -180
  93. package/core/reactivity/zen-untrack.ts +0 -44
  94. package/dist/cli.js +0 -11659
  95. package/dist/zen-build.js +0 -15633
  96. package/dist/zen-dev.js +0 -15633
  97. package/dist/zen-preview.js +0 -15633
  98. package/dist/zenith.js +0 -15633
  99. package/router/index.ts +0 -76
  100. package/router/manifest.ts +0 -314
  101. package/router/navigation/ZenLink.zen +0 -231
  102. package/router/navigation/index.ts +0 -78
  103. package/router/navigation/zen-link.ts +0 -584
  104. package/router/runtime.ts +0 -458
  105. package/router/types.ts +0 -168
  106. package/runtime/build.ts +0 -17
  107. package/runtime/bundle-generator.ts +0 -943
  108. package/runtime/client-runtime.ts +0 -549
  109. package/runtime/serve.ts +0 -93
  110. package/tsconfig.json +0 -28
@@ -1,943 +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
- // HMR Client (Development Only)
881
- // ============================================
882
-
883
- if (typeof window !== 'undefined' && (location.hostname === 'localhost' || location.hostname === '127.0.0.1')) {
884
- let socket;
885
- function connectHMR() {
886
- const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
887
- socket = new WebSocket(protocol + '//' + location.host + '/hmr');
888
-
889
- socket.onmessage = function(event) {
890
- try {
891
- const data = JSON.parse(event.data);
892
- if (data.type === 'reload') {
893
- console.log('[Zenith] HMR: Reloading page...');
894
- location.reload();
895
- } else if (data.type === 'style-update') {
896
- console.log('[Zenith] HMR: Updating style ' + data.url);
897
- const links = document.querySelectorAll('link[rel="stylesheet"]');
898
- for (let i = 0; i < links.length; i++) {
899
- const link = links[i];
900
- const url = new URL(link.href);
901
- if (url.pathname === data.url) {
902
- link.href = data.url + '?t=' + Date.now();
903
- break;
904
- }
905
- }
906
- }
907
- } catch (e) {
908
- console.error('[Zenith] HMR Error:', e);
909
- }
910
- };
911
-
912
- socket.onclose = function() {
913
- console.log('[Zenith] HMR: Connection closed. Retrying in 2s...');
914
- setTimeout(connectHMR, 2000);
915
- };
916
- }
917
-
918
- // Connect unless explicitly disabled
919
- if (!window.__ZENITH_NO_HMR__) {
920
- connectHMR();
921
- }
922
- }
923
-
924
- })(typeof window !== 'undefined' ? window : this);
925
- `
926
- }
927
-
928
- /**
929
- * Generate a minified version of the bundle
930
- * For production builds
931
- */
932
- export function generateMinifiedBundleJS(): string {
933
- // For now, return non-minified
934
- // TODO: Add minification via terser or similar
935
- return generateBundleJS()
936
- }
937
-
938
- /**
939
- * Get bundle version for cache busting
940
- */
941
- export function getBundleVersion(): string {
942
- return '0.1.0'
943
- }