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