@zenithbuild/bundler 1.3.17 → 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 (48) 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.map +1 -0
  32. package/dist/runtime-generator.d.ts +5 -0
  33. package/dist/runtime-generator.d.ts.map +1 -0
  34. package/dist/runtime-generator.js +21 -0
  35. package/dist/runtime-generator.js.map +1 -0
  36. package/dist/spa-build.d.ts +27 -0
  37. package/dist/spa-build.d.ts.map +1 -0
  38. package/dist/spa-build.js +862 -0
  39. package/dist/spa-build.js.map +1 -0
  40. package/dist/ssg-build.d.ts +32 -0
  41. package/dist/ssg-build.d.ts.map +1 -0
  42. package/dist/ssg-build.js +429 -0
  43. package/dist/ssg-build.js.map +1 -0
  44. package/dist/types.d.ts +6 -0
  45. package/dist/types.d.ts.map +1 -0
  46. package/dist/types.js +2 -0
  47. package/dist/types.js.map +1 -0
  48. package/package.json +2 -1
@@ -0,0 +1,838 @@
1
+ import { readFileSync, existsSync } from 'fs';
2
+ import path from 'path';
3
+ /**
4
+ * Zenith Bundle Generator
5
+ *
6
+ * Generates the shared client runtime bundle that gets served as:
7
+ * - /assets/bundle.js in production
8
+ * - /runtime.js in development
9
+ *
10
+ * This is a cacheable, versioned file that contains:
11
+ * - Reactivity primitives (zenSignal, zenState, zenEffect, etc.)
12
+ * - Lifecycle hooks (zenOnMount, zenOnUnmount)
13
+ * - Hydration functions (zenithHydrate)
14
+ * - Event binding utilities
15
+ */
16
+ /**
17
+ * Generate the complete client runtime bundle
18
+ * This is served as an external JS file, not inlined
19
+ */
20
+ export function generateBundleJS(pluginData) {
21
+ // Serialize plugin data blindly - CLI never inspects what's inside.
22
+ // We escape </script> sequences just in case this bundle is ever inlined (unlikely but safe).
23
+ const serializedData = pluginData
24
+ ? JSON.stringify(pluginData).replace(/<\/script/g, '<\\/script')
25
+ : '{}';
26
+ // Resolve core runtime paths - assumes sibling directory or relative in node_modules
27
+ const rootDir = process.cwd();
28
+ let coreRuntimePath = path.join(rootDir, '../zenith-core/dist/runtime');
29
+ if (!existsSync(coreRuntimePath)) {
30
+ coreRuntimePath = path.join(rootDir, '../zenith-core/core');
31
+ }
32
+ let reactivityJS = '';
33
+ let lifecycleJS = '';
34
+ try {
35
+ let reactivityFile = path.join(coreRuntimePath, 'reactivity/index.js');
36
+ if (!existsSync(reactivityFile))
37
+ reactivityFile = path.join(coreRuntimePath, 'reactivity/index.ts');
38
+ let lifecycleFile = path.join(coreRuntimePath, 'lifecycle/index.js');
39
+ if (!existsSync(lifecycleFile))
40
+ lifecycleFile = path.join(coreRuntimePath, 'lifecycle/index.ts');
41
+ if (existsSync(reactivityFile) && reactivityFile.endsWith('.js')) {
42
+ reactivityJS = transformExportsToGlobal(readFileSync(reactivityFile, 'utf-8'));
43
+ }
44
+ if (existsSync(lifecycleFile) && lifecycleFile.endsWith('.js')) {
45
+ lifecycleJS = transformExportsToGlobal(readFileSync(lifecycleFile, 'utf-8'));
46
+ }
47
+ }
48
+ catch (e) {
49
+ if (process.env.ZENITH_DEBUG === 'true') {
50
+ console.warn('[Zenith] Could not load runtime from core, falling back to internal', e);
51
+ }
52
+ }
53
+ // Fallback to internal hydration_runtime.js from native compiler source
54
+ // Use the compiler's own location to find the file, not process.cwd()
55
+ if (!reactivityJS || !lifecycleJS) {
56
+ // Resolve relative to this bundle-generator.ts file's location
57
+ // In compiled form, this will be in dist/runtime/, so we go up to find native/
58
+ // ADAPTATION: zenith-bundler is sibling to zenith-compiler
59
+ const compilerRoot = path.resolve(path.dirname(import.meta.url.replace('file://', '')), '../../zenith-compiler');
60
+ const nativeRuntimePath = path.join(compilerRoot, 'native/compiler-native/src/hydration_runtime.js');
61
+ if (existsSync(nativeRuntimePath)) {
62
+ const nativeJS = readFileSync(nativeRuntimePath, 'utf-8');
63
+ // IMPORTANT: Include the FULL IIFE - do NOT strip the wrapper!
64
+ // The runtime has its own bootstrap guard and idempotency check.
65
+ // It will install primitives to window and create window.__ZENITH_RUNTIME__
66
+ reactivityJS = nativeJS;
67
+ lifecycleJS = ' '; // Ensure it doesn't trigger the "not found" message
68
+ }
69
+ }
70
+ return `/*!
71
+ * Zenith Runtime v1.0.1
72
+ * Shared client-side runtime for hydration and reactivity
73
+ */
74
+ (function(global) {
75
+ 'use strict';
76
+
77
+ // Initialize plugin data envelope
78
+ global.__ZENITH_PLUGIN_DATA__ = ${serializedData};
79
+
80
+ ${reactivityJS ? ` // ============================================
81
+ // Core Reactivity (Injected from @zenithbuild/core)
82
+ // ============================================
83
+ ${reactivityJS}` : ` // Fallback: Reactivity not found`}
84
+
85
+ ${lifecycleJS ? ` // ============================================
86
+ // Lifecycle Hooks (Injected from @zenithbuild/core)
87
+ // ============================================
88
+ ${lifecycleJS}` : ` // Fallback: Lifecycle not found`}
89
+
90
+ // ----------------------------------------------------------------------
91
+ // COMPAT: Expose internal exports as globals
92
+ // ----------------------------------------------------------------------
93
+ // The code above was stripped of "export { ... }" but assigned to internal variables.
94
+ // We need to map them back to global scope if they weren't attached by the code itself.
95
+
96
+ // Reactivity primitives map (internal name -> global alias)
97
+ // Based on zenith-core/core/reactivity/index.ts re-exports:
98
+ // export { zenSignal, zenState, ... }
99
+
100
+ // Since we stripped exports, we rely on the fact that the bundled code
101
+ // defines variables like "var zenSignal = ..." or "function zenSignal...".
102
+ // Note: Minified code variables might be renamed (e.g., "var P=...").
103
+ // Ideally, @zenithbuild/core should export an IIFE build for this purpose.
104
+ // For now, we assume the code above already does "global.zenSignal = ..."
105
+ // OR we rely on the Aliases section below to do the mapping if the names match.
106
+
107
+ // ============================================
108
+ // Lifecycle Hooks (Required for hydration)
109
+ // ============================================
110
+ // These functions are required by the runtime - define them if not injected from core
111
+
112
+ const mountCallbacks = [];
113
+ const unmountCallbacks = [];
114
+ let isMounted = false;
115
+
116
+ function zenOnMount(fn) {
117
+ if (isMounted) {
118
+ // Already mounted, run immediately
119
+ const cleanup = fn();
120
+ if (typeof cleanup === 'function') {
121
+ unmountCallbacks.push(cleanup);
122
+ }
123
+ } else {
124
+ mountCallbacks.push(fn);
125
+ }
126
+ }
127
+
128
+ function zenOnUnmount(fn) {
129
+ unmountCallbacks.push(fn);
130
+ }
131
+
132
+ // Called by hydration when page mounts
133
+ function triggerMount() {
134
+ isMounted = true;
135
+ for (let i = 0; i < mountCallbacks.length; i++) {
136
+ try {
137
+ const cleanup = mountCallbacks[i]();
138
+ if (typeof cleanup === 'function') {
139
+ unmountCallbacks.push(cleanup);
140
+ }
141
+ } catch(e) {
142
+ console.error('[Zenith] Mount callback error:', e);
143
+ }
144
+ }
145
+ mountCallbacks.length = 0;
146
+ }
147
+
148
+ // Called by router when page unmounts
149
+ function triggerUnmount() {
150
+ isMounted = false;
151
+ for (let i = 0; i < unmountCallbacks.length; i++) {
152
+ try { unmountCallbacks[i](); } catch(e) { console.error('[Zenith] Unmount error:', e); }
153
+ }
154
+ unmountCallbacks.length = 0;
155
+ }
156
+
157
+ // ============================================
158
+ // Component Instance System
159
+ // ============================================
160
+ // Each component instance gets isolated state, effects, and lifecycles
161
+ // Instances are tied to DOM elements via hydration markers
162
+
163
+ const componentRegistry = {};
164
+
165
+ function createComponentInstance(componentName, rootElement) {
166
+ const instanceMountCallbacks = [];
167
+ const instanceUnmountCallbacks = [];
168
+ const instanceEffects = [];
169
+ let instanceMounted = false;
170
+
171
+ return {
172
+ // DOM reference
173
+ root: rootElement,
174
+
175
+ // Lifecycle hooks (instance-scoped)
176
+ onMount: function(fn) {
177
+ if (instanceMounted) {
178
+ const cleanup = fn();
179
+ if (typeof cleanup === 'function') {
180
+ instanceUnmountCallbacks.push(cleanup);
181
+ }
182
+ } else {
183
+ instanceMountCallbacks.push(fn);
184
+ }
185
+ },
186
+ onUnmount: function(fn) {
187
+ instanceUnmountCallbacks.push(fn);
188
+ },
189
+
190
+ // Reactivity (uses global primitives but tracks for cleanup)
191
+ signal: function(initial) {
192
+ return global.zenSignal(initial);
193
+ },
194
+ state: function(initial) {
195
+ return global.zenState(initial);
196
+ },
197
+ ref: function(initial) {
198
+ return global.zenRef(initial);
199
+ },
200
+ effect: function(fn) {
201
+ const cleanup = global.zenEffect(fn);
202
+ instanceEffects.push(cleanup);
203
+ return cleanup;
204
+ },
205
+ memo: function(fn) {
206
+ return global.zenMemo(fn);
207
+ },
208
+ batch: function(fn) {
209
+ global.zenBatch(fn);
210
+ },
211
+ untrack: function(fn) {
212
+ return global.zenUntrack(fn);
213
+ },
214
+
215
+ // Lifecycle execution
216
+ mount: function() {
217
+ instanceMounted = true;
218
+ for (let i = 0; i < instanceMountCallbacks.length; i++) {
219
+ try {
220
+ const cleanup = instanceMountCallbacks[i]();
221
+ if (typeof cleanup === 'function') {
222
+ instanceUnmountCallbacks.push(cleanup);
223
+ }
224
+ } catch(e) {
225
+ console.error('[Zenith] Component mount error:', componentName, e);
226
+ }
227
+ }
228
+ instanceMountCallbacks.length = 0;
229
+ },
230
+ unmount: function() {
231
+ instanceMounted = false;
232
+ // Cleanup effects
233
+ for (let i = 0; i < instanceEffects.length; i++) {
234
+ try {
235
+ if (typeof instanceEffects[i] === 'function') instanceEffects[i]();
236
+ } catch(e) {
237
+ console.error('[Zenith] Effect cleanup error:', e);
238
+ }
239
+ }
240
+ instanceEffects.length = 0;
241
+ // Run unmount callbacks
242
+ for (let i = 0; i < instanceUnmountCallbacks.length; i++) {
243
+ try { instanceUnmountCallbacks[i](); } catch(e) { console.error('[Zenith] Unmount error:', e); }
244
+ }
245
+ instanceUnmountCallbacks.length = 0;
246
+ }
247
+ };
248
+ }
249
+
250
+ function defineComponent(name, factory) {
251
+ componentRegistry[name] = factory;
252
+ }
253
+
254
+ function instantiateComponent(name, props, rootElement) {
255
+ const factory = componentRegistry[name];
256
+ if (!factory) {
257
+ if (name === 'ErrorPage') {
258
+ // Built-in fallback for ErrorPage if not registered by user
259
+ return fallbackErrorPage(props, rootElement);
260
+ }
261
+ console.warn('[Zenith] Component not found:', name);
262
+ return null;
263
+ }
264
+ return factory(props, rootElement);
265
+ }
266
+
267
+ function renderErrorPage(error, metadata) {
268
+ console.error('[Zenith Runtime Error]', error, metadata);
269
+
270
+ // In production, we might want a simpler page, but for now let's use the high-fidelity one
271
+ // if it's available.
272
+ const container = document.getElementById('app') || document.body;
273
+
274
+ // If we've already rendered an error page, don't do it again to avoid infinite loops
275
+ if (window.__ZENITH_ERROR_RENDERED__) return;
276
+ window.__ZENITH_ERROR_RENDERED__ = true;
277
+
278
+ const errorProps = {
279
+ message: error.message || 'Unknown Error',
280
+ stack: error.stack,
281
+ file: metadata.file || (error.file),
282
+ line: metadata.line || (error.line),
283
+ column: metadata.column || (error.column),
284
+ errorType: metadata.errorType || error.name || 'RuntimeError',
285
+ code: metadata.code || 'ERR500',
286
+ context: metadata.context || (metadata.expressionId ? 'Expression: ' + metadata.expressionId : ''),
287
+ hints: metadata.hints || [],
288
+ isProd: false // Check env here if possible
289
+ };
290
+
291
+ // Try to instantiate the user's ErrorPage
292
+ const instance = instantiateComponent('ErrorPage', errorProps, container);
293
+ if (instance) {
294
+ container.innerHTML = '';
295
+ instance.mount();
296
+ } else {
297
+ // Fallback to basic HTML if ErrorPage component fails or is missing
298
+ container.innerHTML = \`
299
+ <div style="padding: 4rem; font-family: system-ui, sans-serif; background: #000; color: #fff; min-h: 100vh;">
300
+ <h1 style="font-size: 3rem; margin-bottom: 1rem; color: #ef4444;">Zenith Runtime Error</h1>
301
+ <p style="font-size: 1.5rem; opacity: 0.8;">\${errorProps.message}</p>
302
+ <pre style="margin-top: 2rem; padding: 1rem; background: #111; border-radius: 8px; overflow: auto; font-size: 0.8rem; color: #888;">\${errorProps.stack}</pre>
303
+ </div>
304
+ \`;
305
+ }
306
+ }
307
+
308
+ function fallbackErrorPage(props, el) {
309
+ // This could be a more complex fallback, but for now we just return null
310
+ // to trigger the basic HTML fallback in renderErrorPage.
311
+ return null;
312
+ }
313
+
314
+ /**
315
+ * Hydrate components by discovering data-zen-component markers
316
+ * This is the ONLY place component instantiation should happen
317
+ */
318
+ function hydrateComponents(container) {
319
+ try {
320
+ const componentElements = container.querySelectorAll('[data-zen-component]');
321
+
322
+ for (let i = 0; i < componentElements.length; i++) {
323
+ const el = componentElements[i];
324
+ const componentName = el.getAttribute('data-zen-component');
325
+
326
+ // Skip if already hydrated OR if handled by instance script (data-zen-inst)
327
+ if (el.__zenith_instance || el.hasAttribute('data-zen-inst')) continue;
328
+
329
+ // Parse props from data attribute if present
330
+ const propsJson = el.getAttribute('data-zen-props') || '{}';
331
+ let props = {};
332
+ try {
333
+ props = JSON.parse(propsJson);
334
+ } catch(e) {
335
+ console.warn('[Zenith] Invalid props JSON for', componentName);
336
+ }
337
+
338
+ try {
339
+ // Instantiate component and bind to DOM element
340
+ const instance = instantiateComponent(componentName, props, el);
341
+
342
+ if (instance) {
343
+ el.__zenith_instance = instance;
344
+ }
345
+ } catch (e) {
346
+ renderErrorPage(e, { component: componentName, props: props });
347
+ }
348
+ }
349
+ } catch (e) {
350
+ renderErrorPage(e, { activity: 'hydrateComponents' });
351
+ }
352
+ }
353
+
354
+ // ============================================
355
+ // Expression Registry & Hydration
356
+ // ============================================
357
+
358
+ const expressionRegistry = new Map();
359
+
360
+ function registerExpression(id, fn) {
361
+ expressionRegistry.set(id, fn);
362
+ }
363
+
364
+ function getExpression(id) {
365
+ return expressionRegistry.get(id);
366
+ }
367
+
368
+ function updateNode(node, exprId, pageState) {
369
+ const expr = getExpression(exprId);
370
+ if (!expr) return;
371
+
372
+ zenEffect(function() {
373
+ try {
374
+ const result = expr(pageState);
375
+
376
+ if (node.hasAttribute('data-zen-text')) {
377
+ // Handle complex text/children results
378
+ if (result === null || result === undefined || result === false) {
379
+ node.textContent = '';
380
+ } else if (typeof result === 'string') {
381
+ if (result.trim().startsWith('<') && result.trim().endsWith('>')) {
382
+ node.innerHTML = result;
383
+ } else {
384
+ node.textContent = result;
385
+ }
386
+ } else if (result instanceof Node) {
387
+ node.innerHTML = '';
388
+ node.appendChild(result);
389
+ } else if (Array.isArray(result)) {
390
+ node.innerHTML = '';
391
+ const fragment = document.createDocumentFragment();
392
+ result.flat(Infinity).forEach(item => {
393
+ if (item instanceof Node) fragment.appendChild(item);
394
+ else if (item != null && item !== false) fragment.appendChild(document.createTextNode(String(item)));
395
+ });
396
+ node.appendChild(fragment);
397
+ } else {
398
+ node.textContent = String(result);
399
+ }
400
+ } else {
401
+ // Attribute update
402
+ const attrNames = ['class', 'style', 'src', 'href', 'disabled', 'checked'];
403
+ for (const attr of attrNames) {
404
+ if (node.hasAttribute('data-zen-attr-' + attr)) {
405
+ if (attr === 'class' || attr === 'className') {
406
+ node.className = String(result || '');
407
+ } else if (attr === 'disabled' || attr === 'checked') {
408
+ if (result) node.setAttribute(attr, '');
409
+ else node.removeAttribute(attr);
410
+ } else {
411
+ if (result != null && result !== false) node.setAttribute(attr, String(result));
412
+ else node.removeAttribute(attr);
413
+ }
414
+ }
415
+ }
416
+ }
417
+ } catch (e) {
418
+ renderErrorPage(e, { expressionId: exprId, node: node });
419
+ }
420
+ });
421
+ }
422
+
423
+ /**
424
+ * Hydrate a page with reactive bindings
425
+ * Called after page HTML is in DOM
426
+ */
427
+ function updateLoopBinding(template, exprId, pageState) {
428
+ const expr = getExpression(exprId);
429
+ if (!expr) return;
430
+
431
+ const itemVar = template.getAttribute('data-zen-item');
432
+ const indexVar = template.getAttribute('data-zen-index');
433
+
434
+ // Use a marker or a container next to the template to hold instances
435
+ let container = template.__zen_container;
436
+ if (!container) {
437
+ container = document.createElement('div');
438
+ container.style.display = 'contents';
439
+ template.parentNode.insertBefore(container, template.nextSibling);
440
+ template.__zen_container = container;
441
+ }
442
+
443
+ zenEffect(function() {
444
+ try {
445
+ const items = expr(pageState);
446
+ if (!Array.isArray(items)) return;
447
+
448
+ // Simple reconciliation: clear and redraw
449
+ container.innerHTML = '';
450
+
451
+ items.forEach(function(item, index) {
452
+ const fragment = template.content.cloneNode(true);
453
+
454
+ // Create child scope
455
+ const childState = Object.assign({}, pageState);
456
+ if (itemVar) childState[itemVar] = item;
457
+ if (indexVar) childState[indexVar] = index;
458
+
459
+ // Recursive hydration for the fragment
460
+ zenithHydrate(childState, fragment);
461
+
462
+ container.appendChild(fragment);
463
+ });
464
+ } catch (e) {
465
+ renderErrorPage(e, { expressionId: exprId, activity: 'loopReconciliation' });
466
+ }
467
+ });
468
+ }
469
+
470
+ /**
471
+ * Hydrate static HTML with dynamic expressions
472
+ */
473
+ /**
474
+ * Hydrate static HTML with dynamic expressions (Comment-based)
475
+ */
476
+ function zenithHydrate(pageState, container) {
477
+ try {
478
+ container = container || document;
479
+
480
+ // Walker to find comment nodes efficiently
481
+ const walker = document.createTreeWalker(
482
+ container,
483
+ NodeFilter.SHOW_COMMENT,
484
+ null,
485
+ false
486
+ );
487
+
488
+ const exprLocationMap = new Map();
489
+ let node;
490
+
491
+ while(node = walker.nextNode()) {
492
+ const content = node.nodeValue || '';
493
+ if (content.startsWith('zen:expr_')) {
494
+ const exprId = content.replace('zen:expr_', '');
495
+ exprLocationMap.set(node, exprId);
496
+ }
497
+ }
498
+
499
+ // Process expressions
500
+ for (const [commentNode, exprId] of exprLocationMap) {
501
+ updateNode(commentNode, exprId, pageState);
502
+ }
503
+
504
+ // Wire up event handlers (still attribute based, usually safe)
505
+ const eventTypes = ['click', 'change', 'input', 'submit', 'focus', 'blur', 'keyup', 'keydown'];
506
+ eventTypes.forEach(eventType => {
507
+ const elements = container.querySelectorAll('[data-zen-' + eventType + ']');
508
+ elements.forEach(el => {
509
+ const handlerName = el.getAttribute('data-zen-' + eventType);
510
+ // Check global scope (window) or expression registry
511
+ if (handlerName) {
512
+ el.addEventListener(eventType, function(e) {
513
+ // Resolve handler at runtime to allow for late definition
514
+ const handler = global[handlerName] || getExpression(handlerName);
515
+ if (typeof handler === 'function') {
516
+ handler(e, el);
517
+ } else {
518
+ console.warn('[Zenith] Handler not found:', handlerName);
519
+ }
520
+ });
521
+ }
522
+ });
523
+ });
524
+
525
+ // Trigger mount
526
+ if (container === document || container.id === 'app' || container.tagName === 'BODY') {
527
+ triggerMount();
528
+ }
529
+ } catch (e) {
530
+ renderErrorPage(e, { activity: 'zenithHydrate' });
531
+ }
532
+ }
533
+
534
+ // Update logic for comment placeholders
535
+ function updateNode(placeholder, exprId, pageState) {
536
+ const expr = getExpression(exprId);
537
+ if (!expr) return;
538
+
539
+ // Store reference to current nodes for cleanup
540
+ let currentNodes = [];
541
+
542
+ zenEffect(function() {
543
+ try {
544
+ const result = expr(pageState);
545
+
546
+ // Cleanup old nodes
547
+ currentNodes.forEach(n => n.remove());
548
+ currentNodes = [];
549
+
550
+ if (result == null || result === false) {
551
+ // Render nothing
552
+ } else if (result instanceof Node) {
553
+ placeholder.parentNode.insertBefore(result, placeholder);
554
+ currentNodes.push(result);
555
+ } else if (Array.isArray(result)) {
556
+ result.flat(Infinity).forEach(item => {
557
+ const n = item instanceof Node ? item : document.createTextNode(String(item));
558
+ placeholder.parentNode.insertBefore(n, placeholder);
559
+ currentNodes.push(n);
560
+ });
561
+ } else {
562
+ // Primitive
563
+ const n = document.createTextNode(String(result));
564
+ placeholder.parentNode.insertBefore(n, placeholder);
565
+ currentNodes.push(n);
566
+ }
567
+ } catch (e) {
568
+ renderErrorPage(e, { expressionId: exprId });
569
+ }
570
+ });
571
+ }
572
+
573
+ // ============================================
574
+ // zenith:content - Content Engine
575
+ // ============================================
576
+
577
+ const schemaRegistry = new Map();
578
+ const builtInEnhancers = {
579
+ readTime: (item) => {
580
+ const wordsPerMinute = 200;
581
+ const text = item.content || '';
582
+ const wordCount = text.split(/\\s+/).length;
583
+ const minutes = Math.ceil(wordCount / wordsPerMinute);
584
+ return Object.assign({}, item, { readTime: minutes + ' min' });
585
+ },
586
+ wordCount: (item) => {
587
+ const text = item.content || '';
588
+ const wordCount = text.split(/\\s+/).length;
589
+ return Object.assign({}, item, { wordCount: wordCount });
590
+ }
591
+ };
592
+
593
+ async function applyEnhancers(item, enhancers) {
594
+ let enrichedItem = Object.assign({}, item);
595
+ for (const enhancer of enhancers) {
596
+ if (typeof enhancer === 'string') {
597
+ const fn = builtInEnhancers[enhancer];
598
+ if (fn) enrichedItem = await fn(enrichedItem);
599
+ } else if (typeof enhancer === 'function') {
600
+ enrichedItem = await enhancer(enrichedItem);
601
+ }
602
+ }
603
+ return enrichedItem;
604
+ }
605
+
606
+ class ZenCollection {
607
+ constructor(items) {
608
+ this.items = [...items];
609
+ this.filters = [];
610
+ this.sortField = null;
611
+ this.sortOrder = 'desc';
612
+ this.limitCount = null;
613
+ this.selectedFields = null;
614
+ this.enhancers = [];
615
+ this._groupByFolder = false;
616
+ }
617
+ where(fn) { this.filters.push(fn); return this; }
618
+ sortBy(field, order = 'desc') { this.sortField = field; this.sortOrder = order; return this; }
619
+ limit(n) { this.limitCount = n; return this; }
620
+ fields(f) { this.selectedFields = f; return this; }
621
+ enhanceWith(e) { this.enhancers.push(e); return this; }
622
+ groupByFolder() { this._groupByFolder = true; return this; }
623
+ get() {
624
+ let results = [...this.items];
625
+ for (const filter of this.filters) results = results.filter(filter);
626
+ if (this.sortField) {
627
+ results.sort((a, b) => {
628
+ const valA = a[this.sortField];
629
+ const valB = b[this.sortField];
630
+ if (valA < valB) return this.sortOrder === 'asc' ? -1 : 1;
631
+ if (valA > valB) return this.sortOrder === 'asc' ? 1 : -1;
632
+ return 0;
633
+ });
634
+ }
635
+ if (this.limitCount !== null) results = results.slice(0, this.limitCount);
636
+
637
+ // Apply enhancers synchronously if possible
638
+ if (this.enhancers.length > 0) {
639
+ results = results.map(item => {
640
+ let enrichedItem = Object.assign({}, item);
641
+ for (const enhancer of this.enhancers) {
642
+ if (typeof enhancer === 'string') {
643
+ const fn = builtInEnhancers[enhancer];
644
+ if (fn) enrichedItem = fn(enrichedItem);
645
+ } else if (typeof enhancer === 'function') {
646
+ enrichedItem = enhancer(enrichedItem);
647
+ }
648
+ }
649
+ return enrichedItem;
650
+ });
651
+ }
652
+
653
+ if (this.selectedFields) {
654
+ results = results.map(item => {
655
+ const newItem = {};
656
+ this.selectedFields.forEach(f => { newItem[f] = item[f]; });
657
+ return newItem;
658
+ });
659
+ }
660
+
661
+ // Group by folder if requested
662
+ if (this._groupByFolder) {
663
+ const groups = {};
664
+ const groupOrder = [];
665
+ for (const item of results) {
666
+ // Extract folder from slug (e.g., "getting-started/installation" -> "getting-started")
667
+ const slug = item.slug || item.id || '';
668
+ const parts = slug.split('/');
669
+ const folder = parts.length > 1 ? parts[0] : 'root';
670
+
671
+ if (!groups[folder]) {
672
+ groups[folder] = {
673
+ id: folder,
674
+ title: folder.split('-').map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(' '),
675
+ items: []
676
+ };
677
+ groupOrder.push(folder);
678
+ }
679
+ groups[folder].items.push(item);
680
+ }
681
+ return groupOrder.map(f => groups[f]);
682
+ }
683
+
684
+ return results;
685
+ }
686
+ }
687
+
688
+ function defineSchema(name, schema) { schemaRegistry.set(name, schema); }
689
+
690
+ function zenCollection(collectionName) {
691
+ // Access plugin data from the neutral envelope
692
+ // Content plugin stores all items under 'content' namespace
693
+ const pluginData = global.__ZENITH_PLUGIN_DATA__ || {};
694
+ const contentItems = pluginData.content || [];
695
+
696
+ // Filter by collection name (plugin owns data structure, runtime just filters)
697
+ const data = Array.isArray(contentItems)
698
+ ? contentItems.filter(item => item && item.collection === collectionName)
699
+ : [];
700
+
701
+ return new ZenCollection(data);
702
+ }
703
+
704
+ // ============================================
705
+ // useZenOrder - Documentation ordering & navigation
706
+ // ============================================
707
+
708
+ function slugify(text) {
709
+ return String(text || '')
710
+ .toLowerCase()
711
+ .replace(/[^\\w\\s-]/g, '')
712
+ .replace(/\\s+/g, '-')
713
+ .replace(/-+/g, '-')
714
+ .trim();
715
+ }
716
+
717
+ function getDocSlug(doc) {
718
+ const slugOrId = String(doc.slug || doc.id || '');
719
+ const parts = slugOrId.split('/');
720
+ const filename = parts[parts.length - 1];
721
+ return filename ? slugify(filename) : slugify(doc.title || 'untitled');
722
+ }
723
+
724
+ function processRawSections(rawSections) {
725
+ const sections = (rawSections || []).map(function(rawSection) {
726
+ const sectionSlug = slugify(rawSection.title || rawSection.id || 'section');
727
+ const items = (rawSection.items || []).map(function(item) {
728
+ return Object.assign({}, item, {
729
+ slug: getDocSlug(item),
730
+ sectionSlug: sectionSlug,
731
+ isIntro: item.intro === true || (item.tags && item.tags.includes && item.tags.includes('intro'))
732
+ });
733
+ });
734
+
735
+ // Sort items: intro first, then order, then alphabetical
736
+ items.sort(function(a, b) {
737
+ if (a.isIntro && !b.isIntro) return -1;
738
+ if (!a.isIntro && b.isIntro) return 1;
739
+ if (a.order !== undefined && b.order !== undefined) return a.order - b.order;
740
+ if (a.order !== undefined) return -1;
741
+ if (b.order !== undefined) return 1;
742
+ return (a.title || '').localeCompare(b.title || '');
743
+ });
744
+
745
+ return {
746
+ id: rawSection.id || sectionSlug,
747
+ title: rawSection.title || 'Untitled',
748
+ slug: sectionSlug,
749
+ order: rawSection.order !== undefined ? rawSection.order : (rawSection.meta && rawSection.meta.order),
750
+ hasIntro: items.some(function(i) { return i.isIntro; }),
751
+ items: items
752
+ };
753
+ });
754
+
755
+ // Sort sections: order → hasIntro → alphabetical
756
+ sections.sort(function(a, b) {
757
+ if (a.order !== undefined && b.order !== undefined) return a.order - b.order;
758
+ if (a.order !== undefined) return -1;
759
+ if (b.order !== undefined) return 1;
760
+ if (a.hasIntro && !b.hasIntro) return -1;
761
+ if (!a.hasIntro && b.hasIntro) return 1;
762
+ return a.title.localeCompare(b.title);
763
+ });
764
+
765
+ return sections;
766
+ }
767
+
768
+ function createZenOrder(rawSections) {
769
+ const sections = processRawSections(rawSections);
770
+
771
+ return {
772
+ sections: sections,
773
+ selectedSection: sections[0] || null,
774
+ selectedDoc: sections[0] && sections[0].items[0] || null,
775
+
776
+ getSectionBySlug: function(sectionSlug) {
777
+ return sections.find(function(s) { return s.slug === sectionSlug; }) || null;
778
+ },
779
+
780
+ getDocBySlug: function(sectionSlug, docSlug) {
781
+ var section = sections.find(function(s) { return s.slug === sectionSlug; });
782
+ if (!section) return null;
783
+ return section.items.find(function(d) { return d.slug === docSlug; }) || null;
784
+ },
785
+
786
+ getNextDoc: function(currentDoc) {
787
+ if (!currentDoc) return null;
788
+ var currentSection = sections.find(function(s) { return s.slug === currentDoc.sectionSlug; });
789
+ if (!currentSection) return null;
790
+ var idx = currentSection.items.findIndex(function(d) { return d.slug === currentDoc.slug; });
791
+ if (idx < currentSection.items.length - 1) return currentSection.items[idx + 1];
792
+ var secIdx = sections.findIndex(function(s) { return s.slug === currentSection.slug; });
793
+ if (secIdx < sections.length - 1) return sections[secIdx + 1].items[0] || null;
794
+ return null;
795
+ },
796
+
797
+ getPrevDoc: function(currentDoc) {
798
+ if (!currentDoc) return null;
799
+ var currentSection = sections.find(function(s) { return s.slug === currentDoc.sectionSlug; });
800
+ if (!currentSection) return null;
801
+ var idx = currentSection.items.findIndex(function(d) { return d.slug === currentDoc.slug; });
802
+ if (idx > 0) return currentSection.items[idx - 1];
803
+ var secIdx = sections.findIndex(function(s) { return s.slug === currentSection.slug; });
804
+ if (secIdx > 0) {
805
+ var prevSec = sections[secIdx - 1];
806
+ return prevSec.items[prevSec.items.length - 1] || null;
807
+ }
808
+ return null;
809
+ }
810
+ };
811
+ }
812
+
813
+ // ============================================
814
+ // Export to global window
815
+ // ============================================
816
+
817
+ global.defineComponent = defineComponent;
818
+ global.hydrateComponents = hydrateComponents;
819
+ global.zenithHydrate = zenithHydrate;
820
+ global.registerExpression = registerExpression;
821
+ global.getExpression = getExpression;
822
+ global.updateNode = updateNode;
823
+ global.updateLoopBinding = updateLoopBinding;
824
+ global.zenCollection = zenCollection;
825
+ global.defineSchema = defineSchema;
826
+ global.createZenOrder = createZenOrder;
827
+
828
+ // Initialize component registry
829
+ global.componentRegistry = componentRegistry;
830
+
831
+ })(typeof window !== 'undefined' ? window : globalThis);
832
+ `;
833
+ }
834
+ // Helpers
835
+ function transformExportsToGlobal(source) {
836
+ return source.replace(/export\s+(const|function|class)\s+(\w+)/g, 'var $2');
837
+ }
838
+ //# sourceMappingURL=bundle-generator.js.map