@coherent.js/fastify 1.0.0-beta.3 → 1.0.0-beta.6

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.
package/dist/index.js CHANGED
@@ -1,1592 +1,8 @@
1
- // ../core/src/core/object-utils.js
2
- function validateComponent(component, path2 = "root") {
3
- if (component === null || component === void 0) {
4
- throw new Error(`Invalid component at ${path2}: null or undefined`);
5
- }
6
- if (["string", "number", "boolean"].includes(typeof component)) {
7
- return true;
8
- }
9
- if (typeof component === "function") {
10
- return true;
11
- }
12
- if (Array.isArray(component)) {
13
- component.forEach((child, index) => {
14
- validateComponent(child, `${path2}[${index}]`);
15
- });
16
- return true;
17
- }
18
- if (typeof component === "object") {
19
- const keys = Object.keys(component);
20
- if (keys.length === 0) {
21
- throw new Error(`Empty object at ${path2}`);
22
- }
23
- keys.forEach((key) => {
24
- const value = component[key];
25
- if (!/^[a-zA-Z][a-zA-Z0-9-]*$/.test(key) && key !== "text") {
26
- console.warn(`Potentially invalid tag name at ${path2}: ${key}`);
27
- }
28
- if (value && typeof value === "object" && !Array.isArray(value)) {
29
- if (value.children) {
30
- validateComponent(value.children, `${path2}.${key}.children`);
31
- }
32
- } else if (value && typeof value !== "string" && typeof value !== "number" && typeof value !== "function") {
33
- throw new Error(`Invalid value type at ${path2}.${key}: ${typeof value}`);
34
- }
35
- });
36
- return true;
37
- }
38
- throw new Error(`Invalid component type at ${path2}: ${typeof component}`);
39
- }
40
- function isCoherentObject(obj) {
41
- if (!obj || typeof obj !== "object" || Array.isArray(obj)) {
42
- return false;
43
- }
44
- const keys = Object.keys(obj);
45
- if (keys.length === 0) {
46
- return false;
47
- }
48
- return keys.every((key) => {
49
- if (key === "text") return true;
50
- return /^[a-zA-Z][a-zA-Z0-9-]*$/.test(key);
51
- });
52
- }
53
- function extractProps(coherentObj) {
54
- if (!isCoherentObject(coherentObj)) {
55
- return {};
56
- }
57
- const props = {};
58
- const keys = Object.keys(coherentObj);
59
- keys.forEach((tag) => {
60
- const value = coherentObj[tag];
61
- if (value && typeof value === "object" && !Array.isArray(value)) {
62
- props[tag] = { ...value };
63
- } else {
64
- props[tag] = { text: value };
65
- }
66
- });
67
- return props;
68
- }
69
- function hasChildren(component) {
70
- if (Array.isArray(component)) {
71
- return component.length > 0;
72
- }
73
- if (isCoherentObject(component)) {
74
- if (component.children !== void 0 && component.children !== null) {
75
- return Array.isArray(component.children) ? component.children.length > 0 : true;
76
- }
77
- const keys = Object.keys(component);
78
- return keys.some((key) => {
79
- const value = component[key];
80
- return value && typeof value === "object" && value.children;
81
- });
82
- }
83
- return false;
84
- }
85
- function normalizeChildren(children) {
86
- if (children === null || children === void 0) {
87
- return [];
88
- }
89
- if (Array.isArray(children)) {
90
- return children.flat().filter((child) => child !== null && child !== void 0);
91
- }
92
- return [children];
93
- }
94
-
95
- // ../core/src/performance/monitor.js
96
- function createPerformanceMonitor(options = {}) {
97
- const opts = {
98
- enabled: true,
99
- metrics: {
100
- custom: {}
101
- },
102
- sampling: {
103
- enabled: false,
104
- rate: 1,
105
- strategy: "random"
106
- },
107
- reporting: {
108
- enabled: false,
109
- interval: 6e4,
110
- format: "json",
111
- batch: {
112
- enabled: false,
113
- maxSize: 100,
114
- flushInterval: 5e3
115
- },
116
- onReport: null
117
- },
118
- alerts: {
119
- enabled: true,
120
- rules: []
121
- },
122
- resources: {
123
- enabled: false,
124
- track: ["memory"],
125
- interval: 1e3
126
- },
127
- profiling: {
128
- enabled: false,
129
- mode: "production",
130
- flamegraph: false,
131
- tracing: {
132
- enabled: false,
133
- sampleRate: 0.01
134
- }
135
- },
136
- ...options
137
- };
138
- opts.reporting.batch = {
139
- enabled: false,
140
- maxSize: 100,
141
- flushInterval: 5e3,
142
- ...options.reporting?.batch || {}
143
- };
144
- const metrics = {
145
- builtin: {
146
- renderTime: { type: "histogram", unit: "ms", values: [] },
147
- componentCount: { type: "counter", unit: "renders", value: 0 },
148
- errorCount: { type: "counter", unit: "errors", value: 0 },
149
- memoryUsage: { type: "gauge", unit: "MB", values: [] }
150
- },
151
- custom: {}
152
- };
153
- Object.entries(opts.metrics.custom).forEach(([name, config]) => {
154
- metrics.custom[name] = {
155
- type: config.type || "counter",
156
- unit: config.unit || "",
157
- threshold: config.threshold,
158
- values: config.type === "histogram" ? [] : void 0,
159
- value: config.type === "counter" || config.type === "gauge" ? 0 : void 0
160
- };
161
- });
162
- const samplingState = {
163
- count: 0,
164
- sampled: 0,
165
- adaptiveRate: opts.sampling.rate
166
- };
167
- const reportingState = {
168
- batch: [],
169
- lastReport: Date.now(),
170
- reportTimer: null,
171
- flushTimer: null
172
- };
173
- const alertState = {
174
- triggered: /* @__PURE__ */ new Map(),
175
- history: []
176
- };
177
- const resourceState = {
178
- samples: [],
179
- timer: null
180
- };
181
- const profilingState = {
182
- traces: [],
183
- flamegraphData: []
184
- };
185
- const stats = {
186
- metricsRecorded: 0,
187
- sampleRate: opts.sampling.rate,
188
- reportsGenerated: 0,
189
- alertsTriggered: 0
190
- };
191
- function shouldSample() {
192
- if (!opts.sampling.enabled) return true;
193
- samplingState.count++;
194
- if (opts.sampling.strategy === "random") {
195
- return Math.random() < samplingState.adaptiveRate;
196
- } else if (opts.sampling.strategy === "deterministic") {
197
- return samplingState.count % Math.ceil(1 / samplingState.adaptiveRate) === 0;
198
- } else if (opts.sampling.strategy === "adaptive") {
199
- const recentRenderTimes = metrics.builtin.renderTime.values.slice(-10);
200
- if (recentRenderTimes.length > 0) {
201
- const avgTime = recentRenderTimes.reduce((a, b) => a + b, 0) / recentRenderTimes.length;
202
- samplingState.adaptiveRate = avgTime > 16 ? Math.min(1, opts.sampling.rate * 2) : opts.sampling.rate;
203
- }
204
- return Math.random() < samplingState.adaptiveRate;
205
- }
206
- return true;
207
- }
208
- function recordMetric(name, value, metadata = {}) {
209
- if (!opts.enabled) return;
210
- if (!shouldSample()) return;
211
- stats.metricsRecorded++;
212
- const builtinMetric = metrics.builtin[name];
213
- if (builtinMetric) {
214
- if (builtinMetric.type === "histogram") {
215
- builtinMetric.values.push(value);
216
- if (builtinMetric.values.length > 1e3) {
217
- builtinMetric.values = builtinMetric.values.slice(-1e3);
218
- }
219
- } else if (builtinMetric.type === "counter") {
220
- builtinMetric.value += value;
221
- } else if (builtinMetric.type === "gauge") {
222
- builtinMetric.values.push(value);
223
- if (builtinMetric.values.length > 100) {
224
- builtinMetric.values = builtinMetric.values.slice(-100);
225
- }
226
- }
227
- }
228
- const customMetric = metrics.custom[name];
229
- if (customMetric) {
230
- if (customMetric.type === "histogram") {
231
- customMetric.values = customMetric.values || [];
232
- customMetric.values.push(value);
233
- if (customMetric.values.length > 1e3) {
234
- customMetric.values = customMetric.values.slice(-1e3);
235
- }
236
- } else if (customMetric.type === "counter") {
237
- customMetric.value = (customMetric.value || 0) + value;
238
- } else if (customMetric.type === "gauge") {
239
- customMetric.values = customMetric.values || [];
240
- customMetric.values.push(value);
241
- if (customMetric.values.length > 100) {
242
- customMetric.values = customMetric.values.slice(-100);
243
- }
244
- }
245
- if (customMetric.threshold) {
246
- const currentValue = customMetric.type === "histogram" || customMetric.type === "gauge" ? customMetric.values[customMetric.values.length - 1] : customMetric.value;
247
- if (currentValue > customMetric.threshold) {
248
- checkAlerts(name, currentValue);
249
- }
250
- }
251
- }
252
- if (opts.reporting.enabled && opts.reporting.batch.enabled) {
253
- reportingState.batch.push({
254
- metric: name,
255
- value,
256
- metadata,
257
- timestamp: Date.now()
258
- });
259
- if (reportingState.batch.length >= opts.reporting.batch.maxSize) {
260
- flushBatch();
261
- }
262
- }
263
- checkAlerts(name, value);
264
- }
265
- function checkAlerts(metric, value) {
266
- if (!opts.alerts.enabled) return;
267
- opts.alerts.rules.forEach((rule) => {
268
- if (rule.metric !== metric) return;
269
- let triggered = false;
270
- if (rule.condition === "exceeds" && value > rule.threshold) {
271
- triggered = true;
272
- } else if (rule.condition === "below" && value < rule.threshold) {
273
- triggered = true;
274
- } else if (rule.condition === "equals" && value === rule.threshold) {
275
- triggered = true;
276
- }
277
- if (triggered) {
278
- const alertKey = `${rule.metric}-${rule.condition}-${rule.threshold}`;
279
- const lastTriggered = alertState.triggered.get(alertKey);
280
- const now = Date.now();
281
- if (!lastTriggered || now - lastTriggered > 5e3) {
282
- alertState.triggered.set(alertKey, now);
283
- alertState.history.push({
284
- rule,
285
- value,
286
- timestamp: now
287
- });
288
- stats.alertsTriggered++;
289
- if (rule.action) {
290
- rule.action(value, rule);
291
- }
292
- }
293
- }
294
- });
295
- }
296
- function flushBatch() {
297
- if (reportingState.batch.length === 0) return;
298
- const batch = [...reportingState.batch];
299
- reportingState.batch = [];
300
- if (opts.reporting.onReport) {
301
- opts.reporting.onReport({ type: "batch", data: batch });
302
- }
303
- }
304
- function generateReport() {
305
- const report = {
306
- timestamp: Date.now(),
307
- statistics: { ...stats },
308
- metrics: {}
309
- };
310
- Object.entries(metrics.builtin).forEach(([name, metric]) => {
311
- if (metric.type === "histogram") {
312
- report.metrics[name] = {
313
- type: "histogram",
314
- unit: metric.unit,
315
- count: metric.values.length,
316
- min: metric.values.length > 0 ? Math.min(...metric.values) : 0,
317
- max: metric.values.length > 0 ? Math.max(...metric.values) : 0,
318
- avg: metric.values.length > 0 ? metric.values.reduce((a, b) => a + b, 0) / metric.values.length : 0,
319
- p50: percentile(metric.values, 0.5),
320
- p95: percentile(metric.values, 0.95),
321
- p99: percentile(metric.values, 0.99)
322
- };
323
- } else if (metric.type === "counter") {
324
- report.metrics[name] = {
325
- type: "counter",
326
- unit: metric.unit,
327
- value: metric.value
328
- };
329
- } else if (metric.type === "gauge") {
330
- report.metrics[name] = {
331
- type: "gauge",
332
- unit: metric.unit,
333
- current: metric.values.length > 0 ? metric.values[metric.values.length - 1] : 0,
334
- avg: metric.values.length > 0 ? metric.values.reduce((a, b) => a + b, 0) / metric.values.length : 0
335
- };
336
- }
337
- });
338
- Object.entries(metrics.custom).forEach(([name, metric]) => {
339
- if (metric.type === "histogram") {
340
- report.metrics[name] = {
341
- type: "histogram",
342
- unit: metric.unit,
343
- count: metric.values?.length || 0,
344
- min: metric.values?.length > 0 ? Math.min(...metric.values) : 0,
345
- max: metric.values?.length > 0 ? Math.max(...metric.values) : 0,
346
- avg: metric.values?.length > 0 ? metric.values.reduce((a, b) => a + b, 0) / metric.values.length : 0,
347
- p95: percentile(metric.values || [], 0.95),
348
- p99: percentile(metric.values || [], 0.99)
349
- };
350
- } else if (metric.type === "counter") {
351
- report.metrics[name] = {
352
- type: "counter",
353
- unit: metric.unit,
354
- value: metric.value || 0
355
- };
356
- } else if (metric.type === "gauge") {
357
- report.metrics[name] = {
358
- type: "gauge",
359
- unit: metric.unit,
360
- current: metric.values?.length > 0 ? metric.values[metric.values.length - 1] : 0,
361
- avg: metric.values?.length > 0 ? metric.values.reduce((a, b) => a + b, 0) / metric.values.length : 0
362
- };
363
- }
364
- });
365
- report.alerts = {
366
- total: alertState.history.length,
367
- recent: alertState.history.slice(-10)
368
- };
369
- if (opts.resources.enabled) {
370
- report.resources = {
371
- samples: resourceState.samples.slice(-20)
372
- };
373
- }
374
- stats.reportsGenerated++;
375
- if (opts.reporting.onReport) {
376
- opts.reporting.onReport({ type: "report", data: report });
377
- }
378
- return report;
379
- }
380
- function percentile(values, p) {
381
- if (values.length === 0) return 0;
382
- const sorted = [...values].sort((a, b) => a - b);
383
- const index = Math.ceil(sorted.length * p) - 1;
384
- return sorted[Math.max(0, index)];
385
- }
386
- function startResourceMonitoring() {
387
- if (!opts.resources.enabled) return;
388
- const collectResources = () => {
389
- const sample = {
390
- timestamp: Date.now()
391
- };
392
- if (opts.resources.track.includes("memory")) {
393
- if (typeof process !== "undefined" && process.memoryUsage) {
394
- const mem = process.memoryUsage();
395
- sample.memory = {
396
- heapUsed: mem.heapUsed / 1024 / 1024,
397
- heapTotal: mem.heapTotal / 1024 / 1024,
398
- external: mem.external / 1024 / 1024,
399
- rss: mem.rss / 1024 / 1024
400
- };
401
- } else if (typeof performance !== "undefined" && performance.memory) {
402
- sample.memory = {
403
- heapUsed: performance.memory.usedJSHeapSize / 1024 / 1024,
404
- heapTotal: performance.memory.totalJSHeapSize / 1024 / 1024
405
- };
406
- }
407
- }
408
- resourceState.samples.push(sample);
409
- if (resourceState.samples.length > 100) {
410
- resourceState.samples = resourceState.samples.slice(-100);
411
- }
412
- resourceState.timer = setTimeout(collectResources, opts.resources.interval);
413
- };
414
- collectResources();
415
- }
416
- function stopResourceMonitoring() {
417
- if (resourceState.timer) {
418
- clearTimeout(resourceState.timer);
419
- resourceState.timer = null;
420
- }
421
- }
422
- function startReporting() {
423
- if (!opts.reporting.enabled) return;
424
- reportingState.reportTimer = setInterval(() => {
425
- generateReport();
426
- }, opts.reporting.interval);
427
- if (opts.reporting.batch.enabled) {
428
- reportingState.flushTimer = setInterval(() => {
429
- flushBatch();
430
- }, opts.reporting.batch.flushInterval);
431
- }
432
- }
433
- function stopReporting() {
434
- if (reportingState.reportTimer) {
435
- clearInterval(reportingState.reportTimer);
436
- reportingState.reportTimer = null;
437
- }
438
- if (reportingState.flushTimer) {
439
- clearInterval(reportingState.flushTimer);
440
- reportingState.flushTimer = null;
441
- }
442
- flushBatch();
443
- }
444
- function startProfiling() {
445
- if (!opts.profiling.enabled) return;
446
- }
447
- function recordTrace(name, duration, metadata = {}) {
448
- if (!opts.profiling.enabled || !opts.profiling.tracing.enabled) return;
449
- if (Math.random() < opts.profiling.tracing.sampleRate) {
450
- profilingState.traces.push({
451
- name,
452
- duration,
453
- metadata,
454
- timestamp: Date.now()
455
- });
456
- if (profilingState.traces.length > 1e3) {
457
- profilingState.traces = profilingState.traces.slice(-1e3);
458
- }
459
- }
460
- }
461
- function measure(name, fn, metadata = {}) {
462
- if (!opts.enabled) return fn();
463
- const start = performance.now();
464
- try {
465
- const result = fn();
466
- const duration = performance.now() - start;
467
- recordMetric("renderTime", duration, { name, ...metadata });
468
- recordTrace(name, duration, metadata);
469
- return result;
470
- } catch (error) {
471
- recordMetric("errorCount", 1, { name, error: error.message });
472
- throw error;
473
- }
474
- }
475
- async function measureAsync(name, fn, metadata = {}) {
476
- if (!opts.enabled) return fn();
477
- const start = performance.now();
478
- try {
479
- const result = await fn();
480
- const duration = performance.now() - start;
481
- recordMetric("renderTime", duration, { name, ...metadata });
482
- recordTrace(name, duration, metadata);
483
- return result;
484
- } catch (error) {
485
- recordMetric("errorCount", 1, { name, error: error.message });
486
- throw error;
487
- }
488
- }
489
- function addMetric(name, config) {
490
- metrics.custom[name] = {
491
- type: config.type || "counter",
492
- unit: config.unit || "",
493
- threshold: config.threshold,
494
- values: config.type === "histogram" ? [] : void 0,
495
- value: config.type === "counter" || config.type === "gauge" ? 0 : void 0
496
- };
497
- }
498
- function addAlertRule(rule) {
499
- opts.alerts.rules.push(rule);
500
- }
501
- function getStats() {
502
- return {
503
- ...stats,
504
- sampleRate: samplingState.adaptiveRate,
505
- batchSize: reportingState.batch.length,
506
- resourceSamples: resourceState.samples.length,
507
- traces: profilingState.traces.length,
508
- alerts: {
509
- total: alertState.history.length,
510
- unique: alertState.triggered.size
511
- }
512
- };
513
- }
514
- function reset() {
515
- Object.values(metrics.builtin).forEach((metric) => {
516
- if (metric.type === "histogram" || metric.type === "gauge") {
517
- metric.values = [];
518
- } else if (metric.type === "counter") {
519
- metric.value = 0;
520
- }
521
- });
522
- Object.values(metrics.custom).forEach((metric) => {
523
- if (metric.type === "histogram" || metric.type === "gauge") {
524
- metric.values = [];
525
- } else if (metric.type === "counter") {
526
- metric.value = 0;
527
- }
528
- });
529
- samplingState.count = 0;
530
- samplingState.sampled = 0;
531
- reportingState.batch = [];
532
- alertState.history = [];
533
- alertState.triggered.clear();
534
- resourceState.samples = [];
535
- profilingState.traces = [];
536
- stats.metricsRecorded = 0;
537
- stats.reportsGenerated = 0;
538
- stats.alertsTriggered = 0;
539
- }
540
- if (opts.enabled) {
541
- startResourceMonitoring();
542
- startReporting();
543
- startProfiling();
544
- }
545
- return {
546
- recordMetric,
547
- measure,
548
- measureAsync,
549
- addMetric,
550
- addAlertRule,
551
- generateReport,
552
- getStats,
553
- reset,
554
- start() {
555
- opts.enabled = true;
556
- startResourceMonitoring();
557
- startReporting();
558
- startProfiling();
559
- },
560
- stop() {
561
- opts.enabled = false;
562
- stopResourceMonitoring();
563
- stopReporting();
564
- return generateReport();
565
- }
566
- };
567
- }
568
- var performanceMonitor = createPerformanceMonitor();
569
-
570
- // ../core/src/rendering/base-renderer.js
571
- var DEFAULT_RENDERER_CONFIG = {
572
- // Core rendering options
573
- maxDepth: 100,
574
- enableValidation: true,
575
- enableMonitoring: false,
576
- validateInput: true,
577
- // HTML Renderer specific options
578
- enableCache: true,
579
- minify: false,
580
- cacheSize: 1e3,
581
- cacheTTL: 3e5,
582
- // 5 minutes
583
- // Streaming Renderer specific options
584
- chunkSize: 1024,
585
- // Size of each chunk in bytes
586
- bufferSize: 4096,
587
- // Internal buffer size
588
- enableMetrics: false,
589
- // Track streaming metrics
590
- yieldThreshold: 100,
591
- // Yield control after N elements
592
- encoding: "utf8",
593
- // Output encoding
594
- // DOM Renderer specific options
595
- enableHydration: true,
596
- // Enable hydration support
597
- namespace: null,
598
- // SVG namespace support
599
- // Performance options
600
- enablePerformanceTracking: false,
601
- performanceThreshold: 10,
602
- // ms threshold for slow renders
603
- // Development options
604
- enableDevWarnings: typeof process !== "undefined" && process.env && true,
605
- enableDebugLogging: false,
606
- // Error handling options
607
- errorFallback: "",
608
- // Fallback content on errors
609
- throwOnError: true
610
- // Whether to throw or return fallback
611
- };
612
- var BaseRenderer = class {
613
- constructor(options = {}) {
614
- this.config = this.validateAndMergeConfig(options);
615
- this.metrics = {
616
- startTime: null,
617
- endTime: null,
618
- elementsProcessed: 0
619
- };
620
- }
621
- /**
622
- * Validate and merge configuration options
623
- */
624
- validateAndMergeConfig(options) {
625
- const config = { ...DEFAULT_RENDERER_CONFIG, ...options };
626
- if (typeof config.maxDepth !== "number") {
627
- throw new Error("maxDepth must be a number");
628
- }
629
- if (config.maxDepth <= 0) {
630
- throw new Error("maxDepth must be a positive number");
631
- }
632
- if (typeof config.chunkSize !== "number") {
633
- throw new Error("chunkSize must be a number");
634
- }
635
- if (config.chunkSize <= 0) {
636
- throw new Error("chunkSize must be a positive number");
637
- }
638
- if (typeof config.yieldThreshold !== "number") {
639
- throw new Error("yieldThreshold must be a number");
640
- }
641
- if (config.yieldThreshold <= 0) {
642
- throw new Error("yieldThreshold must be a positive number");
643
- }
644
- if (config.enableDevWarnings) {
645
- if (config.maxDepth > 1e3) {
646
- console.warn("Coherent.js: maxDepth > 1000 may cause performance issues");
647
- }
648
- if (config.chunkSize > 16384) {
649
- console.warn("Coherent.js: Large chunkSize may increase memory usage");
650
- }
651
- }
652
- return config;
653
- }
654
- /**
655
- * Get configuration for specific renderer type
656
- */
657
- getRendererConfig(rendererType) {
658
- const baseConfig = { ...this.config };
659
- switch (rendererType) {
660
- case "html":
661
- return {
662
- ...baseConfig,
663
- // HTML-specific defaults
664
- enableCache: baseConfig.enableCache !== false,
665
- enableMonitoring: baseConfig.enableMonitoring !== false
666
- };
667
- case "streaming":
668
- return {
669
- ...baseConfig,
670
- // Streaming-specific defaults
671
- enableMetrics: baseConfig.enableMetrics ?? false,
672
- maxDepth: baseConfig.maxDepth ?? 1e3
673
- // Higher default for streaming
674
- };
675
- case "dom":
676
- return {
677
- ...baseConfig,
678
- // DOM-specific defaults
679
- enableHydration: baseConfig.enableHydration !== false
680
- };
681
- default:
682
- return baseConfig;
683
- }
684
- }
685
- /**
686
- * Validate component structure
687
- */
688
- validateComponent(component) {
689
- if (this.config.validateInput !== false) {
690
- return validateComponent(component);
691
- }
692
- return true;
693
- }
694
- /**
695
- * Check if component is valid for rendering
696
- */
697
- isValidComponent(component) {
698
- if (component === null || component === void 0) return true;
699
- if (typeof component === "string" || typeof component === "number") return true;
700
- if (typeof component === "function") return true;
701
- if (Array.isArray(component)) return component.every((child) => this.isValidComponent(child));
702
- if (isCoherentObject(component)) return true;
703
- return false;
704
- }
705
- /**
706
- * Validate rendering depth to prevent stack overflow
707
- */
708
- validateDepth(depth) {
709
- if (depth > this.config.maxDepth) {
710
- throw new Error(`Maximum render depth (${this.config.maxDepth}) exceeded`);
711
- }
712
- }
713
- /**
714
- * Handle different component types with consistent logic
715
- */
716
- processComponentType(component) {
717
- if (component === null || component === void 0) {
718
- return { type: "empty", value: "" };
719
- }
720
- if (typeof component === "string") {
721
- return { type: "text", value: component };
722
- }
723
- if (typeof component === "number" || typeof component === "boolean") {
724
- return { type: "text", value: String(component) };
725
- }
726
- if (typeof component === "function") {
727
- return { type: "function", value: component };
728
- }
729
- if (Array.isArray(component)) {
730
- return { type: "array", value: component };
731
- }
732
- if (isCoherentObject(component)) {
733
- return { type: "element", value: component };
734
- }
735
- return { type: "unknown", value: component };
736
- }
737
- /**
738
- * Execute function components with _error handling
739
- */
740
- executeFunctionComponent(func, depth = 0) {
741
- try {
742
- const isContextProvider = func.length > 0 || func.isContextProvider;
743
- let result;
744
- if (isContextProvider) {
745
- result = func((children) => {
746
- return this.renderComponent(children, this.config, depth + 1);
747
- });
748
- } else {
749
- result = func();
750
- }
751
- if (typeof result === "function") {
752
- return this.executeFunctionComponent(result, depth);
753
- }
754
- return result;
755
- } catch (_error) {
756
- if (this.config.enableMonitoring) {
757
- performanceMonitor.recordError("functionComponent", _error);
758
- }
759
- if (typeof process !== "undefined" && process.env && true) {
760
- console.warn("Coherent.js Function Component Error:", _error.message);
761
- }
762
- return null;
763
- }
764
- }
765
- /**
766
- * Process element children consistently
767
- */
768
- processChildren(children, options, depth) {
769
- if (!hasChildren({ children })) {
770
- return [];
771
- }
772
- const normalizedChildren = normalizeChildren(children);
773
- return normalizedChildren.map(
774
- (child) => this.renderComponent(child, options, depth + 1)
775
- );
776
- }
777
- /**
778
- * Extract and process element attributes
779
- */
780
- extractElementAttributes(props) {
781
- if (!props || typeof props !== "object") return {};
782
- const attributes = { ...props };
783
- delete attributes.children;
784
- delete attributes.text;
785
- return attributes;
786
- }
787
- /**
788
- * Record performance metrics
789
- */
790
- recordPerformance(operation, startTime, fromCache = false, metadata = {}) {
791
- if (this.config.enableMonitoring) {
792
- performanceMonitor.recordRender(
793
- operation,
794
- this.getCurrentTime() - startTime,
795
- fromCache,
796
- metadata
797
- );
798
- }
799
- }
800
- /**
801
- * Record _error for monitoring
802
- */
803
- recordError(operation, _error, metadata = {}) {
804
- if (this.config.enableMonitoring) {
805
- performanceMonitor.recordError(operation, _error, metadata);
806
- }
807
- }
808
- /**
809
- * Get current timestamp with fallback
810
- */
811
- getCurrentTime() {
812
- if (typeof performance !== "undefined" && performance.now) {
813
- return performance.now();
814
- }
815
- return Date.now();
816
- }
817
- /**
818
- * Start performance timing
819
- */
820
- startTiming() {
821
- this.metrics.startTime = this.getCurrentTime();
822
- }
823
- /**
824
- * End performance timing
825
- */
826
- endTiming() {
827
- this.metrics.endTime = this.getCurrentTime();
828
- }
829
- /**
830
- * Get performance metrics
831
- */
832
- getMetrics() {
833
- const duration = this.metrics.endTime ? this.metrics.endTime - this.metrics.startTime : this.getCurrentTime() - this.metrics.startTime;
834
- return {
835
- ...this.metrics,
836
- duration,
837
- elementsPerSecond: this.metrics.elementsProcessed / (duration / 1e3)
838
- };
839
- }
840
- /**
841
- * Reset metrics for new render
842
- */
843
- resetMetrics() {
844
- this.metrics = {
845
- startTime: null,
846
- endTime: null,
847
- elementsProcessed: 0
848
- };
849
- }
850
- /**
851
- * Abstract method - must be implemented by subclasses
852
- */
853
- renderComponent() {
854
- throw new Error("renderComponent must be implemented by subclass");
855
- }
856
- /**
857
- * Abstract method - must be implemented by subclasses
858
- */
859
- render() {
860
- throw new Error("render must be implemented by subclass");
861
- }
862
- };
863
- var RendererUtils = {
864
- /**
865
- * Check if element is static (no functions)
866
- */
867
- isStaticElement(element) {
868
- if (!element || typeof element !== "object") {
869
- return typeof element === "string" || typeof element === "number";
870
- }
871
- for (const [key, value] of Object.entries(element)) {
872
- if (typeof value === "function") return false;
873
- if (key === "children" && Array.isArray(value)) {
874
- return value.every((child) => RendererUtils.isStaticElement(child));
875
- }
876
- if (key === "children" && typeof value === "object" && value !== null) {
877
- return RendererUtils.isStaticElement(value);
878
- }
879
- }
880
- return true;
881
- },
882
- /**
883
- * Check if object has functions (for caching decisions)
884
- */
885
- hasFunctions(obj, visited = /* @__PURE__ */ new WeakSet()) {
886
- if (visited.has(obj)) return false;
887
- visited.add(obj);
888
- for (const value of Object.values(obj)) {
889
- if (typeof value === "function") return true;
890
- if (typeof value === "object" && value !== null && RendererUtils.hasFunctions(value, visited)) {
891
- return true;
892
- }
893
- }
894
- return false;
895
- },
896
- /**
897
- * Get element complexity score
898
- */
899
- getElementComplexity(element) {
900
- if (!element || typeof element !== "object") return 1;
901
- let complexity = Object.keys(element).length;
902
- if (element.children && Array.isArray(element.children)) {
903
- complexity += element.children.reduce(
904
- (sum, child) => sum + RendererUtils.getElementComplexity(child),
905
- 0
906
- );
907
- }
908
- return complexity;
909
- },
910
- /**
911
- * Generate cache key for element
912
- */
913
- generateCacheKey(tagName, element) {
914
- try {
915
- const keyData = {
916
- tag: tagName,
917
- props: extractProps(element),
918
- hasChildren: hasChildren(element),
919
- childrenType: Array.isArray(element.children) ? "array" : typeof element.children
920
- };
921
- return `element:${JSON.stringify(keyData)}`;
922
- } catch (_error) {
923
- if (typeof process !== "undefined" && process.env && true) {
924
- console.warn("Failed to generate cache key:", _error);
925
- }
926
- return null;
927
- }
928
- },
929
- /**
930
- * Check if element is cacheable
931
- */
932
- isCacheable(element, options) {
933
- if (!options.enableCache) return false;
934
- if (RendererUtils.hasFunctions(element)) return false;
935
- if (RendererUtils.getElementComplexity(element) > 1e3) return false;
936
- const cacheKey = RendererUtils.generateCacheKey(element.tagName || "unknown", element);
937
- if (!cacheKey) return false;
938
- return true;
939
- }
940
- };
941
-
942
- // ../core/src/core/html-utils.js
943
- function escapeHtml(text) {
944
- if (typeof text !== "string") return text;
945
- return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
946
- }
947
- function isVoidElement(tagName) {
948
- if (typeof tagName !== "string") {
949
- return false;
950
- }
951
- const voidElements = /* @__PURE__ */ new Set([
952
- "area",
953
- "base",
954
- "br",
955
- "col",
956
- "embed",
957
- "hr",
958
- "img",
959
- "input",
960
- "link",
961
- "meta",
962
- "param",
963
- "source",
964
- "track",
965
- "wbr"
966
- ]);
967
- return voidElements.has(tagName.toLowerCase());
968
- }
969
- function formatAttributes(props) {
970
- let formatted = "";
971
- for (const key in props) {
972
- if (props.hasOwnProperty(key)) {
973
- let value = props[key];
974
- const attributeName = key === "className" ? "class" : key;
975
- if (typeof value === "function") {
976
- if (attributeName.startsWith("on")) {
977
- const actionId = `__coherent_action_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
978
- const DEBUG = typeof process !== "undefined" && process && process.env && (process.env.COHERENT_DEBUG === "1" || true) || typeof window !== "undefined" && window && window.COHERENT_DEBUG === true;
979
- if (typeof global !== "undefined") {
980
- if (!global.__coherentActionRegistry) {
981
- global.__coherentActionRegistry = {};
982
- if (DEBUG) console.log("Initialized global action registry");
983
- }
984
- global.__coherentActionRegistry[actionId] = value;
985
- if (DEBUG) console.log(`Added action ${actionId} to global registry, total: ${Object.keys(global.__coherentActionRegistry).length}`);
986
- if (DEBUG) console.log(`Global registry keys: ${Object.keys(global.__coherentActionRegistry).join(", ")}`);
987
- if (DEBUG) {
988
- if (typeof global.__coherentActionRegistryLog === "undefined") {
989
- global.__coherentActionRegistryLog = [];
990
- }
991
- global.__coherentActionRegistryLog.push({
992
- action: "add",
993
- actionId,
994
- timestamp: Date.now(),
995
- registrySize: Object.keys(global.__coherentActionRegistry).length
996
- });
997
- }
998
- } else if (typeof window !== "undefined") {
999
- if (!window.__coherentActionRegistry) {
1000
- window.__coherentActionRegistry = {};
1001
- if (DEBUG) console.log("Initialized window action registry");
1002
- }
1003
- window.__coherentActionRegistry[actionId] = value;
1004
- if (DEBUG) console.log(`Added action ${actionId} to window registry, total: ${Object.keys(window.__coherentActionRegistry).length}`);
1005
- if (DEBUG) console.log(`Window registry keys: ${Object.keys(window.__coherentActionRegistry).join(", ")}`);
1006
- }
1007
- const eventType = attributeName.substring(2);
1008
- formatted += ` data-action="${actionId}" data-event="${eventType}"`;
1009
- continue;
1010
- } else {
1011
- try {
1012
- value = value();
1013
- } catch (_error) {
1014
- console.warn(`Error executing function for attribute '${key}':`, {
1015
- _error: _error.message,
1016
- stack: _error.stack,
1017
- attributeKey: key
1018
- });
1019
- value = "";
1020
- }
1021
- }
1022
- }
1023
- if (value === true) {
1024
- formatted += ` ${attributeName}`;
1025
- } else if (value !== false && value !== null && value !== void 0) {
1026
- formatted += ` ${attributeName}="${escapeHtml(String(value))}"`;
1027
- }
1028
- }
1029
- }
1030
- return formatted.trim();
1031
- }
1032
- function minifyHtml(html, options = {}) {
1033
- if (!options.minify) return html;
1034
- return html.replace(/<!--[\s\S]*?-->/g, "").replace(/\s+/g, " ").replace(/>\s+</g, "><").trim();
1035
- }
1036
-
1037
- // ../core/src/performance/cache-manager.js
1038
- function createCacheManager(options = {}) {
1039
- const {
1040
- maxCacheSize = 1e3,
1041
- maxMemoryMB = 100,
1042
- ttlMs = 1e3 * 60 * 5,
1043
- // 5 minutes
1044
- enableStatistics = true
1045
- } = options;
1046
- const caches = {
1047
- static: /* @__PURE__ */ new Map(),
1048
- // Never-changing components
1049
- component: /* @__PURE__ */ new Map(),
1050
- // Component results with deps
1051
- template: /* @__PURE__ */ new Map(),
1052
- // Template strings
1053
- data: /* @__PURE__ */ new Map()
1054
- // General purpose data
1055
- };
1056
- let memoryUsage = 0;
1057
- const stats = {
1058
- hits: 0,
1059
- misses: 0,
1060
- hitRate: {
1061
- static: 0,
1062
- component: 0,
1063
- template: 0,
1064
- data: 0
1065
- },
1066
- accessCount: {
1067
- static: 0,
1068
- component: 0,
1069
- template: 0,
1070
- data: 0
1071
- }
1072
- };
1073
- let cleanupInterval;
1074
- if (typeof setInterval === "function") {
1075
- cleanupInterval = setInterval(() => cleanup(), 3e4);
1076
- if (cleanupInterval.unref) {
1077
- cleanupInterval.unref();
1078
- }
1079
- }
1080
- function generateCacheKey(component, props = {}, context = {}) {
1081
- const componentStr = typeof component === "function" ? component.name || component.toString() : JSON.stringify(component);
1082
- const propsStr = JSON.stringify(props, Object.keys(props).sort());
1083
- const contextStr = JSON.stringify(context);
1084
- const hash = simpleHash(componentStr + propsStr + contextStr);
1085
- return `${extractComponentName(component)}_${hash}`;
1086
- }
1087
- function get(key, type = "component") {
1088
- const cache = caches[type] || caches.component;
1089
- const entry = cache.get(key);
1090
- if (!entry) {
1091
- stats.misses++;
1092
- if (enableStatistics) stats.accessCount[type]++;
1093
- return null;
1094
- }
1095
- if (Date.now() - entry.timestamp > ttlMs) {
1096
- cache.delete(key);
1097
- updateMemoryUsage(-entry.size);
1098
- stats.misses++;
1099
- if (enableStatistics) stats.accessCount[type]++;
1100
- return null;
1101
- }
1102
- entry.lastAccess = Date.now();
1103
- entry.accessCount++;
1104
- stats.hits++;
1105
- if (enableStatistics) {
1106
- stats.accessCount[type]++;
1107
- stats.hitRate[type] = stats.hits / (stats.hits + stats.misses) * 100;
1108
- }
1109
- return entry.value;
1110
- }
1111
- function set(key, value, type = "component", metadata = {}) {
1112
- const cache = caches[type] || caches.component;
1113
- const size = calculateSize(value);
1114
- if (memoryUsage + size > maxMemoryMB * 1024 * 1024) {
1115
- optimize(type, size);
1116
- }
1117
- const entry = {
1118
- value,
1119
- timestamp: Date.now(),
1120
- lastAccess: Date.now(),
1121
- size,
1122
- metadata,
1123
- accessCount: 0
1124
- };
1125
- const existing = cache.get(key);
1126
- if (existing) {
1127
- updateMemoryUsage(-existing.size);
1128
- }
1129
- cache.set(key, entry);
1130
- updateMemoryUsage(size);
1131
- if (cache.size > maxCacheSize) {
1132
- optimize(type);
1133
- }
1134
- }
1135
- function remove(key, type) {
1136
- if (type) {
1137
- const cache = caches[type];
1138
- if (!cache) return false;
1139
- const entry = cache.get(key);
1140
- if (entry) {
1141
- updateMemoryUsage(-entry.size);
1142
- return cache.delete(key);
1143
- }
1144
- return false;
1145
- }
1146
- for (const [, cache] of Object.entries(caches)) {
1147
- const entry = cache.get(key);
1148
- if (entry) {
1149
- updateMemoryUsage(-entry.size);
1150
- return cache.delete(key);
1151
- }
1152
- }
1153
- return false;
1154
- }
1155
- function clear(type) {
1156
- if (type) {
1157
- const cache = caches[type];
1158
- if (cache) {
1159
- cache.clear();
1160
- }
1161
- } else {
1162
- Object.values(caches).forEach((cache) => cache.clear());
1163
- }
1164
- memoryUsage = 0;
1165
- }
1166
- function getStats() {
1167
- const entries = Object.values(caches).reduce((sum, cache) => sum + cache.size, 0);
1168
- return {
1169
- hits: stats.hits,
1170
- misses: stats.misses,
1171
- size: memoryUsage,
1172
- entries,
1173
- hitRate: stats.hitRate,
1174
- accessCount: stats.accessCount
1175
- };
1176
- }
1177
- function cleanup() {
1178
- const now = Date.now();
1179
- let freed = 0;
1180
- for (const [, cache] of Object.entries(caches)) {
1181
- for (const [key, entry] of cache.entries()) {
1182
- if (now - entry.timestamp > ttlMs) {
1183
- cache.delete(key);
1184
- updateMemoryUsage(-entry.size);
1185
- freed++;
1186
- }
1187
- }
1188
- }
1189
- return { freed };
1190
- }
1191
- function calculateSize(value) {
1192
- if (value === null || value === void 0) return 0;
1193
- if (typeof value === "string") return value.length * 2;
1194
- if (typeof value === "number") return 8;
1195
- if (typeof value === "boolean") return 4;
1196
- if (Array.isArray(value)) {
1197
- return value.reduce((sum, item) => sum + calculateSize(item), 0);
1198
- }
1199
- if (typeof value === "object") {
1200
- return Object.values(value).reduce((sum, val) => sum + calculateSize(val), 0);
1201
- }
1202
- return 0;
1203
- }
1204
- function updateMemoryUsage(delta) {
1205
- memoryUsage = Math.max(0, memoryUsage + delta);
1206
- }
1207
- function optimize(type, requiredSpace = 0) {
1208
- const cache = caches[type] || caches.component;
1209
- const entries = Array.from(cache.entries()).sort(([, a], [, b]) => a.lastAccess - b.lastAccess);
1210
- let freed = 0;
1211
- for (const [key, entry] of entries) {
1212
- if (freed >= requiredSpace) break;
1213
- cache.delete(key);
1214
- updateMemoryUsage(-entry.size);
1215
- freed += entry.size;
1216
- }
1217
- return { freed };
1218
- }
1219
- function simpleHash(str) {
1220
- let hash = 0;
1221
- for (let i = 0; i < str.length; i++) {
1222
- const char = str.charCodeAt(i);
1223
- hash = (hash << 5) - hash + char;
1224
- hash = hash & hash;
1225
- }
1226
- return Math.abs(hash).toString(36);
1227
- }
1228
- function extractComponentName(component) {
1229
- if (typeof component === "function") {
1230
- return component.name || "AnonymousComponent";
1231
- }
1232
- if (component && typeof component === "object") {
1233
- const keys = Object.keys(component);
1234
- return keys.length > 0 ? keys[0] : "ObjectComponent";
1235
- }
1236
- return "UnknownComponent";
1237
- }
1238
- function destroy() {
1239
- if (cleanupInterval) {
1240
- clearInterval(cleanupInterval);
1241
- }
1242
- clear();
1243
- }
1244
- return {
1245
- get,
1246
- set,
1247
- remove,
1248
- clear,
1249
- getStats,
1250
- cleanup,
1251
- destroy,
1252
- generateCacheKey,
1253
- get memoryUsage() {
1254
- return memoryUsage;
1255
- },
1256
- get maxMemory() {
1257
- return maxMemoryMB * 1024 * 1024;
1258
- }
1259
- };
1260
- }
1261
- var cacheManager = createCacheManager();
1262
-
1263
- // ../core/src/rendering/css-manager.js
1264
- import fs from "node:fs/promises";
1265
- import path from "node:path";
1266
- var CSSManager = class {
1267
- constructor(options = {}) {
1268
- this.options = {
1269
- basePath: process.cwd(),
1270
- minify: false,
1271
- cache: true,
1272
- autoprefixer: false,
1273
- ...options
1274
- };
1275
- this.cache = /* @__PURE__ */ new Map();
1276
- this.loadedFiles = /* @__PURE__ */ new Set();
1277
- }
1278
- /**
1279
- * Load CSS file content
1280
- */
1281
- async loadCSSFile(filePath) {
1282
- const fullPath = path.resolve(this.options.basePath, filePath);
1283
- const cacheKey = fullPath;
1284
- if (this.options.cache && this.cache.has(cacheKey)) {
1285
- return this.cache.get(cacheKey);
1286
- }
1287
- try {
1288
- let content = await fs.readFile(fullPath, "utf8");
1289
- if (this.options.minify) {
1290
- content = this.minifyCSS(content);
1291
- }
1292
- if (this.options.cache) {
1293
- this.cache.set(cacheKey, content);
1294
- }
1295
- this.loadedFiles.add(filePath);
1296
- return content;
1297
- } catch (_error) {
1298
- console.warn(`Failed to load CSS file: ${filePath}`, _error.message);
1299
- return "";
1300
- }
1301
- }
1302
- /**
1303
- * Load multiple CSS files
1304
- */
1305
- async loadCSSFiles(filePaths) {
1306
- if (!Array.isArray(filePaths)) {
1307
- filePaths = [filePaths];
1308
- }
1309
- const cssContents = await Promise.all(
1310
- filePaths.map((filePath) => this.loadCSSFile(filePath))
1311
- );
1312
- return cssContents.join("\n");
1313
- }
1314
- /**
1315
- * Generate CSS link tags for external files
1316
- */
1317
- generateCSSLinks(filePaths, baseUrl = "/") {
1318
- if (!Array.isArray(filePaths)) {
1319
- filePaths = [filePaths];
1320
- }
1321
- return filePaths.map((filePath) => {
1322
- const href = filePath.startsWith("http") ? filePath : `${baseUrl}${filePath}`.replace(/\/+/g, "/");
1323
- return `<link rel="stylesheet" href="${this.escapeHtml(href)}" />`;
1324
- }).join("\n");
1325
- }
1326
- /**
1327
- * Generate inline style tag with CSS content
1328
- */
1329
- generateInlineStyles(cssContent) {
1330
- if (!cssContent) return "";
1331
- return `<style type="text/css">
1332
- ${cssContent}
1333
- </style>`;
1334
- }
1335
- /**
1336
- * Basic CSS minification
1337
- */
1338
- minifyCSS(css) {
1339
- return css.replace(/\/\*[\s\S]*?\*\//g, "").replace(/\s+/g, " ").replace(/;\s*}/g, "}").replace(/{\s+/g, "{").replace(/;\s+/g, ";").trim();
1340
- }
1341
- /**
1342
- * Escape HTML entities
1343
- */
1344
- escapeHtml(text) {
1345
- const div = { textContent: text };
1346
- return div.innerHTML || text;
1347
- }
1348
- /**
1349
- * Clear cache
1350
- */
1351
- clearCache() {
1352
- this.cache.clear();
1353
- this.loadedFiles.clear();
1354
- }
1355
- /**
1356
- * Get loaded file list
1357
- */
1358
- getLoadedFiles() {
1359
- return Array.from(this.loadedFiles);
1360
- }
1361
- };
1362
- var defaultCSSManager = new CSSManager();
1363
-
1364
- // ../core/src/rendering/html-renderer.js
1365
- var rendererCache = createCacheManager({
1366
- maxSize: 1e3,
1367
- ttlMs: 3e5
1368
- // 5 minutes
1369
- });
1370
- var HTMLRenderer = class extends BaseRenderer {
1371
- constructor(options = {}) {
1372
- super({
1373
- enableCache: options.enableCache !== false,
1374
- enableMonitoring: options.enableMonitoring !== false,
1375
- minify: options.minify || false,
1376
- streaming: options.streaming || false,
1377
- maxDepth: options.maxDepth || 100,
1378
- ...options
1379
- });
1380
- if (this.config.enableCache && !this.cache) {
1381
- this.cache = rendererCache;
1382
- }
1383
- }
1384
- /**
1385
- * Main render method - converts components to HTML string
1386
- *
1387
- * @param {Object|Array|string|Function} component - Component to render
1388
- * @param {Object} [options={}] - Rendering options
1389
- * @param {Object} [options.context] - Rendering context
1390
- * @param {boolean} [options.enableCache] - Override cache setting
1391
- * @param {number} [options.depth=0] - Current rendering depth
1392
- * @returns {string} Rendered HTML string
1393
- *
1394
- * @example
1395
- * const html = renderer.render({
1396
- * div: {
1397
- * className: 'container',
1398
- * children: [
1399
- * { h1: { text: 'Title' } },
1400
- * { p: { text: 'Content' } }
1401
- * ]
1402
- * }
1403
- * });
1404
- */
1405
- render(component, options = {}) {
1406
- const config = { ...this.config, ...options };
1407
- this.startTiming();
1408
- try {
1409
- if (config.validateInput && !this.isValidComponent(component)) {
1410
- throw new Error("Invalid component structure");
1411
- }
1412
- const html = this.renderComponent(component, config, 0);
1413
- const finalHtml = config.minify ? minifyHtml(html, config) : html;
1414
- this.endTiming();
1415
- this.recordPerformance("render", this.metrics.startTime, false, {
1416
- cacheEnabled: config.enableCache
1417
- });
1418
- return finalHtml;
1419
- } catch (_error) {
1420
- this.recordError("render", _error);
1421
- throw _error;
1422
- }
1423
- }
1424
- /**
1425
- * Render a single component with full optimization pipeline
1426
- */
1427
- renderComponent(component, options, depth = 0) {
1428
- this.validateDepth(depth);
1429
- const { type, value } = this.processComponentType(component);
1430
- switch (type) {
1431
- case "empty":
1432
- return "";
1433
- case "text":
1434
- return escapeHtml(value);
1435
- case "function":
1436
- const result = this.executeFunctionComponent(value, depth);
1437
- return this.renderComponent(result, options, depth + 1);
1438
- case "array":
1439
- return value.map((child) => this.renderComponent(child, options, depth + 1)).join("");
1440
- case "element":
1441
- const tagName = Object.keys(value)[0];
1442
- const elementContent = value[tagName];
1443
- return this.renderElement(tagName, elementContent, options, depth);
1444
- default:
1445
- this.recordError("renderComponent", new Error(`Unknown component type: ${type}`));
1446
- return "";
1447
- }
1448
- }
1449
- /**
1450
- * Render an HTML element with advanced caching and optimization
1451
- */
1452
- renderElement(tagName, element, options, depth = 0) {
1453
- const startTime = performance.now();
1454
- if (options.enableMonitoring && this.cache) {
1455
- }
1456
- if (options.enableCache && this.cache && RendererUtils.isStaticElement(element)) {
1457
- const cacheKey = `static:${tagName}:${JSON.stringify(element)}`;
1458
- const cached = this.cache.get("static", cacheKey);
1459
- if (cached) {
1460
- this.recordPerformance(tagName, startTime, true);
1461
- return cached.value;
1462
- }
1463
- }
1464
- if (typeof element === "string" || typeof element === "number" || typeof element === "boolean") {
1465
- const html2 = isVoidElement(tagName) ? `<${tagName}>` : `<${tagName}>${escapeHtml(String(element))}</${tagName}>`;
1466
- this.cacheIfStatic(tagName, element, html2, options);
1467
- this.recordPerformance(tagName, startTime, false);
1468
- return html2;
1469
- }
1470
- if (typeof element === "function") {
1471
- const result = this.executeFunctionComponent(element, depth);
1472
- return this.renderElement(tagName, result, options, depth);
1473
- }
1474
- if (element && typeof element === "object") {
1475
- return this.renderObjectElement(tagName, element, options, depth);
1476
- }
1477
- if (element === null || element === void 0) {
1478
- const html2 = isVoidElement(tagName) ? `<${tagName}>` : `<${tagName}></${tagName}>`;
1479
- this.recordPerformance(tagName, startTime, false);
1480
- return html2;
1481
- }
1482
- const html = `<${tagName}>${escapeHtml(String(element))}</${tagName}>`;
1483
- this.recordPerformance(tagName, startTime, false);
1484
- return html;
1485
- }
1486
- /**
1487
- * Cache element if it's static
1488
- */
1489
- cacheIfStatic(tagName, element, html) {
1490
- if (this.config.enableCache && this.cache && RendererUtils.isStaticElement(element)) {
1491
- const cacheKey = `static:${tagName}:${JSON.stringify(element)}`;
1492
- this.cache.set("static", cacheKey, html, {
1493
- ttlMs: this.config.cacheTTL || 5 * 60 * 1e3,
1494
- // 5 minutes default
1495
- size: html.length
1496
- // Approximate size
1497
- });
1498
- }
1499
- }
1500
- /**
1501
- * Render complex object elements with attributes and children
1502
- */
1503
- renderObjectElement(tagName, element, options, depth = 0) {
1504
- const startTime = performance.now();
1505
- if (options.enableCache && this.cache) {
1506
- const cacheKey = RendererUtils.generateCacheKey(tagName, element);
1507
- if (cacheKey) {
1508
- const cached = this.cache.get(cacheKey);
1509
- if (cached) {
1510
- this.recordPerformance(tagName, startTime, true);
1511
- return cached;
1512
- }
1513
- }
1514
- }
1515
- const { children, text, ...attributes } = element || {};
1516
- const attributeString = formatAttributes(attributes);
1517
- const openingTag = attributeString ? `<${tagName} ${attributeString}>` : `<${tagName}>`;
1518
- let textContent = "";
1519
- if (text !== void 0) {
1520
- const isScript = tagName === "script";
1521
- const isStyle = tagName === "style";
1522
- const isRawTag = isScript || isStyle;
1523
- const raw = typeof text === "function" ? String(text()) : String(text);
1524
- if (isRawTag) {
1525
- const safe = raw.replace(/<\/(script)/gi, "<\\/$1").replace(/<\/(style)/gi, "<\\/$1").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
1526
- textContent = safe;
1527
- } else {
1528
- textContent = escapeHtml(raw);
1529
- }
1530
- }
1531
- let childrenHtml = "";
1532
- if (hasChildren(element)) {
1533
- const normalizedChildren = normalizeChildren(children);
1534
- childrenHtml = normalizedChildren.map((child) => this.renderComponent(child, options, depth + 1)).join("");
1535
- }
1536
- const html = `${openingTag}${textContent}${childrenHtml}</${tagName}>`;
1537
- if (options.enableCache && this.cache && RendererUtils.isCacheable(element, options)) {
1538
- const cacheKey = RendererUtils.generateCacheKey(tagName, element);
1539
- if (cacheKey) {
1540
- this.cache.set(cacheKey, html);
1541
- }
1542
- }
1543
- this.recordPerformance(tagName, startTime, false);
1544
- return html;
1545
- }
1546
- };
1547
- function render(component, options = {}) {
1548
- const mergedOptions = {
1549
- enableCache: true,
1550
- enableMonitoring: false,
1551
- ...options
1552
- };
1553
- const renderer = new HTMLRenderer(mergedOptions);
1554
- return renderer.render(component, mergedOptions);
1555
- }
1556
-
1557
- // ../core/src/utils/render-utils.js
1558
- function renderWithMonitoring(component, options = {}) {
1559
- const {
1560
- enablePerformanceMonitoring = false
1561
- } = options;
1562
- let html;
1563
- if (enablePerformanceMonitoring) {
1564
- const renderId = performanceMonitor.startRender();
1565
- html = render(component);
1566
- performanceMonitor.endRender(renderId);
1567
- } else {
1568
- html = render(component);
1569
- }
1570
- return html;
1571
- }
1572
- function renderWithTemplate(component, options = {}) {
1573
- const {
1574
- template = "<!DOCTYPE html>\n{{content}}"
1575
- } = options;
1576
- const html = renderWithMonitoring(component, options);
1577
- return template.replace("{{content}}", html);
1578
- }
1579
- async function renderComponentFactory(componentFactory, factoryArgs, options = {}) {
1580
- const component = await Promise.resolve(
1581
- componentFactory(...factoryArgs)
1582
- );
1583
- if (!component) {
1584
- throw new Error("Component factory returned null/undefined");
1585
- }
1586
- return renderWithTemplate(component, options);
1587
- }
1588
-
1589
1
  // src/coherent-fastify.js
2
+ import {
3
+ renderWithTemplate,
4
+ renderComponentFactory
5
+ } from "@coherent.js/core";
1590
6
  function coherentFastify(fastify, options, done) {
1591
7
  const {
1592
8
  enablePerformanceMonitoring = false,
@@ -1660,10 +76,4 @@ export {
1660
76
  coherent_fastify_default as default,
1661
77
  setupCoherent
1662
78
  };
1663
- /**
1664
- * Advanced caching system with memory management and smart invalidation for Coherent.js
1665
- *
1666
- * @module @coherent/performance/cache-manager
1667
- * @license MIT
1668
- */
1669
79
  //# sourceMappingURL=index.js.map