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