@teyik0/furin 0.1.0-alpha.8 → 0.1.0-alpha.9

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/router.js CHANGED
@@ -3,7 +3,7 @@
3
3
  import { existsSync } from "fs";
4
4
  import { readdir } from "fs/promises";
5
5
  import { join, parse } from "path";
6
- import { Elysia as Elysia2 } from "elysia";
6
+ import { Elysia as Elysia2, t } from "elysia";
7
7
 
8
8
  // src/internal.ts
9
9
  var _compileCtx = null;
@@ -147,7 +147,800 @@ function assembleHTML(template, headData, reactHtml, data) {
147
147
  // src/render/index.ts
148
148
  import { createElement as createElement2 } from "react";
149
149
  import { renderToReadableStream } from "react-dom/server";
150
+ // ../../node_modules/.bun/evlog@2.13.0+449e6d239244fccb/node_modules/evlog/dist/utils.mjs
151
+ function formatDuration(ms) {
152
+ if (ms < 1000)
153
+ return `${Math.round(ms)}ms`;
154
+ return `${(ms / 1000).toFixed(2)}s`;
155
+ }
156
+ function isClient() {
157
+ return typeof window !== "undefined";
158
+ }
159
+ function isDev() {
160
+ if (typeof process !== "undefined")
161
+ return true;
162
+ if (typeof window !== "undefined")
163
+ return true;
164
+ return false;
165
+ }
166
+ function detectEnvironment() {
167
+ const env = typeof process !== "undefined" ? process.env : {};
168
+ const defaultEnvironment = isDev() ? "development" : "production";
169
+ return {
170
+ environment: env.NODE_ENV || defaultEnvironment,
171
+ service: env.SERVICE_NAME || "app",
172
+ version: env.APP_VERSION,
173
+ commitHash: env.COMMIT_SHA || env.GITHUB_SHA || env.VERCEL_GIT_COMMIT_SHA || env.CF_PAGES_COMMIT_SHA,
174
+ region: env.VERCEL_REGION || env.AWS_REGION || env.FLY_REGION || env.CF_REGION
175
+ };
176
+ }
177
+ var LEVEL_ORDER = {
178
+ debug: 0,
179
+ info: 1,
180
+ warn: 2,
181
+ error: 3
182
+ };
183
+ function isLevelEnabled(level, minLevel) {
184
+ return LEVEL_ORDER[level] >= LEVEL_ORDER[minLevel];
185
+ }
186
+ function getConsoleMethod(level) {
187
+ return level;
188
+ }
189
+ var colors = {
190
+ reset: "\x1B[0m",
191
+ bold: "\x1B[1m",
192
+ dim: "\x1B[2m",
193
+ red: "\x1B[31m",
194
+ green: "\x1B[32m",
195
+ yellow: "\x1B[33m",
196
+ blue: "\x1B[34m",
197
+ magenta: "\x1B[35m",
198
+ cyan: "\x1B[36m",
199
+ white: "\x1B[37m",
200
+ gray: "\x1B[90m"
201
+ };
202
+ var levelColorMap = {
203
+ error: colors.red,
204
+ warn: colors.yellow,
205
+ info: colors.cyan,
206
+ debug: colors.gray
207
+ };
208
+ function getLevelColor(level) {
209
+ return levelColorMap[level] ?? colors.white;
210
+ }
211
+ var cssColors = {
212
+ dim: "color: #6b7280",
213
+ red: "color: #ef4444; font-weight: bold",
214
+ green: "color: #22c55e",
215
+ yellow: "color: #f59e0b; font-weight: bold",
216
+ cyan: "color: #06b6d4; font-weight: bold",
217
+ gray: "color: #6b7280; font-weight: bold",
218
+ reset: "color: inherit; font-weight: normal"
219
+ };
220
+ var cssLevelColorMap = {
221
+ error: cssColors.red,
222
+ warn: cssColors.yellow,
223
+ info: cssColors.cyan,
224
+ debug: cssColors.gray
225
+ };
226
+ function getCssLevelColor(level) {
227
+ return cssLevelColorMap[level] ?? cssColors.reset;
228
+ }
229
+ function escapeFormatString(str) {
230
+ return str.replace(/%/g, "%%");
231
+ }
232
+ var patternCache = /* @__PURE__ */ new Map;
233
+ function matchesPattern(path, pattern) {
234
+ let regex = patternCache.get(pattern);
235
+ if (!regex) {
236
+ const regexPattern = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, "{{GLOBSTAR}}").replace(/\*/g, "[^/]*").replace(/{{GLOBSTAR}}/g, ".*").replace(/\?/g, "[^/]");
237
+ regex = new RegExp(`^${regexPattern}$`);
238
+ patternCache.set(pattern, regex);
239
+ }
240
+ return regex.test(path);
241
+ }
150
242
 
243
+ // ../../node_modules/.bun/evlog@2.13.0+449e6d239244fccb/node_modules/evlog/dist/logger-DnobymUQ.mjs
244
+ var DEFAULT_REPLACEMENT = "[REDACTED]";
245
+ var builtinPatterns = {
246
+ creditCard: {
247
+ pattern: /\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g,
248
+ mask: (m) => `****${m.replace(/[\s-]/g, "").slice(-4)}`
249
+ },
250
+ email: {
251
+ pattern: /[\w.+-]+@[\w-]+\.[\w.]+/g,
252
+ mask: (m) => {
253
+ if (m.indexOf("@") < 1)
254
+ return "***@***";
255
+ const tld = m.slice(m.lastIndexOf("."));
256
+ return `${m[0]}***@***${tld}`;
257
+ }
258
+ },
259
+ ipv4: {
260
+ pattern: /\b(?!0\.0\.0\.0\b)(?!127\.0\.0\.1\b)\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g,
261
+ mask: (m) => `***.***.***.${m.split(".").pop()}`
262
+ },
263
+ phone: {
264
+ pattern: /(?:\+\d{1,3}[\s.-]?)?\(?\d{1,4}\)?[\s.-]?\d{2,4}[\s.-]?\d{2,4}[\s.-]?\d{2,4}\b/g,
265
+ mask: (m) => {
266
+ const digits = m.replace(/[^\d]/g, "");
267
+ if (m.startsWith("+") && digits.length > 4) {
268
+ const ccMatch = m.match(/^\+\d{1,3}/);
269
+ return `${ccMatch ? ccMatch[0] : "+"}******${digits.slice(-2)}`;
270
+ }
271
+ if (digits.length > 2)
272
+ return `${"*".repeat(digits.length - 2)}${digits.slice(-2)}`;
273
+ return "***";
274
+ }
275
+ },
276
+ jwt: {
277
+ pattern: /\beyJ[\w-]*\.[\w-]*\.[\w-]*\b/g,
278
+ mask: () => "eyJ***.***"
279
+ },
280
+ bearer: {
281
+ pattern: /\bBearer\s+[\w\-.~+/]{8,}=*/gi,
282
+ mask: () => "Bearer ***"
283
+ },
284
+ iban: {
285
+ pattern: /\b[A-Z]{2}\d{2}[\s-]?[\dA-Z]{4}[\s-]?[\dA-Z]{4}[\s-]?[\dA-Z]{4}[\s-]?[\dA-Z]{0,4}[\s-]?[\dA-Z]{0,4}[\s-]?[\dA-Z]{0,4}\b/g,
286
+ mask: (m) => {
287
+ const clean = m.replace(/[\s-]/g, "");
288
+ return `${clean.slice(0, 4)}****${clean.slice(-3)}`;
289
+ }
290
+ }
291
+ };
292
+ function resolveRedactConfig(input) {
293
+ if (input === undefined || input === false)
294
+ return;
295
+ if (input === true)
296
+ return { _maskers: allBuiltinMaskers() };
297
+ if (input.builtins === false)
298
+ return input;
299
+ const maskers = Array.isArray(input.builtins) ? input.builtins.map((name) => builtinPatterns[name]).filter(Boolean).map((b) => [cloneRegex(b.pattern), b.mask]) : allBuiltinMaskers();
300
+ return {
301
+ ...input,
302
+ _maskers: maskers
303
+ };
304
+ }
305
+ function allBuiltinMaskers() {
306
+ return Object.values(builtinPatterns).map((b) => [cloneRegex(b.pattern), b.mask]);
307
+ }
308
+ function cloneRegex(re) {
309
+ return new RegExp(re.source, re.flags);
310
+ }
311
+ function redactEvent(event, config) {
312
+ const replacement = config.replacement ?? DEFAULT_REPLACEMENT;
313
+ if (config.paths?.length)
314
+ for (const path of config.paths)
315
+ redactPath(event, path.split("."), replacement);
316
+ if (config._maskers?.length)
317
+ applyMaskersToTree(event, config._maskers);
318
+ if (config.patterns?.length)
319
+ redactPatterns(event, config.patterns, replacement);
320
+ }
321
+ function redactPath(obj, segments, replacement) {
322
+ let current = obj;
323
+ for (let i = 0;i < segments.length - 1; i++) {
324
+ if (current === null || current === undefined || typeof current !== "object")
325
+ return;
326
+ current = current[segments[i]];
327
+ }
328
+ if (current === null || current === undefined || typeof current !== "object")
329
+ return;
330
+ const leaf = segments[segments.length - 1];
331
+ if (leaf in current)
332
+ current[leaf] = replacement;
333
+ }
334
+ function redactPatterns(obj, patterns, replacement) {
335
+ if (obj === null || obj === undefined)
336
+ return;
337
+ if (Array.isArray(obj)) {
338
+ for (let i = 0;i < obj.length; i++)
339
+ if (typeof obj[i] === "string")
340
+ obj[i] = applyPatterns(obj[i], patterns, replacement);
341
+ else if (typeof obj[i] === "object")
342
+ redactPatterns(obj[i], patterns, replacement);
343
+ return;
344
+ }
345
+ if (typeof obj === "object") {
346
+ const record = obj;
347
+ for (const key in record) {
348
+ const val = record[key];
349
+ if (typeof val === "string")
350
+ record[key] = applyPatterns(val, patterns, replacement);
351
+ else if (typeof val === "object")
352
+ redactPatterns(val, patterns, replacement);
353
+ }
354
+ }
355
+ }
356
+ function applyPatterns(value, patterns, replacement) {
357
+ let result = value;
358
+ for (const pattern of patterns) {
359
+ pattern.lastIndex = 0;
360
+ result = result.replace(pattern, replacement);
361
+ }
362
+ return result;
363
+ }
364
+ function applyMaskersToTree(obj, maskers) {
365
+ if (obj === null || obj === undefined)
366
+ return;
367
+ if (Array.isArray(obj)) {
368
+ for (let i = 0;i < obj.length; i++)
369
+ if (typeof obj[i] === "string")
370
+ obj[i] = applyMaskers(obj[i], maskers);
371
+ else if (typeof obj[i] === "object")
372
+ applyMaskersToTree(obj[i], maskers);
373
+ return;
374
+ }
375
+ if (typeof obj === "object") {
376
+ const record = obj;
377
+ for (const key in record) {
378
+ const val = record[key];
379
+ if (typeof val === "string")
380
+ record[key] = applyMaskers(val, maskers);
381
+ else if (typeof val === "object")
382
+ applyMaskersToTree(val, maskers);
383
+ }
384
+ }
385
+ }
386
+ function applyMaskers(value, maskers) {
387
+ let result = value;
388
+ for (const [pattern, mask] of maskers) {
389
+ pattern.lastIndex = 0;
390
+ result = result.replace(pattern, mask);
391
+ }
392
+ return result;
393
+ }
394
+ function isPlainObject(val) {
395
+ return val !== null && typeof val === "object" && !Array.isArray(val);
396
+ }
397
+ var _tsDate = /* @__PURE__ */ new Date;
398
+ function isoNow() {
399
+ _tsDate.setTime(Date.now());
400
+ return _tsDate.toISOString();
401
+ }
402
+ var POST_EMIT_FORK_HINT = "For intentional background work tied to this request, use log.fork('label', fn) when your integration supports it (see https://evlog.dev).";
403
+ function warnPostEmit(method, detail) {
404
+ console.warn(`[evlog] ${method} called after the wide event was emitted \u2014 ${detail} This data will not appear in observability. ${POST_EMIT_FORK_HINT}`);
405
+ }
406
+ function mergeInto(target, source) {
407
+ for (const key in source) {
408
+ const sourceVal = source[key];
409
+ if (sourceVal === undefined || sourceVal === null)
410
+ continue;
411
+ const targetVal = target[key];
412
+ if (isPlainObject(sourceVal) && isPlainObject(targetVal))
413
+ mergeInto(targetVal, sourceVal);
414
+ else if (Array.isArray(targetVal) && Array.isArray(sourceVal))
415
+ target[key] = [...targetVal, ...sourceVal];
416
+ else
417
+ target[key] = sourceVal;
418
+ }
419
+ }
420
+ var globalEnv = {
421
+ service: "app",
422
+ environment: "development"
423
+ };
424
+ var globalPretty = isDev();
425
+ var globalSampling = {};
426
+ var globalStringify = true;
427
+ var globalDrain;
428
+ var globalRedact;
429
+ var globalEnabled = true;
430
+ var globalSilent = false;
431
+ var globalMinLevel = "debug";
432
+ function initLogger(config = {}) {
433
+ globalEnabled = config.enabled ?? true;
434
+ const detected = detectEnvironment();
435
+ globalEnv = {
436
+ service: config.env?.service ?? detected.service ?? "app",
437
+ environment: config.env?.environment ?? detected.environment ?? "development",
438
+ version: config.env?.version ?? detected.version,
439
+ commitHash: config.env?.commitHash ?? detected.commitHash,
440
+ region: config.env?.region ?? detected.region
441
+ };
442
+ globalPretty = config.pretty ?? isDev();
443
+ globalSampling = config.sampling ?? {};
444
+ globalStringify = config.stringify ?? true;
445
+ globalDrain = config.drain;
446
+ globalRedact = resolveRedactConfig(config.redact ?? !isDev());
447
+ globalSilent = config.silent ?? false;
448
+ globalMinLevel = config.minLevel ?? "debug";
449
+ if (globalSilent && !globalDrain && !config._suppressDrainWarning)
450
+ console.warn("[evlog] silent mode is enabled but no drain is configured. Events will be built and sampled but not output anywhere. Set a drain via initLogger({ drain }) or a framework hook (evlog:drain).");
451
+ }
452
+ function shouldSample(level) {
453
+ const { rates } = globalSampling;
454
+ if (!rates)
455
+ return true;
456
+ const percentage = level === "error" && rates.error === undefined ? 100 : rates[level] ?? 100;
457
+ if (percentage <= 0)
458
+ return false;
459
+ if (percentage >= 100)
460
+ return true;
461
+ return Math.random() * 100 < percentage;
462
+ }
463
+ function shouldKeep(ctx) {
464
+ const { keep } = globalSampling;
465
+ if (!keep?.length)
466
+ return false;
467
+ return keep.some((condition) => {
468
+ if (condition.status !== undefined && ctx.status !== undefined && ctx.status >= condition.status)
469
+ return true;
470
+ if (condition.duration !== undefined && ctx.duration !== undefined && ctx.duration >= condition.duration)
471
+ return true;
472
+ if (condition.path && ctx.path && matchesPattern(ctx.path, condition.path))
473
+ return true;
474
+ return false;
475
+ });
476
+ }
477
+ function emitWideEvent(level, event, deferDrain = false, ownsEvent = false) {
478
+ if (!globalEnabled)
479
+ return null;
480
+ if (!ownsEvent) {
481
+ if (!isLevelEnabled(level, globalMinLevel))
482
+ return null;
483
+ if (!shouldSample(level))
484
+ return null;
485
+ }
486
+ let formatted;
487
+ if (ownsEvent) {
488
+ event.timestamp = isoNow();
489
+ event.level = level;
490
+ if (event.service === undefined)
491
+ event.service = globalEnv.service;
492
+ if (event.environment === undefined)
493
+ event.environment = globalEnv.environment;
494
+ if (globalEnv.version !== undefined && event.version === undefined)
495
+ event.version = globalEnv.version;
496
+ if (globalEnv.commitHash !== undefined && event.commitHash === undefined)
497
+ event.commitHash = globalEnv.commitHash;
498
+ if (globalEnv.region !== undefined && event.region === undefined)
499
+ event.region = globalEnv.region;
500
+ formatted = event;
501
+ } else
502
+ formatted = {
503
+ timestamp: isoNow(),
504
+ level,
505
+ ...globalEnv,
506
+ ...event
507
+ };
508
+ if (globalRedact)
509
+ redactEvent(formatted, globalRedact);
510
+ if (!globalSilent)
511
+ if (globalPretty)
512
+ prettyPrintWideEvent(formatted);
513
+ else if (globalStringify)
514
+ console[getConsoleMethod(level)](JSON.stringify(formatted));
515
+ else
516
+ console[getConsoleMethod(level)](formatted);
517
+ if (globalDrain && !deferDrain)
518
+ Promise.resolve(globalDrain({ event: formatted })).catch((err) => {
519
+ console.error("[evlog] drain failed:", err);
520
+ });
521
+ return formatted;
522
+ }
523
+ function emitTaggedLog(level, tag, message) {
524
+ if (!globalEnabled)
525
+ return;
526
+ if (globalPretty && !globalSilent) {
527
+ if (!isLevelEnabled(level, globalMinLevel))
528
+ return;
529
+ if (!shouldSample(level))
530
+ return;
531
+ if (isClient()) {
532
+ const levelColor = getCssLevelColor(level);
533
+ const timestamp = isoNow().slice(11, 23);
534
+ console.log(`%c${timestamp}%c %c[${escapeFormatString(tag)}]%c ${escapeFormatString(message)}`, cssColors.dim, cssColors.reset, levelColor, cssColors.reset);
535
+ } else {
536
+ const color = getLevelColor(level);
537
+ const timestamp = isoNow().slice(11, 23);
538
+ console.log(`${colors.dim}${timestamp}${colors.reset} ${color}[${tag}]${colors.reset} ${message}`);
539
+ }
540
+ return;
541
+ }
542
+ emitWideEvent(level, {
543
+ tag,
544
+ message
545
+ });
546
+ }
547
+ function formatValue(value) {
548
+ if (value === null || value === undefined)
549
+ return String(value);
550
+ if (typeof value === "object") {
551
+ const pairs = [];
552
+ for (const [k, v] of Object.entries(value))
553
+ if (v !== undefined && v !== null)
554
+ if (typeof v === "object")
555
+ pairs.push(`${k}=${JSON.stringify(v)}`);
556
+ else
557
+ pairs.push(`${k}=${v}`);
558
+ return pairs.join(" ");
559
+ }
560
+ return String(value);
561
+ }
562
+ function formatCost(cost) {
563
+ if (cost < 0.01)
564
+ return `$${cost.toFixed(6)}`;
565
+ if (cost < 1)
566
+ return `$${cost.toFixed(4)}`;
567
+ return `$${cost.toFixed(2)}`;
568
+ }
569
+ function buildAIEntries(ai) {
570
+ const entries = [];
571
+ const headerParts = [];
572
+ if (ai.model) {
573
+ let m = String(ai.model);
574
+ if (ai.provider)
575
+ m += ` (${ai.provider})`;
576
+ headerParts.push(m);
577
+ }
578
+ if (ai.calls)
579
+ headerParts.push(`${ai.calls} call${ai.calls > 1 ? "s" : ""}`);
580
+ if (ai.steps && ai.steps > 1)
581
+ headerParts.push(`${ai.steps} steps`);
582
+ entries.push({
583
+ key: "ai",
584
+ value: headerParts.join(" \xB7 ")
585
+ });
586
+ const inputTokens = ai.inputTokens;
587
+ const outputTokens = ai.outputTokens;
588
+ const totalTokens = ai.totalTokens;
589
+ if (inputTokens !== undefined && outputTokens !== undefined) {
590
+ let tokLine = `${inputTokens} in \u2192 ${outputTokens} out`;
591
+ if (totalTokens)
592
+ tokLine += ` (${totalTokens} total)`;
593
+ const extras = [];
594
+ if (ai.cacheReadTokens)
595
+ extras.push(`${ai.cacheReadTokens} cache read`);
596
+ if (ai.cacheWriteTokens)
597
+ extras.push(`${ai.cacheWriteTokens} cache write`);
598
+ if (ai.reasoningTokens)
599
+ extras.push(`${ai.reasoningTokens} reasoning`);
600
+ if (extras.length)
601
+ tokLine += ` \xB7 ${extras.join(" \xB7 ")}`;
602
+ entries.push({
603
+ key: "ai.tokens",
604
+ value: tokLine
605
+ });
606
+ }
607
+ const msFirst = ai.msToFirstChunk;
608
+ const msFinish = ai.msToFinish;
609
+ const tps = ai.tokensPerSecond;
610
+ if (msFirst !== undefined || msFinish !== undefined) {
611
+ const parts = [];
612
+ if (msFirst !== undefined)
613
+ parts.push(`${formatDuration(msFirst)} to first chunk`);
614
+ if (msFinish !== undefined)
615
+ parts.push(`${formatDuration(msFinish)} total`);
616
+ let streamLine = parts.join(" \u2192 ");
617
+ if (tps)
618
+ streamLine += ` \xB7 ${tps} tok/s`;
619
+ entries.push({
620
+ key: "ai.streaming",
621
+ value: streamLine
622
+ });
623
+ }
624
+ if (ai.estimatedCost !== undefined)
625
+ entries.push({
626
+ key: "ai.cost",
627
+ value: formatCost(ai.estimatedCost)
628
+ });
629
+ if (ai.totalDurationMs !== undefined)
630
+ entries.push({
631
+ key: "ai.totalDuration",
632
+ value: formatDuration(ai.totalDurationMs)
633
+ });
634
+ const toolCalls = ai.toolCalls;
635
+ const tools = ai.tools;
636
+ const hasInputs = toolCalls?.length ? typeof toolCalls[0] === "object" : false;
637
+ if (tools?.length) {
638
+ const children = tools.map((t, idx) => {
639
+ const mark = t.success ? "\u2713" : "\u2717";
640
+ let line = `${t.name} ${formatDuration(t.durationMs)} ${mark}`;
641
+ if (t.error)
642
+ line += ` ${t.error}`;
643
+ if (hasInputs && toolCalls && idx < toolCalls.length) {
644
+ const tc = toolCalls[idx];
645
+ const inputStr = typeof tc.input === "string" ? tc.input : JSON.stringify(tc.input);
646
+ const truncated = inputStr.length > 100 ? `${inputStr.slice(0, 100)}\u2026` : inputStr;
647
+ line += ` ${truncated}`;
648
+ }
649
+ return line;
650
+ });
651
+ entries.push({
652
+ key: "ai.tools",
653
+ value: "",
654
+ children
655
+ });
656
+ } else if (toolCalls?.length)
657
+ if (hasInputs) {
658
+ const children = toolCalls.map((tc) => {
659
+ const inputStr = typeof tc.input === "string" ? tc.input : JSON.stringify(tc.input);
660
+ const truncated = inputStr.length > 100 ? `${inputStr.slice(0, 100)}\u2026` : inputStr;
661
+ return `${tc.name}(${truncated})`;
662
+ });
663
+ entries.push({
664
+ key: "ai.tools",
665
+ value: "",
666
+ children
667
+ });
668
+ } else
669
+ entries.push({
670
+ key: "ai.tools",
671
+ value: toolCalls.join(", ")
672
+ });
673
+ const stepsUsage = ai.stepsUsage;
674
+ if (stepsUsage?.length) {
675
+ const allSameModel = stepsUsage.every((s) => s.model === stepsUsage[0].model);
676
+ const children = stepsUsage.map((s) => {
677
+ let line = `${allSameModel ? "" : `${s.model} `}${s.inputTokens} in \u2192 ${s.outputTokens} out`;
678
+ const stepTools = s.toolCalls;
679
+ if (stepTools?.length)
680
+ line += ` [${stepTools.join(", ")}]`;
681
+ return line;
682
+ });
683
+ entries.push({
684
+ key: "ai.steps",
685
+ value: "",
686
+ children
687
+ });
688
+ } else if (ai.steps && ai.steps > 1)
689
+ entries.push({
690
+ key: "ai.steps",
691
+ value: String(ai.steps)
692
+ });
693
+ const embedding = ai.embedding;
694
+ if (embedding) {
695
+ const parts = [];
696
+ if (embedding.model)
697
+ parts.push(String(embedding.model));
698
+ parts.push(`${embedding.tokens} tokens`);
699
+ if (embedding.dimensions)
700
+ parts.push(`${embedding.dimensions}d`);
701
+ if (embedding.count)
702
+ parts.push(`${embedding.count} items`);
703
+ entries.push({
704
+ key: "ai.embedding",
705
+ value: parts.join(" \xB7 ")
706
+ });
707
+ }
708
+ if (ai.finishReason)
709
+ entries.push({
710
+ key: "ai.finishReason",
711
+ value: String(ai.finishReason)
712
+ });
713
+ if (ai.error)
714
+ entries.push({
715
+ key: "ai.error",
716
+ value: String(ai.error)
717
+ });
718
+ if (ai.responseId)
719
+ entries.push({
720
+ key: "ai.responseId",
721
+ value: String(ai.responseId)
722
+ });
723
+ return entries;
724
+ }
725
+ function prettyPrintWideEvent(event) {
726
+ const { timestamp, level, service, environment, version, ...rest } = event;
727
+ const ts = timestamp.slice(11, 23);
728
+ const browser = isClient();
729
+ const parts = [];
730
+ const styles = [];
731
+ if (browser) {
732
+ const lc = getCssLevelColor(level);
733
+ parts.push(`%c${ts}%c %c${level.toUpperCase()}%c %c[${escapeFormatString(String(service))}]%c`);
734
+ styles.push(cssColors.dim, cssColors.reset, lc, cssColors.reset, cssColors.cyan, cssColors.reset);
735
+ } else {
736
+ const lc = getLevelColor(level);
737
+ parts.push(`${colors.dim}${ts}${colors.reset} ${lc}${level.toUpperCase()}${colors.reset} ${colors.cyan}[${service}]${colors.reset}`);
738
+ }
739
+ if (rest.method && rest.path) {
740
+ parts.push(browser ? ` ${escapeFormatString(String(rest.method))} ${escapeFormatString(String(rest.path))}` : ` ${rest.method} ${rest.path}`);
741
+ delete rest.method;
742
+ delete rest.path;
743
+ }
744
+ if (rest.status) {
745
+ const sc = browser ? rest.status >= 400 ? cssColors.red : cssColors.green : rest.status >= 400 ? colors.red : colors.green;
746
+ if (browser) {
747
+ parts.push(` %c${rest.status}%c`);
748
+ styles.push(sc, cssColors.reset);
749
+ } else
750
+ parts.push(` ${sc}${rest.status}${colors.reset}`);
751
+ delete rest.status;
752
+ }
753
+ if (rest.duration) {
754
+ if (browser) {
755
+ parts.push(` %c${escapeFormatString(`in ${rest.duration}`)}%c`);
756
+ styles.push(cssColors.dim, cssColors.reset);
757
+ } else
758
+ parts.push(` ${colors.dim}in ${rest.duration}${colors.reset}`);
759
+ delete rest.duration;
760
+ }
761
+ console.log(parts.join(""), ...styles);
762
+ const aiData = rest.ai;
763
+ if (aiData && typeof aiData === "object")
764
+ delete rest.ai;
765
+ const restEntries = Object.entries(rest).filter(([_, v]) => v !== undefined);
766
+ const aiEntries = aiData ? buildAIEntries(aiData) : [];
767
+ const allEntries = [...restEntries.map(([key, value]) => ({
768
+ key,
769
+ value: formatValue(value)
770
+ })), ...aiEntries];
771
+ for (let i = 0;i < allEntries.length; i++) {
772
+ const entry = allEntries[i];
773
+ const hasChildren = entry.children && entry.children.length > 0;
774
+ const prefix = i === allEntries.length - 1 && !hasChildren ? "\u2514\u2500" : "\u251C\u2500";
775
+ if (browser) {
776
+ const val = entry.value ? ` ${escapeFormatString(entry.value)}` : "";
777
+ console.log(` %c${prefix}%c %c${escapeFormatString(entry.key)}:%c${val}`, cssColors.dim, cssColors.reset, cssColors.cyan, cssColors.reset);
778
+ } else {
779
+ const val = entry.value ? ` ${entry.value}` : "";
780
+ console.log(` ${colors.dim}${prefix}${colors.reset} ${colors.cyan}${entry.key}:${colors.reset}${val}`);
781
+ }
782
+ if (hasChildren) {
783
+ const connector = i === allEntries.length - 1 ? " " : "\u2502";
784
+ for (let j = 0;j < entry.children.length; j++) {
785
+ const child = entry.children[j];
786
+ const childPrefix = j === entry.children.length - 1 ? "\u2514\u2500" : "\u251C\u2500";
787
+ if (browser)
788
+ console.log(` %c${connector} ${childPrefix}%c ${escapeFormatString(child)}`, cssColors.dim, cssColors.reset);
789
+ else
790
+ console.log(` ${colors.dim}${connector} ${childPrefix}${colors.reset} ${child}`);
791
+ }
792
+ }
793
+ }
794
+ }
795
+ function createLogMethod(level) {
796
+ return function logMethod(tagOrEvent, message) {
797
+ if (typeof tagOrEvent === "string" && message !== undefined)
798
+ emitTaggedLog(level, tagOrEvent, message);
799
+ else if (typeof tagOrEvent === "object")
800
+ emitWideEvent(level, tagOrEvent);
801
+ else
802
+ emitTaggedLog(level, "log", String(tagOrEvent));
803
+ };
804
+ }
805
+ var _log = {
806
+ info: createLogMethod("info"),
807
+ error: createLogMethod("error"),
808
+ warn: createLogMethod("warn"),
809
+ debug: createLogMethod("debug")
810
+ };
811
+ var noopLogger = {
812
+ set() {},
813
+ error() {},
814
+ info() {},
815
+ warn() {},
816
+ emit() {
817
+ return null;
818
+ },
819
+ getContext() {
820
+ return {};
821
+ }
822
+ };
823
+ function createLogger(initialContext = {}, internalOptions) {
824
+ if (!globalEnabled)
825
+ return noopLogger;
826
+ const deferDrain = internalOptions?._deferDrain ?? false;
827
+ const startTime = Date.now();
828
+ const context = { ...initialContext };
829
+ let hasError = false;
830
+ let hasWarn = false;
831
+ let emitted = false;
832
+ function addLog(level, message) {
833
+ if (!Array.isArray(context.requestLogs))
834
+ context.requestLogs = [];
835
+ context.requestLogs.push({
836
+ level,
837
+ message,
838
+ timestamp: isoNow()
839
+ });
840
+ }
841
+ return {
842
+ set(data) {
843
+ if (emitted) {
844
+ const keys = Object.keys(data);
845
+ warnPostEmit("log.set()", `Keys dropped: ${keys.length ? keys.join(", ") : "(empty)"}.`);
846
+ return;
847
+ }
848
+ mergeInto(context, data);
849
+ },
850
+ error(error, errorContext) {
851
+ if (emitted) {
852
+ warnPostEmit("log.error()", `Keys dropped: ${(errorContext ? [...Object.keys(errorContext), "error"] : ["error"]).join(", ")}.`);
853
+ return;
854
+ }
855
+ hasError = true;
856
+ const err = typeof error === "string" ? new Error(error) : error;
857
+ if (errorContext)
858
+ mergeInto(context, errorContext);
859
+ const errorObj = {
860
+ name: err.name,
861
+ message: err.message,
862
+ stack: err.stack
863
+ };
864
+ const errRecord = err;
865
+ for (const k of [
866
+ "status",
867
+ "statusText",
868
+ "statusCode",
869
+ "statusMessage",
870
+ "data",
871
+ "cause",
872
+ "internal"
873
+ ])
874
+ if (k in err)
875
+ errorObj[k] = errRecord[k];
876
+ if (isPlainObject(context.error))
877
+ mergeInto(context.error, errorObj);
878
+ else
879
+ context.error = errorObj;
880
+ },
881
+ info(message, infoContext) {
882
+ if (emitted) {
883
+ warnPostEmit("log.info()", `Keys dropped: ${(infoContext ? ["message", ...Object.keys(infoContext).filter((k) => k !== "requestLogs")] : ["message"]).join(", ")}.`);
884
+ return;
885
+ }
886
+ addLog("info", message);
887
+ if (infoContext) {
888
+ const { requestLogs: _, ...rest } = infoContext;
889
+ mergeInto(context, rest);
890
+ }
891
+ },
892
+ warn(message, warnContext) {
893
+ if (emitted) {
894
+ warnPostEmit("log.warn()", `Keys dropped: ${(warnContext ? ["message", ...Object.keys(warnContext).filter((k) => k !== "requestLogs")] : ["message"]).join(", ")}.`);
895
+ return;
896
+ }
897
+ hasWarn = true;
898
+ addLog("warn", message);
899
+ if (warnContext) {
900
+ const { requestLogs: _, ...rest } = warnContext;
901
+ mergeInto(context, rest);
902
+ }
903
+ },
904
+ emit(overrides) {
905
+ if (emitted) {
906
+ warnPostEmit("log.emit()", "Ignoring duplicate emit.");
907
+ return null;
908
+ }
909
+ const durationMs = Date.now() - startTime;
910
+ const level = hasError ? "error" : hasWarn ? "warn" : "info";
911
+ let forceKeep = false;
912
+ if (overrides?._forceKeep)
913
+ forceKeep = true;
914
+ else if (globalSampling.keep?.length)
915
+ forceKeep = shouldKeep({
916
+ status: overrides?.status ?? context.status,
917
+ duration: durationMs,
918
+ path: context.path,
919
+ method: context.method,
920
+ context
921
+ });
922
+ if (!forceKeep && !shouldSample(level)) {
923
+ emitted = true;
924
+ return null;
925
+ }
926
+ if (overrides) {
927
+ const obj = overrides;
928
+ for (const key in obj)
929
+ if (key !== "_forceKeep")
930
+ context[key] = obj[key];
931
+ }
932
+ context.duration = formatDuration(durationMs);
933
+ const wide = emitWideEvent(level, context, deferDrain, true);
934
+ emitted = true;
935
+ return wide;
936
+ },
937
+ getContext() {
938
+ return { ...context };
939
+ }
940
+ };
941
+ }
942
+ if (typeof __EVLOG_CONFIG__ !== "undefined")
943
+ initLogger(__EVLOG_CONFIG__);
151
944
  // src/link.tsx
152
945
  import {
153
946
  createContext,
@@ -230,6 +1023,52 @@ function buildElement(route, data, rootLayout) {
230
1023
  return element;
231
1024
  }
232
1025
 
1026
+ // src/context-logger.ts
1027
+ import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
1028
+
1029
+ // ../../node_modules/.bun/evlog@2.13.0+449e6d239244fccb/node_modules/evlog/dist/elysia/index.mjs
1030
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
1031
+ import { Elysia } from "elysia";
1032
+ var storage = new AsyncLocalStorage2;
1033
+ var activeLoggers = /* @__PURE__ */ new WeakSet;
1034
+ function useLogger2() {
1035
+ const logger = storage.getStore();
1036
+ if (!logger || !activeLoggers.has(logger))
1037
+ throw new Error("[evlog] useLogger() was called outside of an evlog plugin context. Make sure app.use(evlog()) is registered before your routes.");
1038
+ return logger;
1039
+ }
1040
+
1041
+ // src/context-logger.ts
1042
+ var noopLogger2 = {
1043
+ set: () => {},
1044
+ error: () => {},
1045
+ info: () => {},
1046
+ warn: () => {},
1047
+ emit: () => null,
1048
+ getContext: () => ({}),
1049
+ fork: (_label, fn) => fn()
1050
+ };
1051
+ var syntheticRenderStorage = new AsyncLocalStorage3;
1052
+ function useLogger3() {
1053
+ try {
1054
+ return useLogger2();
1055
+ } catch {
1056
+ return syntheticRenderStorage.getStore() ?? noopLogger2;
1057
+ }
1058
+ }
1059
+ async function runInSyntheticRenderScope(fn, initialContext) {
1060
+ const logger = createLogger(initialContext);
1061
+ try {
1062
+ const result = await syntheticRenderStorage.run(logger, () => Promise.resolve(fn()));
1063
+ logger.emit();
1064
+ return result;
1065
+ } catch (err) {
1066
+ logger.error(err instanceof Error ? err : new Error(String(err)));
1067
+ logger.emit();
1068
+ throw err;
1069
+ }
1070
+ }
1071
+
233
1072
  // src/render/loaders.ts
234
1073
  function createLoaderCtx(ctx, accumulatedParentPromise) {
235
1074
  const cache = new Map;
@@ -255,7 +1094,7 @@ function createLoaderCtx(ctx, accumulatedParentPromise) {
255
1094
  }
256
1095
  async function runLoaders(route, ctx, _rootLayout) {
257
1096
  try {
258
- const ctxRecord = ctx;
1097
+ const ctxRecord = { ...ctx, log: useLogger3() };
259
1098
  const loaderMap = new Map;
260
1099
  let accumulatedParentPromise = Promise.resolve({});
261
1100
  for (const r of route.routeChain) {
@@ -318,18 +1157,6 @@ function getProductionTemplate() {
318
1157
  return null;
319
1158
  }
320
1159
  }
321
- // ../../node_modules/.bun/evlog@2.13.0+449e6d239244fccb/node_modules/evlog/dist/elysia/index.mjs
322
- import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
323
- import { Elysia } from "elysia";
324
- var storage = new AsyncLocalStorage2;
325
- var activeLoggers = /* @__PURE__ */ new WeakSet;
326
- function useLogger() {
327
- const logger = storage.getStore();
328
- if (!logger || !activeLoggers.has(logger))
329
- throw new Error("[evlog] useLogger() was called outside of an evlog plugin context. Make sure app.use(evlog()) is registered before your routes.");
330
- return logger;
331
- }
332
-
333
1160
  // src/runtime-env.ts
334
1161
  var IS_DEV = true;
335
1162
 
@@ -381,7 +1208,7 @@ async function renderForPath(route, params, root, origin, basePath) {
381
1208
  set: { headers: {} },
382
1209
  path: resolvedPath
383
1210
  };
384
- const prepared = await prepareRender(route, ctx, root, basePath);
1211
+ const prepared = await runInSyntheticRenderScope(() => prepareRender(route, ctx, root, basePath), { route: route.pattern });
385
1212
  if (prepared instanceof Response) {
386
1213
  throw prepared;
387
1214
  }
@@ -420,7 +1247,7 @@ async function renderSSR(route, ctx, root) {
420
1247
  if (prepared instanceof Response) {
421
1248
  return prepared;
422
1249
  }
423
- useLogger().set({
1250
+ useLogger2().set({
424
1251
  furin: { render: "ssr", route: route.pattern, loader_ms: prepared.loader_ms }
425
1252
  });
426
1253
  const { componentProps, element, headData, headers, template } = prepared;
@@ -472,7 +1299,7 @@ function serveISRCacheHit(cached, ctx, route, params, cacheKey, revalidate, root
472
1299
  if (etag) {
473
1300
  ctx.set.headers.etag = etag;
474
1301
  }
475
- useLogger().set({ furin: { render: "isr", route: route.pattern, cache: "hit" } });
1302
+ useLogger2().set({ furin: { render: "isr", route: route.pattern, cache: "hit" } });
476
1303
  return cached.html;
477
1304
  }
478
1305
  async function handleISR(route, ctx, root, buildId = "") {
@@ -494,7 +1321,7 @@ async function handleISR(route, ctx, root, buildId = "") {
494
1321
  const reactHtml = await streamToString(stream);
495
1322
  const html = assembleHTML(template, headData, reactHtml, componentProps);
496
1323
  const generatedAt = Date.now();
497
- useLogger().set({
1324
+ useLogger2().set({
498
1325
  furin: {
499
1326
  render: "isr",
500
1327
  route: route.pattern,
@@ -737,10 +1564,23 @@ async function handleSSGRequest(route, ctx, root, buildId) {
737
1564
  ctx.set.headers["cache-tag"] = resolvedPath;
738
1565
  return entry.html;
739
1566
  }
1567
+ var TOBJECT_STRUCTURAL_KEYS = new Set(["type", "properties", "required"]);
1568
+ function mergeRouteSchemas(routeChain, key) {
1569
+ const schemas = routeChain.map((r) => r[key]).filter(Boolean);
1570
+ if (schemas.length === 0) {
1571
+ return;
1572
+ }
1573
+ if (schemas.length === 1) {
1574
+ return schemas[0];
1575
+ }
1576
+ const mergedProperties = Object.assign({}, ...schemas.map((s) => s.properties ?? {}));
1577
+ const mergedOptions = Object.assign({}, ...schemas.map((s) => Object.fromEntries(Object.entries(s).filter(([k]) => !TOBJECT_STRUCTURAL_KEYS.has(k)))));
1578
+ return t.Object(mergedProperties, mergedOptions);
1579
+ }
740
1580
  function createRoutePlugin(route, root, buildId = "") {
741
1581
  const { pattern, routeChain } = route;
742
- const allParams = routeChain.findLast((r) => r.params)?.params;
743
- const allQuery = routeChain.findLast((r) => r.query)?.query;
1582
+ const allParams = mergeRouteSchemas(routeChain, "params");
1583
+ const allQuery = mergeRouteSchemas(routeChain, "query");
744
1584
  const hasQuerySchema = !!allQuery;
745
1585
  const plugin = new Elysia2;
746
1586
  if (allParams || allQuery) {
@@ -824,6 +1664,7 @@ export {
824
1664
  scanPages,
825
1665
  resolveMode,
826
1666
  queryDefaultRedirectHook,
1667
+ mergeRouteSchemas,
827
1668
  loadProdRoutes,
828
1669
  filePathToPattern,
829
1670
  createRoutePlugin