@coherent.js/koa 1.0.0-beta.2

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