@emeryld/rrroutes-contract 2.7.12 → 2.8.0

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.mjs CHANGED
@@ -42,9 +42,9 @@ function collectNestedFieldSuggestions(shape, prefix = []) {
42
42
  }
43
43
  return suggestions;
44
44
  }
45
- function compilePath(path4, params) {
46
- if (!params) return path4;
47
- const withParams = path4.replace(/:([A-Za-z0-9_]+)/g, (_, k) => {
45
+ function compilePath(path, params) {
46
+ if (!params) return path;
47
+ const withParams = path.replace(/:([A-Za-z0-9_]+)/g, (_, k) => {
48
48
  const v = params[k];
49
49
  if (v === void 0 || v === null) throw new Error(`Missing param :${k}`);
50
50
  return String(v);
@@ -119,8 +119,8 @@ function buildLowProfileLeaf(leaf) {
119
119
  }
120
120
  };
121
121
  }
122
- var keyOf = (method, path4, encodeSafe) => {
123
- const key = `${method.toUpperCase()} ${path4}`;
122
+ var keyOf = (method, path, encodeSafe) => {
123
+ const key = `${method.toUpperCase()} ${path}`;
124
124
  return encodeSafe ? encodeURIComponent(key) : key;
125
125
  };
126
126
 
@@ -296,8 +296,8 @@ function joinPaths(parent, child) {
296
296
  if (!trimmedChild) return trimmedParent;
297
297
  return `${trimmedParent}/${trimmedChild}`;
298
298
  }
299
- function assertDynamicLayerUniqueness(path4, dynamicLayerMap) {
300
- const segments = path4.split("/").filter(Boolean);
299
+ function assertDynamicLayerUniqueness(path, dynamicLayerMap) {
300
+ const segments = path.split("/").filter(Boolean);
301
301
  if (segments.length === 0) return;
302
302
  for (let i = 0; i < segments.length; i++) {
303
303
  const segment = segments[i];
@@ -335,1350 +335,21 @@ function finalize(leaves) {
335
335
  function defineSocketEvents(config, events) {
336
336
  return { config, events };
337
337
  }
338
-
339
- // src/export/schemaIntrospection.ts
340
- import * as z3 from "zod";
341
- var serializableSchemaKinds = [
342
- "object",
343
- "string",
344
- "number",
345
- "boolean",
346
- "bigint",
347
- "date",
348
- "array",
349
- "enum",
350
- "literal",
351
- "union",
352
- "record",
353
- "tuple",
354
- "unknown",
355
- "any"
356
- ];
357
- var globalHandlers = {};
358
- function registerSchemaIntrospectionHandler(kind, handler) {
359
- globalHandlers[kind] = handler;
360
- }
361
- function clearSchemaIntrospectionHandlers() {
362
- for (const key of Object.keys(globalHandlers)) {
363
- delete globalHandlers[key];
364
- }
365
- }
366
- function getDef(schema) {
367
- if (!schema || typeof schema !== "object") return void 0;
368
- const anySchema = schema;
369
- return anySchema._zod?.def ?? anySchema._def;
370
- }
371
- function getDescription(schema) {
372
- const anyZ = z3;
373
- const registry = anyZ.globalRegistry?.get ? anyZ.globalRegistry.get(schema) : void 0;
374
- if (registry && typeof registry.description === "string") {
375
- return registry.description;
376
- }
377
- const def = getDef(schema);
378
- if (def && typeof def.description === "string") {
379
- return def.description;
380
- }
381
- return void 0;
382
- }
383
- function unwrap(schema) {
384
- let current = schema;
385
- let optional = false;
386
- let nullable = false;
387
- const ZodEffectsCtor = z3.ZodEffects;
388
- while (true) {
389
- if (ZodEffectsCtor && current instanceof ZodEffectsCtor) {
390
- const def = getDef(current) || {};
391
- const sourceType = typeof current.sourceType === "function" ? current.sourceType() : def.schema;
392
- if (!sourceType) break;
393
- current = sourceType;
394
- continue;
395
- }
396
- if (current instanceof z3.ZodOptional) {
397
- optional = true;
398
- const def = getDef(current);
399
- current = def && def.innerType || current;
400
- continue;
401
- }
402
- if (current instanceof z3.ZodNullable) {
403
- nullable = true;
404
- const def = getDef(current);
405
- current = def && def.innerType || current;
406
- continue;
407
- }
408
- if (current instanceof z3.ZodDefault) {
409
- const def = getDef(current);
410
- current = def && def.innerType || current;
411
- continue;
412
- }
413
- break;
414
- }
415
- return { base: current, optional, nullable };
416
- }
417
- function mergeProps(a, b) {
418
- if (!a && !b) return void 0;
419
- return { ...a ?? {}, ...b ?? {} };
420
- }
421
- function inferKind(schema) {
422
- if (schema instanceof z3.ZodString) return "string";
423
- if (schema instanceof z3.ZodNumber) return "number";
424
- if (schema instanceof z3.ZodBoolean) return "boolean";
425
- if (schema instanceof z3.ZodBigInt) return "bigint";
426
- if (schema instanceof z3.ZodDate) return "date";
427
- if (schema instanceof z3.ZodArray) return "array";
428
- if (schema instanceof z3.ZodObject) return "object";
429
- if (schema instanceof z3.ZodUnion) return "union";
430
- if (schema instanceof z3.ZodLiteral) return "literal";
431
- if (schema instanceof z3.ZodEnum) return "enum";
432
- if (schema instanceof z3.ZodRecord) return "record";
433
- if (schema instanceof z3.ZodTuple) return "tuple";
434
- if (schema instanceof z3.ZodUnknown) return "unknown";
435
- if (schema instanceof z3.ZodAny) return "any";
436
- return "unknown";
437
- }
438
- var defaultHandlers = {
439
- intersection({ base, def, node }, ctx) {
440
- const left = def?.left;
441
- const right = def?.right;
442
- const leftNode = left ? ctx.introspect(left) : void 0;
443
- const rightNode = right ? ctx.introspect(right) : void 0;
444
- const leftIsObj = leftNode?.kind === "object" && !!leftNode.properties;
445
- const rightIsObj = rightNode?.kind === "object" && !!rightNode.properties;
446
- if (leftIsObj && rightIsObj) {
447
- node.kind = "object";
448
- node.description = node.description ?? leftNode.description ?? rightNode.description;
449
- node.properties = mergeProps(leftNode.properties, rightNode.properties);
450
- return node;
451
- }
452
- if (leftNode && rightNode) {
453
- node.properties = {
454
- left: leftNode,
455
- right: rightNode
456
- };
457
- }
458
- return node;
459
- },
460
- object({ base, def, node }, ctx) {
461
- const rawShape = base.shape ?? (def && typeof def.shape === "function" ? def.shape() : def?.shape);
462
- const shape = typeof rawShape === "function" ? rawShape() : rawShape ?? {};
463
- const props = {};
464
- for (const key of Object.keys(shape)) {
465
- const child = shape[key];
466
- const childNode = ctx.introspect(child);
467
- if (childNode) props[key] = childNode;
468
- }
469
- node.properties = props;
470
- return node;
471
- },
472
- array({ def, node }, ctx) {
473
- const inner = def && def.element || def && def.type || void 0;
474
- if (inner) {
475
- node.element = ctx.introspect(inner);
476
- }
477
- return node;
478
- },
479
- union({ def, node }, ctx) {
480
- const options = def && def.options || [];
481
- node.union = options.map((opt) => ctx.introspect(opt)).filter(Boolean);
482
- return node;
483
- },
484
- literal({ def, node }) {
485
- if (def) {
486
- if (Array.isArray(def.values)) {
487
- node.literal = def.values.length === 1 ? def.values[0] : def.values.slice();
488
- } else {
489
- node.literal = def.value;
490
- }
491
- }
492
- return node;
493
- },
494
- enum({ def, node }) {
495
- if (def) {
496
- if (Array.isArray(def.values)) {
497
- node.enumValues = def.values.slice();
498
- } else if (def.entries && typeof def.entries === "object") {
499
- node.enumValues = Object.values(def.entries).map((v) => String(v));
500
- }
501
- }
502
- return node;
503
- }
504
- };
505
- function createSchemaIntrospector(options = {}) {
506
- const handlers = {
507
- ...defaultHandlers,
508
- ...globalHandlers,
509
- ...options.handlers ?? {}
510
- };
511
- const introspect = (schema) => {
512
- if (!schema) return void 0;
513
- const unwrapped = unwrap(schema);
514
- const base = unwrapped.base;
515
- const def = getDef(base);
516
- const kind = base instanceof z3.ZodIntersection ? "intersection" : inferKind(base);
517
- const node = {
518
- kind: kind === "intersection" ? "unknown" : kind,
519
- optional: unwrapped.optional || void 0,
520
- nullable: unwrapped.nullable || void 0,
521
- description: getDescription(base)
522
- };
523
- const handler = handlers[kind];
524
- if (!handler) return node;
525
- return handler(
526
- {
527
- schema,
528
- base,
529
- def,
530
- kind,
531
- optional: unwrapped.optional,
532
- nullable: unwrapped.nullable,
533
- node
534
- },
535
- {
536
- zod: z3,
537
- introspect,
538
- getDef,
539
- unwrap,
540
- getDescription
541
- }
542
- );
543
- };
544
- return introspect;
545
- }
546
- function introspectSchema(schema, options = {}) {
547
- const introspect = createSchemaIntrospector(options);
548
- return introspect(schema);
549
- }
550
-
551
- // src/export/serializeLeafContract.ts
552
- function serializeContractSchema(schema, options) {
553
- return schema ? introspectSchema(routeSchemaParse(schema), options) : void 0;
554
- }
555
- function serializeBodyFiles(cfg) {
556
- if (!Array.isArray(cfg.bodyFiles) || cfg.bodyFiles.length === 0) {
557
- return void 0;
558
- }
559
- return cfg.bodyFiles.map(({ name, maxCount }) => ({ name, maxCount }));
560
- }
561
- function serializeLeafContract(leaf, options = {}) {
562
- const cfg = leaf.cfg;
563
- return {
564
- key: `${leaf.method.toUpperCase()} ${leaf.path}`,
565
- method: leaf.method,
566
- path: leaf.path,
567
- cfg: {
568
- description: cfg.description,
569
- summary: cfg.summary,
570
- docsGroup: cfg.docsGroup,
571
- tags: Array.isArray(cfg.tags) ? cfg.tags.slice() : void 0,
572
- deprecated: cfg.deprecated,
573
- stability: cfg.stability,
574
- docsHidden: cfg.docsHidden,
575
- docsMeta: cfg.docsMeta,
576
- feed: cfg.feed,
577
- bodyFiles: serializeBodyFiles(cfg),
578
- schemas: {
579
- body: serializeContractSchema(cfg.bodySchema, options),
580
- query: serializeContractSchema(cfg.querySchema, options),
581
- params: serializeContractSchema(cfg.paramsSchema, options),
582
- output: serializeContractSchema(cfg.outputSchema, options),
583
- outputMeta: serializeContractSchema(cfg.outputMetaSchema, options),
584
- queryExtension: serializeContractSchema(cfg.queryExtensionSchema, options)
585
- }
586
- }
587
- };
588
- }
589
- function serializeLeavesContract(leaves, options = {}) {
590
- return leaves.map((leaf) => serializeLeafContract(leaf, options));
591
- }
592
-
593
- // src/export/flattenSchema.ts
594
- function formatLiteralType(literal) {
595
- if (typeof literal === "string") return literal;
596
- if (typeof literal === "number" || typeof literal === "boolean" || typeof literal === "bigint") {
597
- return String(literal);
598
- }
599
- if (literal === null) return "null";
600
- if (Array.isArray(literal)) {
601
- return literal.map((item) => formatLiteralType(item)).join("|");
602
- }
603
- if (typeof literal === "object") {
604
- try {
605
- return JSON.stringify(literal);
606
- } catch {
607
- return "object";
608
- }
609
- }
610
- return "unknown";
611
- }
612
- function normalizeType(schema) {
613
- switch (schema.kind) {
614
- case "string":
615
- case "number":
616
- case "date":
617
- case "boolean":
618
- case "object":
619
- case "array":
620
- return schema.kind;
621
- case "enum": {
622
- if (Array.isArray(schema.enumValues) && schema.enumValues.length > 0) {
623
- return schema.enumValues.join("|");
624
- }
625
- return "unknown";
626
- }
627
- case "literal": {
628
- return formatLiteralType(schema.literal);
629
- }
630
- default:
631
- return "unknown";
632
- }
633
- }
634
- function isNonEmptyPath(path4) {
635
- return typeof path4 === "string" && path4.length > 0;
636
- }
637
- function setNode(out, path4, schema, inherited) {
638
- if (!isNonEmptyPath(path4)) return;
639
- out[path4] = {
640
- type: normalizeType(schema),
641
- nullable: inherited.nullable || Boolean(schema.nullable),
642
- optional: inherited.optional || Boolean(schema.optional),
643
- literal: schema.kind === "literal" ? schema.literal : void 0
644
- };
645
- }
646
- function flattenInto(out, schema, path4, inherited) {
647
- if (!schema || !isNonEmptyPath(path4)) return;
648
- const nextInherited = {
649
- optional: inherited.optional || Boolean(schema.optional),
650
- nullable: inherited.nullable || Boolean(schema.nullable)
651
- };
652
- if (schema.kind === "union" && Array.isArray(schema.union) && schema.union.length > 0) {
653
- schema.union.forEach((option, index) => {
654
- const optionPath = `${path4}-${index + 1}`;
655
- flattenInto(out, option, optionPath, inherited);
656
- });
657
- return;
658
- }
659
- setNode(out, path4, schema, inherited);
660
- if (schema.kind === "object" && schema.properties) {
661
- for (const [key, child] of Object.entries(schema.properties)) {
662
- const childPath = `${path4}.${key}`;
663
- flattenInto(out, child, childPath, nextInherited);
664
- }
665
- return;
666
- }
667
- if (schema.kind === "array" && schema.element) {
668
- flattenInto(out, schema.element, `${path4}[]`, nextInherited);
669
- }
670
- }
671
- function flattenSerializableSchema(schema, path4) {
672
- const out = {};
673
- flattenInto(out, schema, path4, { optional: false, nullable: false });
674
- return out;
675
- }
676
- function isSerializedLeaf(value) {
677
- if (!value || typeof value !== "object") return false;
678
- const item = value;
679
- return typeof item.key === "string" && !!item.cfg && typeof item.cfg === "object";
680
- }
681
- function flattenLeafSchemas(leaf) {
682
- const serialized = isSerializedLeaf(leaf) ? leaf : serializeLeafContract(leaf);
683
- const out = {};
684
- const sections = serialized.cfg.schemas;
685
- Object.assign(out, flattenSerializableSchema(sections.params, "params"));
686
- Object.assign(out, flattenSerializableSchema(sections.query, "query"));
687
- Object.assign(out, flattenSerializableSchema(sections.body, "body"));
688
- Object.assign(out, flattenSerializableSchema(sections.output, "output"));
689
- return out;
690
- }
691
-
692
- // src/export/exportFinalizedLeaves.ts
693
- import fs from "fs/promises";
694
- import path2 from "path";
695
- import { spawn } from "child_process";
696
-
697
- // src/export/defaultViewerTemplate.ts
698
- var DEFAULT_VIEWER_TEMPLATE = `<!doctype html>
699
- <html lang="en">
700
- <head>
701
- <meta charset="UTF-8" />
702
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
703
- <title>Finalized Leaves Viewer</title>
704
- <style>
705
- :root {
706
- --bg: #212121;
707
- --surface: #2a2a2a;
708
- --border: #4a4a4a;
709
- --text: #fffafa;
710
- --muted: #c8c2c2;
711
- --accent: #a764d3;
712
- }
713
- body {
714
- margin: 0;
715
- font-family: 'Iosevka Web', 'SFMono-Regular', Menlo, Consolas, monospace;
716
- color: var(--text);
717
- background: var(--bg);
718
- }
719
- .wrap { max-width: 1100px; margin: 0 auto; padding: 20px; }
720
- .card { background: var(--surface); border: 1px solid var(--border); border-radius: 12px; padding: 14px; }
721
- .meta { color: var(--muted); font-size: 12px; }
722
- #results { margin-top: 12px; display: grid; gap: 8px; }
723
- details { background: var(--surface); border: 1px solid var(--border); border-radius: 10px; padding: 8px 10px; }
724
- summary { cursor: pointer; font-weight: 700; color: var(--accent); }
725
- pre { margin: 10px 0 0; overflow: auto; border: 1px solid var(--border); border-radius: 8px; padding: 10px; background: #303030; color: var(--text); }
726
- </style>
727
- </head>
728
- <body>
729
- <div class="wrap">
730
- <h1>Finalized Leaves Viewer (Baked)</h1>
731
- <div class="card">
732
- <div id="status" class="meta">Waiting for baked payload...</div>
733
- </div>
734
- <div id="results"></div>
735
- </div>
736
-
737
- <!--__FINALIZED_LEAVES_BAKED_PAYLOAD__-->
738
-
739
- <script>
740
- const statusEl = document.getElementById('status')
741
- const resultsEl = document.getElementById('results')
742
- const payload = window.__FINALIZED_LEAVES_PAYLOAD
743
-
744
- if (!payload || !Array.isArray(payload.leaves)) {
745
- statusEl.textContent = 'No baked payload found in this HTML file.'
746
- } else {
747
- statusEl.textContent = 'Loaded baked payload with ' + payload.leaves.length + ' routes.'
748
-
749
- const toHref = (source) => {
750
- if (!source || !source.file) return null
751
- const normalizedPath = String(source.file).replace(/\\\\/g, '/')
752
- const platform =
753
- (navigator.userAgentData && navigator.userAgentData.platform) ||
754
- navigator.platform ||
755
- ''
756
- const isWindows = /win/i.test(platform)
757
- const vscodePath = isWindows
758
- ? normalizedPath.replace(/^\\/+/, '')
759
- : normalizedPath.startsWith('/')
760
- ? normalizedPath
761
- : '/' + normalizedPath
762
- const line = Number.isFinite(source.line) ? source.line : 1
763
- const column = Number.isFinite(source.column) ? source.column : 1
764
- return 'vscode://file/' + encodeURI(vscodePath) + ':' + line + ':' + column
765
- }
766
-
767
- const sourceDisplay = (source) => {
768
- return ''
769
- }
770
-
771
- payload.leaves.forEach((leaf) => {
772
- const details = document.createElement('details')
773
- const summary = document.createElement('summary')
774
- summary.textContent = String(leaf.method || '').toUpperCase() + ' ' + (leaf.path || '')
775
-
776
- const pre = document.createElement('pre')
777
- pre.textContent = JSON.stringify(leaf, null, 2)
778
-
779
- const source = payload.sourceByLeaf && payload.sourceByLeaf[leaf.key]
780
- let sourceWrap = null
781
- if (source) {
782
- sourceWrap = document.createElement('div')
783
- sourceWrap.className = 'meta'
784
-
785
- const definitionHref = toHref(source.definition)
786
- if (definitionHref) {
787
- const label = document.createElement('div')
788
- const link = document.createElement('a')
789
- link.href = definitionHref
790
- link.target = '_blank'
791
- link.rel = 'noopener noreferrer'
792
- link.textContent = 'definition'
793
- label.appendChild(link)
794
- sourceWrap.appendChild(label)
795
- }
796
-
797
- if (source.schemas && typeof source.schemas === 'object') {
798
- Object.entries(source.schemas).forEach(([name, schema]) => {
799
- if (!schema) return
800
- const href = toHref(schema)
801
- const row = document.createElement('div')
802
- if (href) {
803
- const link = document.createElement('a')
804
- link.href = href
805
- link.target = '_blank'
806
- link.rel = 'noopener noreferrer'
807
- link.textContent =
808
- name + ': ' + (schema.sourceName || schema.tag || '<anonymous>')
809
- row.appendChild(link)
810
- } else {
811
- row.textContent = name + ': ' + (schema.sourceName || schema.tag || '<anonymous>')
812
- }
813
- sourceWrap.appendChild(row)
814
- })
815
- }
816
-
817
- }
818
-
819
- details.appendChild(summary)
820
- if (sourceWrap) details.appendChild(sourceWrap)
821
- details.appendChild(pre)
822
- resultsEl.appendChild(details)
823
- })
824
- }
825
- </script>
826
- </body>
827
- </html>
828
- `;
829
-
830
- // src/export/extractLeafSourceByAst.ts
831
- import path from "path";
832
- import ts from "typescript";
833
- var SCHEMA_KEYS = [
834
- "bodySchema",
835
- "querySchema",
836
- "paramsSchema",
837
- "outputSchema",
838
- "outputMetaSchema",
839
- "queryExtensionSchema"
840
- ];
841
- var HTTP_METHODS = /* @__PURE__ */ new Set(["get", "post", "put", "patch", "delete"]);
842
- var MAX_RECURSION_DEPTH = 120;
843
- function toLocation(node) {
844
- const sourceFile = node.getSourceFile();
845
- const { line, character } = sourceFile.getLineAndCharacterOfPosition(
846
- node.getStart(sourceFile)
847
- );
848
- return {
849
- file: path.resolve(sourceFile.fileName),
850
- line: line + 1,
851
- column: character + 1
852
- };
853
- }
854
- function markFile(ctx, sourceFile) {
855
- if (!sourceFile) return;
856
- ctx.visitedFilePaths.add(path.resolve(sourceFile.fileName));
857
- }
858
- function trimPreview(text, max = 80) {
859
- const normalized = text.replace(/\s+/g, " ").trim();
860
- return normalized.length > max ? `${normalized.slice(0, max)}...` : normalized;
861
- }
862
- function unwrapExpression(expression) {
863
- let current = expression;
864
- while (true) {
865
- if (ts.isParenthesizedExpression(current) || ts.isAsExpression(current) || ts.isTypeAssertionExpression(current) || ts.isNonNullExpression(current) || ts.isSatisfiesExpression(current)) {
866
- current = current.expression;
867
- continue;
868
- }
869
- break;
870
- }
871
- return current;
872
- }
873
- function getTextName(name) {
874
- if (ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name)) {
875
- return name.text;
876
- }
877
- return void 0;
878
- }
879
- function joinPaths2(parent, child) {
880
- if (!parent) return child;
881
- if (!child) return parent;
882
- const trimmedParent = parent.endsWith("/") ? parent.replace(/\/+$/, "") : parent;
883
- const trimmedChild = child.startsWith("/") ? child.replace(/^\/+/, "") : child;
884
- if (!trimmedChild) return trimmedParent;
885
- return `${trimmedParent}/${trimmedChild}`;
886
- }
887
- function buildLeafKey(method, leafPath) {
888
- return `${method.toUpperCase()} ${leafPath}`;
889
- }
890
- function normalizeResourceBase(raw) {
891
- if (raw === "") return "";
892
- if (raw.startsWith("/") || raw.startsWith(":") || raw.startsWith("*")) {
893
- return raw;
894
- }
895
- return `/${raw}`;
896
- }
897
- function getModuleSymbol(checker, sourceFile) {
898
- return checker.getSymbolAtLocation(sourceFile);
899
- }
900
- function getAliasedSymbolIfNeeded(checker, symbol) {
901
- if ((symbol.flags & ts.SymbolFlags.Alias) !== 0) {
902
- try {
903
- return checker.getAliasedSymbol(symbol);
904
- } catch {
905
- return symbol;
906
- }
907
- }
908
- return symbol;
909
- }
910
- function findSourceFile(program, filePath) {
911
- const wanted = path.resolve(filePath);
912
- const normalizedWanted = path.normalize(wanted);
913
- return program.getSourceFiles().find((file) => path.normalize(path.resolve(file.fileName)) === normalizedWanted);
914
- }
915
- function declarationToExpression(declaration) {
916
- if (!declaration) return void 0;
917
- if (ts.isVariableDeclaration(declaration)) {
918
- return declaration.initializer;
919
- }
920
- if (ts.isExportAssignment(declaration)) {
921
- return declaration.expression;
922
- }
923
- if (ts.isPropertyAssignment(declaration)) {
924
- return declaration.initializer;
925
- }
926
- if (ts.isShorthandPropertyAssignment(declaration)) {
927
- return declaration.name;
928
- }
929
- if (ts.isBindingElement(declaration)) {
930
- return declaration.initializer;
931
- }
932
- if (ts.isEnumMember(declaration)) {
933
- return declaration.initializer;
934
- }
935
- return void 0;
936
- }
937
- function symbolKey(symbol) {
938
- const decl = symbol.declarations?.[0];
939
- if (!decl) return `${symbol.getName()}#${symbol.flags}`;
940
- const file = path.resolve(decl.getSourceFile().fileName);
941
- return `${file}:${decl.getStart()}:${symbol.getName()}`;
942
- }
943
- function resolveSymbolFromNode(node, ctx) {
944
- const symbol = ctx.checker.getSymbolAtLocation(node);
945
- if (!symbol) {
946
- ctx.unresolvedReferences += 1;
947
- return void 0;
948
- }
949
- const target = getAliasedSymbolIfNeeded(ctx.checker, symbol);
950
- const key = symbolKey(target);
951
- ctx.visitedSymbolKeys.add(key);
952
- return target;
953
- }
954
- function getExpressionFromSymbol(symbol, ctx, depth) {
955
- const key = symbolKey(symbol);
956
- if (ctx.activeSymbols.has(key)) return void 0;
957
- if (depth > MAX_RECURSION_DEPTH) return void 0;
958
- ctx.activeSymbols.add(key);
959
- try {
960
- const declaration = symbol.declarations?.[0];
961
- markFile(ctx, declaration?.getSourceFile());
962
- const direct = declarationToExpression(declaration);
963
- if (direct) return direct;
964
- if (declaration && ts.isImportSpecifier(declaration)) {
965
- const target = getAliasedSymbolIfNeeded(ctx.checker, symbol);
966
- if (target !== symbol) {
967
- return getExpressionFromSymbol(target, ctx, depth + 1);
968
- }
969
- }
970
- return void 0;
971
- } finally {
972
- ctx.activeSymbols.delete(key);
973
- }
974
- }
975
- function resolveIdentifierExpression(identifier, ctx, depth) {
976
- const symbol = resolveSymbolFromNode(identifier, ctx);
977
- if (!symbol) return void 0;
978
- return getExpressionFromSymbol(symbol, ctx, depth);
979
- }
980
- function resolvePropertyExpression(expression, ctx, depth) {
981
- if (depth > MAX_RECURSION_DEPTH) return void 0;
982
- if (ts.isPropertyAccessExpression(expression)) {
983
- const symbol = resolveSymbolFromNode(expression.name, ctx);
984
- if (symbol) {
985
- const fromSymbol = getExpressionFromSymbol(symbol, ctx, depth + 1);
986
- if (fromSymbol) return fromSymbol;
987
- }
988
- } else if (expression.argumentExpression) {
989
- const symbol = resolveSymbolFromNode(expression.argumentExpression, ctx);
990
- if (symbol) {
991
- const fromSymbol = getExpressionFromSymbol(symbol, ctx, depth + 1);
992
- if (fromSymbol) return fromSymbol;
993
- }
994
- }
995
- const ownerExpr = evaluateExpressionReference(expression.expression, ctx, depth + 1);
996
- const owner = ownerExpr ? maybeObjectLiteral(ownerExpr, ctx, depth + 1) : void 0;
997
- if (!owner) return void 0;
998
- const propName = ts.isPropertyAccessExpression(expression) ? expression.name.text : expression.argumentExpression && ts.isStringLiteralLike(expression.argumentExpression) ? expression.argumentExpression.text : void 0;
999
- if (!propName) return void 0;
1000
- for (const property of owner.properties) {
1001
- if (ts.isPropertyAssignment(property) && getTextName(property.name) === propName) {
1002
- return property.initializer;
1003
- }
1004
- if (ts.isShorthandPropertyAssignment(property) && property.name.text === propName) {
1005
- return property.name;
1006
- }
1007
- }
1008
- return void 0;
1009
- }
1010
- function evaluateExpressionReference(expression, ctx, depth) {
1011
- const resolved = unwrapExpression(expression);
1012
- markFile(ctx, resolved.getSourceFile());
1013
- if (depth > MAX_RECURSION_DEPTH) return void 0;
1014
- if (ts.isIdentifier(resolved)) {
1015
- return resolveIdentifierExpression(resolved, ctx, depth + 1);
1016
- }
1017
- if (ts.isPropertyAccessExpression(resolved) || ts.isElementAccessExpression(resolved)) {
1018
- return resolvePropertyExpression(resolved, ctx, depth + 1);
1019
- }
1020
- return void 0;
1021
- }
1022
- function resolveExportExpression(sourceFile, exportName, checker) {
1023
- const moduleSymbol = getModuleSymbol(checker, sourceFile);
1024
- if (!moduleSymbol) return void 0;
1025
- const exports = checker.getExportsOfModule(moduleSymbol);
1026
- const explicit = exports.find((entry) => entry.getName() === exportName);
1027
- if (explicit) {
1028
- const declaration = getAliasedSymbolIfNeeded(checker, explicit).declarations?.[0];
1029
- return declarationToExpression(declaration);
1030
- }
1031
- const defaultExport = exports.find((entry) => entry.getName() === "default");
1032
- if (!defaultExport) return void 0;
1033
- const defaultDecl = getAliasedSymbolIfNeeded(checker, defaultExport).declarations?.[0];
1034
- const defaultExpr = declarationToExpression(defaultDecl);
1035
- if (!defaultExpr) return void 0;
1036
- const resolved = unwrapExpression(defaultExpr);
1037
- if (!ts.isObjectLiteralExpression(resolved)) return void 0;
1038
- for (const property of resolved.properties) {
1039
- if (!ts.isPropertyAssignment(property)) continue;
1040
- const propertyName = getTextName(property.name);
1041
- if (propertyName !== exportName) continue;
1042
- return property.initializer;
1043
- }
1044
- return void 0;
1045
- }
1046
- function maybeObjectLiteral(expression, ctx, depth = 0) {
1047
- if (!expression || depth > MAX_RECURSION_DEPTH) return void 0;
1048
- const resolved = unwrapExpression(expression);
1049
- markFile(ctx, resolved.getSourceFile());
1050
- if (ts.isObjectLiteralExpression(resolved)) return resolved;
1051
- const referenced = evaluateExpressionReference(resolved, ctx, depth + 1);
1052
- if (!referenced) return void 0;
1053
- return maybeObjectLiteral(referenced, ctx, depth + 1);
1054
- }
1055
- function collectSchemaExpressionsFromObject(objectLiteral, ctx, depth) {
1056
- const schemas = {};
1057
- for (const property of objectLiteral.properties) {
1058
- if (ts.isSpreadAssignment(property)) {
1059
- const spreadObject = maybeObjectLiteral(property.expression, ctx, depth + 1);
1060
- if (!spreadObject) continue;
1061
- Object.assign(
1062
- schemas,
1063
- collectSchemaExpressionsFromObject(spreadObject, ctx, depth + 1)
1064
- );
1065
- continue;
1066
- }
1067
- if (ts.isPropertyAssignment(property)) {
1068
- const key = getTextName(property.name);
1069
- if (!key || !SCHEMA_KEYS.includes(key)) continue;
1070
- schemas[key] = property.initializer;
1071
- continue;
1072
- }
1073
- if (ts.isShorthandPropertyAssignment(property)) {
1074
- const key = property.name.text;
1075
- if (!SCHEMA_KEYS.includes(key)) continue;
1076
- schemas[key] = property.name;
1077
- }
1078
- }
1079
- return schemas;
1080
- }
1081
- function extractSchemaExpressions(cfgExpression, ctx, depth) {
1082
- const objectLiteral = maybeObjectLiteral(cfgExpression, ctx, depth);
1083
- if (!objectLiteral) return {};
1084
- return collectSchemaExpressionsFromObject(objectLiteral, ctx, depth);
1085
- }
1086
- function getNearestVariableName(node) {
1087
- let current = node;
1088
- while (current) {
1089
- if (ts.isVariableDeclaration(current) && ts.isIdentifier(current.name)) {
1090
- return current.name.text;
1091
- }
1092
- current = current.parent;
1093
- }
1094
- return void 0;
1095
- }
1096
- function isAllAccess(expression) {
1097
- if (ts.isPropertyAccessExpression(expression)) {
1098
- return expression.name.text === "all";
1099
- }
1100
- return Boolean(
1101
- expression.argumentExpression && ts.isStringLiteralLike(expression.argumentExpression) && expression.argumentExpression.text === "all"
1102
- );
1103
- }
1104
- function evaluateBranchExpression(expression, ctx, depth) {
1105
- const resolved = unwrapExpression(expression);
1106
- markFile(ctx, resolved.getSourceFile());
1107
- if (depth > MAX_RECURSION_DEPTH) return void 0;
1108
- if (ts.isIdentifier(resolved)) {
1109
- const valueExpr = resolveIdentifierExpression(resolved, ctx, depth + 1);
1110
- if (!valueExpr) return void 0;
1111
- return evaluateBranchExpression(valueExpr, ctx, depth + 1);
1112
- }
1113
- if (!ts.isCallExpression(resolved)) return void 0;
1114
- const call = resolved;
1115
- if (ts.isIdentifier(call.expression) && call.expression.text === "resource") {
1116
- const firstArg = call.arguments[0];
1117
- if (!firstArg || !ts.isStringLiteralLike(firstArg)) {
1118
- ctx.unsupportedShapeSeen = true;
1119
- return void 0;
1120
- }
1121
- return { base: normalizeResourceBase(firstArg.text), leaves: [] };
1122
- }
1123
- if (!ts.isPropertyAccessExpression(call.expression)) {
1124
- ctx.unsupportedShapeSeen = true;
1125
- return void 0;
1126
- }
1127
- const owner = call.expression.expression;
1128
- const method = call.expression.name.text;
1129
- const branch = evaluateBranchExpression(owner, ctx, depth + 1);
1130
- if (!branch) return void 0;
1131
- if (method === "with") return branch;
1132
- if (HTTP_METHODS.has(method)) {
1133
- const cfgExpression = call.arguments[0];
1134
- const schemas = extractSchemaExpressions(cfgExpression, ctx, depth + 1);
1135
- const nextLeaf = {
1136
- method,
1137
- path: branch.base,
1138
- definitionNode: call.expression.name,
1139
- schemas
1140
- };
1141
- return {
1142
- ...branch,
1143
- leaves: [...branch.leaves, nextLeaf]
1144
- };
1145
- }
1146
- if (method === "sub") {
1147
- const mountedLeaves = call.arguments.flatMap(
1148
- (arg) => evaluateLeavesFromExpression(arg, ctx, depth + 1)
1149
- );
1150
- const prefixed = mountedLeaves.map((leaf) => ({
1151
- ...leaf,
1152
- path: joinPaths2(branch.base, leaf.path)
1153
- }));
1154
- return {
1155
- ...branch,
1156
- leaves: [...branch.leaves, ...prefixed]
1157
- };
1158
- }
1159
- ctx.unsupportedShapeSeen = true;
1160
- return void 0;
1161
- }
1162
- function expressionKey(expression) {
1163
- const source = expression.getSourceFile();
1164
- return `${path.resolve(source.fileName)}:${expression.getStart(source)}:${expression.getEnd()}:${expression.kind}`;
1165
- }
1166
- function evaluateLeavesFromExpression(expression, ctx, depth = 0) {
1167
- const resolved = unwrapExpression(expression);
1168
- markFile(ctx, resolved.getSourceFile());
1169
- const key = expressionKey(resolved);
1170
- if (ctx.activeExpressionKeys.has(key)) return [];
1171
- if (depth > MAX_RECURSION_DEPTH) return [];
1172
- ctx.activeExpressionKeys.add(key);
1173
- try {
1174
- if (ts.isIdentifier(resolved)) {
1175
- const valueExpr = resolveIdentifierExpression(resolved, ctx, depth + 1);
1176
- if (!valueExpr) return [];
1177
- return evaluateLeavesFromExpression(valueExpr, ctx, depth + 1);
1178
- }
1179
- if (ts.isPropertyAccessExpression(resolved) || ts.isElementAccessExpression(resolved)) {
1180
- if (isAllAccess(resolved)) {
1181
- return evaluateLeavesFromExpression(resolved.expression, ctx, depth + 1);
1182
- }
1183
- const refExpr = resolvePropertyExpression(resolved, ctx, depth + 1);
1184
- if (refExpr) {
1185
- return evaluateLeavesFromExpression(refExpr, ctx, depth + 1);
1186
- }
1187
- return [];
1188
- }
1189
- if (ts.isArrayLiteralExpression(resolved)) {
1190
- const leaves = [];
1191
- for (const element of resolved.elements) {
1192
- if (ts.isSpreadElement(element)) {
1193
- leaves.push(...evaluateLeavesFromExpression(element.expression, ctx, depth + 1));
1194
- continue;
1195
- }
1196
- leaves.push(...evaluateLeavesFromExpression(element, ctx, depth + 1));
1197
- }
1198
- return leaves;
1199
- }
1200
- if (ts.isCallExpression(resolved)) {
1201
- if (ts.isIdentifier(resolved.expression)) {
1202
- const callName = resolved.expression.text;
1203
- if (callName === "finalize") {
1204
- const arg = resolved.arguments[0];
1205
- if (!arg) return [];
1206
- return evaluateLeavesFromExpression(arg, ctx, depth + 1);
1207
- }
1208
- if (callName === "mergeArrays") {
1209
- return resolved.arguments.flatMap(
1210
- (arg) => evaluateLeavesFromExpression(arg, ctx, depth + 1)
1211
- );
1212
- }
1213
- }
1214
- if (ts.isPropertyAccessExpression(resolved.expression)) {
1215
- const prop = resolved.expression.name.text;
1216
- if (prop === "done") {
1217
- const branch2 = evaluateBranchExpression(
1218
- resolved.expression.expression,
1219
- ctx,
1220
- depth + 1
1221
- );
1222
- return branch2?.leaves ?? [];
1223
- }
1224
- }
1225
- const refExpr = evaluateExpressionReference(resolved, ctx, depth + 1);
1226
- if (refExpr) return evaluateLeavesFromExpression(refExpr, ctx, depth + 1);
1227
- ctx.unsupportedShapeSeen = true;
1228
- return [];
1229
- }
1230
- const branch = evaluateBranchExpression(resolved, ctx, depth + 1);
1231
- if (branch) return branch.leaves;
1232
- ctx.unsupportedShapeSeen = true;
1233
- return [];
1234
- } finally {
1235
- ctx.activeExpressionKeys.delete(key);
1236
- }
1237
- }
1238
- function resolveSchemaMetadata(expression, ctx) {
1239
- const resolved = unwrapExpression(expression);
1240
- if (ts.isIdentifier(resolved)) {
1241
- const symbol = resolveSymbolFromNode(resolved, ctx);
1242
- const declaration = symbol?.declarations?.[0];
1243
- const locationNode = declaration ? ts.isVariableDeclaration(declaration) ? declaration.name : declaration : resolved;
1244
- const sourceName = declaration && ts.isVariableDeclaration(declaration) && ts.isIdentifier(declaration.name) ? declaration.name.text : resolved.text;
1245
- return {
1246
- ...toLocation(locationNode),
1247
- sourceName,
1248
- tag: declaration ? void 0 : "<anonymous>"
1249
- };
1250
- }
1251
- if (ts.isPropertyAccessExpression(resolved) || ts.isElementAccessExpression(resolved)) {
1252
- return {
1253
- ...toLocation(resolved),
1254
- sourceName: trimPreview(resolved.getText()),
1255
- tag: "<expression>"
1256
- };
1257
- }
1258
- return {
1259
- ...toLocation(resolved),
1260
- sourceName: trimPreview(resolved.getText()),
1261
- tag: "<inline>"
1262
- };
1263
- }
1264
- function parseTsConfig(cwd, tsconfigPath) {
1265
- const resolvedTsconfig = tsconfigPath ? path.resolve(cwd, tsconfigPath) : ts.findConfigFile(cwd, ts.sys.fileExists, "tsconfig.json");
1266
- if (!resolvedTsconfig) {
1267
- return void 0;
1268
- }
1269
- const read = ts.readConfigFile(resolvedTsconfig, ts.sys.readFile);
1270
- if (read.error) {
1271
- throw new Error(ts.flattenDiagnosticMessageText(read.error.messageText, "\n"));
1272
- }
1273
- const parsed = ts.parseJsonConfigFileContent(
1274
- read.config,
1275
- ts.sys,
1276
- path.dirname(resolvedTsconfig),
1277
- void 0,
1278
- resolvedTsconfig
1279
- );
1280
- const nonEmptyInputErrors = parsed.errors.filter((entry) => entry.code !== 18003);
1281
- if (nonEmptyInputErrors.length > 0) {
1282
- throw new Error(
1283
- nonEmptyInputErrors.map((entry) => ts.flattenDiagnosticMessageText(entry.messageText, "\n")).join("\n")
1284
- );
1285
- }
1286
- return { resolvedTsconfig, parsed };
1287
- }
1288
- function createProgramWithFallback(parsed, moduleFileAbs) {
1289
- const base = ts.createProgram({
1290
- rootNames: parsed.fileNames,
1291
- options: parsed.options
1292
- });
1293
- if (findSourceFile(base, moduleFileAbs)) {
1294
- return base;
1295
- }
1296
- const rootNames = Array.from(/* @__PURE__ */ new Set([...parsed.fileNames, moduleFileAbs]));
1297
- return ts.createProgram({ rootNames, options: parsed.options });
1298
- }
1299
- function extractLeafSourceByAst({
1300
- modulePath,
1301
- exportName,
1302
- tsconfigPath,
1303
- cwd = process.cwd()
1304
- }) {
1305
- const parsedConfig = parseTsConfig(cwd, tsconfigPath);
1306
- if (!parsedConfig) {
1307
- return {
1308
- sourceByLeaf: {},
1309
- reason: "module_not_in_program",
1310
- stats: { visitedSymbols: 0, visitedFiles: 0, unresolvedReferences: 0 }
1311
- };
1312
- }
1313
- const moduleAbs = path.resolve(cwd, modulePath);
1314
- const program = createProgramWithFallback(parsedConfig.parsed, moduleAbs);
1315
- const checker = program.getTypeChecker();
1316
- const moduleFile = findSourceFile(program, moduleAbs);
1317
- if (!moduleFile) {
1318
- return {
1319
- sourceByLeaf: {},
1320
- tsconfigPath: parsedConfig.resolvedTsconfig,
1321
- reason: "module_not_in_program",
1322
- stats: { visitedSymbols: 0, visitedFiles: 0, unresolvedReferences: 0 }
1323
- };
1324
- }
1325
- const exportedExpression = resolveExportExpression(moduleFile, exportName, checker);
1326
- if (!exportedExpression) {
1327
- return {
1328
- sourceByLeaf: {},
1329
- tsconfigPath: parsedConfig.resolvedTsconfig,
1330
- reason: "export_not_found",
1331
- stats: { visitedSymbols: 0, visitedFiles: 1, unresolvedReferences: 0 }
1332
- };
1333
- }
1334
- const ctx = {
1335
- checker,
1336
- activeExpressionKeys: /* @__PURE__ */ new Set(),
1337
- activeSymbols: /* @__PURE__ */ new Set(),
1338
- visitedSymbolKeys: /* @__PURE__ */ new Set(),
1339
- visitedFilePaths: /* @__PURE__ */ new Set([path.resolve(moduleFile.fileName)]),
1340
- unresolvedReferences: 0,
1341
- unsupportedShapeSeen: false
1342
- };
1343
- const evaluatedLeaves = evaluateLeavesFromExpression(exportedExpression, ctx, 0);
1344
- const sourceByLeaf = {};
1345
- for (const leaf of evaluatedLeaves) {
1346
- const key = buildLeafKey(leaf.method, leaf.path);
1347
- const definition = {
1348
- ...toLocation(leaf.definitionNode),
1349
- symbolName: getNearestVariableName(leaf.definitionNode)
1350
- };
1351
- ctx.visitedFilePaths.add(definition.file);
1352
- const schemas = {};
1353
- for (const schemaKey of SCHEMA_KEYS) {
1354
- const schemaExpression = leaf.schemas[schemaKey];
1355
- if (!schemaExpression) continue;
1356
- const schemaMeta = resolveSchemaMetadata(schemaExpression, ctx);
1357
- ctx.visitedFilePaths.add(schemaMeta.file);
1358
- schemas[schemaKey] = schemaMeta;
1359
- }
1360
- sourceByLeaf[key] = { definition, schemas };
1361
- }
1362
- const reason = Object.keys(sourceByLeaf).length > 0 ? void 0 : ctx.unsupportedShapeSeen ? "unsupported_expression_shape" : "resolved_zero_leaves";
1363
- return {
1364
- sourceByLeaf,
1365
- tsconfigPath: parsedConfig.resolvedTsconfig,
1366
- reason,
1367
- stats: {
1368
- visitedSymbols: ctx.visitedSymbolKeys.size,
1369
- visitedFiles: ctx.visitedFilePaths.size,
1370
- unresolvedReferences: ctx.unresolvedReferences
1371
- }
1372
- };
1373
- }
1374
-
1375
- // src/export/exportFinalizedLeaves.ts
1376
- function isRegistry(value) {
1377
- return typeof value === "object" && value !== null && "all" in value && "byKey" in value;
1378
- }
1379
- function getLeaves(input) {
1380
- return isRegistry(input) ? input.all : input;
1381
- }
1382
- function buildMeta(sourceExtraction) {
1383
- return {
1384
- generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1385
- description: "Finalized RRRoutes leaves export with serialized schemas and flattened schema paths for downstream processing.",
1386
- sourceExtraction,
1387
- fieldCatalog: {
1388
- leaf: ["key", "method", "path", "cfg"],
1389
- cfg: [
1390
- "description?",
1391
- "summary?",
1392
- "docsGroup?",
1393
- "tags?",
1394
- "deprecated?",
1395
- "stability?",
1396
- "docsHidden?",
1397
- "docsMeta?",
1398
- "feed?",
1399
- "bodyFiles?",
1400
- "schemas"
1401
- ],
1402
- schemaNode: [
1403
- "kind",
1404
- "optional?",
1405
- "nullable?",
1406
- "description?",
1407
- "properties?",
1408
- "element?",
1409
- "union?",
1410
- "literal?",
1411
- "enumValues?"
1412
- ],
1413
- flatSchemaEntry: ["type", "nullable", "optional", "literal?"]
1414
- },
1415
- flattening: {
1416
- notation: "dot+[]",
1417
- unionBranchSuffix: "-N",
1418
- sections: ["params", "query", "body", "output"]
1419
- }
1420
- };
1421
- }
1422
- var BAKED_PAYLOAD_MARKER = "<!--__FINALIZED_LEAVES_BAKED_PAYLOAD__-->";
1423
- function escapePayloadForInlineScript(payload) {
1424
- return JSON.stringify(payload).replace(/<\//g, "<\\/").replace(/<!--/g, "<\\!--");
1425
- }
1426
- function injectPayloadIntoViewerHtml(htmlTemplate, payload) {
1427
- const payloadScript = `${BAKED_PAYLOAD_MARKER}
1428
- <script id="finalized-leaves-baked-payload">window.__FINALIZED_LEAVES_PAYLOAD = ${escapePayloadForInlineScript(
1429
- payload
1430
- )};</script>`;
1431
- if (htmlTemplate.includes(BAKED_PAYLOAD_MARKER)) {
1432
- return htmlTemplate.replace(BAKED_PAYLOAD_MARKER, payloadScript);
1433
- }
1434
- if (htmlTemplate.includes("</body>")) {
1435
- return htmlTemplate.replace("</body>", `${payloadScript}
1436
- </body>`);
1437
- }
1438
- return `${payloadScript}
1439
- ${htmlTemplate}`;
1440
- }
1441
- async function resolveViewerTemplatePath(viewerTemplateFile) {
1442
- if (viewerTemplateFile) {
1443
- const resolved = path2.resolve(viewerTemplateFile);
1444
- await fs.access(resolved);
1445
- return resolved;
1446
- }
1447
- const candidates = [
1448
- path2.resolve(
1449
- process.cwd(),
1450
- "node_modules/@emeryld/rrroutes-contract/tools/finalized-leaves-viewer.html"
1451
- ),
1452
- path2.resolve(
1453
- process.cwd(),
1454
- "tools/finalized-leaves-viewer.html"
1455
- ),
1456
- path2.resolve(
1457
- process.cwd(),
1458
- "packages/contract/tools/finalized-leaves-viewer.html"
1459
- )
1460
- ];
1461
- for (const candidate of candidates) {
1462
- try {
1463
- await fs.access(candidate);
1464
- return candidate;
1465
- } catch {
1466
- }
1467
- }
1468
- return void 0;
1469
- }
1470
- async function writeJsonExport(payload, outFile) {
1471
- const resolved = path2.resolve(outFile);
1472
- await fs.mkdir(path2.dirname(resolved), { recursive: true });
1473
- await fs.writeFile(resolved, `${JSON.stringify(payload, null, 2)}
1474
- `, "utf8");
1475
- return resolved;
1476
- }
1477
- async function writeBakedHtmlExport(payload, htmlFile, viewerTemplateFile) {
1478
- const templatePath = await resolveViewerTemplatePath(viewerTemplateFile);
1479
- const template = templatePath ? await fs.readFile(templatePath, "utf8") : DEFAULT_VIEWER_TEMPLATE;
1480
- const baked = injectPayloadIntoViewerHtml(template, payload);
1481
- const resolved = path2.resolve(htmlFile);
1482
- await fs.mkdir(path2.dirname(resolved), { recursive: true });
1483
- await fs.writeFile(resolved, baked, "utf8");
1484
- return resolved;
1485
- }
1486
- async function openHtmlInBrowser(filePath) {
1487
- const resolved = path2.resolve(filePath);
1488
- const platform = process.platform;
1489
- if (platform === "darwin") {
1490
- spawn("open", [resolved], { detached: true, stdio: "ignore" }).unref();
1491
- return;
1492
- }
1493
- if (platform === "win32") {
1494
- spawn("cmd", ["/c", "start", "", resolved], {
1495
- detached: true,
1496
- stdio: "ignore"
1497
- }).unref();
1498
- return;
1499
- }
1500
- spawn("xdg-open", [resolved], { detached: true, stdio: "ignore" }).unref();
1501
- }
1502
- async function writeFinalizedLeavesExport(payload, outFileOrOptions) {
1503
- const options = typeof outFileOrOptions === "string" ? { outFile: outFileOrOptions } : outFileOrOptions;
1504
- const written = {};
1505
- if (options.outFile) {
1506
- written.outFile = await writeJsonExport(payload, options.outFile);
1507
- }
1508
- if (options.htmlFile) {
1509
- written.htmlFile = await writeBakedHtmlExport(
1510
- payload,
1511
- options.htmlFile,
1512
- options.viewerTemplateFile
1513
- );
1514
- }
1515
- if (options.openOnFinish) {
1516
- if (!written.htmlFile) {
1517
- throw new Error(
1518
- "openOnFinish requires htmlFile. Provide htmlFile to open the baked viewer."
1519
- );
1520
- }
1521
- await openHtmlInBrowser(written.htmlFile);
1522
- }
1523
- return written;
1524
- }
1525
- async function exportFinalizedLeaves(input, options = {}) {
1526
- const leaves = getLeaves(input);
1527
- const serializedLeaves = serializeLeavesContract(leaves, options);
1528
- const schemaFlatByLeaf = Object.fromEntries(
1529
- serializedLeaves.map((leaf) => [leaf.key, flattenLeafSchemas(leaf)])
1530
- );
1531
- const sourceByLeaf = {};
1532
- let sourceExtraction;
1533
- if (options.includeSource) {
1534
- const modulePath = options.sourceModulePath;
1535
- const exportName = options.sourceExportName ?? "leaves";
1536
- if (modulePath) {
1537
- const extracted = extractLeafSourceByAst({
1538
- modulePath,
1539
- exportName,
1540
- tsconfigPath: options.tsconfigPath
1541
- });
1542
- const allowedLeafKeys = new Set(serializedLeaves.map((leaf) => leaf.key));
1543
- for (const [key, source] of Object.entries(extracted.sourceByLeaf)) {
1544
- if (allowedLeafKeys.has(key)) {
1545
- sourceByLeaf[key] = source;
1546
- }
1547
- }
1548
- sourceExtraction = {
1549
- mode: "ast",
1550
- enabled: true,
1551
- modulePath: path2.resolve(modulePath),
1552
- exportName,
1553
- tsconfigPath: extracted.tsconfigPath,
1554
- resolvedLeafCount: Object.keys(sourceByLeaf).length,
1555
- reason: extracted.reason,
1556
- stats: extracted.stats
1557
- };
1558
- } else {
1559
- sourceExtraction = {
1560
- mode: "ast",
1561
- enabled: false,
1562
- exportName,
1563
- tsconfigPath: options.tsconfigPath ? path2.resolve(options.tsconfigPath) : void 0,
1564
- resolvedLeafCount: 0,
1565
- reason: "resolved_zero_leaves",
1566
- stats: {
1567
- visitedSymbols: 0,
1568
- visitedFiles: 0,
1569
- unresolvedReferences: 0
1570
- }
1571
- };
1572
- }
1573
- }
1574
- const payload = {
1575
- _meta: buildMeta(sourceExtraction),
1576
- leaves: serializedLeaves,
1577
- schemaFlatByLeaf,
1578
- sourceByLeaf: options.includeSource && Object.keys(sourceByLeaf).length > 0 ? sourceByLeaf : void 0
1579
- };
1580
- if (options.outFile || options.htmlFile) {
1581
- await writeFinalizedLeavesExport(payload, {
1582
- outFile: options.outFile,
1583
- htmlFile: options.htmlFile,
1584
- viewerTemplateFile: options.viewerTemplateFile,
1585
- openOnFinish: options.openOnFinish
1586
- });
1587
- }
1588
- return payload;
1589
- }
1590
-
1591
- // src/export/exportFinalizedLeaves.cli.ts
1592
- import path3 from "path";
1593
- import { pathToFileURL } from "url";
1594
- function parseFinalizedLeavesCliArgs(argv) {
1595
- const args = /* @__PURE__ */ new Map();
1596
- let withSource = false;
1597
- for (let i = 0; i < argv.length; i += 1) {
1598
- const key = argv[i];
1599
- if (key === "--") continue;
1600
- if (!key.startsWith("--")) continue;
1601
- if (key === "--with-source") {
1602
- withSource = true;
1603
- continue;
1604
- }
1605
- const value = argv[i + 1];
1606
- if (!value || value.startsWith("--")) {
1607
- throw new Error(`Missing value for ${key}`);
1608
- }
1609
- args.set(key, value);
1610
- i += 1;
1611
- }
1612
- const modulePath = args.get("--module");
1613
- if (!modulePath) {
1614
- throw new Error("Missing required --module argument");
1615
- }
1616
- return {
1617
- modulePath,
1618
- exportName: args.get("--export") ?? "leaves",
1619
- outFile: args.get("--out") ?? "finalized-leaves.export.json",
1620
- withSource,
1621
- tsconfigPath: args.get("--tsconfig") ?? void 0
1622
- };
1623
- }
1624
- async function loadFinalizedLeavesInput({
1625
- modulePath,
1626
- exportName
1627
- }) {
1628
- const resolvedModule = path3.resolve(process.cwd(), modulePath);
1629
- const mod = await import(pathToFileURL(resolvedModule).href);
1630
- const value = mod[exportName] ?? (mod.default && mod.default[exportName]);
1631
- if (!value) {
1632
- throw new Error(`Export "${exportName}" not found in module: ${resolvedModule}`);
1633
- }
1634
- return value;
1635
- }
1636
- async function runExportFinalizedLeavesCli(argv) {
1637
- const args = parseFinalizedLeavesCliArgs(argv);
1638
- const input = await loadFinalizedLeavesInput(args);
1639
- const payload = await exportFinalizedLeaves(input, {
1640
- outFile: args.outFile,
1641
- includeSource: args.withSource,
1642
- tsconfigPath: args.tsconfigPath,
1643
- sourceModulePath: args.modulePath,
1644
- sourceExportName: args.exportName
1645
- });
1646
- return {
1647
- payload,
1648
- outFile: path3.resolve(args.outFile)
1649
- };
1650
- }
1651
338
  export {
1652
- DEFAULT_VIEWER_TEMPLATE,
1653
339
  buildCacheKey,
1654
340
  buildLowProfileLeaf,
1655
- clearSchemaIntrospectionHandlers,
1656
341
  collectNestedFieldSuggestions,
1657
342
  compilePath,
1658
- createSchemaIntrospector,
1659
343
  defineSocketEvents,
1660
- exportFinalizedLeaves,
1661
- extractLeafSourceByAst,
1662
344
  finalize,
1663
- flattenLeafSchemas,
1664
- flattenSerializableSchema,
1665
345
  getZodShape,
1666
- introspectSchema,
1667
346
  keyOf,
1668
- loadFinalizedLeavesInput,
1669
347
  lowProfileParse,
1670
348
  lowProfileSafeParse,
1671
349
  mergeArrays,
1672
350
  mergeSchemas,
1673
- parseFinalizedLeavesCliArgs,
1674
- registerSchemaIntrospectionHandler,
1675
351
  resource,
1676
352
  routeSchemaParse,
1677
- runExportFinalizedLeavesCli,
1678
- serializableSchemaKinds,
1679
- serializeLeafContract,
1680
- serializeLeavesContract,
1681
- staticBase,
1682
- writeFinalizedLeavesExport
353
+ staticBase
1683
354
  };
1684
355
  //# sourceMappingURL=index.mjs.map