apps 0.0.1-beta.13 → 0.0.1-beta.14

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/js/openapi.js CHANGED
@@ -1,6 +1,10 @@
1
1
  import {
2
2
  parse
3
3
  } from "./chunk-UVL56Z6E.js";
4
+ import {
5
+ substitute_default,
6
+ test_default
7
+ } from "./chunk-OD3KFKZD.js";
4
8
  import {
5
9
  protocolOperations,
6
10
  protocolRouter
@@ -38,7 +42,8 @@ import {
38
42
  } from "./chunk-6HSH75OI.js";
39
43
  import "./chunk-N7YDVXYJ.js";
40
44
  import {
41
- ProviderError
45
+ ProviderError,
46
+ cacheLimits
42
47
  } from "./chunk-R3EV5FTO.js";
43
48
  import "./chunk-JU7VHODU.js";
44
49
  import {
@@ -56,8 +61,7 @@ import {
56
61
  } from "./chunk-5T57N25Q.js";
57
62
  import "./chunk-PZB6T6KU.js";
58
63
  import {
59
- JsonObject,
60
- JsonValue
64
+ JsonObject
61
65
  } from "./chunk-27F7W2LG.js";
62
66
  import {
63
67
  Deferred_exports,
@@ -73,7 +77,7 @@ import {
73
77
  import "./chunk-CZ7CSFO4.js";
74
78
 
75
79
  // src/implementation/swagger-client.ts
76
- var loadSwaggerClient = () => import("./es-APDZKREY.js").then((module) => module.default);
80
+ var loadSwaggerClient = () => import("./es-DIULA3ZF.js").then((module) => module.default);
77
81
 
78
82
  // src/implementation/openapi-request.ts
79
83
  var bodyRecovery = Schema_exports.decodeUnknownOption(Schema_exports.Struct({ recovery: ApiErrorRecovery }));
@@ -538,538 +542,2496 @@ var OpenapiCompileError = class extends Schema_exports.TaggedError()(
538
542
  ) {
539
543
  };
540
544
 
541
- // src/contracts/openapi-document.ts
542
- var Server = Schema_exports.Struct({ url: Schema_exports.String, variables: Schema_exports.optionalKey(JsonObject) });
543
- var Specification = Schema_exports.Struct({
544
- openapi: Schema_exports.String,
545
- servers: Schema_exports.optionalKey(Schema_exports.Array(Server)),
546
- paths: Schema_exports.Record(Schema_exports.String, JsonObject),
547
- components: Schema_exports.optionalKey(
548
- Schema_exports.Struct({
549
- schemas: Schema_exports.optionalKey(Schema_exports.Record(Schema_exports.String, JsonObject)),
550
- securitySchemes: Schema_exports.optionalKey(Schema_exports.Record(Schema_exports.String, JsonObject))
551
- })
552
- ),
553
- security: Schema_exports.optionalKey(
554
- Schema_exports.Array(Schema_exports.Record(Schema_exports.String, Schema_exports.Array(Schema_exports.String)))
555
- )
545
+ // ../../node_modules/.bun/js-yaml@5.4.2/node_modules/js-yaml/dist/js-yaml.mjs
546
+ var NOT_RESOLVED = /* @__PURE__ */ Symbol("NOT_RESOLVED");
547
+ function defineScalarTag(tagName, options) {
548
+ return {
549
+ tagName,
550
+ nodeKind: "scalar",
551
+ implicit: options.implicit ?? false,
552
+ matchByTagPrefix: options.matchByTagPrefix ?? false,
553
+ implicitFirstChars: options.implicitFirstChars ?? null,
554
+ resolve: options.resolve,
555
+ identify: options.identify,
556
+ represent: options.represent ?? ((data) => String(data)),
557
+ representTagName: options.representTagName ?? (() => tagName)
558
+ };
559
+ }
560
+ function defineSequenceTag(tagName, options) {
561
+ const carrierIsResult = options.finalize === void 0;
562
+ return {
563
+ tagName,
564
+ nodeKind: "sequence",
565
+ implicit: false,
566
+ matchByTagPrefix: options.matchByTagPrefix ?? false,
567
+ create: options.create,
568
+ addItem: options.addItem,
569
+ finalize: options.finalize ?? ((carrier) => carrier),
570
+ carrierIsResult,
571
+ identify: options.identify,
572
+ represent: options.represent ?? ((data) => data),
573
+ representTagName: options.representTagName ?? (() => tagName)
574
+ };
575
+ }
576
+ function defineMappingTag(tagName, options) {
577
+ const carrierIsResult = options.finalize === void 0;
578
+ return {
579
+ tagName,
580
+ nodeKind: "mapping",
581
+ implicit: false,
582
+ matchByTagPrefix: options.matchByTagPrefix ?? false,
583
+ create: options.create,
584
+ addPair: options.addPair,
585
+ has: options.has,
586
+ keys: options.keys,
587
+ get: options.get,
588
+ finalize: options.finalize ?? ((carrier) => carrier),
589
+ carrierIsResult,
590
+ identify: options.identify,
591
+ represent: options.represent ?? ((data) => data),
592
+ representTagName: options.representTagName ?? (() => tagName)
593
+ };
594
+ }
595
+ var strTag = defineScalarTag("tag:yaml.org,2002:str", {
596
+ resolve: (source) => source,
597
+ identify: (data) => typeof data === "string"
556
598
  });
557
- var Operation = Schema_exports.Struct({
558
- operationId: Schema_exports.optionalKey(Schema_exports.String),
559
- responses: Schema_exports.optionalKey(Schema_exports.Record(Schema_exports.String, JsonObject)),
560
- summary: Schema_exports.optionalKey(Schema_exports.String),
561
- description: Schema_exports.optionalKey(Schema_exports.String),
562
- parameters: Schema_exports.optionalKey(Schema_exports.Array(JsonObject)),
563
- requestBody: Schema_exports.optionalKey(JsonObject),
564
- security: Schema_exports.optionalKey(
565
- Schema_exports.Array(Schema_exports.Record(Schema_exports.String, Schema_exports.Array(Schema_exports.String)))
566
- ),
567
- servers: Schema_exports.optionalKey(Schema_exports.Array(Server))
599
+ var NULL_VALUES$1 = [
600
+ "",
601
+ "~",
602
+ "null",
603
+ "Null",
604
+ "NULL"
605
+ ];
606
+ var nullCoreTag = defineScalarTag("tag:yaml.org,2002:null", {
607
+ implicit: true,
608
+ implicitFirstChars: [
609
+ "",
610
+ "~",
611
+ "n",
612
+ "N"
613
+ ],
614
+ resolve: (source) => {
615
+ if (NULL_VALUES$1.indexOf(source) !== -1) return null;
616
+ return NOT_RESOLVED;
617
+ },
618
+ identify: (object2) => object2 === null,
619
+ represent: () => "null"
568
620
  });
569
-
570
- // ../../node_modules/.bun/@scalar+helpers@0.14.0/node_modules/@scalar/helpers/dist/object/is-object.js
571
- var isObject2 = (value) => {
572
- if (value === null || typeof value !== "object") {
573
- return false;
621
+ var nullJsonTag = defineScalarTag("tag:yaml.org,2002:null", {
622
+ implicit: true,
623
+ implicitFirstChars: ["n"],
624
+ resolve: (source, isExplicit) => {
625
+ if (source === "null" || isExplicit && source === "") return null;
626
+ return NOT_RESOLVED;
627
+ },
628
+ identify: (object2) => object2 === null,
629
+ represent: () => "null"
630
+ });
631
+ var NULL_VALUES = [
632
+ "",
633
+ "~",
634
+ "null",
635
+ "Null",
636
+ "NULL"
637
+ ];
638
+ var nullYaml11Tag = defineScalarTag("tag:yaml.org,2002:null", {
639
+ implicit: true,
640
+ implicitFirstChars: [
641
+ "",
642
+ "~",
643
+ "n",
644
+ "N"
645
+ ],
646
+ resolve: (source) => {
647
+ if (NULL_VALUES.indexOf(source) !== -1) return null;
648
+ return NOT_RESOLVED;
649
+ },
650
+ identify: (object2) => object2 === null,
651
+ represent: () => "null"
652
+ });
653
+ var TRUE_VALUES$2 = [
654
+ "true",
655
+ "True",
656
+ "TRUE"
657
+ ];
658
+ var FALSE_VALUES$2 = [
659
+ "false",
660
+ "False",
661
+ "FALSE"
662
+ ];
663
+ var boolCoreTag = defineScalarTag("tag:yaml.org,2002:bool", {
664
+ implicit: true,
665
+ implicitFirstChars: [
666
+ "t",
667
+ "T",
668
+ "f",
669
+ "F"
670
+ ],
671
+ resolve: (source) => {
672
+ if (TRUE_VALUES$2.indexOf(source) !== -1) return true;
673
+ if (FALSE_VALUES$2.indexOf(source) !== -1) return false;
674
+ return NOT_RESOLVED;
675
+ },
676
+ identify: (object2) => Object.prototype.toString.call(object2) === "[object Boolean]",
677
+ represent: (object2) => object2 ? "true" : "false"
678
+ });
679
+ var TRUE_VALUES$1 = ["true"];
680
+ var FALSE_VALUES$1 = ["false"];
681
+ var boolJsonTag = defineScalarTag("tag:yaml.org,2002:bool", {
682
+ implicit: true,
683
+ implicitFirstChars: ["t", "f"],
684
+ resolve: (source) => {
685
+ if (TRUE_VALUES$1.indexOf(source) !== -1) return true;
686
+ if (FALSE_VALUES$1.indexOf(source) !== -1) return false;
687
+ return NOT_RESOLVED;
688
+ },
689
+ identify: (object2) => Object.prototype.toString.call(object2) === "[object Boolean]",
690
+ represent: (object2) => object2 ? "true" : "false"
691
+ });
692
+ var TRUE_VALUES = [
693
+ "true",
694
+ "True",
695
+ "TRUE",
696
+ "y",
697
+ "Y",
698
+ "yes",
699
+ "Yes",
700
+ "YES",
701
+ "on",
702
+ "On",
703
+ "ON"
704
+ ];
705
+ var FALSE_VALUES = [
706
+ "false",
707
+ "False",
708
+ "FALSE",
709
+ "n",
710
+ "N",
711
+ "no",
712
+ "No",
713
+ "NO",
714
+ "off",
715
+ "Off",
716
+ "OFF"
717
+ ];
718
+ var boolYaml11Tag = defineScalarTag("tag:yaml.org,2002:bool", {
719
+ implicit: true,
720
+ implicitFirstChars: [
721
+ "y",
722
+ "Y",
723
+ "n",
724
+ "N",
725
+ "t",
726
+ "T",
727
+ "f",
728
+ "F",
729
+ "o",
730
+ "O"
731
+ ],
732
+ resolve: (source) => {
733
+ if (TRUE_VALUES.indexOf(source) !== -1) return true;
734
+ if (FALSE_VALUES.indexOf(source) !== -1) return false;
735
+ return NOT_RESOLVED;
736
+ },
737
+ identify: (object2) => Object.prototype.toString.call(object2) === "[object Boolean]",
738
+ represent: (object2) => object2 ? "true" : "false"
739
+ });
740
+ var YAML_INTEGER_IMPLICIT_PATTERN$1 = /* @__PURE__ */ new RegExp("^(?:0o[0-7]+|0x[0-9a-fA-F]+|[-+]?[0-9]+)$");
741
+ var YAML_INTEGER_EXPLICIT_PATTERN$1 = /* @__PURE__ */ new RegExp("^(?:[-+]?0b[0-1]+|[-+]?0o[0-7]+|[-+]?0x[0-9a-fA-F]+|[-+]?[0-9]+)$");
742
+ function parseYamlInteger$2(source) {
743
+ let value = source;
744
+ let sign = 1;
745
+ if (value[0] === "-" || value[0] === "+") {
746
+ if (value[0] === "-") sign = -1;
747
+ value = value.slice(1);
574
748
  }
575
- const proto = Object.getPrototypeOf(value);
576
- return proto === Object.prototype || proto === null;
577
- };
578
- var isObjectLike = (value) => typeof value === "object" && value !== null;
579
-
580
- // ../../node_modules/.bun/@scalar+openapi-upgrader@0.3.1/node_modules/@scalar/openapi-upgrader/dist/helpers/clone-document.js
581
- var ALIAS_EXPANSION_ENTRY_FLOOR = 1e5;
582
- var MAX_ALIAS_EXPANSION_RATIO = 10;
583
- var cloneDocument = (document) => {
584
- const ancestors = /* @__PURE__ */ new WeakSet();
585
- const expansion = { sourceEntries: 0, copiedEntries: 0, sizes: /* @__PURE__ */ new Map() };
586
- const clone = (value) => {
587
- if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "undefined") {
588
- return value;
749
+ if (value.startsWith("0b")) return sign * parseInt(value.slice(2), 2);
750
+ if (value.startsWith("0o")) return sign * parseInt(value.slice(2), 8);
751
+ if (value.startsWith("0x")) return sign * parseInt(value.slice(2), 16);
752
+ return sign * parseInt(value, 10);
753
+ }
754
+ function resolveYamlInteger$2(source, isExplicit) {
755
+ if (isExplicit) {
756
+ if (!YAML_INTEGER_EXPLICIT_PATTERN$1.test(source)) return NOT_RESOLVED;
757
+ } else if (!YAML_INTEGER_IMPLICIT_PATTERN$1.test(source)) return NOT_RESOLVED;
758
+ const result = parseYamlInteger$2(source);
759
+ return Number.isFinite(result) ? result : NOT_RESOLVED;
760
+ }
761
+ var intCoreTag = defineScalarTag("tag:yaml.org,2002:int", {
762
+ implicit: true,
763
+ implicitFirstChars: [
764
+ "-",
765
+ "+",
766
+ ..."0123456789"
767
+ ],
768
+ resolve: resolveYamlInteger$2,
769
+ identify: (object2) => Number.isInteger(object2) && !Object.is(object2, -0) && object2.toString(10).indexOf("e") < 0,
770
+ represent: (object2) => object2.toString(10)
771
+ });
772
+ var YAML_INTEGER_IMPLICIT_PATTERN = /* @__PURE__ */ new RegExp("^-?(?:0|[1-9][0-9]*)$");
773
+ var YAML_INTEGER_EXPLICIT_PATTERN = /* @__PURE__ */ new RegExp("^(?:[-+]?0b[0-1]+|[-+]?0o[0-7]+|[-+]?0x[0-9a-fA-F]+|[-+]?[0-9]+)$");
774
+ function parseYamlInteger$1(source) {
775
+ let value = source;
776
+ let sign = 1;
777
+ if (value[0] === "-" || value[0] === "+") {
778
+ if (value[0] === "-") sign = -1;
779
+ value = value.slice(1);
780
+ }
781
+ if (value.startsWith("0b")) return sign * parseInt(value.slice(2), 2);
782
+ if (value.startsWith("0o")) return sign * parseInt(value.slice(2), 8);
783
+ if (value.startsWith("0x")) return sign * parseInt(value.slice(2), 16);
784
+ return sign * parseInt(value, 10);
785
+ }
786
+ function resolveYamlInteger$1(source, isExplicit) {
787
+ if (isExplicit) {
788
+ if (!YAML_INTEGER_EXPLICIT_PATTERN.test(source)) return NOT_RESOLVED;
789
+ } else if (!YAML_INTEGER_IMPLICIT_PATTERN.test(source)) return NOT_RESOLVED;
790
+ const result = parseYamlInteger$1(source);
791
+ return Number.isFinite(result) ? result : NOT_RESOLVED;
792
+ }
793
+ var intJsonTag = defineScalarTag("tag:yaml.org,2002:int", {
794
+ implicit: true,
795
+ implicitFirstChars: ["-", ..."0123456789"],
796
+ resolve: resolveYamlInteger$1,
797
+ identify: (object2) => Number.isInteger(object2) && !Object.is(object2, -0) && object2.toString(10).indexOf("e") < 0,
798
+ represent: (object2) => object2.toString(10)
799
+ });
800
+ var YAML_INTEGER_PATTERN = /* @__PURE__ */ new RegExp("^(?:[-+]?0b[0-1_]+|[-+]?0[0-7_]+|[-+]?0x[0-9a-fA-F_]+|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+|[-+]?(?:0|[1-9][0-9_]*))$");
801
+ function parseYamlInteger(source) {
802
+ let value = source.replace(/_/g, "");
803
+ let sign = 1;
804
+ if (value[0] === "-" || value[0] === "+") {
805
+ if (value[0] === "-") sign = -1;
806
+ value = value.slice(1);
807
+ }
808
+ if (value.startsWith("0b")) return sign * parseInt(value.slice(2), 2);
809
+ if (value.startsWith("0x")) return sign * parseInt(value.slice(2), 16);
810
+ if (value.includes(":")) {
811
+ let result = 0;
812
+ for (const part of value.split(":")) result = result * 60 + Number(part);
813
+ return sign * result;
814
+ }
815
+ if (value !== "0" && value[0] === "0") return sign * parseInt(value, 8);
816
+ return sign * parseInt(value, 10);
817
+ }
818
+ function resolveYamlInteger(source) {
819
+ if (!YAML_INTEGER_PATTERN.test(source)) return NOT_RESOLVED;
820
+ const result = parseYamlInteger(source);
821
+ return Number.isFinite(result) ? result : NOT_RESOLVED;
822
+ }
823
+ var intYaml11Tag = defineScalarTag("tag:yaml.org,2002:int", {
824
+ implicit: true,
825
+ implicitFirstChars: [
826
+ "-",
827
+ "+",
828
+ ..."0123456789"
829
+ ],
830
+ resolve: resolveYamlInteger,
831
+ identify: (object2) => Number.isInteger(object2) && !Object.is(object2, -0) && object2.toString(10).indexOf("e") < 0,
832
+ represent: (object2) => object2.toString(10)
833
+ });
834
+ var YAML_FLOAT_PATTERN$1 = /* @__PURE__ */ new RegExp("^(?:[-+]?[0-9]+(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?|[-+]?\\.[0-9]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");
835
+ var YAML_FLOAT_SPECIAL_PATTERN$1 = /* @__PURE__ */ new RegExp("^(?:[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");
836
+ function resolveYamlFloat$2(source) {
837
+ if (!YAML_FLOAT_PATTERN$1.test(source)) return NOT_RESOLVED;
838
+ let value = source.toLowerCase();
839
+ const sign = value[0] === "-" ? -1 : 1;
840
+ if ("+-".includes(value[0])) value = value.slice(1);
841
+ if (value === ".inf") return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
842
+ if (value === ".nan") return NaN;
843
+ const result = sign * parseFloat(value);
844
+ if (Number.isFinite(result) || YAML_FLOAT_SPECIAL_PATTERN$1.test(source)) return result;
845
+ return NOT_RESOLVED;
846
+ }
847
+ function representYamlFloat$2(object2) {
848
+ if (isNaN(object2)) return ".nan";
849
+ if (object2 === Number.POSITIVE_INFINITY) return ".inf";
850
+ if (object2 === Number.NEGATIVE_INFINITY) return "-.inf";
851
+ if (Object.is(object2, -0)) return "-0.0";
852
+ const result = object2.toString(10);
853
+ return /^[-+]?[0-9]+e/.test(result) ? result.replace("e", ".e") : result;
854
+ }
855
+ var floatCoreTag = defineScalarTag("tag:yaml.org,2002:float", {
856
+ implicit: true,
857
+ implicitFirstChars: [
858
+ "-",
859
+ "+",
860
+ ".",
861
+ ..."0123456789"
862
+ ],
863
+ resolve: resolveYamlFloat$2,
864
+ identify: (object2) => typeof object2 === "number" && (!Number.isInteger(object2) || Object.is(object2, -0) || object2.toString(10).indexOf("e") >= 0),
865
+ represent: representYamlFloat$2
866
+ });
867
+ var YAML_FLOAT_IMPLICIT_PATTERN = /* @__PURE__ */ new RegExp("^-?(?:0|[1-9][0-9]*)(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$");
868
+ var YAML_FLOAT_EXPLICIT_PATTERN = /* @__PURE__ */ new RegExp("^(?:[-+]?[0-9]+(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?|[-+]?\\.[0-9]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");
869
+ function resolveYamlFloat$1(source, isExplicit) {
870
+ if (isExplicit) {
871
+ if (!YAML_FLOAT_EXPLICIT_PATTERN.test(source)) return NOT_RESOLVED;
872
+ let value = source.toLowerCase();
873
+ const sign = value[0] === "-" ? -1 : 1;
874
+ if ("+-".includes(value[0])) value = value.slice(1);
875
+ if (value === ".inf") return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
876
+ if (value === ".nan") return NaN;
877
+ const result2 = sign * parseFloat(value);
878
+ return Number.isFinite(result2) ? result2 : NOT_RESOLVED;
879
+ }
880
+ if (!YAML_FLOAT_IMPLICIT_PATTERN.test(source)) return NOT_RESOLVED;
881
+ const result = Number(source);
882
+ if (Number.isFinite(result)) return result;
883
+ return NOT_RESOLVED;
884
+ }
885
+ function representYamlFloat$1(object2) {
886
+ if (isNaN(object2)) return ".nan";
887
+ if (object2 === Number.POSITIVE_INFINITY) return ".inf";
888
+ if (object2 === Number.NEGATIVE_INFINITY) return "-.inf";
889
+ if (Object.is(object2, -0)) return "-0.0";
890
+ const result = object2.toString(10);
891
+ return /^[-+]?[0-9]+e/.test(result) ? result.replace("e", ".e") : result;
892
+ }
893
+ var floatJsonTag = defineScalarTag("tag:yaml.org,2002:float", {
894
+ implicit: true,
895
+ implicitFirstChars: ["-", ..."0123456789"],
896
+ resolve: resolveYamlFloat$1,
897
+ identify: (object2) => typeof object2 === "number" && (!Number.isInteger(object2) || Object.is(object2, -0) || object2.toString(10).indexOf("e") >= 0),
898
+ represent: representYamlFloat$1
899
+ });
900
+ var YAML_FLOAT_PATTERN = /* @__PURE__ */ new RegExp("^(?:[-+]?(?:(?:[0-9][0-9_]*)?\\.[0-9_]*)(?:[eE][-+][0-9]+)?|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");
901
+ var YAML_FLOAT_SPECIAL_PATTERN = /* @__PURE__ */ new RegExp("^(?:[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");
902
+ function resolveYamlFloat(source) {
903
+ if (!YAML_FLOAT_PATTERN.test(source)) return NOT_RESOLVED;
904
+ let value = source.toLowerCase().replace(/_/g, "");
905
+ const sign = value[0] === "-" ? -1 : 1;
906
+ if ("+-".includes(value[0])) value = value.slice(1);
907
+ if (value === ".inf") return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
908
+ if (value === ".nan") return NaN;
909
+ let result = 0;
910
+ if (value.includes(":")) {
911
+ for (const part of value.split(":")) result = result * 60 + Number(part);
912
+ result *= sign;
913
+ } else result = sign * parseFloat(value);
914
+ if (Number.isFinite(result) || YAML_FLOAT_SPECIAL_PATTERN.test(source)) return result;
915
+ return NOT_RESOLVED;
916
+ }
917
+ function representYamlFloat(object2) {
918
+ if (isNaN(object2)) return ".nan";
919
+ if (object2 === Number.POSITIVE_INFINITY) return ".inf";
920
+ if (object2 === Number.NEGATIVE_INFINITY) return "-.inf";
921
+ if (Object.is(object2, -0)) return "-0.0";
922
+ const result = object2.toString(10);
923
+ return /^[-+]?[0-9]+e/.test(result) ? result.replace("e", ".e") : result;
924
+ }
925
+ var floatYaml11Tag = defineScalarTag("tag:yaml.org,2002:float", {
926
+ implicit: true,
927
+ implicitFirstChars: [
928
+ "-",
929
+ "+",
930
+ ".",
931
+ ..."0123456789"
932
+ ],
933
+ resolve: resolveYamlFloat,
934
+ identify: (object2) => typeof object2 === "number" && (!Number.isInteger(object2) || Object.is(object2, -0) || object2.toString(10).indexOf("e") >= 0),
935
+ represent: representYamlFloat
936
+ });
937
+ var mergeTag = defineScalarTag("tag:yaml.org,2002:merge", {
938
+ implicit: true,
939
+ implicitFirstChars: ["<"],
940
+ resolve: (source, isExplicit) => {
941
+ if (source === "<<" || isExplicit && source === "") return "<<";
942
+ return NOT_RESOLVED;
943
+ },
944
+ identify: () => false
945
+ });
946
+ var BASE64_PATTERN = /^[A-Za-z0-9+/]*={0,2}$/;
947
+ function resolveYamlBinary(source) {
948
+ const input = source.replace(/\s/g, "");
949
+ if (input.length % 4 !== 0 || !BASE64_PATTERN.test(input)) return NOT_RESOLVED;
950
+ const binary = atob(input);
951
+ const result = new Uint8Array(binary.length);
952
+ for (let index = 0; index < binary.length; index++) result[index] = binary.charCodeAt(index);
953
+ return result;
954
+ }
955
+ function representYamlBinary(object2) {
956
+ let binary = "";
957
+ for (let index = 0; index < object2.length; index++) binary += String.fromCharCode(object2[index]);
958
+ return btoa(binary);
959
+ }
960
+ var binaryTag = defineScalarTag("tag:yaml.org,2002:binary", {
961
+ resolve: resolveYamlBinary,
962
+ identify: (object2) => Object.prototype.toString.call(object2) === "[object Uint8Array]",
963
+ represent: representYamlBinary
964
+ });
965
+ var YAML_DATE_REGEXP = /* @__PURE__ */ new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$");
966
+ var YAML_TIMESTAMP_REGEXP = /* @__PURE__ */ new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");
967
+ function makeUtcDate(year, month, day, hour = 0, minute = 0, second = 0, fraction = 0) {
968
+ const date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
969
+ date.setUTCFullYear(year, month, day);
970
+ return date;
971
+ }
972
+ function resolveYamlTimestamp(source) {
973
+ let match = YAML_DATE_REGEXP.exec(source);
974
+ if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(source);
975
+ if (match === null) return NOT_RESOLVED;
976
+ const year = +match[1];
977
+ const month = +match[2] - 1;
978
+ const day = +match[3];
979
+ if (!match[4]) {
980
+ const date2 = makeUtcDate(year, month, day);
981
+ if (date2.getUTCFullYear() !== year || date2.getUTCMonth() !== month || date2.getUTCDate() !== day) return NOT_RESOLVED;
982
+ return date2;
983
+ }
984
+ const hour = +match[4];
985
+ const minute = +match[5];
986
+ const second = +match[6];
987
+ let fraction = 0;
988
+ if (hour > 23 || minute > 59 || second > 59) return NOT_RESOLVED;
989
+ if (match[7]) {
990
+ let value = match[7].slice(0, 3);
991
+ while (value.length < 3) value += "0";
992
+ fraction = +value;
993
+ }
994
+ const date = makeUtcDate(year, month, day, hour, minute, second, fraction);
995
+ if (date.getUTCFullYear() !== year || date.getUTCMonth() !== month || date.getUTCDate() !== day) return NOT_RESOLVED;
996
+ if (match[9]) {
997
+ const offsetHour = +match[10];
998
+ const offsetMinute = +(match[11] || 0);
999
+ if (offsetHour > 23 || offsetMinute > 59) return NOT_RESOLVED;
1000
+ const offset = (offsetHour * 60 + offsetMinute) * 6e4;
1001
+ date.setTime(date.getTime() - (match[9] === "-" ? -offset : offset));
1002
+ }
1003
+ return date;
1004
+ }
1005
+ var timestampTag = defineScalarTag("tag:yaml.org,2002:timestamp", {
1006
+ implicit: true,
1007
+ implicitFirstChars: [..."0123456789"],
1008
+ resolve: resolveYamlTimestamp,
1009
+ identify: (object2) => object2 instanceof Date,
1010
+ represent: (object2) => object2.toISOString()
1011
+ });
1012
+ var seqTag = defineSequenceTag("tag:yaml.org,2002:seq", {
1013
+ create: () => [],
1014
+ addItem: (container, item) => {
1015
+ container.push(item);
1016
+ },
1017
+ identify: Array.isArray
1018
+ });
1019
+ function isPlainObject(data) {
1020
+ if (data === null || typeof data !== "object" || Array.isArray(data)) return false;
1021
+ const prototype = Object.getPrototypeOf(data);
1022
+ return prototype === null || prototype === Object.prototype;
1023
+ }
1024
+ function pick(object2, keys) {
1025
+ const result = {};
1026
+ for (const key of keys) if (object2[key] !== void 0) result[key] = object2[key];
1027
+ return result;
1028
+ }
1029
+ var omapTag = defineSequenceTag("tag:yaml.org,2002:omap", {
1030
+ create: () => ({
1031
+ list: [],
1032
+ seen: /* @__PURE__ */ new Set()
1033
+ }),
1034
+ addItem: (carrier, item) => {
1035
+ let key;
1036
+ if (item instanceof Map) {
1037
+ if (item.size !== 1) return "cannot resolve an ordered map item";
1038
+ key = item.keys().next().value;
1039
+ } else if (isPlainObject(item)) {
1040
+ const itemKeys = Object.keys(item);
1041
+ if (itemKeys.length !== 1) return "cannot resolve an ordered map item";
1042
+ key = itemKeys[0];
1043
+ } else return "cannot resolve an ordered map item";
1044
+ if (carrier.seen.has(key)) return "duplicate key in ordered map";
1045
+ carrier.seen.add(key);
1046
+ carrier.list.push(item);
1047
+ return "";
1048
+ },
1049
+ finalize: (carrier) => carrier.list,
1050
+ identify: () => false
1051
+ });
1052
+ var pairsTag = defineSequenceTag("tag:yaml.org,2002:pairs", {
1053
+ create: () => [],
1054
+ addItem: (container, item) => {
1055
+ if (item instanceof Map) {
1056
+ if (item.size !== 1) return "cannot resolve a pairs item";
1057
+ container.push(item.entries().next().value);
1058
+ return "";
589
1059
  }
590
- if (!Array.isArray(value) && !isObject2(value)) {
591
- return structuredClone(value);
1060
+ if (Object.prototype.toString.call(item) !== "[object Object]") return "cannot resolve a pairs item";
1061
+ const object2 = item;
1062
+ const keys = Object.keys(object2);
1063
+ if (keys.length !== 1) return "cannot resolve a pairs item";
1064
+ container.push([keys[0], object2[keys[0]]]);
1065
+ return "";
1066
+ },
1067
+ identify: () => false
1068
+ });
1069
+ var mapTag = defineMappingTag("tag:yaml.org,2002:map", {
1070
+ create: () => ({}),
1071
+ identify: isPlainObject,
1072
+ represent: (o) => {
1073
+ const map = /* @__PURE__ */ new Map();
1074
+ for (const key of Object.keys(o)) map.set(key, o[key]);
1075
+ return map;
1076
+ },
1077
+ addPair: (container, key, value) => {
1078
+ if (key !== null && typeof key === "object") return "object-based map does not support complex keys";
1079
+ const normalizedKey = String(key);
1080
+ if (normalizedKey === "__proto__") Object.defineProperty(container, normalizedKey, {
1081
+ value,
1082
+ enumerable: true,
1083
+ configurable: true,
1084
+ writable: true
1085
+ });
1086
+ else container[normalizedKey] = value;
1087
+ return "";
1088
+ },
1089
+ has: (container, key) => {
1090
+ if (key !== null && typeof key === "object") return false;
1091
+ return Object.prototype.hasOwnProperty.call(container, String(key));
1092
+ },
1093
+ keys: (container) => Object.keys(container),
1094
+ get: (container, key) => {
1095
+ const normalizedKey = String(key);
1096
+ if (!Object.prototype.hasOwnProperty.call(container, normalizedKey)) return null;
1097
+ return container[normalizedKey];
1098
+ }
1099
+ });
1100
+ var setTag = defineMappingTag("tag:yaml.org,2002:set", {
1101
+ create: () => /* @__PURE__ */ new Set(),
1102
+ identify: (data) => data instanceof Set,
1103
+ represent: (data) => {
1104
+ const map = /* @__PURE__ */ new Map();
1105
+ for (const key of data) map.set(key, null);
1106
+ return map;
1107
+ },
1108
+ addPair: (container, key, value) => {
1109
+ if (value !== null) return "cannot resolve a set item";
1110
+ container.add(key);
1111
+ return "";
1112
+ },
1113
+ has: (container, key) => container.has(key),
1114
+ keys: (container) => container.keys(),
1115
+ get: () => null
1116
+ });
1117
+ function createTagDefinitionMap() {
1118
+ return {
1119
+ scalar: /* @__PURE__ */ Object.create(null),
1120
+ sequence: /* @__PURE__ */ Object.create(null),
1121
+ mapping: /* @__PURE__ */ Object.create(null)
1122
+ };
1123
+ }
1124
+ function createTagDefinitionListMap() {
1125
+ return {
1126
+ scalar: [],
1127
+ sequence: [],
1128
+ mapping: []
1129
+ };
1130
+ }
1131
+ function compileTags(tags) {
1132
+ const result = [];
1133
+ for (const tag of tags) {
1134
+ let index = result.length;
1135
+ for (let previousIndex = 0; previousIndex < result.length; previousIndex++) {
1136
+ const previous = result[previousIndex];
1137
+ if (previous.nodeKind === tag.nodeKind && previous.tagName === tag.tagName && previous.matchByTagPrefix === tag.matchByTagPrefix) {
1138
+ index = previousIndex;
1139
+ break;
1140
+ }
592
1141
  }
593
- if (ancestors.has(value)) {
594
- throw new Error("Cannot upgrade to OpenAPI 3.2: cyclic objects cannot be represented in JSON. Use $ref instead.");
1142
+ result[index] = tag;
1143
+ }
1144
+ return result;
1145
+ }
1146
+ var Schema = class Schema2 {
1147
+ tags;
1148
+ /** @internal */
1149
+ implicitScalarTags;
1150
+ /**
1151
+ * Dispatch implicit scalar resolvers by `source.charAt(0)`. Each bucket holds
1152
+ * the resolvers that may match that key, in schema order; a key absent from
1153
+ * the map uses
1154
+ * {@link Schema.implicitScalarAnyFirstChar}
1155
+ * (resolvers that declared no first-char constraint, so they apply to any
1156
+ * first character).
1157
+ */
1158
+ implicitScalarByFirstChar;
1159
+ implicitScalarAnyFirstChar;
1160
+ /**
1161
+ * The default scalar tag (`!!str`), resolved once so the composer's fallback
1162
+ * for unresolved plain scalars avoids a keyed lookup per scalar.
1163
+ *
1164
+ * @internal
1165
+ */
1166
+ defaultScalarTag;
1167
+ /**
1168
+ * The default container tags (`!!seq` / `!!map`), used by the dumper: when a
1169
+ * value is identified by its default tag, the tag is implicit and not
1170
+ * printed. Undefined if the schema does not define them (then such values
1171
+ * can't be dumped).
1172
+ *
1173
+ * @internal
1174
+ */
1175
+ defaultSequenceTag;
1176
+ /** @internal */
1177
+ defaultMappingTag;
1178
+ exact;
1179
+ prefix;
1180
+ constructor(tags) {
1181
+ const compiledTags = compileTags(tags);
1182
+ const implicitScalarTags = [];
1183
+ const exact = createTagDefinitionMap();
1184
+ const prefix = createTagDefinitionListMap();
1185
+ for (const tag of compiledTags) {
1186
+ if (tag.nodeKind === "scalar" && tag.implicit) {
1187
+ if (tag.matchByTagPrefix) throw new Error("Implicit scalar tags cannot match by tag prefix");
1188
+ implicitScalarTags.push(tag);
1189
+ }
1190
+ switch (tag.nodeKind) {
1191
+ case "scalar":
1192
+ if (tag.matchByTagPrefix) prefix.scalar.push(tag);
1193
+ else exact.scalar[tag.tagName] = tag;
1194
+ break;
1195
+ case "sequence":
1196
+ if (tag.matchByTagPrefix) prefix.sequence.push(tag);
1197
+ else exact.sequence[tag.tagName] = tag;
1198
+ break;
1199
+ case "mapping":
1200
+ if (tag.matchByTagPrefix) prefix.mapping.push(tag);
1201
+ else exact.mapping[tag.tagName] = tag;
1202
+ break;
1203
+ }
595
1204
  }
596
- const size = expansion.sizes.get(value) ?? 1 + (Array.isArray(value) ? value.length : Object.keys(value).length);
597
- if (!expansion.sizes.has(value)) {
598
- expansion.sizes.set(value, size);
599
- expansion.sourceEntries += size;
1205
+ const implicitScalarAnyFirstChar = implicitScalarTags.filter((tag) => tag.implicitFirstChars === null);
1206
+ const keys = /* @__PURE__ */ new Set();
1207
+ for (const tag of implicitScalarTags) if (tag.implicitFirstChars !== null) for (const key of tag.implicitFirstChars) keys.add(key);
1208
+ const implicitScalarByFirstChar = /* @__PURE__ */ new Map();
1209
+ for (const key of keys) implicitScalarByFirstChar.set(key, implicitScalarTags.filter((tag) => tag.implicitFirstChars === null || tag.implicitFirstChars.indexOf(key) !== -1));
1210
+ const defaultScalarTag = exact.scalar["tag:yaml.org,2002:str"];
1211
+ if (!defaultScalarTag) throw new Error("schema does not define the default scalar tag (tag:yaml.org,2002:str)");
1212
+ this.tags = compiledTags;
1213
+ this.implicitScalarTags = implicitScalarTags;
1214
+ this.implicitScalarByFirstChar = implicitScalarByFirstChar;
1215
+ this.implicitScalarAnyFirstChar = implicitScalarAnyFirstChar;
1216
+ this.defaultScalarTag = defaultScalarTag;
1217
+ this.defaultSequenceTag = exact.sequence["tag:yaml.org,2002:seq"];
1218
+ this.defaultMappingTag = exact.mapping["tag:yaml.org,2002:map"];
1219
+ this.exact = exact;
1220
+ this.prefix = prefix;
1221
+ }
1222
+ /** @internal */
1223
+ lookupScalarTag(tagName) {
1224
+ const exactTag = this.exact.scalar[tagName];
1225
+ if (exactTag) return exactTag;
1226
+ for (const tag of this.prefix.scalar) if (tagName.startsWith(tag.tagName)) return tag;
1227
+ }
1228
+ /** @internal */
1229
+ lookupSequenceTag(tagName) {
1230
+ const exactTag = this.exact.sequence[tagName];
1231
+ if (exactTag) return exactTag;
1232
+ for (const tag of this.prefix.sequence) if (tagName.startsWith(tag.tagName)) return tag;
1233
+ }
1234
+ /** @internal */
1235
+ lookupMappingTag(tagName) {
1236
+ const exactTag = this.exact.mapping[tagName];
1237
+ if (exactTag) return exactTag;
1238
+ for (const tag of this.prefix.mapping) if (tagName.startsWith(tag.tagName)) return tag;
1239
+ }
1240
+ /** @internal */
1241
+ resolveImplicitScalarTag(source) {
1242
+ const candidates = this.implicitScalarByFirstChar.get(source.charAt(0)) ?? this.implicitScalarAnyFirstChar;
1243
+ for (const tag2 of candidates) {
1244
+ const value = tag2.resolve(source, false, tag2.tagName);
1245
+ if (value !== NOT_RESOLVED) return {
1246
+ value,
1247
+ tag: tag2
1248
+ };
600
1249
  }
601
- expansion.copiedEntries += size;
602
- if (expansion.copiedEntries > ALIAS_EXPANSION_ENTRY_FLOOR && expansion.copiedEntries > expansion.sourceEntries * MAX_ALIAS_EXPANSION_RATIO) {
603
- throw new Error("Cannot upgrade to OpenAPI 3.2: excessive YAML alias expansion. Use $ref for shared schemas.");
1250
+ const tag = this.defaultScalarTag;
1251
+ return {
1252
+ value: tag.resolve(source, false, tag.tagName),
1253
+ tag
1254
+ };
1255
+ }
1256
+ /**
1257
+ * Creates a new schema with the specified tags added. If a tag already
1258
+ * exists, it is replaced by the specified tag.
1259
+ *
1260
+ * @example
1261
+ *
1262
+ * ```javascript
1263
+ * import { CORE_SCHEMA, mergeTag, realMapTag } from 'js-yaml'
1264
+ *
1265
+ * const schema = CORE_SCHEMA.withTags(mergeTag, realMapTag)
1266
+ * ```
1267
+ */
1268
+ withTags(...tags) {
1269
+ let flatTags = [];
1270
+ for (const tag of tags) flatTags = flatTags.concat(tag);
1271
+ return new Schema2([...this.tags, ...flatTags]);
1272
+ }
1273
+ };
1274
+ var FAILSAFE_SCHEMA = new Schema([
1275
+ strTag,
1276
+ seqTag,
1277
+ mapTag
1278
+ ]);
1279
+ var JSON_SCHEMA = new Schema([
1280
+ ...FAILSAFE_SCHEMA.tags,
1281
+ nullJsonTag,
1282
+ boolJsonTag,
1283
+ intJsonTag,
1284
+ floatJsonTag
1285
+ ]);
1286
+ var CORE_SCHEMA = new Schema([
1287
+ ...FAILSAFE_SCHEMA.tags,
1288
+ nullCoreTag,
1289
+ boolCoreTag,
1290
+ intCoreTag,
1291
+ floatCoreTag
1292
+ ]);
1293
+ var YAML11_SCHEMA = new Schema([
1294
+ ...FAILSAFE_SCHEMA.tags,
1295
+ nullYaml11Tag,
1296
+ boolYaml11Tag,
1297
+ intYaml11Tag,
1298
+ floatYaml11Tag,
1299
+ timestampTag,
1300
+ mergeTag,
1301
+ binaryTag,
1302
+ omapTag,
1303
+ pairsTag,
1304
+ setTag
1305
+ ]);
1306
+ var DUMP_SCHEMA = YAML11_SCHEMA.withTags({
1307
+ ...intYaml11Tag,
1308
+ resolve: (source, isExplicit, tagName) => {
1309
+ const result = intYaml11Tag.resolve(source, isExplicit, tagName);
1310
+ return result === NOT_RESOLVED ? intCoreTag.resolve(source, isExplicit, tagName) : result;
1311
+ }
1312
+ }, {
1313
+ ...floatYaml11Tag,
1314
+ resolve: (source, isExplicit, tagName) => {
1315
+ const result = floatYaml11Tag.resolve(source, isExplicit, tagName);
1316
+ return result === NOT_RESOLVED ? floatCoreTag.resolve(source, isExplicit, tagName) : result;
1317
+ }
1318
+ });
1319
+ var realMapTag = defineMappingTag("tag:yaml.org,2002:map", {
1320
+ create: () => /* @__PURE__ */ new Map(),
1321
+ addPair: (container, key, value) => {
1322
+ container.set(key, value);
1323
+ return "";
1324
+ },
1325
+ has: (container, key) => container.has(key),
1326
+ keys: (container) => container.keys(),
1327
+ get: (container, key) => container.get(key),
1328
+ identify: (data) => data instanceof Map || isPlainObject(data),
1329
+ represent: (data) => {
1330
+ if (data instanceof Map) return data;
1331
+ const map = /* @__PURE__ */ new Map();
1332
+ const obj = data;
1333
+ for (const key of Object.keys(obj)) map.set(key, obj[key]);
1334
+ return map;
1335
+ }
1336
+ });
1337
+ function normalizeKey(key) {
1338
+ if (Array.isArray(key)) {
1339
+ const array = Array.prototype.slice.call(key);
1340
+ for (let index = 0; index < array.length; index++) {
1341
+ if (Array.isArray(array[index])) return null;
1342
+ if (typeof array[index] === "object" && Object.prototype.toString.call(array[index]) === "[object Object]") array[index] = "[object Object]";
604
1343
  }
605
- ancestors.add(value);
606
- const result = Array.isArray(value) ? value.map(clone) : Object.fromEntries(Object.entries(value).map(([key, item]) => [key, clone(item)]));
607
- ancestors.delete(value);
608
- return result;
609
- };
610
- return clone(document);
1344
+ return String(array);
1345
+ }
1346
+ if (typeof key === "object" && Object.prototype.toString.call(key) === "[object Object]") return "[object Object]";
1347
+ return String(key);
1348
+ }
1349
+ var legacyMapTag = defineMappingTag("tag:yaml.org,2002:map", {
1350
+ create: () => ({}),
1351
+ identify: isPlainObject,
1352
+ represent: (o) => {
1353
+ const map = /* @__PURE__ */ new Map();
1354
+ for (const key of Object.keys(o)) map.set(key, o[key]);
1355
+ return map;
1356
+ },
1357
+ addPair: (container, key, value) => {
1358
+ const normalizedKey = normalizeKey(key);
1359
+ if (normalizedKey === null) return "nested arrays are not supported inside keys";
1360
+ if (normalizedKey === "__proto__") Object.defineProperty(container, normalizedKey, {
1361
+ value,
1362
+ enumerable: true,
1363
+ configurable: true,
1364
+ writable: true
1365
+ });
1366
+ else container[normalizedKey] = value;
1367
+ return "";
1368
+ },
1369
+ has: (container, key) => {
1370
+ const normalizedKey = normalizeKey(key);
1371
+ return normalizedKey !== null && Object.prototype.hasOwnProperty.call(container, normalizedKey);
1372
+ },
1373
+ keys: (container) => Object.keys(container),
1374
+ get: (container, key) => {
1375
+ const normalizedKey = String(key);
1376
+ if (!Object.prototype.hasOwnProperty.call(container, normalizedKey)) return null;
1377
+ return container[normalizedKey];
1378
+ }
1379
+ });
1380
+ var DEFAULT_SNIPPET_OPTIONS = {
1381
+ maxLength: 79,
1382
+ indent: 1,
1383
+ linesBefore: 3,
1384
+ linesAfter: 2
611
1385
  };
1386
+ function getLine(buffer, lineStart, lineEnd, position, maxLineLength) {
1387
+ let head = "";
1388
+ let tail = "";
1389
+ const maxHalfLength = Math.floor(maxLineLength / 2) - 1;
1390
+ if (position - lineStart > maxHalfLength) {
1391
+ head = " ... ";
1392
+ lineStart = position - maxHalfLength + head.length;
1393
+ }
1394
+ if (lineEnd - position > maxHalfLength) {
1395
+ tail = " ...";
1396
+ lineEnd = position + maxHalfLength - tail.length;
1397
+ }
1398
+ return {
1399
+ str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, "\u2192") + tail,
1400
+ pos: position - lineStart + head.length
1401
+ };
1402
+ }
1403
+ function padStart(string, max) {
1404
+ return " ".repeat(Math.max(max - string.length, 0)) + string;
1405
+ }
1406
+ function makeSnippet(mark, options) {
1407
+ if (!mark.buffer) return null;
1408
+ const opts = {
1409
+ ...DEFAULT_SNIPPET_OPTIONS,
1410
+ ...options
1411
+ };
1412
+ const re = /\r?\n|\r|\0/g;
1413
+ const lineStarts = [0];
1414
+ const lineEnds = [];
1415
+ let match;
1416
+ let foundLineNo = -1;
1417
+ while (match = re.exec(mark.buffer)) {
1418
+ lineEnds.push(match.index);
1419
+ lineStarts.push(match.index + match[0].length);
1420
+ if (mark.position <= match.index && foundLineNo < 0) foundLineNo = lineStarts.length - 2;
1421
+ }
1422
+ if (foundLineNo < 0) foundLineNo = lineStarts.length - 1;
1423
+ let result = "";
1424
+ const lineNoLength = Math.min(mark.line + opts.linesAfter, lineEnds.length).toString().length;
1425
+ const maxLineLength = opts.maxLength - (opts.indent + lineNoLength + 3);
1426
+ for (let i = 1; i <= opts.linesBefore; i++) {
1427
+ if (foundLineNo - i < 0) break;
1428
+ const line2 = getLine(mark.buffer, lineStarts[foundLineNo - i], lineEnds[foundLineNo - i], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]), maxLineLength);
1429
+ result = `${" ".repeat(opts.indent)}${padStart((mark.line - i + 1).toString(), lineNoLength)} | ${line2.str}
1430
+ ${result}`;
1431
+ }
1432
+ const line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength);
1433
+ result += `${" ".repeat(opts.indent)}${padStart((mark.line + 1).toString(), lineNoLength)} | ${line.str}
1434
+ `;
1435
+ result += `${"-".repeat(opts.indent + lineNoLength + 3 + line.pos)}^
1436
+ `;
1437
+ for (let i = 1; i <= opts.linesAfter; i++) {
1438
+ if (foundLineNo + i >= lineEnds.length) break;
1439
+ const line2 = getLine(mark.buffer, lineStarts[foundLineNo + i], lineEnds[foundLineNo + i], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]), maxLineLength);
1440
+ result += `${" ".repeat(opts.indent)}${padStart((mark.line + i + 1).toString(), lineNoLength)} | ${line2.str}
1441
+ `;
1442
+ }
1443
+ return result.replace(/\n$/, "");
1444
+ }
1445
+ function formatError(exception, compact) {
1446
+ let where = "";
1447
+ if (!exception.mark) return exception.reason;
1448
+ if (exception.mark.name) where += `in "${exception.mark.name}" `;
1449
+ where += `(${exception.mark.line + 1}:${exception.mark.column + 1})`;
1450
+ if (!compact && exception.mark.snippet) where += `
612
1451
 
613
- // ../../node_modules/.bun/@scalar+helpers@0.14.0/node_modules/@scalar/helpers/dist/json/escape-json-pointer.js
614
- var escapeJsonPointer = (str) => str.replace(/~/g, "~0").replace(/\//g, "~1");
615
-
616
- // ../../node_modules/.bun/@scalar+helpers@0.14.0/node_modules/@scalar/helpers/dist/json/unescape-json-pointer.js
617
- var unescapeJsonPointer = (uri) => decodeURI(uri.replace(/~1/g, "/").replace(/~0/g, "~"));
618
-
619
- // ../../node_modules/.bun/@scalar+helpers@0.14.0/node_modules/@scalar/helpers/dist/json/parse-json-pointer-segments.js
620
- var parseJsonPointerSegments = (path) => path.split("/").slice(1).map(unescapeJsonPointer);
621
-
622
- // ../../node_modules/.bun/@scalar+openapi-upgrader@0.3.1/node_modules/@scalar/openapi-upgrader/dist/upgrade-incompatibility-error.js
623
- var UpgradeIncompatibilityError = class extends AggregateError {
624
- errors;
625
- constructor(errors) {
626
- super(errors, errors.map((error) => error.message).join("\n"));
627
- this.errors = errors;
628
- this.name = "UpgradeIncompatibilityError";
1452
+ ${exception.mark.snippet}`;
1453
+ return `${exception.reason} ${where}`;
1454
+ }
1455
+ var YAMLException = class YAMLException2 extends Error {
1456
+ reason;
1457
+ mark;
1458
+ /**
1459
+ * Optional `mark` contains source snippet data. Usually, use
1460
+ * {@link YAMLException.throwAt} instead of passing it directly.
1461
+ */
1462
+ constructor(reason, mark) {
1463
+ super();
1464
+ this.name = "YAMLException";
1465
+ this.reason = reason;
1466
+ this.mark = mark;
1467
+ this.message = formatError(this, false);
1468
+ if (Error.captureStackTrace) Error.captureStackTrace(this, this.constructor);
1469
+ }
1470
+ /**
1471
+ * Returns the formatted error, omitting the source snippet in compact mode.
1472
+ */
1473
+ toString(compact) {
1474
+ return `${this.name}: ${formatError(this, compact)}`;
1475
+ }
1476
+ /**
1477
+ * Builds a YAMLException with a source snippet and throws it. `source` is
1478
+ * the raw input text; `position` is an offset into it.
1479
+ */
1480
+ static throwAt(source, position, message, filename = "") {
1481
+ let line = 0;
1482
+ let lineStart = 0;
1483
+ for (let index = 0; index < position; index++) {
1484
+ const ch = source.charCodeAt(index);
1485
+ if (ch === 10) {
1486
+ line++;
1487
+ lineStart = index + 1;
1488
+ } else if (ch === 13) {
1489
+ line++;
1490
+ if (source.charCodeAt(index + 1) === 10) index++;
1491
+ lineStart = index + 1;
1492
+ }
1493
+ }
1494
+ const mark = {
1495
+ name: filename,
1496
+ buffer: source,
1497
+ position,
1498
+ line,
1499
+ column: position - lineStart
1500
+ };
1501
+ mark.snippet = makeSnippet(mark);
1502
+ throw new YAMLException2(message, mark);
629
1503
  }
630
1504
  };
631
-
632
- // ../../node_modules/.bun/@scalar+openapi-upgrader@0.3.1/node_modules/@scalar/openapi-upgrader/dist/3.1-to-3.2/migrate-objects.js
633
- var schemaMaps = ["properties", "patternProperties", "$defs", "dependentSchemas"];
634
- var schemaArrays = ["allOf", "anyOf", "oneOf", "prefixItems"];
635
- var schemaSingles = [
636
- "items",
637
- "contains",
638
- "additionalProperties",
639
- "unevaluatedProperties",
640
- "unevaluatedItems",
641
- "propertyNames",
642
- "not",
643
- "if",
644
- "then",
645
- "else",
646
- "contentSchema"
647
- ];
648
- var migrateObjects = (document) => {
649
- const properties = /* @__PURE__ */ new WeakMap();
650
- const own = (value, key) => {
651
- const entries = properties.get(value) ?? new Map(Object.entries(Object.getOwnPropertyDescriptors(value)).filter(([, descriptor]) => Object.hasOwn(descriptor, "value")).map(([name, descriptor]) => [name, descriptor.value]));
652
- properties.set(value, entries);
653
- return entries.get(key);
1505
+ var EVENT_ID = {
1506
+ DOCUMENT: 1,
1507
+ SEQUENCE: 2,
1508
+ MAPPING: 3,
1509
+ SCALAR: 4,
1510
+ ALIAS: 5,
1511
+ POP: 6
1512
+ };
1513
+ var SCALAR_STYLE = {
1514
+ PLAIN: 1,
1515
+ SINGLE_QUOTED: 2,
1516
+ DOUBLE_QUOTED: 3,
1517
+ LITERAL_BLOCK: 4,
1518
+ FOLDED_BLOCK: 5
1519
+ };
1520
+ var COLLECTION_STYLE = {
1521
+ BLOCK: 1,
1522
+ FLOW: 2
1523
+ };
1524
+ var CHOMPING_MODE = {
1525
+ CLIP: 1,
1526
+ STRIP: 2,
1527
+ KEEP: 3
1528
+ };
1529
+ var NO_RANGE$3 = -1;
1530
+ function simpleEscapeSequence(c) {
1531
+ switch (c) {
1532
+ case 48:
1533
+ return "\0";
1534
+ case 97:
1535
+ return "\x07";
1536
+ case 98:
1537
+ return "\b";
1538
+ case 116:
1539
+ return " ";
1540
+ case 9:
1541
+ return " ";
1542
+ case 110:
1543
+ return "\n";
1544
+ case 118:
1545
+ return "\v";
1546
+ case 102:
1547
+ return "\f";
1548
+ case 114:
1549
+ return "\r";
1550
+ case 101:
1551
+ return "\x1B";
1552
+ case 32:
1553
+ return " ";
1554
+ case 34:
1555
+ return '"';
1556
+ case 47:
1557
+ return "/";
1558
+ case 92:
1559
+ return "\\";
1560
+ case 78:
1561
+ return "\x85";
1562
+ case 95:
1563
+ return "\xA0";
1564
+ case 76:
1565
+ return "\u2028";
1566
+ case 80:
1567
+ return "\u2029";
1568
+ default:
1569
+ return "";
1570
+ }
1571
+ }
1572
+ var simpleEscapeCheck = new Array(256);
1573
+ var simpleEscapeMap = new Array(256);
1574
+ for (let i = 0; i < 256; i++) {
1575
+ simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0;
1576
+ simpleEscapeMap[i] = simpleEscapeSequence(i);
1577
+ }
1578
+ function charFromCodepoint(c) {
1579
+ if (c <= 65535) return String.fromCharCode(c);
1580
+ return String.fromCharCode((c - 65536 >> 10) + 55296, (c - 65536 & 1023) + 56320);
1581
+ }
1582
+ function fromHexCode$1(c) {
1583
+ if (c >= 48 && c <= 57) return c - 48;
1584
+ return (c | 32) - 97 + 10;
1585
+ }
1586
+ function escapedHexLen$1(c) {
1587
+ if (c === 120) return 2;
1588
+ if (c === 117) return 4;
1589
+ return 8;
1590
+ }
1591
+ function skipFoldedBreaks(input, position, end) {
1592
+ let breaks = 0;
1593
+ while (position < end) {
1594
+ const ch = input.charCodeAt(position);
1595
+ if (ch === 10) {
1596
+ breaks++;
1597
+ position++;
1598
+ } else if (ch === 13) {
1599
+ breaks++;
1600
+ position++;
1601
+ if (input.charCodeAt(position) === 10) position++;
1602
+ } else if (ch === 32 || ch === 9) position++;
1603
+ else break;
1604
+ }
1605
+ return {
1606
+ position,
1607
+ breaks
654
1608
  };
655
- const operationTags = /* @__PURE__ */ new Set();
656
- const errors = [];
657
- const requiredCache = /* @__PURE__ */ new WeakMap();
658
- const cyclicRequired = /* @__PURE__ */ new WeakSet();
659
- const requiredWork = { evaluations: 0 };
660
- const propertySchemas = /* @__PURE__ */ new WeakSet();
661
- const xmlRoots = [];
662
- const markPropertySchema = (schema2) => {
663
- if (!isObject2(schema2) || propertySchemas.has(schema2)) {
664
- return;
1609
+ }
1610
+ function foldedBreaks(count) {
1611
+ if (count === 1) return " ";
1612
+ return "\n".repeat(count - 1);
1613
+ }
1614
+ function getPlainValue(input, start, end) {
1615
+ let result = "";
1616
+ let position = start;
1617
+ let captureStart = start;
1618
+ let captureEnd = start;
1619
+ while (position < end) {
1620
+ const ch = input.charCodeAt(position);
1621
+ if (ch === 10 || ch === 13) {
1622
+ result += input.slice(captureStart, captureEnd);
1623
+ const fold = skipFoldedBreaks(input, position, end);
1624
+ result += foldedBreaks(fold.breaks);
1625
+ position = captureStart = captureEnd = fold.position;
1626
+ } else {
1627
+ position++;
1628
+ if (ch !== 32 && ch !== 9) captureEnd = position;
665
1629
  }
666
- propertySchemas.add(schema2);
667
- markPropertySchema(schema2.items);
668
- if (Array.isArray(schema2.prefixItems)) {
669
- schema2.prefixItems.forEach(markPropertySchema);
1630
+ }
1631
+ return result + input.slice(captureStart, captureEnd);
1632
+ }
1633
+ function getSingleQuotedValue(input, start, end) {
1634
+ let result = "";
1635
+ let position = start;
1636
+ let captureStart = start;
1637
+ let captureEnd = start;
1638
+ while (position < end) {
1639
+ const ch = input.charCodeAt(position);
1640
+ if (ch === 39) {
1641
+ result += input.slice(captureStart, position) + "'";
1642
+ position += 2;
1643
+ captureStart = captureEnd = position;
1644
+ } else if (ch === 10 || ch === 13) {
1645
+ result += input.slice(captureStart, captureEnd);
1646
+ const fold = skipFoldedBreaks(input, position, end);
1647
+ result += foldedBreaks(fold.breaks);
1648
+ position = captureStart = captureEnd = fold.position;
1649
+ } else {
1650
+ position++;
1651
+ if (ch !== 32 && ch !== 9) captureEnd = position;
670
1652
  }
1653
+ }
1654
+ return result + input.slice(captureStart, end);
1655
+ }
1656
+ function getDoubleQuotedValue(input, start, end) {
1657
+ let result = "";
1658
+ let position = start;
1659
+ let captureStart = start;
1660
+ let captureEnd = start;
1661
+ while (position < end) {
1662
+ const ch = input.charCodeAt(position);
1663
+ if (ch === 92) {
1664
+ result += input.slice(captureStart, position);
1665
+ position++;
1666
+ const escaped = input.charCodeAt(position);
1667
+ if (escaped === 10 || escaped === 13) position = skipFoldedBreaks(input, position, end).position;
1668
+ else if (escaped < 256 && simpleEscapeCheck[escaped]) {
1669
+ result += simpleEscapeMap[escaped];
1670
+ position++;
1671
+ } else {
1672
+ let hexLength = escapedHexLen$1(escaped);
1673
+ let hexResult = 0;
1674
+ for (; hexLength > 0; hexLength--) {
1675
+ position++;
1676
+ const digit = fromHexCode$1(input.charCodeAt(position));
1677
+ hexResult = (hexResult << 4) + digit;
1678
+ }
1679
+ result += charFromCodepoint(hexResult);
1680
+ position++;
1681
+ }
1682
+ captureStart = captureEnd = position;
1683
+ } else if (ch === 10 || ch === 13) {
1684
+ result += input.slice(captureStart, captureEnd);
1685
+ const fold = skipFoldedBreaks(input, position, end);
1686
+ result += foldedBreaks(fold.breaks);
1687
+ position = captureStart = captureEnd = fold.position;
1688
+ } else {
1689
+ position++;
1690
+ if (ch !== 32 && ch !== 9) captureEnd = position;
1691
+ }
1692
+ }
1693
+ return result + input.slice(captureStart, end);
1694
+ }
1695
+ function getBlockValue(input, start, end, indent, chomping, folded) {
1696
+ const textIndent = indent < 0 ? 0 : indent;
1697
+ const region = input.slice(start, end).replace(/\r\n?/g, "\n");
1698
+ const lines = region === "" ? [] : (region.endsWith("\n") ? region.slice(0, -1) : region).split("\n");
1699
+ let result = "";
1700
+ let didReadContent = false;
1701
+ let emptyLines = 0;
1702
+ let atMoreIndented = false;
1703
+ for (const line of lines) {
1704
+ let column = 0;
1705
+ while (column < textIndent && line.charCodeAt(column) === 32) column++;
1706
+ if (indent < 0 || column >= line.length) {
1707
+ emptyLines++;
1708
+ continue;
1709
+ }
1710
+ const content = line.slice(textIndent);
1711
+ const first = content.charCodeAt(0);
1712
+ if (folded) if (first === 32 || first === 9) {
1713
+ atMoreIndented = true;
1714
+ result += "\n".repeat(didReadContent ? 1 + emptyLines : emptyLines);
1715
+ } else if (atMoreIndented) {
1716
+ atMoreIndented = false;
1717
+ result += "\n".repeat(emptyLines + 1);
1718
+ } else if (emptyLines === 0) {
1719
+ if (didReadContent) result += " ";
1720
+ } else result += "\n".repeat(emptyLines);
1721
+ else result += "\n".repeat(didReadContent ? 1 + emptyLines : emptyLines);
1722
+ result += content;
1723
+ didReadContent = true;
1724
+ emptyLines = 0;
1725
+ }
1726
+ if (chomping === CHOMPING_MODE.KEEP) result += "\n".repeat(didReadContent ? 1 + emptyLines : emptyLines);
1727
+ else if (chomping !== CHOMPING_MODE.STRIP) {
1728
+ if (didReadContent) result += "\n";
1729
+ }
1730
+ return result;
1731
+ }
1732
+ function getScalarValue(input, scalar2) {
1733
+ if (scalar2.valueStart === NO_RANGE$3) return "";
1734
+ const { valueStart, valueEnd } = scalar2;
1735
+ if (scalar2.fast) return input.slice(valueStart, valueEnd);
1736
+ switch (scalar2.style) {
1737
+ case SCALAR_STYLE.SINGLE_QUOTED:
1738
+ return getSingleQuotedValue(input, valueStart, valueEnd);
1739
+ case SCALAR_STYLE.DOUBLE_QUOTED:
1740
+ return getDoubleQuotedValue(input, valueStart, valueEnd);
1741
+ case SCALAR_STYLE.LITERAL_BLOCK:
1742
+ return getBlockValue(input, valueStart, valueEnd, scalar2.indent, scalar2.chomping, false);
1743
+ case SCALAR_STYLE.FOLDED_BLOCK:
1744
+ return getBlockValue(input, valueStart, valueEnd, scalar2.indent, scalar2.chomping, true);
1745
+ default:
1746
+ return getPlainValue(input, valueStart, valueEnd);
1747
+ }
1748
+ }
1749
+ var DEFAULT_TAG_HANDLERS = Object.assign(/* @__PURE__ */ Object.create(null), {
1750
+ "!": "!",
1751
+ "!!": "tag:yaml.org,2002:"
1752
+ });
1753
+ function tagNameFull(rawTag, tagHandlers) {
1754
+ if (rawTag.startsWith("!<") && rawTag.endsWith(">")) return decodeURIComponent(rawTag.slice(2, -1));
1755
+ const handleEnd = rawTag.indexOf("!", 1);
1756
+ const handle = handleEnd === -1 ? "!" : rawTag.slice(0, handleEnd + 1);
1757
+ const prefix = tagHandlers?.[handle] ?? DEFAULT_TAG_HANDLERS[handle] ?? handle;
1758
+ return decodeURIComponent(prefix) + decodeURIComponent(rawTag.slice(handle.length));
1759
+ }
1760
+ var NO_RANGE$2 = -1;
1761
+ var MERGE_TAG_NAME = "tag:yaml.org,2002:merge";
1762
+ var DEFAULT_CONSTRUCTOR_OPTIONS = {
1763
+ filename: "",
1764
+ schema: CORE_SCHEMA,
1765
+ json: false,
1766
+ maxTotalMergeKeys: 1e4,
1767
+ maxAliases: -1
1768
+ };
1769
+ function eventPosition$1(event) {
1770
+ if ("tagStart" in event && event.tagStart !== NO_RANGE$2) return event.tagStart;
1771
+ if ("anchorStart" in event && event.anchorStart !== NO_RANGE$2) return event.anchorStart;
1772
+ if ("valueStart" in event && event.valueStart !== NO_RANGE$2) return event.valueStart;
1773
+ if ("start" in event) return event.start;
1774
+ return 0;
1775
+ }
1776
+ function throwError$1(state, message) {
1777
+ YAMLException.throwAt(state.source, state.position, message, state.filename);
1778
+ }
1779
+ function finalizeCollection(state, position, tag, carrier) {
1780
+ try {
1781
+ return tag.finalize(carrier);
1782
+ } catch (error) {
1783
+ if (error instanceof YAMLException) throw error;
1784
+ YAMLException.throwAt(state.source, position, error instanceof Error ? error.message : String(error), state.filename);
1785
+ }
1786
+ }
1787
+ function constructScalar(state, event) {
1788
+ const source = getScalarValue(state.source, event);
1789
+ const rawTag = event.tagStart === NO_RANGE$2 ? "" : state.source.slice(event.tagStart, event.tagEnd);
1790
+ const strTag2 = state.schema.defaultScalarTag;
1791
+ if (rawTag !== "") {
1792
+ if (rawTag === "!") return {
1793
+ value: source,
1794
+ tag: strTag2
1795
+ };
1796
+ const tagName = tagNameFull(rawTag, state.tagHandlers);
1797
+ const scalarTag = state.schema.lookupScalarTag(tagName);
1798
+ if (scalarTag) {
1799
+ const result = scalarTag.resolve(source, true, tagName);
1800
+ if (result === NOT_RESOLVED) throwError$1(state, `cannot resolve a node with !<${tagName}> explicit tag`);
1801
+ return {
1802
+ value: result,
1803
+ tag: scalarTag
1804
+ };
1805
+ }
1806
+ const collectionTagDef = state.schema.lookupMappingTag(tagName) ?? state.schema.lookupSequenceTag(tagName);
1807
+ if (collectionTagDef) {
1808
+ if (source !== "") throwError$1(state, `cannot resolve a node with !<${tagName}> explicit tag`);
1809
+ const carrier = collectionTagDef.create(tagName);
1810
+ return {
1811
+ value: collectionTagDef.carrierIsResult ? carrier : finalizeCollection(state, state.position, collectionTagDef, carrier),
1812
+ tag: collectionTagDef
1813
+ };
1814
+ }
1815
+ throwError$1(state, `unknown scalar tag !<${tagName}>`);
1816
+ }
1817
+ if (event.style === SCALAR_STYLE.PLAIN) return state.schema.resolveImplicitScalarTag(source);
1818
+ return {
1819
+ value: strTag2.resolve(source, false, strTag2.tagName),
1820
+ tag: strTag2
671
1821
  };
672
- const xmlCache = /* @__PURE__ */ new WeakMap();
673
- const visited = /* @__PURE__ */ new WeakMap();
674
- const fail3 = (path, message) => {
675
- errors.push(new Error(`Cannot upgrade to OpenAPI 3.2 at ${path}: ${message}`));
676
- };
677
- const resolve = (ref, schemaReference = false) => {
678
- if (typeof ref !== "string" || !ref.startsWith("#/")) {
679
- return void 0;
1822
+ }
1823
+ function collectionTagName(state, event, defaultTagName) {
1824
+ const rawTag = event.tagStart === NO_RANGE$2 ? "" : state.source.slice(event.tagStart, event.tagEnd);
1825
+ return rawTag === "" || rawTag === "!" ? defaultTagName : tagNameFull(rawTag, state.tagHandlers);
1826
+ }
1827
+ function isMappingTag(tag) {
1828
+ return tag.nodeKind === "mapping";
1829
+ }
1830
+ function chargeMergeWork(state) {
1831
+ state.totalMergeKeys++;
1832
+ if (state.maxTotalMergeKeys !== -1 && state.totalMergeKeys > state.maxTotalMergeKeys) throwError$1(state, `merge keys exceeded maxTotalMergeKeys (${state.maxTotalMergeKeys})`);
1833
+ }
1834
+ function mergeKeys(state, frame, source, sourceTag) {
1835
+ chargeMergeWork(state);
1836
+ for (const sourceKey of sourceTag.keys(source)) {
1837
+ chargeMergeWork(state);
1838
+ if (frame.tag.has(frame.value, sourceKey)) continue;
1839
+ const err = frame.tag.addPair(frame.value, sourceKey, sourceTag.get(source, sourceKey));
1840
+ if (err) throwError$1(state, err);
1841
+ frame.overridable ??= /* @__PURE__ */ new Set();
1842
+ frame.overridable.add(sourceKey);
1843
+ }
1844
+ }
1845
+ function mergeSource(state, frame, source, sourceTag) {
1846
+ state.position = frame.keyPosition;
1847
+ if (isMappingTag(sourceTag)) mergeKeys(state, frame, source, sourceTag);
1848
+ else if (sourceTag.nodeKind === "sequence" && Array.isArray(source)) {
1849
+ if (source.length > 100) throwError$1(state, "abnormal merge sequence size");
1850
+ for (const element of source) {
1851
+ const elementTag = state.nodeTags.get(element);
1852
+ if (!elementTag) throwError$1(state, "cannot merge mappings; the provided source object is unacceptable");
1853
+ mergeKeys(state, frame, element, elementTag);
680
1854
  }
681
- try {
682
- return parseJsonPointerSegments(decodeURIComponent(ref.slice(1))).reduce((value, key) => {
683
- if (schemaReference && isObject2(value) && (value.$id !== void 0 || value.$schema !== void 0)) {
684
- return void 0;
685
- }
686
- if (Array.isArray(value) && !/^(0|[1-9]\d*)$/.test(key)) {
687
- return void 0;
1855
+ } else throwError$1(state, "cannot merge mappings; the provided source object is unacceptable");
1856
+ }
1857
+ function addMappingValue(state, frame, key, value, tag) {
1858
+ state.position = frame.keyPosition;
1859
+ if (frame.keyIsMerge) {
1860
+ mergeSource(state, frame, value, tag);
1861
+ return;
1862
+ }
1863
+ if (!state.json && frame.tag.has(frame.value, key) && !frame.overridable?.has(key)) throwError$1(state, "duplicated mapping key");
1864
+ const err = frame.tag.addPair(frame.value, key, value);
1865
+ if (err) throwError$1(state, err);
1866
+ frame.overridable?.delete(key);
1867
+ }
1868
+ function addValue(state, value, tag) {
1869
+ const frame = state.frames[state.frames.length - 1];
1870
+ if (frame.kind === "document") {
1871
+ frame.value = value;
1872
+ frame.hasValue = true;
1873
+ } else if (frame.kind === "sequence") {
1874
+ if (isMappingTag(tag)) state.nodeTags.set(value, tag);
1875
+ const err = frame.tag.addItem(frame.value, value, frame.index++);
1876
+ if (err) throwError$1(state, err);
1877
+ } else if (frame.hasKey) {
1878
+ const key = frame.key;
1879
+ frame.key = void 0;
1880
+ frame.hasKey = false;
1881
+ addMappingValue(state, frame, key, value, tag);
1882
+ } else {
1883
+ frame.key = value;
1884
+ frame.keyPosition = state.position;
1885
+ frame.hasKey = true;
1886
+ frame.keyIsMerge = tag.tagName === MERGE_TAG_NAME;
1887
+ }
1888
+ }
1889
+ function storeAnchor(state, event, value, tag, isValueFinal) {
1890
+ if (event.anchorStart !== NO_RANGE$2) {
1891
+ const anchor = {
1892
+ value,
1893
+ tag,
1894
+ isValueFinal
1895
+ };
1896
+ state.anchors.set(state.source.slice(event.anchorStart, event.anchorEnd), anchor);
1897
+ return anchor;
1898
+ }
1899
+ return null;
1900
+ }
1901
+ function constructFromEvents(events, options) {
1902
+ const state = {
1903
+ ...DEFAULT_CONSTRUCTOR_OPTIONS,
1904
+ ...options,
1905
+ events,
1906
+ documents: [],
1907
+ eventIndex: 0,
1908
+ position: 0,
1909
+ frames: [],
1910
+ anchors: /* @__PURE__ */ new Map(),
1911
+ nodeTags: /* @__PURE__ */ new Map(),
1912
+ tagHandlers: /* @__PURE__ */ Object.create(null),
1913
+ totalMergeKeys: 0,
1914
+ aliasCount: 0
1915
+ };
1916
+ while (state.eventIndex < state.events.length) {
1917
+ const event = state.events[state.eventIndex++];
1918
+ state.position = eventPosition$1(event);
1919
+ switch (event.type) {
1920
+ case EVENT_ID.DOCUMENT:
1921
+ state.anchors = /* @__PURE__ */ new Map();
1922
+ state.nodeTags = /* @__PURE__ */ new Map();
1923
+ state.aliasCount = 0;
1924
+ state.tagHandlers = /* @__PURE__ */ Object.create(null);
1925
+ for (const directive of event.directives) if (directive.kind === "tag") state.tagHandlers[directive.handle] = directive.prefix;
1926
+ state.frames.push({
1927
+ kind: "document",
1928
+ position: state.position,
1929
+ value: void 0,
1930
+ hasValue: false
1931
+ });
1932
+ break;
1933
+ case EVENT_ID.SCALAR: {
1934
+ const { value, tag } = constructScalar(state, event);
1935
+ storeAnchor(state, event, value, tag, true);
1936
+ addValue(state, value, tag);
1937
+ break;
1938
+ }
1939
+ case EVENT_ID.SEQUENCE: {
1940
+ const tagName = collectionTagName(state, event, "tag:yaml.org,2002:seq");
1941
+ const tag = state.schema.lookupSequenceTag(tagName);
1942
+ if (!tag) throwError$1(state, `unknown sequence tag !<${tagName}>`);
1943
+ const value = tag.create(tagName);
1944
+ const anchor = storeAnchor(state, event, value, tag, tag.carrierIsResult);
1945
+ state.frames.push({
1946
+ kind: "sequence",
1947
+ position: state.position,
1948
+ value,
1949
+ tag,
1950
+ anchor,
1951
+ index: 0
1952
+ });
1953
+ break;
1954
+ }
1955
+ case EVENT_ID.MAPPING: {
1956
+ const tagName = collectionTagName(state, event, "tag:yaml.org,2002:map");
1957
+ const tag = state.schema.lookupMappingTag(tagName);
1958
+ if (!tag) throwError$1(state, `unknown mapping tag !<${tagName}>`);
1959
+ const value = tag.create(tagName);
1960
+ const anchor = storeAnchor(state, event, value, tag, tag.carrierIsResult);
1961
+ state.frames.push({
1962
+ kind: "mapping",
1963
+ position: state.position,
1964
+ value,
1965
+ tag,
1966
+ anchor,
1967
+ key: void 0,
1968
+ keyPosition: state.position,
1969
+ hasKey: false,
1970
+ keyIsMerge: false,
1971
+ overridable: null
1972
+ });
1973
+ break;
1974
+ }
1975
+ case EVENT_ID.ALIAS: {
1976
+ if (state.maxAliases !== -1 && ++state.aliasCount > state.maxAliases) throwError$1(state, `aliases exceeded maxAliases (${state.maxAliases})`);
1977
+ const name = state.source.slice(event.anchorStart, event.anchorEnd);
1978
+ const anchor = state.anchors.get(name);
1979
+ if (!anchor) throwError$1(state, `unidentified alias "${name}"`);
1980
+ if (!anchor.isValueFinal) throwError$1(state, `recursive alias "${name}" is not supported for tag ${anchor.tag.tagName} because it uses finalize()`);
1981
+ addValue(state, anchor.value, anchor.tag);
1982
+ break;
1983
+ }
1984
+ case EVENT_ID.POP: {
1985
+ const frame = state.frames.pop();
1986
+ if (frame.kind === "mapping" && frame.hasKey) {
1987
+ state.position = frame.keyPosition;
1988
+ throwError$1(state, "incomplete mapping pair in event stream");
688
1989
  }
689
- if (!isObject2(value) && !Array.isArray(value) || !Object.hasOwn(value, key)) {
690
- return void 0;
1990
+ if (frame.kind === "document") state.documents.push(frame.value);
1991
+ else {
1992
+ const value = frame.tag.carrierIsResult ? frame.value : finalizeCollection(state, frame.position, frame.tag, frame.value);
1993
+ if (frame.anchor) {
1994
+ frame.anchor.value = value;
1995
+ frame.anchor.isValueFinal = true;
1996
+ }
1997
+ addValue(state, value, frame.tag);
691
1998
  }
692
- return own(value, key);
693
- }, document);
694
- } catch {
695
- return void 0;
1999
+ break;
2000
+ }
696
2001
  }
2002
+ }
2003
+ return state.documents;
2004
+ }
2005
+ var NO_RANGE$1 = -1;
2006
+ var HAS_OWN = Object.prototype.hasOwnProperty;
2007
+ var CONTEXT_FLOW_IN = 1;
2008
+ var CONTEXT_FLOW_OUT = 2;
2009
+ var CONTEXT_BLOCK_IN = 3;
2010
+ var CONTEXT_BLOCK_OUT = 4;
2011
+ var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
2012
+ var PATTERN_FLOW_INDICATORS = /[,\[\]{}]/;
2013
+ var PATTERN_TAG_HANDLE = /^(?:!|!!|![0-9A-Za-z-]+!)$/;
2014
+ var NS_URI_CHAR = String.raw`(?:%[0-9A-Fa-f]{2}|[0-9A-Za-z\-#;/?:@&=+$,_.!~*'()\[\]])`;
2015
+ var NS_TAG_CHAR = String.raw`(?:%[0-9A-Fa-f]{2}|[0-9A-Za-z\-#;/?:@&=+$.~*'()_])`;
2016
+ var PATTERN_TAG_URI = new RegExp(`^(?:${NS_URI_CHAR})*$`);
2017
+ var PATTERN_TAG_SUFFIX = new RegExp(`^(?:${NS_TAG_CHAR})+$`);
2018
+ var PATTERN_TAG_PREFIX = new RegExp(`^(?:!(?:${NS_URI_CHAR})*|${NS_TAG_CHAR}(?:${NS_URI_CHAR})*)$`);
2019
+ var DEFAULT_PARSER_OPTIONS = {
2020
+ filename: "",
2021
+ maxDepth: 100
2022
+ };
2023
+ function addDocumentEvent(state, explicitStart, explicitEnd) {
2024
+ state.events.push({
2025
+ type: EVENT_ID.DOCUMENT,
2026
+ explicitStart,
2027
+ explicitEnd,
2028
+ directives: state.directives
2029
+ });
2030
+ }
2031
+ function addSequenceEvent(state, start, anchorStart, anchorEnd, tagStart, tagEnd, style) {
2032
+ state.events.push({
2033
+ type: EVENT_ID.SEQUENCE,
2034
+ start,
2035
+ anchorStart,
2036
+ anchorEnd,
2037
+ tagStart,
2038
+ tagEnd,
2039
+ style
2040
+ });
2041
+ }
2042
+ function addMappingEvent(state, start, anchorStart, anchorEnd, tagStart, tagEnd, style) {
2043
+ state.events.push({
2044
+ type: EVENT_ID.MAPPING,
2045
+ start,
2046
+ anchorStart,
2047
+ anchorEnd,
2048
+ tagStart,
2049
+ tagEnd,
2050
+ style
2051
+ });
2052
+ }
2053
+ function insertFlowPairMappingEvent(state, snapshot) {
2054
+ state.events.splice(snapshot.eventsLength, 0, {
2055
+ type: EVENT_ID.MAPPING,
2056
+ start: snapshot.position,
2057
+ anchorStart: NO_RANGE$1,
2058
+ anchorEnd: NO_RANGE$1,
2059
+ tagStart: NO_RANGE$1,
2060
+ tagEnd: NO_RANGE$1,
2061
+ style: COLLECTION_STYLE.FLOW
2062
+ });
2063
+ }
2064
+ function addScalarEvent(state, valueStart, valueEnd, anchorStart, anchorEnd, tagStart, tagEnd, style, chomping = CHOMPING_MODE.CLIP, indent = -1, fast = false) {
2065
+ state.events.push({
2066
+ type: EVENT_ID.SCALAR,
2067
+ valueStart,
2068
+ valueEnd,
2069
+ anchorStart,
2070
+ anchorEnd,
2071
+ tagStart,
2072
+ tagEnd,
2073
+ style,
2074
+ chomping,
2075
+ indent,
2076
+ fast
2077
+ });
2078
+ }
2079
+ function addAliasEvent(state, anchorStart, anchorEnd) {
2080
+ state.events.push({
2081
+ type: EVENT_ID.ALIAS,
2082
+ anchorStart,
2083
+ anchorEnd
2084
+ });
2085
+ }
2086
+ function addPopEvent(state) {
2087
+ state.events.push({ type: EVENT_ID.POP });
2088
+ }
2089
+ function addEmptyScalarEvent(state) {
2090
+ addScalarEvent(state, NO_RANGE$1, NO_RANGE$1, NO_RANGE$1, NO_RANGE$1, NO_RANGE$1, NO_RANGE$1, SCALAR_STYLE.PLAIN);
2091
+ }
2092
+ function emptyProperties() {
2093
+ return {
2094
+ anchorStart: NO_RANGE$1,
2095
+ anchorEnd: NO_RANGE$1,
2096
+ tagStart: NO_RANGE$1,
2097
+ tagEnd: NO_RANGE$1
697
2098
  };
698
- const repeatedVariables = (value, path) => {
699
- if (typeof value !== "string") {
700
- return;
701
- }
702
- const names = [...value.matchAll(/\{([^{}]+)\}/g)].map((match) => match[1]);
703
- if (new Set(names).size !== names.length) {
704
- fail3(path, "Template variables must not be repeated. Rename the repeated variable and define it separately.");
705
- }
2099
+ }
2100
+ function snapshotState(state) {
2101
+ return {
2102
+ position: state.position,
2103
+ line: state.line,
2104
+ lineStart: state.lineStart,
2105
+ lineIndent: state.lineIndent,
2106
+ firstTabInLine: state.firstTabInLine,
2107
+ eventsLength: state.events.length
706
2108
  };
707
- const requires = (schema2, name, seen = /* @__PURE__ */ new Set()) => {
708
- if (schema2 === false) {
709
- return true;
2109
+ }
2110
+ function restoreState(state, snapshot) {
2111
+ state.position = snapshot.position;
2112
+ state.line = snapshot.line;
2113
+ state.lineStart = snapshot.lineStart;
2114
+ state.lineIndent = snapshot.lineIndent;
2115
+ state.firstTabInLine = snapshot.firstTabInLine;
2116
+ state.events.length = snapshot.eventsLength;
2117
+ }
2118
+ function throwError(state, message) {
2119
+ YAMLException.throwAt(state.input.slice(0, state.length), state.position, message, state.filename);
2120
+ }
2121
+ function isEol(c) {
2122
+ return c === 10 || c === 13;
2123
+ }
2124
+ function isWhiteSpace(c) {
2125
+ return c === 9 || c === 32;
2126
+ }
2127
+ function isWsOrEol(c) {
2128
+ return isWhiteSpace(c) || isEol(c);
2129
+ }
2130
+ function isWsOrEolOrEnd(c) {
2131
+ return c === 0 || isWsOrEol(c);
2132
+ }
2133
+ function isFlowIndicator(c) {
2134
+ return c === 44 || c === 91 || c === 93 || c === 123 || c === 125;
2135
+ }
2136
+ function fromDecimalCode(c) {
2137
+ return c >= 48 && c <= 57 ? c - 48 : -1;
2138
+ }
2139
+ function fromHexCode(c) {
2140
+ if (c >= 48 && c <= 57) return c - 48;
2141
+ const lc = c | 32;
2142
+ if (lc >= 97 && lc <= 102) return lc - 97 + 10;
2143
+ return -1;
2144
+ }
2145
+ function escapedHexLen(c) {
2146
+ if (c === 120) return 2;
2147
+ if (c === 117) return 4;
2148
+ if (c === 85) return 8;
2149
+ return 0;
2150
+ }
2151
+ function isSimpleEscape(c) {
2152
+ return c === 48 || c === 97 || c === 98 || c === 116 || c === 9 || c === 110 || c === 118 || c === 102 || c === 114 || c === 101 || c === 32 || c === 34 || c === 47 || c === 92 || c === 78 || c === 95 || c === 76 || c === 80;
2153
+ }
2154
+ function consumeLineBreak(state) {
2155
+ if (state.input.charCodeAt(state.position) === 10) state.position++;
2156
+ else {
2157
+ state.position++;
2158
+ if (state.input.charCodeAt(state.position) === 10) state.position++;
2159
+ }
2160
+ state.line++;
2161
+ state.lineStart = state.position;
2162
+ state.lineIndent = 0;
2163
+ state.firstTabInLine = -1;
2164
+ }
2165
+ function skipSeparationSpace(state, allowComments) {
2166
+ let lineBreaks = 0;
2167
+ let ch = state.input.charCodeAt(state.position);
2168
+ let hasSeparation = state.position === state.lineStart || isWsOrEol(state.input.charCodeAt(state.position - 1));
2169
+ while (ch !== 0) {
2170
+ while (isWhiteSpace(ch)) {
2171
+ hasSeparation = true;
2172
+ if (ch === 9 && state.firstTabInLine === -1) state.firstTabInLine = state.position;
2173
+ ch = state.input.charCodeAt(++state.position);
710
2174
  }
711
- if (schema2 === true) {
712
- return false;
2175
+ if (allowComments && hasSeparation && ch === 35) do
2176
+ ch = state.input.charCodeAt(++state.position);
2177
+ while (!isEol(ch) && ch !== 0);
2178
+ if (!isEol(ch)) break;
2179
+ consumeLineBreak(state);
2180
+ lineBreaks++;
2181
+ hasSeparation = true;
2182
+ ch = state.input.charCodeAt(state.position);
2183
+ while (ch === 32) {
2184
+ state.lineIndent++;
2185
+ ch = state.input.charCodeAt(++state.position);
713
2186
  }
714
- if (!isObject2(schema2) || schema2.$id !== void 0 || schema2.$schema !== void 0) {
715
- return void 0;
2187
+ }
2188
+ return lineBreaks;
2189
+ }
2190
+ function testDocumentSeparator(state, position = state.position) {
2191
+ const ch = state.input.charCodeAt(position);
2192
+ if ((ch === 45 || ch === 46) && ch === state.input.charCodeAt(position + 1) && ch === state.input.charCodeAt(position + 2)) {
2193
+ const following = state.input.charCodeAt(position + 3);
2194
+ return following === 0 || isWsOrEol(following);
2195
+ }
2196
+ return false;
2197
+ }
2198
+ function skipByteOrderMark(state) {
2199
+ if (state.position === state.lineStart && state.input.charCodeAt(state.position) === 65279) {
2200
+ state.position++;
2201
+ state.lineStart = state.position;
2202
+ }
2203
+ }
2204
+ function testDocumentBoundary(state) {
2205
+ if (state.position !== state.lineStart) return false;
2206
+ if (testDocumentSeparator(state)) return true;
2207
+ if (state.input.charCodeAt(state.position) !== 65279) return false;
2208
+ const snapshot = snapshotState(state);
2209
+ skipByteOrderMark(state);
2210
+ skipSeparationSpace(state, true);
2211
+ const ch = state.input.charCodeAt(state.position);
2212
+ const result = state.position === state.lineStart && (ch === 37 || ch === 45 && testDocumentSeparator(state));
2213
+ restoreState(state, snapshot);
2214
+ return result;
2215
+ }
2216
+ function skipUntilLineEnd(state) {
2217
+ let ch = state.input.charCodeAt(state.position);
2218
+ while (ch !== 0 && !isEol(ch)) ch = state.input.charCodeAt(++state.position);
2219
+ }
2220
+ function checkPrintable(state, start, end) {
2221
+ if (PATTERN_NON_PRINTABLE.test(state.input.slice(start, end))) throwError(state, "the stream contains non-printable characters");
2222
+ }
2223
+ function readTagProperty(state, props, inFlow) {
2224
+ if (state.input.charCodeAt(state.position) !== 33) return false;
2225
+ if (props.tagStart !== NO_RANGE$1) throwError(state, "duplication of a tag property");
2226
+ const start = state.position;
2227
+ let isVerbatim = false;
2228
+ let isNamed = false;
2229
+ let tagHandle = "!";
2230
+ let ch = state.input.charCodeAt(++state.position);
2231
+ if (ch === 60) {
2232
+ isVerbatim = true;
2233
+ ch = state.input.charCodeAt(++state.position);
2234
+ } else if (ch === 33) {
2235
+ isNamed = true;
2236
+ tagHandle = "!!";
2237
+ ch = state.input.charCodeAt(++state.position);
2238
+ }
2239
+ let suffixStart = state.position;
2240
+ let tagName;
2241
+ if (isVerbatim) {
2242
+ while (ch !== 0 && ch !== 62) ch = state.input.charCodeAt(++state.position);
2243
+ if (ch !== 62) throwError(state, "unexpected end of the stream within a verbatim tag");
2244
+ tagName = state.input.slice(suffixStart, state.position);
2245
+ state.position++;
2246
+ } else {
2247
+ while (ch !== 0 && !isWsOrEol(ch) && !(inFlow && isFlowIndicator(ch))) {
2248
+ if (ch === 33) if (!isNamed) {
2249
+ tagHandle = state.input.slice(suffixStart - 1, state.position + 1);
2250
+ if (!PATTERN_TAG_HANDLE.test(tagHandle)) throwError(state, "named tag handle cannot contain such characters");
2251
+ isNamed = true;
2252
+ suffixStart = state.position + 1;
2253
+ } else throwError(state, "tag suffix cannot contain exclamation marks");
2254
+ ch = state.input.charCodeAt(++state.position);
716
2255
  }
717
- if (seen.has(schema2)) {
718
- for (const ancestor of seen) {
719
- cyclicRequired.add(ancestor);
2256
+ tagName = state.input.slice(suffixStart, state.position);
2257
+ if (PATTERN_FLOW_INDICATORS.test(tagName)) throwError(state, "tag suffix cannot contain flow indicator characters");
2258
+ }
2259
+ if (tagName && !(isVerbatim ? PATTERN_TAG_URI.test(tagName) : PATTERN_TAG_SUFFIX.test(tagName))) throwError(state, `tag name cannot contain such characters: ${tagName}`);
2260
+ if (!isVerbatim && tagHandle !== "!" && tagHandle !== "!!" && !HAS_OWN.call(state.tagHandlers, tagHandle)) throwError(state, `undeclared tag handle "${tagHandle}"`);
2261
+ props.tagStart = start;
2262
+ props.tagEnd = state.position;
2263
+ return true;
2264
+ }
2265
+ function readAnchorProperty(state, props) {
2266
+ if (state.input.charCodeAt(state.position) !== 38) return false;
2267
+ if (props.anchorStart !== NO_RANGE$1) throwError(state, "duplication of an anchor property");
2268
+ state.position++;
2269
+ const start = state.position;
2270
+ while (state.input.charCodeAt(state.position) !== 0 && !isWsOrEol(state.input.charCodeAt(state.position)) && !isFlowIndicator(state.input.charCodeAt(state.position))) state.position++;
2271
+ if (state.position === start) throwError(state, "name of an anchor node must contain at least one character");
2272
+ props.anchorStart = start;
2273
+ props.anchorEnd = state.position;
2274
+ return true;
2275
+ }
2276
+ function readAlias(state, props) {
2277
+ if (state.input.charCodeAt(state.position) !== 42) return false;
2278
+ if (props.anchorStart !== NO_RANGE$1 || props.tagStart !== NO_RANGE$1) throwError(state, "alias node should not have any properties");
2279
+ state.position++;
2280
+ const start = state.position;
2281
+ while (state.input.charCodeAt(state.position) !== 0 && !isWsOrEol(state.input.charCodeAt(state.position)) && !isFlowIndicator(state.input.charCodeAt(state.position))) state.position++;
2282
+ if (state.position === start) throwError(state, "name of an alias node must contain at least one character");
2283
+ addAliasEvent(state, start, state.position);
2284
+ return true;
2285
+ }
2286
+ function readFlowScalarBreak(state, nodeIndent) {
2287
+ skipSeparationSpace(state, false);
2288
+ if (state.lineIndent < nodeIndent) throwError(state, "deficient indentation");
2289
+ }
2290
+ function readSingleQuotedScalar(state, nodeIndent, props) {
2291
+ if (state.input.charCodeAt(state.position) !== 39) return false;
2292
+ state.position++;
2293
+ const start = state.position;
2294
+ let simple = true;
2295
+ while (state.input.charCodeAt(state.position) !== 0) {
2296
+ const ch = state.input.charCodeAt(state.position);
2297
+ if (ch === 39) {
2298
+ if (state.input.charCodeAt(state.position + 1) === 39) {
2299
+ simple = false;
2300
+ state.position += 2;
2301
+ continue;
720
2302
  }
721
- return void 0;
2303
+ const end = state.position;
2304
+ state.position++;
2305
+ addScalarEvent(state, start, end, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, SCALAR_STYLE.SINGLE_QUOTED, CHOMPING_MODE.CLIP, -1, simple);
2306
+ return true;
722
2307
  }
723
- const cached = requiredCache.get(schema2) ?? /* @__PURE__ */ new Map();
724
- if (cached.has(name)) {
725
- return cached.get(name);
2308
+ if (isEol(ch)) {
2309
+ simple = false;
2310
+ readFlowScalarBreak(state, nodeIndent);
2311
+ } else if (state.position === state.lineStart && testDocumentSeparator(state)) throwError(state, "unexpected end of the document within a single quoted scalar");
2312
+ else if (ch !== 9 && ch < 32) throwError(state, "expected valid JSON character");
2313
+ else state.position++;
2314
+ }
2315
+ throwError(state, "unexpected end of the stream within a single quoted scalar");
2316
+ }
2317
+ function readDoubleQuotedScalar(state, nodeIndent, props) {
2318
+ if (state.input.charCodeAt(state.position) !== 34) return false;
2319
+ state.position++;
2320
+ const start = state.position;
2321
+ let simple = true;
2322
+ while (state.input.charCodeAt(state.position) !== 0) {
2323
+ const ch = state.input.charCodeAt(state.position);
2324
+ if (ch === 34) {
2325
+ const end = state.position;
2326
+ state.position++;
2327
+ addScalarEvent(state, start, end, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, SCALAR_STYLE.DOUBLE_QUOTED, CHOMPING_MODE.CLIP, -1, simple);
2328
+ return true;
726
2329
  }
727
- if (++requiredWork.evaluations > 1e5) {
728
- if (requiredWork.evaluations === 100001) {
729
- fail3("#", "Discriminator requiredness analysis was truncated after 100,000 evaluations.");
2330
+ if (ch === 92) {
2331
+ simple = false;
2332
+ const escaped = state.input.charCodeAt(++state.position);
2333
+ if (isEol(escaped)) readFlowScalarBreak(state, nodeIndent);
2334
+ else if (isSimpleEscape(escaped)) state.position++;
2335
+ else {
2336
+ let hexLength = escapedHexLen(escaped);
2337
+ if (hexLength === 0) throwError(state, "unknown escape sequence");
2338
+ while (hexLength-- > 0) {
2339
+ state.position++;
2340
+ if (fromHexCode(state.input.charCodeAt(state.position)) < 0) throwError(state, "expected hexadecimal character");
2341
+ }
2342
+ state.position++;
730
2343
  }
731
- return void 0;
2344
+ } else if (isEol(ch)) {
2345
+ simple = false;
2346
+ readFlowScalarBreak(state, nodeIndent);
2347
+ } else if (state.position === state.lineStart && testDocumentSeparator(state)) throwError(state, "unexpected end of the document within a double quoted scalar");
2348
+ else if (ch !== 9 && ch < 32) throwError(state, "expected valid JSON character");
2349
+ else state.position++;
2350
+ }
2351
+ throwError(state, "unexpected end of the stream within a double quoted scalar");
2352
+ }
2353
+ function readBlockScalar(state, parentIndent, props) {
2354
+ const ch = state.input.charCodeAt(state.position);
2355
+ let chomping = CHOMPING_MODE.CLIP;
2356
+ let indent = -1;
2357
+ let detectedIndent = false;
2358
+ if (ch !== 124 && ch !== 62) return false;
2359
+ const style = ch === 124 ? SCALAR_STYLE.LITERAL_BLOCK : SCALAR_STYLE.FOLDED_BLOCK;
2360
+ state.position++;
2361
+ while (state.input.charCodeAt(state.position) !== 0) {
2362
+ const current = state.input.charCodeAt(state.position);
2363
+ const digit = fromDecimalCode(current);
2364
+ if (current === 43 || current === 45) {
2365
+ if (chomping !== CHOMPING_MODE.CLIP) throwError(state, "repeat of a chomping mode identifier");
2366
+ chomping = current === 43 ? CHOMPING_MODE.KEEP : CHOMPING_MODE.STRIP;
2367
+ state.position++;
2368
+ } else if (digit >= 0) {
2369
+ if (digit === 0) throwError(state, "bad explicit indentation width of a block scalar; it cannot be less than one");
2370
+ if (detectedIndent) throwError(state, "repeat of an indentation width identifier");
2371
+ indent = parentIndent + digit - 1;
2372
+ detectedIndent = true;
2373
+ state.position++;
2374
+ } else break;
2375
+ }
2376
+ let hadWhitespace = false;
2377
+ while (isWhiteSpace(state.input.charCodeAt(state.position))) {
2378
+ hadWhitespace = true;
2379
+ state.position++;
2380
+ }
2381
+ if (hadWhitespace && state.input.charCodeAt(state.position) === 35) skipUntilLineEnd(state);
2382
+ if (isEol(state.input.charCodeAt(state.position))) consumeLineBreak(state);
2383
+ else if (state.input.charCodeAt(state.position) !== 0) throwError(state, "a line break is expected");
2384
+ let contentIndent = detectedIndent ? indent : -1;
2385
+ let maxLeadingIndent = 0;
2386
+ const valueStart = state.position;
2387
+ let valueEnd = state.position;
2388
+ while (state.input.charCodeAt(state.position) !== 0) {
2389
+ const linePosition = state.position;
2390
+ let column = 0;
2391
+ while (state.input.charCodeAt(linePosition + column) === 32) column++;
2392
+ const first = state.input.charCodeAt(linePosition + column);
2393
+ if (first === 0) {
2394
+ if (contentIndent >= 0) {
2395
+ if (column > contentIndent) valueEnd = linePosition + column;
2396
+ } else if (column > 0) valueEnd = linePosition + column;
2397
+ break;
732
2398
  }
733
- const remember2 = (result) => {
734
- if (result !== void 0 || !cyclicRequired.has(schema2)) {
735
- cached.set(name, result);
736
- requiredCache.set(schema2, cached);
2399
+ if (testDocumentBoundary(state)) break;
2400
+ if (!detectedIndent && contentIndent === -1 && isEol(first)) maxLeadingIndent = Math.max(maxLeadingIndent, column);
2401
+ if (!detectedIndent && contentIndent === -1 && !isEol(first)) {
2402
+ if (first === 9 && column < parentIndent) {
2403
+ state.position = linePosition + column;
2404
+ throwError(state, "tab characters must not be used in indentation");
737
2405
  }
738
- return result;
739
- };
740
- if (Array.isArray(schema2.required) && schema2.required.includes(name)) {
741
- return remember2(true);
742
- }
743
- const next = /* @__PURE__ */ new Set([...seen, schema2]);
744
- const constraints = [];
745
- if (schema2.$ref !== void 0) {
746
- constraints.push(requires(resolve(schema2.$ref, true), name, next));
747
- }
748
- if (Array.isArray(schema2.allOf)) {
749
- constraints.push(...schema2.allOf.map((item) => requires(item, name, next)));
750
- }
751
- for (const keyword of ["oneOf", "anyOf"]) {
752
- if (Array.isArray(schema2[keyword])) {
753
- const alternatives = schema2[keyword].map((item) => requires(item, name, next));
754
- if (alternatives.every((value) => value === true)) {
755
- constraints.push(true);
756
- } else if (alternatives.every((value) => value === false)) {
757
- constraints.push(false);
758
- } else {
759
- constraints.push(void 0);
760
- }
2406
+ if (column < maxLeadingIndent) {
2407
+ state.position = linePosition + column;
2408
+ throwError(state, "bad indentation of a mapping entry");
761
2409
  }
762
2410
  }
763
- if (constraints.includes(true)) {
764
- return remember2(true);
2411
+ if (contentIndent === -1 && first !== 0 && !isEol(first) && column < parentIndent) {
2412
+ state.lineIndent = column;
2413
+ state.position = linePosition + column;
2414
+ break;
765
2415
  }
766
- if (constraints.includes(void 0) || ["if", "not", "$dynamicRef", "const", "enum", "minProperties", "dependentRequired", "dependentSchemas"].some((key) => key in schema2)) {
767
- return remember2(void 0);
768
- }
769
- return remember2(false);
770
- };
771
- const validateXmlNames = (schema2, path, { inferredName, propertyName, dialect, ancestors = /* @__PURE__ */ new Set(), baseChanged = false }) => {
772
- if (!isObject2(schema2) || ancestors.has(schema2) || (schema2.$schema ?? dialect) !== void 0) {
773
- return;
2416
+ if (!detectedIndent && first !== 0 && !isEol(first) && contentIndent === -1) contentIndent = column;
2417
+ const requiredIndent = contentIndent === -1 ? parentIndent + 1 : contentIndent;
2418
+ if (first !== 0 && !isEol(first) && column < requiredIndent) {
2419
+ state.lineIndent = column;
2420
+ state.position = linePosition + column;
2421
+ break;
774
2422
  }
775
- const changedBase = baseChanged || schema2.$id !== void 0;
776
- const context = [inferredName, propertyName, changedBase].join(":");
777
- const completed = xmlCache.get(schema2) ?? /* @__PURE__ */ new Set();
778
- if (completed.has(context)) {
779
- return;
2423
+ skipUntilLineEnd(state);
2424
+ valueEnd = state.position;
2425
+ if (isEol(state.input.charCodeAt(state.position))) {
2426
+ consumeLineBreak(state);
2427
+ valueEnd = state.position;
780
2428
  }
781
- const xml = isObject2(schema2.xml) ? schema2.xml : {};
782
- const defaultNodeType = schema2.$ref !== void 0 || schema2.$dynamicRef !== void 0 || schema2.type === "array" ? "none" : "element";
783
- const wrappedNodeType = xml.wrapped === true ? "element" : defaultNodeType;
784
- const nodeType = xml.nodeType ?? (xml.attribute === true ? "attribute" : wrappedNodeType);
785
- if ((nodeType === "element" || nodeType === "attribute") && !inferredName && xml.name === void 0) {
786
- fail3(path, "An inline XML element needs an explicit xml.name.");
787
- }
788
- const childContext = { dialect, ancestors: /* @__PURE__ */ new Set([...ancestors, schema2]), baseChanged: changedBase };
789
- if (!changedBase && typeof schema2.$ref === "string") {
790
- const target = resolve(schema2.$ref, true);
791
- if (isObject2(target)) {
792
- const segments2 = parseJsonPointerSegments(decodeURIComponent(schema2.$ref.slice(1)));
793
- const componentRoot = segments2.length === 3 && segments2[0] === "components" && segments2[1] === "schemas";
794
- const fromProperty = propertySchemas.has(target);
795
- validateXmlNames(target, schema2.$ref, {
796
- ...childContext,
797
- inferredName: componentRoot || fromProperty,
798
- propertyName: fromProperty
799
- });
2429
+ }
2430
+ checkPrintable(state, valueStart, valueEnd);
2431
+ addScalarEvent(state, valueStart, valueEnd, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, style, chomping, contentIndent);
2432
+ return true;
2433
+ }
2434
+ function canStartPlainScalar(state, nodeContext) {
2435
+ const ch = state.input.charCodeAt(state.position);
2436
+ const inFlow = nodeContext === CONTEXT_FLOW_IN;
2437
+ if (ch === 0 || isWsOrEol(ch) || ch === 35 || ch === 38 || ch === 42 || ch === 33 || ch === 124 || ch === 62 || ch === 39 || ch === 34 || ch === 37 || ch === 64 || ch === 96 || inFlow && isFlowIndicator(ch)) return false;
2438
+ if (ch === 63 || ch === 45) {
2439
+ const following = state.input.charCodeAt(state.position + 1);
2440
+ if (isWsOrEolOrEnd(following) || inFlow && isFlowIndicator(following)) return false;
2441
+ }
2442
+ return true;
2443
+ }
2444
+ function readPlainScalar(state, nodeIndent, nodeContext, props) {
2445
+ if (!canStartPlainScalar(state, nodeContext)) return false;
2446
+ const start = state.position;
2447
+ let end = state.position;
2448
+ let ch = state.input.charCodeAt(state.position);
2449
+ const inFlow = nodeContext === CONTEXT_FLOW_IN;
2450
+ let multiline = false;
2451
+ while (ch !== 0) {
2452
+ if (testDocumentBoundary(state)) break;
2453
+ if (ch === 58) {
2454
+ const following = state.input.charCodeAt(state.position + 1);
2455
+ if (isWsOrEolOrEnd(following) || inFlow && isFlowIndicator(following)) break;
2456
+ } else if (ch === 35) {
2457
+ if (isWsOrEol(state.input.charCodeAt(state.position - 1))) break;
2458
+ } else if (inFlow && isFlowIndicator(ch)) break;
2459
+ else if (isEol(ch)) {
2460
+ const savedPosition = state.position;
2461
+ const savedLine = state.line;
2462
+ const savedLineStart = state.lineStart;
2463
+ const savedLineIndent = state.lineIndent;
2464
+ skipSeparationSpace(state, false);
2465
+ if (state.lineIndent >= nodeIndent) {
2466
+ multiline = true;
2467
+ ch = state.input.charCodeAt(state.position);
2468
+ continue;
800
2469
  }
2470
+ state.position = savedPosition;
2471
+ state.line = savedLine;
2472
+ state.lineStart = savedLineStart;
2473
+ state.lineIndent = savedLineIndent;
2474
+ break;
801
2475
  }
802
- for (const keyword of ["allOf", "anyOf", "oneOf"]) {
803
- const branches = schema2[keyword];
804
- if (Array.isArray(branches)) {
805
- branches.forEach((branch, index) => validateXmlNames(branch, path + "/" + keyword + "/" + index, {
806
- ...childContext,
807
- inferredName: false,
808
- propertyName: false
809
- }));
810
- }
2476
+ if (!isWhiteSpace(ch)) end = state.position + 1;
2477
+ ch = state.input.charCodeAt(++state.position);
2478
+ }
2479
+ if (end === start) return false;
2480
+ checkPrintable(state, start, end);
2481
+ addScalarEvent(state, start, end, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, SCALAR_STYLE.PLAIN, CHOMPING_MODE.CLIP, -1, !multiline);
2482
+ return true;
2483
+ }
2484
+ function skipFlowSeparationSpace(state, nodeIndent) {
2485
+ const startLine = state.line;
2486
+ skipSeparationSpace(state, true);
2487
+ if (state.line > startLine && state.lineIndent < nodeIndent || state.firstTabInLine !== -1 && state.lineIndent < nodeIndent) throwError(state, "deficient indentation");
2488
+ }
2489
+ function readFlowCollection(state, nodeIndent, props) {
2490
+ const ch = state.input.charCodeAt(state.position);
2491
+ const isMapping = ch === 123;
2492
+ const start = state.position;
2493
+ let readNext = true;
2494
+ if (ch !== 91 && ch !== 123) return false;
2495
+ const terminator = isMapping ? 125 : 93;
2496
+ if (isMapping) addMappingEvent(state, start, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, COLLECTION_STYLE.FLOW);
2497
+ else addSequenceEvent(state, start, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, COLLECTION_STYLE.FLOW);
2498
+ state.position++;
2499
+ while (state.input.charCodeAt(state.position) !== 0) {
2500
+ skipFlowSeparationSpace(state, nodeIndent);
2501
+ let ch2 = state.input.charCodeAt(state.position);
2502
+ if (ch2 === terminator) {
2503
+ state.position++;
2504
+ addPopEvent(state);
2505
+ return true;
2506
+ } else if (!readNext) throwError(state, "missed comma between flow collection entries");
2507
+ else if (ch2 === 44) throwError(state, "expected the node content, but found ','");
2508
+ let isPair = false;
2509
+ let isExplicitPair = false;
2510
+ if (ch2 === 63 && isWsOrEol(state.input.charCodeAt(state.position + 1))) {
2511
+ isPair = isExplicitPair = true;
2512
+ state.position += 1;
2513
+ skipFlowSeparationSpace(state, nodeIndent);
811
2514
  }
812
- validateXmlNames(schema2.items, path + "/items", { ...childContext, inferredName: propertyName, propertyName });
813
- if (Array.isArray(schema2.prefixItems)) {
814
- schema2.prefixItems.forEach((item, index) => validateXmlNames(item, path + "/prefixItems/" + index, {
815
- ...childContext,
816
- inferredName: propertyName,
817
- propertyName
818
- }));
819
- }
820
- if (isObject2(schema2.properties)) {
821
- for (const [name, property] of Object.entries(schema2.properties)) {
822
- validateXmlNames(property, path + "/properties/" + escapeJsonPointer(name), {
823
- ...childContext,
824
- inferredName: true,
825
- propertyName: true
826
- });
827
- }
2515
+ const entryLine = state.line;
2516
+ const entryStart = snapshotState(state);
2517
+ const keyWasRead = parseNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
2518
+ skipFlowSeparationSpace(state, nodeIndent);
2519
+ ch2 = state.input.charCodeAt(state.position);
2520
+ if ((isMapping || isExplicitPair || state.line === entryLine) && ch2 === 58) {
2521
+ isPair = true;
2522
+ state.position++;
2523
+ skipFlowSeparationSpace(state, nodeIndent);
2524
+ if (!isMapping) {
2525
+ insertFlowPairMappingEvent(state, entryStart);
2526
+ if (!keyWasRead) addEmptyScalarEvent(state);
2527
+ } else if (!keyWasRead) addEmptyScalarEvent(state);
2528
+ if (!parseNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true)) addEmptyScalarEvent(state);
2529
+ skipFlowSeparationSpace(state, nodeIndent);
2530
+ if (!isMapping) addPopEvent(state);
2531
+ } else if (isMapping && isPair) {
2532
+ if (!keyWasRead) addEmptyScalarEvent(state);
2533
+ addEmptyScalarEvent(state);
2534
+ } else if (isMapping) addEmptyScalarEvent(state);
2535
+ else if (isPair) {
2536
+ insertFlowPairMappingEvent(state, entryStart);
2537
+ if (!keyWasRead) addEmptyScalarEvent(state);
2538
+ addEmptyScalarEvent(state);
2539
+ addPopEvent(state);
828
2540
  }
829
- completed.add(context);
830
- xmlCache.set(schema2, completed);
831
- };
832
- const visit = (value, kind, path, dialect = document.jsonSchemaDialect, baseChanged = false) => {
833
- if (!isObject2(value)) {
834
- return;
2541
+ ch2 = state.input.charCodeAt(state.position);
2542
+ if (ch2 === 44) {
2543
+ readNext = true;
2544
+ state.position++;
2545
+ } else readNext = false;
2546
+ }
2547
+ throwError(state, "unexpected end of the stream within a flow collection");
2548
+ }
2549
+ function readBlockSequence(state, nodeIndent, props) {
2550
+ if (state.firstTabInLine !== -1 || state.input.charCodeAt(state.position) !== 45 || !isWsOrEolOrEnd(state.input.charCodeAt(state.position + 1))) return false;
2551
+ addSequenceEvent(state, state.position, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, COLLECTION_STYLE.BLOCK);
2552
+ while (state.input.charCodeAt(state.position) === 45 && isWsOrEolOrEnd(state.input.charCodeAt(state.position + 1))) {
2553
+ if (state.firstTabInLine !== -1) {
2554
+ state.position = state.firstTabInLine;
2555
+ throwError(state, "tab characters must not be used in indentation");
835
2556
  }
836
- const schemaDialect = kind === "schema" ? value.$schema ?? dialect : dialect;
837
- const schemaBaseChanged = baseChanged || kind === "schema" && value.$id !== void 0;
838
- const visitKey = `${kind}:${String(schemaDialect)}:${schemaBaseChanged}`;
839
- const seen = visited.get(value) ?? /* @__PURE__ */ new Set();
840
- if (seen.has(visitKey)) {
841
- return;
2557
+ const entryLine = state.line;
2558
+ state.position++;
2559
+ const hadBreak = skipSeparationSpace(state, true) > 0;
2560
+ if (state.firstTabInLine !== -1 && state.input.charCodeAt(state.position) === 45 && isWsOrEolOrEnd(state.input.charCodeAt(state.position + 1))) throwError(state, "bad indentation of a sequence entry");
2561
+ if (hadBreak && state.lineIndent <= nodeIndent) addEmptyScalarEvent(state);
2562
+ else parseNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true);
2563
+ skipSeparationSpace(state, true);
2564
+ if (state.lineIndent < nodeIndent || state.position >= state.length) break;
2565
+ if (state.lineIndent > nodeIndent) throwError(state, "bad indentation of a sequence entry");
2566
+ if (state.line === entryLine && state.input.charCodeAt(state.position) === 45 && isWsOrEolOrEnd(state.input.charCodeAt(state.position + 1))) throwError(state, "bad indentation of a sequence entry");
2567
+ }
2568
+ addPopEvent(state);
2569
+ return true;
2570
+ }
2571
+ function readBlockMapping(state, nodeIndent, flowIndent, props) {
2572
+ let atExplicitKey = false;
2573
+ let detected = false;
2574
+ let mappingOpened = false;
2575
+ let pendingExplicitKey = false;
2576
+ if (state.firstTabInLine !== -1) return false;
2577
+ let ch = state.input.charCodeAt(state.position);
2578
+ while (ch !== 0) {
2579
+ if (!atExplicitKey && state.firstTabInLine !== -1) {
2580
+ state.position = state.firstTabInLine;
2581
+ throwError(state, "tab characters must not be used in indentation");
842
2582
  }
843
- seen.add(visitKey);
844
- visited.set(value, seen);
845
- const child = (key, type) => visit(own(value, key), type, `${path}/${escapeJsonPointer(key)}`, schemaDialect, schemaBaseChanged);
846
- const list = (key, type) => {
847
- const items = own(value, key);
848
- if (Array.isArray(items)) {
849
- items.forEach((item, index) => visit(item, type, `${path}/${key}/${index}`, schemaDialect, schemaBaseChanged));
2583
+ const following = state.input.charCodeAt(state.position + 1);
2584
+ const entryLine = state.line;
2585
+ if ((ch === 63 || ch === 58) && isWsOrEolOrEnd(following)) {
2586
+ if (!mappingOpened) {
2587
+ addMappingEvent(state, state.position, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, COLLECTION_STYLE.BLOCK);
2588
+ mappingOpened = true;
850
2589
  }
851
- };
852
- const map = (key, type) => {
853
- const items = own(value, key);
854
- if (isObject2(items)) {
855
- for (const [name, item] of Object.entries(items)) {
856
- if (key === "responses" && name.startsWith("x-")) {
857
- continue;
858
- }
859
- if (kind === "schema" && key === "properties") {
860
- markPropertySchema(item);
861
- }
862
- visit(item, type, `${path}/${key}/${escapeJsonPointer(name)}`, schemaDialect, schemaBaseChanged);
863
- }
2590
+ if (ch === 63) {
2591
+ if (atExplicitKey) addEmptyScalarEvent(state);
2592
+ detected = true;
2593
+ atExplicitKey = true;
2594
+ } else if (atExplicitKey) atExplicitKey = false;
2595
+ else {
2596
+ addEmptyScalarEvent(state);
2597
+ detected = true;
2598
+ atExplicitKey = false;
864
2599
  }
865
- };
866
- if (kind === "schema") {
867
- if (schemaDialect !== void 0) {
868
- return;
2600
+ state.position += 1;
2601
+ pendingExplicitKey = true;
2602
+ } else {
2603
+ if (atExplicitKey) {
2604
+ addEmptyScalarEvent(state);
2605
+ atExplicitKey = false;
869
2606
  }
870
- const xml = own(value, "xml");
871
- if (isObject2(xml)) {
872
- if (xml.wrapped === true && xml.attribute === true) {
873
- fail3(`${path}/xml`, "wrapped and attribute cannot both be true.");
2607
+ const beforeKey = snapshotState(state);
2608
+ if (!parseNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) break;
2609
+ if (state.line === entryLine) {
2610
+ ch = state.input.charCodeAt(state.position);
2611
+ while (isWhiteSpace(ch)) ch = state.input.charCodeAt(++state.position);
2612
+ if (ch === 58) {
2613
+ ch = state.input.charCodeAt(++state.position);
2614
+ if (!isWsOrEolOrEnd(ch)) throwError(state, "a whitespace character is expected after the key-value separator within a block mapping");
2615
+ if (!mappingOpened) {
2616
+ restoreState(state, beforeKey);
2617
+ addMappingEvent(state, beforeKey.position, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, COLLECTION_STYLE.BLOCK);
2618
+ mappingOpened = true;
2619
+ parseNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true);
2620
+ ch = state.input.charCodeAt(state.position);
2621
+ while (isWhiteSpace(ch)) ch = state.input.charCodeAt(++state.position);
2622
+ state.position++;
2623
+ }
2624
+ detected = true;
2625
+ atExplicitKey = false;
2626
+ pendingExplicitKey = false;
2627
+ } else if (detected) throwError(state, "expected ':' after a mapping key");
2628
+ else {
2629
+ if (props.anchorStart !== NO_RANGE$1 || props.tagStart !== NO_RANGE$1) {
2630
+ restoreState(state, beforeKey);
2631
+ return false;
2632
+ }
2633
+ return true;
874
2634
  }
875
- if (xml.wrapped === true || xml.attribute === true) {
876
- xml.nodeType = xml.attribute === true ? "attribute" : "element";
877
- delete xml.wrapped;
878
- delete xml.attribute;
2635
+ } else if (detected) throwError(state, "can not read a block mapping entry; a multiline key may not be an implicit key");
2636
+ else {
2637
+ if (props.anchorStart !== NO_RANGE$1 || props.tagStart !== NO_RANGE$1) {
2638
+ restoreState(state, beforeKey);
2639
+ return false;
879
2640
  }
2641
+ return true;
880
2642
  }
881
- if (!schemaBaseChanged && value.$ref !== void 0) {
882
- visit(resolve(value.$ref, true), "schema", String(value.$ref), schemaDialect);
883
- }
884
- const discriminator = value.discriminator;
885
- if (isObject2(discriminator) && typeof discriminator.propertyName === "string" && discriminator.defaultMapping === void 0 && !schemaBaseChanged && requires(value, discriminator.propertyName) === false) {
886
- fail3(`${path}/discriminator`, "An optional discriminating property needs an explicit defaultMapping.");
887
- }
888
- for (const key of schemaMaps) {
889
- map(key, "schema");
890
- }
891
- for (const key of schemaArrays) {
892
- list(key, "schema");
893
- }
894
- for (const key of schemaSingles) {
895
- child(key, "schema");
896
- }
897
- return;
898
2643
  }
899
- if (value.$ref !== void 0) {
900
- visit(resolve(value.$ref), kind, String(value.$ref), schemaDialect);
2644
+ if (parseNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, pendingExplicitKey)) pendingExplicitKey = false;
2645
+ if (!atExplicitKey) {
2646
+ if (pendingExplicitKey) {
2647
+ addEmptyScalarEvent(state);
2648
+ pendingExplicitKey = false;
2649
+ }
901
2650
  }
902
- switch (kind) {
903
- case "document": {
904
- const paths = own(value, "paths");
905
- if (isObject2(paths)) {
906
- for (const [name, item] of Object.entries(paths)) {
907
- if (!name.startsWith("/")) {
908
- continue;
909
- }
910
- const location = `${path}/paths/${escapeJsonPointer(name)}`;
911
- repeatedVariables(name, location);
912
- visit(item, "pathItem", location);
913
- }
914
- }
915
- map("webhooks", "pathItem");
916
- list("servers", "server");
917
- const componentObjects = own(value, "components");
918
- if (isObject2(componentObjects)) {
919
- const components = {
920
- schemas: "schema",
921
- parameters: "parameter",
922
- headers: "header",
923
- requestBodies: "body",
924
- responses: "response",
925
- callbacks: "callback",
926
- pathItems: "pathItem"
927
- };
928
- for (const [key, type] of Object.entries(components)) {
929
- const entries = own(componentObjects, key);
930
- if (isObject2(entries)) {
931
- for (const [name, item] of Object.entries(entries)) {
932
- visit(item, type, `${path}/components/${key}/${escapeJsonPointer(name)}`);
933
- }
934
- }
935
- }
936
- }
937
- break;
2651
+ skipSeparationSpace(state, true);
2652
+ ch = state.input.charCodeAt(state.position);
2653
+ if ((state.line === entryLine || state.lineIndent > nodeIndent) && ch !== 0) throwError(state, "bad indentation of a mapping entry");
2654
+ else if (state.lineIndent < nodeIndent) break;
2655
+ }
2656
+ if (!detected) return false;
2657
+ if (atExplicitKey) addEmptyScalarEvent(state);
2658
+ if (mappingOpened) addPopEvent(state);
2659
+ return true;
2660
+ }
2661
+ function parseNode(state, parentIndent, nodeContext, allowToSeek, allowCompact, allowPropertyMapping = true) {
2662
+ if (state.depth >= state.maxDepth) throwError(state, `nesting exceeded maxDepth (${state.maxDepth})`);
2663
+ state.depth++;
2664
+ let indentStatus = 1;
2665
+ let atNewLine = false;
2666
+ let hasContent = false;
2667
+ let propertyStart = null;
2668
+ const props = emptyProperties();
2669
+ let allowBlockScalars = nodeContext === CONTEXT_BLOCK_OUT || nodeContext === CONTEXT_BLOCK_IN;
2670
+ let allowBlockCollections = allowBlockScalars;
2671
+ const allowBlockStyles = allowBlockScalars;
2672
+ if (allowToSeek && skipSeparationSpace(state, true)) {
2673
+ atNewLine = true;
2674
+ if (state.lineIndent > parentIndent) indentStatus = 1;
2675
+ else if (state.lineIndent === parentIndent) indentStatus = 0;
2676
+ else indentStatus = -1;
2677
+ }
2678
+ if (indentStatus === 1) while (true) {
2679
+ const ch = state.input.charCodeAt(state.position);
2680
+ const propertyState = snapshotState(state);
2681
+ if (atNewLine && indentStatus !== 1 && (ch === 33 || ch === 38)) break;
2682
+ if (atNewLine && allowBlockStyles && (props.tagStart !== NO_RANGE$1 || props.anchorStart !== NO_RANGE$1) && (ch === 33 || ch === 38)) {
2683
+ const fallbackState = snapshotState(state);
2684
+ const flowIndent = parentIndent + 1;
2685
+ if (readBlockMapping(state, state.position - state.lineStart, flowIndent, props) && state.events[fallbackState.eventsLength]?.type === EVENT_ID.MAPPING) {
2686
+ state.depth--;
2687
+ return true;
938
2688
  }
939
- case "pathItem":
940
- for (const method of ["get", "put", "post", "delete", "options", "head", "patch", "trace"]) {
941
- child(method, "operation");
942
- }
943
- list("parameters", "parameter");
944
- list("servers", "server");
945
- break;
946
- case "operation":
947
- if (Array.isArray(value.tags)) {
948
- for (const tag of value.tags) {
949
- if (typeof tag === "string") {
950
- operationTags.add(tag);
951
- }
952
- }
953
- }
954
- list("parameters", "parameter");
955
- list("servers", "server");
956
- child("requestBody", "body");
957
- map("responses", "response");
958
- map("callbacks", "callback");
959
- break;
960
- case "callback":
961
- for (const [name, item] of Object.entries(value)) {
962
- if (!name.startsWith("x-") && name !== "$ref") {
963
- visit(item, "pathItem", `${path}/${escapeJsonPointer(name)}`, schemaDialect, schemaBaseChanged);
964
- }
965
- }
966
- break;
967
- case "parameter":
968
- if (value.in === "path" || value.in === "cookie") {
969
- delete value.allowReserved;
970
- }
971
- child("schema", "schema");
972
- map("content", "media");
973
- break;
974
- case "header":
975
- child("schema", "schema");
976
- map("content", "media");
977
- break;
978
- case "response":
979
- map("headers", "header");
980
- map("content", "media");
981
- break;
982
- case "body":
983
- map("content", "media");
984
- break;
985
- case "media":
986
- if (/\/(?:[^;]+\+)?xml(?:\s*;|$)/i.test(path.slice(path.lastIndexOf("/") + 1).replace(/~1/g, "/"))) {
987
- xmlRoots.push({ schema: value.schema, path: `${path}/schema`, dialect: schemaDialect });
988
- }
989
- child("schema", "schema");
990
- map("encoding", "encoding");
991
- break;
992
- case "encoding":
993
- map("headers", "header");
994
- break;
995
- case "server":
996
- repeatedVariables(value.url, `${path}/url`);
997
- break;
2689
+ restoreState(state, fallbackState);
998
2690
  }
999
- };
1000
- visit(document, "document", "#");
1001
- for (const { schema: schema2, path, dialect } of xmlRoots) {
1002
- validateXmlNames(schema2, path, { inferredName: false, propertyName: false, dialect });
2691
+ if (atNewLine && (ch === 33 && props.tagStart !== NO_RANGE$1 || ch === 38 && props.anchorStart !== NO_RANGE$1)) break;
2692
+ if (!readTagProperty(state, props, nodeContext === CONTEXT_FLOW_IN) && !readAnchorProperty(state, props)) break;
2693
+ if (propertyStart === null) propertyStart = propertyState;
2694
+ if (skipSeparationSpace(state, true)) {
2695
+ atNewLine = true;
2696
+ allowBlockCollections = allowBlockStyles;
2697
+ if (state.lineIndent > parentIndent) indentStatus = 1;
2698
+ else if (state.lineIndent === parentIndent) indentStatus = 0;
2699
+ else indentStatus = -1;
2700
+ } else allowBlockCollections = false;
1003
2701
  }
1004
- if (errors.length > 0) {
1005
- throw new UpgradeIncompatibilityError(errors);
2702
+ if (allowBlockCollections) allowBlockCollections = atNewLine || allowCompact;
2703
+ if (indentStatus === 1 || nodeContext === CONTEXT_BLOCK_OUT) {
2704
+ const flowIndent = nodeContext === CONTEXT_FLOW_IN || nodeContext === CONTEXT_FLOW_OUT ? parentIndent : parentIndent + 1;
2705
+ const blockIndent = state.position - state.lineStart;
2706
+ if (indentStatus === 1) if (allowBlockCollections && (readBlockSequence(state, blockIndent, props) || readBlockMapping(state, blockIndent, flowIndent, props)) || readFlowCollection(state, flowIndent, props)) hasContent = true;
2707
+ else {
2708
+ const ch = state.input.charCodeAt(state.position);
2709
+ if (propertyStart !== null && allowPropertyMapping && allowBlockStyles && !allowBlockCollections && ch !== 124 && ch !== 62) {
2710
+ const fallbackState = snapshotState(state);
2711
+ const propertyIndent = propertyStart.position - propertyStart.lineStart;
2712
+ restoreState(state, propertyStart);
2713
+ if (readBlockMapping(state, propertyIndent, flowIndent, emptyProperties()) && state.events[fallbackState.eventsLength]?.type === EVENT_ID.MAPPING) hasContent = true;
2714
+ else restoreState(state, fallbackState);
2715
+ }
2716
+ if (!hasContent && (allowBlockScalars && readBlockScalar(state, flowIndent, props) || readSingleQuotedScalar(state, flowIndent, props) || readDoubleQuotedScalar(state, flowIndent, props) || readAlias(state, props) || readPlainScalar(state, flowIndent, nodeContext, props))) hasContent = true;
2717
+ }
2718
+ else if (indentStatus === 0) hasContent = allowBlockCollections && readBlockSequence(state, blockIndent, props);
1006
2719
  }
1007
- return operationTags;
1008
- };
1009
-
1010
- // ../../node_modules/.bun/@scalar+openapi-upgrader@0.3.1/node_modules/@scalar/openapi-upgrader/dist/3.1-to-3.2/migrate-tag-groups.js
1011
- var migrateTagGroups = (document, operationTags) => {
1012
- const groups = document["x-tagGroups"];
1013
- if (!Array.isArray(groups) || groups.length === 0) {
1014
- return;
2720
+ allowBlockScalars = allowBlockScalars && !hasContent;
2721
+ if (!hasContent && (props.anchorStart !== NO_RANGE$1 || props.tagStart !== NO_RANGE$1 || allowBlockScalars)) {
2722
+ addScalarEvent(state, NO_RANGE$1, NO_RANGE$1, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, SCALAR_STYLE.PLAIN);
2723
+ hasContent = true;
1015
2724
  }
1016
- if (document.tags !== void 0 && !Array.isArray(document.tags)) {
1017
- return;
2725
+ state.depth--;
2726
+ return hasContent || props.anchorStart !== NO_RANGE$1 || props.tagStart !== NO_RANGE$1;
2727
+ }
2728
+ function readDirective(state) {
2729
+ if (state.lineIndent > 0 || state.input.charCodeAt(state.position) !== 37) return false;
2730
+ state.position++;
2731
+ const nameStart = state.position;
2732
+ while (state.input.charCodeAt(state.position) !== 0 && !isWsOrEol(state.input.charCodeAt(state.position))) state.position++;
2733
+ const name = state.input.slice(nameStart, state.position);
2734
+ const args = [];
2735
+ if (name.length === 0) throwError(state, "directive name must not be less than one character in length");
2736
+ while (state.input.charCodeAt(state.position) !== 0 && !isEol(state.input.charCodeAt(state.position))) {
2737
+ while (isWhiteSpace(state.input.charCodeAt(state.position))) state.position++;
2738
+ if (state.input.charCodeAt(state.position) === 35 || isEol(state.input.charCodeAt(state.position)) || state.input.charCodeAt(state.position) === 0) break;
2739
+ const start = state.position;
2740
+ while (state.input.charCodeAt(state.position) !== 0 && !isWsOrEol(state.input.charCodeAt(state.position))) state.position++;
2741
+ args.push(state.input.slice(start, state.position));
1018
2742
  }
1019
- const tags = document.tags ?? [];
1020
- if (!tags.every((tag) => isObject2(tag) && typeof tag.name === "string")) {
1021
- return;
2743
+ if (isEol(state.input.charCodeAt(state.position))) consumeLineBreak(state);
2744
+ if (name === "YAML") {
2745
+ if (state.directives.some((directive) => directive.kind === "yaml")) throwError(state, "duplication of %YAML directive");
2746
+ if (args.length !== 1) throwError(state, "YAML directive accepts exactly one argument");
2747
+ const match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]);
2748
+ if (match === null) throwError(state, "ill-formed argument of the YAML directive");
2749
+ if (parseInt(match[1], 10) !== 1) throwError(state, "unacceptable YAML version of the document");
2750
+ state.directives.push({
2751
+ kind: "yaml",
2752
+ version: args[0]
2753
+ });
2754
+ } else if (name === "TAG") {
2755
+ if (args.length !== 2) throwError(state, "TAG directive accepts exactly two arguments");
2756
+ const [handle, prefix] = args;
2757
+ if (!PATTERN_TAG_HANDLE.test(handle)) throwError(state, "ill-formed tag handle (first argument) of the TAG directive");
2758
+ if (HAS_OWN.call(state.tagHandlers, handle)) throwError(state, `there is a previously declared suffix for "${handle}" tag handle`);
2759
+ if (!PATTERN_TAG_PREFIX.test(prefix)) throwError(state, "ill-formed tag prefix (second argument) of the TAG directive");
2760
+ state.tagHandlers[handle] = prefix;
2761
+ state.directives.push({
2762
+ kind: "tag",
2763
+ handle,
2764
+ prefix
2765
+ });
1022
2766
  }
1023
- const existing = new Map(tags.map((tag) => [tag.name, tag]));
1024
- const parents = /* @__PURE__ */ new Set();
1025
- const children = /* @__PURE__ */ new Set();
1026
- for (const group of groups) {
1027
- if (!isObject2(group) || typeof group.name !== "string" || !group.name || !Array.isArray(group.tags) || !group.tags.every((name) => typeof name === "string") || Object.keys(group).some((key) => key !== "name" && key !== "tags") || parents.has(group.name) || existing.has(group.name) || operationTags.has(group.name)) {
1028
- return;
1029
- }
1030
- parents.add(group.name);
1031
- for (const name of group.tags) {
1032
- if (children.has(name) || existing.get(name)?.parent !== void 0) {
1033
- return;
1034
- }
1035
- children.add(name);
1036
- }
2767
+ return true;
2768
+ }
2769
+ function readDocument(state) {
2770
+ state.directives = [];
2771
+ state.tagHandlers = /* @__PURE__ */ Object.create(null);
2772
+ let hasDirectives = false;
2773
+ skipSeparationSpace(state, true);
2774
+ while (readDirective(state)) {
2775
+ hasDirectives = true;
2776
+ skipSeparationSpace(state, true);
1037
2777
  }
1038
- if ([...parents].some((name) => children.has(name)) || existing.size !== tags.length) {
2778
+ let explicitStart = false;
2779
+ let explicitEnd = false;
2780
+ let allowCompact = true;
2781
+ if (state.lineIndent === 0 && state.input.charCodeAt(state.position) === 45 && state.input.charCodeAt(state.position + 1) === 45 && state.input.charCodeAt(state.position + 2) === 45 && isWsOrEolOrEnd(state.input.charCodeAt(state.position + 3))) {
2782
+ explicitStart = true;
2783
+ const markerLine = state.line;
2784
+ state.position += 3;
2785
+ skipSeparationSpace(state, true);
2786
+ allowCompact = state.line > markerLine;
2787
+ } else if (hasDirectives) throwError(state, "directives end mark is expected");
2788
+ const documentEventIndex = state.events.length;
2789
+ if (!explicitStart && state.position === state.lineStart && state.input.charCodeAt(state.position) === 46 && testDocumentSeparator(state)) {
2790
+ state.position += 3;
2791
+ skipSeparationSpace(state, true);
1039
2792
  return;
1040
2793
  }
1041
- const result = [];
1042
- for (const group of groups) {
1043
- result.push({ name: group.name, kind: "nav" });
1044
- for (const name of group.tags) {
1045
- result.push({ ...existing.get(name) ?? { name }, parent: group.name });
2794
+ addDocumentEvent(state, explicitStart, false);
2795
+ if (!parseNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, allowCompact, allowCompact)) addEmptyScalarEvent(state);
2796
+ skipSeparationSpace(state, true);
2797
+ if (state.position === state.lineStart && testDocumentSeparator(state)) {
2798
+ explicitEnd = state.input.charCodeAt(state.position) === 46;
2799
+ if (explicitEnd) {
2800
+ const markerLine = state.line;
2801
+ state.position += 3;
2802
+ skipSeparationSpace(state, true);
2803
+ if (state.line === markerLine && state.position < state.length) throwError(state, "end of the stream or a document separator is expected");
1046
2804
  }
1047
2805
  }
1048
- document.tags = [...result, ...tags.filter((tag) => !children.has(tag.name))];
2806
+ const documentEvent = state.events[documentEventIndex];
2807
+ if (documentEvent?.type === EVENT_ID.DOCUMENT) documentEvent.explicitEnd = explicitEnd;
2808
+ addPopEvent(state);
2809
+ if (!explicitEnd && state.position < state.length && !testDocumentBoundary(state)) throwError(state, "end of the stream or a document separator is expected");
2810
+ }
2811
+ function parseEvents(input, options) {
2812
+ const length = input.length;
2813
+ const state = {
2814
+ ...DEFAULT_PARSER_OPTIONS,
2815
+ ...options,
2816
+ input: `${input}\0`,
2817
+ length,
2818
+ position: 0,
2819
+ line: 0,
2820
+ lineStart: 0,
2821
+ lineIndent: 0,
2822
+ firstTabInLine: -1,
2823
+ depth: 0,
2824
+ directives: [],
2825
+ tagHandlers: /* @__PURE__ */ Object.create(null),
2826
+ events: []
2827
+ };
2828
+ const nullpos = input.indexOf("\0");
2829
+ if (nullpos !== -1) YAMLException.throwAt(input, nullpos, "null byte is not allowed in input", state.filename);
2830
+ while (state.position < state.length) {
2831
+ skipByteOrderMark(state);
2832
+ skipSeparationSpace(state, true);
2833
+ if (state.position >= state.length) break;
2834
+ const documentStart = state.position;
2835
+ readDocument(state);
2836
+ if (state.position === documentStart)
2837
+ throwError(state, "can not read a document");
2838
+ }
2839
+ return state.events;
2840
+ }
2841
+ var DEFAULT_LOAD_OPTIONS = {
2842
+ ...DEFAULT_PARSER_OPTIONS,
2843
+ ...DEFAULT_CONSTRUCTOR_OPTIONS
1049
2844
  };
1050
-
1051
- // ../../node_modules/.bun/@scalar+openapi-upgrader@0.3.1/node_modules/@scalar/openapi-upgrader/dist/3.1-to-3.2/upgrade-from-three-one-to-three-two.js
1052
- var isThreeOneDocument = (document) => {
1053
- if (!isObject2(document) || typeof document.openapi !== "string") {
1054
- return false;
2845
+ function loadDocuments(input, options = {}) {
2846
+ const opts = {
2847
+ ...DEFAULT_LOAD_OPTIONS,
2848
+ ...options
2849
+ };
2850
+ const source = String(input);
2851
+ const PARSER_OPT_KEYS = Object.keys(DEFAULT_PARSER_OPTIONS);
2852
+ const CONSTRUCTOR_OPT_KEYS = Object.keys(DEFAULT_CONSTRUCTOR_OPTIONS);
2853
+ return constructFromEvents(parseEvents(source, pick(opts, PARSER_OPT_KEYS)), {
2854
+ ...pick(opts, CONSTRUCTOR_OPT_KEYS),
2855
+ source
2856
+ });
2857
+ }
2858
+ function load(input, options) {
2859
+ const documents = loadDocuments(input, options);
2860
+ if (documents.length === 0) throw new YAMLException("expected a document, but the input is empty");
2861
+ if (documents.length === 1) return documents[0];
2862
+ throw new YAMLException("expected a single document in the stream, but found more");
2863
+ }
2864
+ function hasBit(mask, bit) {
2865
+ return (mask & 1 << bit) !== 0;
2866
+ }
2867
+ var DEFAULT_SCALAR_STYLE_RULES = {
2868
+ applyQuoteFlowKeysOption,
2869
+ doubleQuoteForInvisibles,
2870
+ doubleQuoteWhitespaceOnly,
2871
+ applyForceQuotesOption,
2872
+ tryLongOrMultilineAsBlock,
2873
+ quoteInvalidPlain,
2874
+ fallbackToDoubleQuoted
2875
+ };
2876
+ function _preferredQuotedStyle(layout) {
2877
+ if (layout.presenterOptions.quoteStyle === "single" && hasBit(layout.allowedStylesMask, SCALAR_STYLE.SINGLE_QUOTED)) return SCALAR_STYLE.SINGLE_QUOTED;
2878
+ return SCALAR_STYLE.DOUBLE_QUOTED;
2879
+ }
2880
+ function applyQuoteFlowKeysOption(layout) {
2881
+ if (!layout.presenterOptions.quoteFlowKeys) return;
2882
+ if (!layout.isKey || !layout.flowOnly || layout.style !== SCALAR_STYLE.PLAIN) return;
2883
+ layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
2884
+ }
2885
+ function doubleQuoteForInvisibles(layout) {
2886
+ if (layout.style === SCALAR_STYLE.PLAIN && /[\t\x7F-\xA0\u2028\u2029\uFEFF\uFFFE\uFFFF]/.test(layout.node.value)) layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
2887
+ }
2888
+ function doubleQuoteWhitespaceOnly(layout) {
2889
+ if (layout.style === SCALAR_STYLE.PLAIN && /^\s+$/.test(layout.node.value)) layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
2890
+ }
2891
+ function applyForceQuotesOption(layout) {
2892
+ if (!layout.presenterOptions.forceQuotes) return;
2893
+ if (layout.isKey || layout.style !== SCALAR_STYLE.PLAIN) return;
2894
+ if (layout.node.tag !== layout.presenterOptions.schema.defaultScalarTag.tagName) return;
2895
+ layout.style = layout.node.value.includes("\n") ? SCALAR_STYLE.DOUBLE_QUOTED : _preferredQuotedStyle(layout);
2896
+ }
2897
+ function tryLongOrMultilineAsBlock(layout) {
2898
+ if (layout.style !== SCALAR_STYLE.PLAIN || layout.isKey) return;
2899
+ const value = layout.node.value;
2900
+ const multiline = value.indexOf("\n") !== -1;
2901
+ if (!hasBit(layout.allowedStylesMask, SCALAR_STYLE.LITERAL_BLOCK)) {
2902
+ if (multiline) layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
2903
+ return;
1055
2904
  }
1056
- if (/^3\.1\.\d+$/.test(document.openapi)) {
1057
- return true;
2905
+ const w = layout.presenterOptions.lineWidth;
2906
+ if (w === -1) {
2907
+ if (multiline) layout.style = SCALAR_STYLE.LITERAL_BLOCK;
2908
+ return;
1058
2909
  }
1059
- if (/^3\.1(?:\D|$)/.test(document.openapi)) {
1060
- throw new Error(`Cannot upgrade to OpenAPI 3.2: invalid OpenAPI version "${document.openapi}". Expected 3.1.x with a numeric patch version.`);
2910
+ const availableWidth = Math.max(Math.min(w, 40), w - layout.shiftOfContent);
2911
+ let position = 0;
2912
+ let shouldFold = false;
2913
+ while (position <= value.length) {
2914
+ let lineEnd = value.length;
2915
+ const nextLineBreak = value.indexOf("\n", position);
2916
+ if (nextLineBreak !== -1) lineEnd = nextLineBreak;
2917
+ const line = value.slice(position, lineEnd);
2918
+ if (line.length > availableWidth && line[0] !== " " && / [^ \t]/.test(line)) shouldFold = true;
2919
+ if (nextLineBreak === -1) break;
2920
+ position = nextLineBreak + 1;
1061
2921
  }
1062
- return false;
2922
+ if (shouldFold) layout.style = SCALAR_STYLE.FOLDED_BLOCK;
2923
+ else if (multiline) layout.style = SCALAR_STYLE.LITERAL_BLOCK;
2924
+ }
2925
+ function quoteInvalidPlain(layout) {
2926
+ if (layout.style === SCALAR_STYLE.PLAIN && !hasBit(layout.allowedStylesMask, SCALAR_STYLE.PLAIN)) layout.style = _preferredQuotedStyle(layout);
2927
+ }
2928
+ function fallbackToDoubleQuoted(layout) {
2929
+ if (!hasBit(layout.allowedStylesMask, layout.style)) layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
2930
+ }
2931
+ var SRC_C_PRINTABLE = "[\\x09\\x0A\\x0D\\x20-\\x7E\\x85\\xA0-\\uD7FF\\uE000-\\uFFFD\\u{10000}-\\u{10FFFF}]";
2932
+ var SRC_B_CHAR = "[\\n\\r]";
2933
+ var SRC_C_BYTE_ORDER_MARK = "\\uFEFF";
2934
+ var SRC_S_WHITE = "[ \\t]";
2935
+ var SRC_NB_CHAR = `(?:(?!(?:${SRC_B_CHAR}|${SRC_C_BYTE_ORDER_MARK}))${SRC_C_PRINTABLE})`;
2936
+ var SRC_NS_CHAR = `(?:(?!${SRC_S_WHITE})${SRC_NB_CHAR})`;
2937
+ var SRC_NB_JSON = "[\\x09\\x20-\\uD7FF\\uE000-\\uFFFF\\u{10000}-\\u{10FFFF}]";
2938
+ var SRC_C_INDICATOR = "[-?:,\\[\\]{}#&*!|>'\"%@`]";
2939
+ var SRC_C_FLOW_INDICATOR = "[,\\[\\]{}]";
2940
+ var SRC_NS_PLAIN_SAFE_FLOW_OUT = SRC_NS_CHAR;
2941
+ var SRC_NS_PLAIN_SAFE_FLOW_IN = `(?:(?!${SRC_C_FLOW_INDICATOR})${SRC_NS_CHAR})`;
2942
+ var SRC_NS_PLAIN_FIRST_FLOW_OUT = `(?:(?:(?!${SRC_C_INDICATOR})${SRC_NS_CHAR})|[?:-](?=${SRC_NS_PLAIN_SAFE_FLOW_OUT}))`;
2943
+ var SRC_NS_PLAIN_FIRST_FLOW_IN = `(?:(?:(?!${SRC_C_INDICATOR})${SRC_NS_CHAR})|[?:-](?=${SRC_NS_PLAIN_SAFE_FLOW_IN}))`;
2944
+ var SRC_NS_PLAIN_CHAR_FLOW_OUT = `(?:(?:(?![:#])${SRC_NS_PLAIN_SAFE_FLOW_OUT})|:(?=${SRC_NS_PLAIN_SAFE_FLOW_OUT}))#*`;
2945
+ var SRC_NS_PLAIN_CHAR_FLOW_IN = `(?:(?:(?![:#])${SRC_NS_PLAIN_SAFE_FLOW_IN})|:(?=${SRC_NS_PLAIN_SAFE_FLOW_IN}))#*`;
2946
+ var SRC_NB_NS_PLAIN_IN_LINE_FLOW_OUT = `(?:${SRC_S_WHITE}*${SRC_NS_PLAIN_CHAR_FLOW_OUT})*`;
2947
+ var SRC_NB_NS_PLAIN_IN_LINE_FLOW_IN = `(?:${SRC_S_WHITE}*${SRC_NS_PLAIN_CHAR_FLOW_IN})*`;
2948
+ var SRC_NS_PLAIN_ONE_LINE_FLOW_OUT = `${SRC_NS_PLAIN_FIRST_FLOW_OUT}#*${SRC_NB_NS_PLAIN_IN_LINE_FLOW_OUT}`;
2949
+ var SRC_NS_PLAIN_ONE_LINE_FLOW_IN = `${SRC_NS_PLAIN_FIRST_FLOW_IN}#*${SRC_NB_NS_PLAIN_IN_LINE_FLOW_IN}`;
2950
+ var SRC_NS_PLAIN_ONE_LINE_BLOCK_KEY = SRC_NS_PLAIN_ONE_LINE_FLOW_OUT;
2951
+ var SRC_NS_PLAIN_ONE_LINE_FLOW_KEY = SRC_NS_PLAIN_ONE_LINE_FLOW_IN;
2952
+ var SRC_S_NS_PLAIN_NEXT_LINE_FLOW_OUT = `\\n+${SRC_NS_PLAIN_CHAR_FLOW_OUT}${SRC_NB_NS_PLAIN_IN_LINE_FLOW_OUT}`;
2953
+ var SRC_S_NS_PLAIN_NEXT_LINE_FLOW_IN = `\\n+${SRC_NS_PLAIN_CHAR_FLOW_IN}${SRC_NB_NS_PLAIN_IN_LINE_FLOW_IN}`;
2954
+ var SRC_NS_PLAIN_MULTI_LINE_FLOW_OUT = `${SRC_NS_PLAIN_ONE_LINE_FLOW_OUT}(?:${SRC_S_NS_PLAIN_NEXT_LINE_FLOW_OUT})*`;
2955
+ var SRC_NS_PLAIN_MULTI_LINE_FLOW_IN = `${SRC_NS_PLAIN_ONE_LINE_FLOW_IN}(?:${SRC_S_NS_PLAIN_NEXT_LINE_FLOW_IN})*`;
2956
+ var NS_PLAIN_FLOW_OUT = new RegExp(`^(?:${SRC_NS_PLAIN_MULTI_LINE_FLOW_OUT})$`, "u");
2957
+ var NS_PLAIN_FLOW_IN = new RegExp(`^(?:${SRC_NS_PLAIN_MULTI_LINE_FLOW_IN})$`, "u");
2958
+ var NS_PLAIN_BLOCK_KEY = new RegExp(`^(?:${SRC_NS_PLAIN_ONE_LINE_BLOCK_KEY})$`, "u");
2959
+ var NS_PLAIN_FLOW_KEY = new RegExp(`^(?:${SRC_NS_PLAIN_ONE_LINE_FLOW_KEY})$`, "u");
2960
+ var NB_SINGLE_ONE_LINE = new RegExp(`^(?:${SRC_NB_JSON})*$`, "u");
2961
+ var NB_SINGLE_MULTI_LINE = new RegExp(`^(?:${SRC_NB_JSON}|\\n)*$`, "u");
2962
+ var BLOCK_SCALAR_CONTENT = new RegExp(`^(?:${SRC_NB_CHAR}|\\n)*$`, "u");
2963
+ var DEFAULT_PRESENTER_OPTIONS = {
2964
+ indent: 2,
2965
+ seqNoIndent: false,
2966
+ seqInlineFirst: true,
2967
+ lineWidth: 80,
2968
+ flowBracketPadding: false,
2969
+ flowSkipCommaSpace: false,
2970
+ flowSkipColonSpace: false,
2971
+ quoteFlowKeys: false,
2972
+ quoteStyle: "single",
2973
+ forceQuotes: false,
2974
+ scalarStyleRules: Object.keys(DEFAULT_SCALAR_STYLE_RULES).map((name) => Reflect.get(DEFAULT_SCALAR_STYLE_RULES, name)),
2975
+ tagBeforeAnchor: false
1063
2976
  };
1064
- var migrateThreeOneToThreeTwo = (document) => {
1065
- if (!isThreeOneDocument(document)) {
1066
- return document;
2977
+ var DEFAULT_DUMP_OPTIONS = {
2978
+ ...DEFAULT_PRESENTER_OPTIONS,
2979
+ schema: DUMP_SCHEMA,
2980
+ skipInvalid: false,
2981
+ noRefs: false,
2982
+ flowLevel: -1,
2983
+ sortKeys: false,
2984
+ transform: () => {
1067
2985
  }
1068
- const operationTags = migrateObjects(document);
1069
- migrateTagGroups(document, operationTags);
1070
- document.openapi = "3.2.0";
1071
- return document;
1072
2986
  };
2987
+ var EVENT_DOCUMENT = EVENT_ID.DOCUMENT;
2988
+ var EVENT_SEQUENCE = EVENT_ID.SEQUENCE;
2989
+ var EVENT_MAPPING = EVENT_ID.MAPPING;
2990
+ var EVENT_SCALAR = EVENT_ID.SCALAR;
2991
+ var EVENT_ALIAS = EVENT_ID.ALIAS;
2992
+ var EVENT_POP = EVENT_ID.POP;
2993
+ var SCALAR_STYLE_PLAIN = SCALAR_STYLE.PLAIN;
2994
+ var SCALAR_STYLE_SINGLE_QUOTED = SCALAR_STYLE.SINGLE_QUOTED;
2995
+ var SCALAR_STYLE_DOUBLE_QUOTED = SCALAR_STYLE.DOUBLE_QUOTED;
2996
+ var SCALAR_STYLE_LITERAL_BLOCK = SCALAR_STYLE.LITERAL_BLOCK;
2997
+ var SCALAR_STYLE_FOLDED_BLOCK = SCALAR_STYLE.FOLDED_BLOCK;
2998
+ var COLLECTION_STYLE_BLOCK = COLLECTION_STYLE.BLOCK;
2999
+ var COLLECTION_STYLE_FLOW = COLLECTION_STYLE.FLOW;
3000
+ var CHOMPING_CLIP = CHOMPING_MODE.CLIP;
3001
+ var CHOMPING_STRIP = CHOMPING_MODE.STRIP;
3002
+ var CHOMPING_KEEP = CHOMPING_MODE.KEEP;
3003
+
3004
+ // src/contracts/openapi-document.ts
3005
+ var Server = Schema_exports.Struct({ url: Schema_exports.String, variables: Schema_exports.optionalKey(JsonObject) });
3006
+ var Specification = Schema_exports.Struct({
3007
+ openapi: Schema_exports.String,
3008
+ servers: Schema_exports.optionalKey(Schema_exports.Array(Server)),
3009
+ paths: Schema_exports.Record(Schema_exports.String, JsonObject),
3010
+ components: Schema_exports.optionalKey(
3011
+ Schema_exports.Struct({
3012
+ schemas: Schema_exports.optionalKey(Schema_exports.Record(Schema_exports.String, JsonObject)),
3013
+ securitySchemes: Schema_exports.optionalKey(Schema_exports.Record(Schema_exports.String, JsonObject))
3014
+ })
3015
+ ),
3016
+ security: Schema_exports.optionalKey(
3017
+ Schema_exports.Array(Schema_exports.Record(Schema_exports.String, Schema_exports.Array(Schema_exports.String)))
3018
+ )
3019
+ });
3020
+ var Operation = Schema_exports.Struct({
3021
+ operationId: Schema_exports.optionalKey(Schema_exports.String),
3022
+ responses: Schema_exports.optionalKey(Schema_exports.Record(Schema_exports.String, JsonObject)),
3023
+ summary: Schema_exports.optionalKey(Schema_exports.String),
3024
+ description: Schema_exports.optionalKey(Schema_exports.String),
3025
+ parameters: Schema_exports.optionalKey(Schema_exports.Array(JsonObject)),
3026
+ requestBody: Schema_exports.optionalKey(JsonObject),
3027
+ security: Schema_exports.optionalKey(
3028
+ Schema_exports.Array(Schema_exports.Record(Schema_exports.String, Schema_exports.Array(Schema_exports.String)))
3029
+ ),
3030
+ servers: Schema_exports.optionalKey(Schema_exports.Array(Server))
3031
+ });
3032
+
3033
+ // ../../node_modules/.bun/@scalar+helpers@0.14.0/node_modules/@scalar/helpers/dist/object/is-object.js
3034
+ var isObjectLike = (value) => typeof value === "object" && value !== null;
1073
3035
 
1074
3036
  // ../../node_modules/.bun/@scalar+openapi-upgrader@0.3.1/node_modules/@scalar/openapi-upgrader/dist/helpers/traverse.js
1075
3037
  function traverse(content, transform, path = []) {
@@ -1834,181 +3796,208 @@ var isSchemaPath = (path) => {
1834
3796
  }
1835
3797
  if (USER_KEYED_MAPS.has(segment)) {
1836
3798
  userKeySegments = 1;
1837
- }
1838
- }
1839
- return false;
1840
- };
1841
-
1842
- // ../../node_modules/.bun/@scalar+openapi-upgrader@0.3.1/node_modules/@scalar/openapi-upgrader/dist/3.0-to-3.1/upgrade-from-three-to-three-one.js
1843
- var NAMED_SCHEMA_MAP_SEGMENTS = /* @__PURE__ */ new Set(["properties", "patternProperties", "$defs", "definitions"]);
1844
- function isNamedSchemaMap(path) {
1845
- const last = path?.[path.length - 1];
1846
- if (last === void 0) {
1847
- return false;
1848
- }
1849
- if (last === "schemas" && path?.[path.length - 2] === "components") {
1850
- return true;
1851
- }
1852
- return NAMED_SCHEMA_MAP_SEGMENTS.has(last);
1853
- }
1854
- var DATA_KEYWORDS = /* @__PURE__ */ new Set(["example", "default", "const", "enum"]);
1855
- function isInsideDataValue(path) {
1856
- if (!path) {
1857
- return false;
1858
- }
1859
- for (const [index, segment] of path.entries()) {
1860
- if (DATA_KEYWORDS.has(segment) && !isNamedSchemaMap(path.slice(0, index))) {
1861
- return true;
1862
- }
1863
- if (segment === "value" && path[index - 2] === "examples" && !isNamedSchemaMap(path.slice(0, index - 2))) {
1864
- return true;
1865
- }
1866
- }
1867
- return false;
1868
- }
1869
- function upgradeFromThreeToThreeOne(originalContent) {
1870
- let content = originalContent;
1871
- if (content === null || typeof content.openapi !== "string" || !content.openapi.startsWith("3.0")) {
1872
- return content;
1873
- }
1874
- content.openapi = "3.1.1";
1875
- content = traverse(content, applyChangesToDocument);
1876
- return content;
1877
- }
1878
- var applyChangesToDocument = (schema2, path) => {
1879
- if (isInsideDataValue(path)) {
1880
- return schema2;
3799
+ }
1881
3800
  }
3801
+ return false;
3802
+ };
3803
+
3804
+ // src/implementation/openapi-upgrade.ts
3805
+ var isNode = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3806
+ var namedSchemaMaps = /* @__PURE__ */ new Set(["properties", "patternProperties", "$defs", "definitions"]);
3807
+ var isNamedSchemaMap = (path, end) => {
3808
+ const last = end > 0 ? path[end - 1] : void 0;
3809
+ if (last === void 0) return false;
3810
+ if (last === "schemas" && path[end - 2] === "components") return true;
3811
+ return namedSchemaMaps.has(last);
3812
+ };
3813
+ var dataKeywords = /* @__PURE__ */ new Set(["example", "default", "const", "enum"]);
3814
+ var entersDataValue = (path) => {
3815
+ const index = path.length - 1;
3816
+ const segment = path[index];
3817
+ if (segment === void 0) return false;
3818
+ if (dataKeywords.has(segment) && !isNamedSchemaMap(path, index)) return true;
3819
+ return segment === "value" && path[index - 2] === "examples" && !isNamedSchemaMap(path, index - 2);
3820
+ };
3821
+ var isInsideExamplesMap = (path) => path.some(
3822
+ (segment, index) => segment === "examples" && index > 0 && !isNamedSchemaMap(path, index)
3823
+ );
3824
+ var replaceKeys = (node, set, drop) => {
3825
+ const result = {};
3826
+ for (const key of Object.keys(node))
3827
+ if (!drop.includes(key)) result[key] = Object.hasOwn(set, key) ? set[key] : node[key];
3828
+ for (const key of Object.keys(set)) if (!Object.hasOwn(result, key)) result[key] = set[key];
3829
+ return result;
3830
+ };
3831
+ var upgradeNode = (input, path) => {
3832
+ let schema2 = input;
1882
3833
  if (schema2.type !== void 0 && schema2.nullable === true) {
1883
- schema2.type = [schema2.type, "null"];
1884
- delete schema2.nullable;
3834
+ schema2 = replaceKeys(schema2, { type: [schema2.type, "null"] }, ["nullable"]);
1885
3835
  } else if (schema2.nullable === true && schema2.type === void 0) {
1886
3836
  if (typeof schema2.$ref === "string") {
1887
- const { nullable: _nullable, $ref, ...rest2 } = schema2;
1888
- return { ...rest2, anyOf: [{ $ref }, { type: "null" }] };
3837
+ const { nullable: _nullable, $ref, ...rest } = schema2;
3838
+ return { ...rest, anyOf: [{ $ref }, { type: "null" }] };
1889
3839
  }
1890
3840
  if (Array.isArray(schema2.allOf)) {
1891
- const { nullable: _nullable, allOf, ...rest2 } = schema2;
3841
+ const { nullable: _nullable, allOf, ...rest } = schema2;
1892
3842
  const base = allOf.length === 1 ? allOf[0] : { allOf };
1893
- return { ...rest2, anyOf: [base, { type: "null" }] };
1894
- }
1895
- }
1896
- if (schema2.exclusiveMinimum === true && schema2.minimum !== void 0) {
1897
- schema2.exclusiveMinimum = schema2.minimum;
1898
- delete schema2.minimum;
1899
- } else if (typeof schema2.exclusiveMinimum === "boolean") {
1900
- delete schema2.exclusiveMinimum;
1901
- }
1902
- if (schema2.exclusiveMaximum === true && schema2.maximum !== void 0) {
1903
- schema2.exclusiveMaximum = schema2.maximum;
1904
- delete schema2.maximum;
1905
- } else if (typeof schema2.exclusiveMaximum === "boolean") {
1906
- delete schema2.exclusiveMaximum;
1907
- }
1908
- const isInsideExamplesMap = path?.some((segment, index) => {
1909
- if (segment === "examples" && index > 0) {
1910
- return !isNamedSchemaMap(path.slice(0, index));
1911
- }
1912
- return false;
1913
- });
1914
- if (schema2.example !== void 0 && !isInsideExamplesMap && !isNamedSchemaMap(path)) {
1915
- if (isSchemaPath(path)) {
1916
- schema2.examples = [schema2.example];
1917
- } else {
1918
- schema2.examples = {
1919
- default: {
1920
- value: schema2.example
1921
- }
1922
- };
3843
+ return { ...rest, anyOf: [base, { type: "null" }] };
1923
3844
  }
1924
- delete schema2.example;
1925
3845
  }
1926
- const { format: _, ...rest } = schema2;
3846
+ if (schema2.exclusiveMinimum === true && schema2.minimum !== void 0)
3847
+ schema2 = replaceKeys(schema2, { exclusiveMinimum: schema2.minimum }, ["minimum"]);
3848
+ else if (typeof schema2.exclusiveMinimum === "boolean")
3849
+ schema2 = replaceKeys(schema2, {}, ["exclusiveMinimum"]);
3850
+ if (schema2.exclusiveMaximum === true && schema2.maximum !== void 0)
3851
+ schema2 = replaceKeys(schema2, { exclusiveMaximum: schema2.maximum }, ["maximum"]);
3852
+ else if (typeof schema2.exclusiveMaximum === "boolean")
3853
+ schema2 = replaceKeys(schema2, {}, ["exclusiveMaximum"]);
3854
+ if (schema2.example !== void 0 && !isInsideExamplesMap(path) && !isNamedSchemaMap(path, path.length))
3855
+ schema2 = replaceKeys(
3856
+ schema2,
3857
+ {
3858
+ examples: isSchemaPath(path) ? [schema2.example] : { default: { value: schema2.example } }
3859
+ },
3860
+ ["example"]
3861
+ );
1927
3862
  if (schema2.type === "string" || Array.isArray(schema2.type) && schema2.type.includes("string")) {
1928
3863
  if (schema2.format === "binary") {
1929
- const { type: _type, ...binarySchema } = rest;
1930
- const hasMediaType = path?.at(-1) === "schema" && path.at(-3) === "content";
3864
+ const { format: _format, type: _type, ...binarySchema } = schema2;
3865
+ const hasMediaType = path.at(-1) === "schema" && path.at(-3) === "content";
1931
3866
  return hasMediaType ? binarySchema : { contentMediaType: "application/octet-stream", ...binarySchema };
1932
3867
  }
1933
3868
  if (schema2.format === "base64" || schema2.format === "byte") {
1934
- return {
1935
- ...rest,
1936
- contentEncoding: "base64"
1937
- };
3869
+ const { format: _format, ...rest } = schema2;
3870
+ return { ...rest, contentEncoding: "base64" };
1938
3871
  }
1939
3872
  }
1940
- if (schema2["x-webhooks"] !== void 0 && (path === void 0 || path.length === 0)) {
1941
- schema2.webhooks = schema2["x-webhooks"];
1942
- delete schema2["x-webhooks"];
1943
- }
3873
+ if (schema2["x-webhooks"] !== void 0 && path.length === 0)
3874
+ schema2 = replaceKeys(schema2, { webhooks: schema2["x-webhooks"] }, ["x-webhooks"]);
1944
3875
  return schema2;
1945
3876
  };
1946
-
1947
- // ../../node_modules/.bun/@scalar+openapi-upgrader@0.3.1/node_modules/@scalar/openapi-upgrader/dist/upgrade.js
1948
- function upgrade(value, targetVersion, options) {
1949
- if (targetVersion === "3.2") {
1950
- const input = cloneDocument(value);
1951
- const openapi302 = upgradeFromTwoToThree(input);
1952
- const openapi31 = upgradeFromThreeToThreeOne(openapi302);
1953
- try {
1954
- const document = migrateThreeOneToThreeTwo(openapi31);
1955
- return options?.onIncompatible === "collect" ? { document, diagnostics: [] } : document;
1956
- } catch (error) {
1957
- if (options?.onIncompatible !== "collect" || !(error instanceof UpgradeIncompatibilityError)) {
1958
- throw error;
3877
+ var upgradeOpenApi30InPlace = (document) => {
3878
+ if (typeof document.openapi !== "string" || !document.openapi.startsWith("3.0")) return document;
3879
+ document.openapi = "3.1.1";
3880
+ const path = [];
3881
+ const visit = (node) => {
3882
+ for (const key of Object.keys(node)) {
3883
+ const value = node[key];
3884
+ path.push(key);
3885
+ if (entersDataValue(path)) {
3886
+ path.pop();
3887
+ continue;
1959
3888
  }
1960
- return {
1961
- document: upgrade(cloneDocument(value), "3.1"),
1962
- diagnostics: error.errors
1963
- };
3889
+ if (Array.isArray(value)) {
3890
+ for (let index = 0; index < value.length; index++) {
3891
+ const item = value[index];
3892
+ if (isNode(item)) {
3893
+ path.push(String(index));
3894
+ value[index] = visit(item);
3895
+ path.pop();
3896
+ }
3897
+ }
3898
+ } else if (isNode(value)) node[key] = visit(value);
3899
+ path.pop();
1964
3900
  }
1965
- }
1966
- const openapi30 = upgradeFromTwoToThree(value);
1967
- return targetVersion === "3.0" ? openapi30 : upgradeFromThreeToThreeOne(openapi30);
1968
- }
3901
+ return upgradeNode(node, path);
3902
+ };
3903
+ return visit(document);
3904
+ };
3905
+
3906
+ // src/implementation/runtime-yield.ts
3907
+ var yieldToRuntime = () => new Promise((resolve) => setTimeout(resolve, 0));
1969
3908
 
1970
3909
  // src/implementation/openapi-document.ts
1971
- var record = Schema_exports.decodeUnknownSync(JsonObject);
3910
+ var DocumentObject = Schema_exports.declare(
3911
+ (value) => typeof value === "object" && value !== null && !Array.isArray(value)
3912
+ );
3913
+ var documentObject = Schema_exports.decodeUnknownSync(DocumentObject);
3914
+ var record = documentObject;
1972
3915
  function fail(code, reason) {
1973
3916
  throw new OpenapiCompileError({ code, reason });
1974
3917
  }
3918
+ var isObject2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3919
+ var pathItemMaps = /* @__PURE__ */ new Set(["paths", "webhooks", "pathItems"]);
3920
+ var localPath = (ref) => {
3921
+ if (!ref.startsWith("#")) return void 0;
3922
+ const strict = JsonPointer_exports.parseUriFragment(ref);
3923
+ if (strict !== void 0) return strict;
3924
+ let pointer = ref.slice(1);
3925
+ try {
3926
+ pointer = decodeURIComponent(pointer);
3927
+ } catch {
3928
+ }
3929
+ if (pointer === "") return [];
3930
+ return pointer.startsWith("/") ? pointer.slice(1).split("/").map(JsonPointer_exports.unescapeToken) : void 0;
3931
+ };
3932
+ function dereference(scope) {
3933
+ const active = /* @__PURE__ */ new Set();
3934
+ const target = (ref) => {
3935
+ const path = localPath(ref);
3936
+ let node = scope;
3937
+ for (const part of path ?? []) {
3938
+ node = isObject2(node) ? Object.hasOwn(node, part) ? node[part] : void 0 : Array.isArray(node) ? node[Number(part)] : void 0;
3939
+ if (node === void 0) return;
3940
+ }
3941
+ return path !== void 0 && isObject2(node) ? node : void 0;
3942
+ };
3943
+ const fields = (object2) => {
3944
+ const result = {};
3945
+ for (const [key, value] of Object.entries(object2))
3946
+ result[key] = key === "schema" ? value : key === "example" || key.startsWith("x-") ? value : pathItemMaps.has(key) && isObject2(value) ? Object.fromEntries(
3947
+ Object.entries(value).map(([name, item]) => [name, visit(item, true)])
3948
+ ) : key === "responses" ? defaultFirst(visit(value, false)) : visit(value, false);
3949
+ return result;
3950
+ };
3951
+ const defaultFirst = (responses) => {
3952
+ if (!isObject2(responses) || !Object.hasOwn(responses, "default")) return responses;
3953
+ const { default: fallback, ...statuses } = responses;
3954
+ return { default: fallback ?? null, ...statuses };
3955
+ };
3956
+ const visit = (value, pathItem) => {
3957
+ if (Array.isArray(value)) return value.map((item) => visit(item, false));
3958
+ if (!isObject2(value)) return value;
3959
+ const ref = value.$ref;
3960
+ const found = typeof ref === "string" && !active.has(ref) ? target(ref) : void 0;
3961
+ if (typeof ref !== "string" || found === void 0) return fields(value);
3962
+ active.add(ref);
3963
+ const resolved2 = visit(found, pathItem);
3964
+ active.delete(ref);
3965
+ if (!isObject2(resolved2)) return resolved2;
3966
+ const { $ref: _, ...siblings } = value;
3967
+ if (pathItem) return { ...resolved2, ...fields(siblings) };
3968
+ return {
3969
+ ...resolved2,
3970
+ ...typeof siblings.summary === "string" ? { summary: siblings.summary } : {},
3971
+ ...typeof siblings.description === "string" ? { description: siblings.description } : {}
3972
+ };
3973
+ };
3974
+ return record(visit(scope, false));
3975
+ }
3976
+ var DocumentSpecification = Schema_exports.Struct({
3977
+ ...Specification.fields,
3978
+ paths: Schema_exports.Record(Schema_exports.String, DocumentObject),
3979
+ components: Schema_exports.optionalKey(
3980
+ Schema_exports.Struct({
3981
+ schemas: Schema_exports.optionalKey(Schema_exports.Record(Schema_exports.String, DocumentObject)),
3982
+ securitySchemes: Schema_exports.optionalKey(Schema_exports.Record(Schema_exports.String, DocumentObject))
3983
+ })
3984
+ )
3985
+ });
3986
+ function upgradeOwned(document) {
3987
+ return record(upgradeOpenApi30InPlace(record(upgradeFromTwoToThree(document))));
3988
+ }
1975
3989
  async function openApiDocument(input) {
1976
- const root = record(upgrade(structuredClone(record(input)), "3.1"));
1977
- const spec = Schema_exports.decodeUnknownSync(Specification)(root);
3990
+ const root = upgradeOwned(record(input));
3991
+ await yieldToRuntime();
3992
+ const spec = Schema_exports.decodeUnknownSync(DocumentSpecification)(root);
1978
3993
  if (!spec.openapi.startsWith("3.1."))
1979
3994
  fail("openapi_version", "This importer supports Swagger 2.0 and OpenAPI 3.0 and 3.1.");
1980
3995
  const components = spec.components?.schemas ?? {};
1981
3996
  const convert = JsonSchema_exports.fromSchemaOpenApi3_1;
1982
- const schemas = [];
1983
3997
  const componentsObject = root.components === void 0 ? {} : record(root.components);
1984
- const masked = JSON.parse(
1985
- JSON.stringify(
1986
- { ...root, components: { ...componentsObject, schemas: {} } },
1987
- (key, value) => {
1988
- if (key !== "schema") return value;
1989
- const index = schemas.push(Schema_exports.decodeUnknownSync(Schema_exports.Json)(value)) - 1;
1990
- return { "x-executor-schema": index };
1991
- }
1992
- )
1993
- );
1994
- const resolved2 = await (await loadSwaggerClient()).resolve({
1995
- spec: masked,
1996
- skipNormalization: true,
1997
- useCircularStructures: false,
1998
- // Spec import uses the host's guarded download. References must not acquire
1999
- // a second, unguarded network capability inside the resolver.
2000
- requestInterceptor: () => fail("external_reference", "External OpenAPI references are not supported yet.")
2001
- });
2002
- const restored = record(
2003
- JSON.parse(JSON.stringify(resolved2.spec), (key, value) => {
2004
- if (key !== "schema") return value;
2005
- const marker = record(value)["x-executor-schema"];
2006
- if (typeof marker !== "number" || schemas[marker] === void 0)
2007
- return fail("invalid_document", "The API resolver did not preserve a schema.");
2008
- return schemas[marker];
2009
- })
2010
- );
2011
- const parsed = Schema_exports.decodeUnknownSync(Specification)({
3998
+ const restored = dereference({ ...root, components: { ...componentsObject, schemas: {} } });
3999
+ await yieldToRuntime();
4000
+ const parsed = Schema_exports.decodeUnknownSync(DocumentSpecification)({
2012
4001
  ...restored,
2013
4002
  components: { ...record(restored.components), schemas: components }
2014
4003
  });
@@ -2171,7 +4160,7 @@ var planOperationNames = (inputs) => {
2171
4160
  function fail2(code, reason) {
2172
4161
  throw new OpenapiCompileError({ code, reason });
2173
4162
  }
2174
- var record2 = (value) => Schema_exports.decodeUnknownSync(JsonObject)(value);
4163
+ var record2 = (value) => documentObject(value);
2175
4164
  var OperationNaming = Schema_exports.Struct({
2176
4165
  operationId: Schema_exports.optionalKey(Schema_exports.String),
2177
4166
  tags: Schema_exports.optionalKey(Schema_exports.Array(Schema_exports.String))
@@ -2185,19 +4174,29 @@ function absolute(value) {
2185
4174
  fail2("server_url", "This API needs a configured server URL before import.");
2186
4175
  return url.href.replace(/\/$/, "");
2187
4176
  }
2188
- function serverAddress(swagger, server, connectUrl, documentServer) {
4177
+ function serverAddress(server, connectUrl, documentServer) {
2189
4178
  const variables = { ...documentServer?.variables, ...server.variables };
2190
- const request = record2(
2191
- swagger.buildRequest({
2192
- spec: {
2193
- openapi: "3.1.0",
2194
- servers: [{ url: server.url, variables }],
2195
- paths: { "/": { get: { operationId: "server" } } }
2196
- },
2197
- operationId: "server"
2198
- })
2199
- );
2200
- return absolute(new URL(Schema_exports.decodeUnknownSync(Schema_exports.String)(request.url), connectUrl).href);
4179
+ const template = test_default(server.url, { strict: true }) ? substitute_default(
4180
+ server.url,
4181
+ Object.fromEntries(
4182
+ Object.entries(variables).map(([name, variable]) => {
4183
+ const value = Option_exports.getOrUndefined(
4184
+ Schema_exports.decodeUnknownOption(JsonObject)(variable)
4185
+ )?.default;
4186
+ return [name, value === void 0 || value === null ? "" : String(value)];
4187
+ })
4188
+ ),
4189
+ { encoder: (value) => value }
4190
+ ) : server.url;
4191
+ let url;
4192
+ try {
4193
+ url = new URL(template);
4194
+ } catch {
4195
+ url = void 0;
4196
+ }
4197
+ const relative = new URL(template, "https://relative.invalid");
4198
+ const base = url?.protocol && url.host ? `${url.protocol.replace(/\W/g, "")}://${url.host}${url.pathname}` : url?.pathname ?? (template.startsWith("/") ? relative.pathname : relative.pathname.slice(1));
4199
+ return absolute(new URL(`${base.endsWith("/") ? base.slice(0, -1) : base}/`, connectUrl).href);
2201
4200
  }
2202
4201
  var binaryInput = {
2203
4202
  type: "string",
@@ -2304,366 +4303,458 @@ function errorResponses(document, operation) {
2304
4303
  }
2305
4304
  return errors;
2306
4305
  }
2307
- var compileOpenApiDocument = (entry, inputDocument, options = {}) => Effect_exports.tryPromise({
2308
- try: async () => {
2309
- const document = await openApiDocument(inputDocument);
2310
- const swagger = await loadSwaggerClient();
2311
- const { spec } = document;
2312
- const schemes = { ...options.securitySchemes ?? spec.components?.securitySchemes };
2313
- const bindings = /* @__PURE__ */ new Map();
2314
- const oauth = [];
2315
- for (const [name, source] of Object.entries(schemes)) {
2316
- const scheme = document.resolve(source);
2317
- if (scheme.type === "http" && scheme.scheme === "bearer" || scheme.type === "apiKey" && (scheme.in === "header" || scheme.in === "query" || scheme.in === "cookie") && typeof scheme.name === "string") {
2318
- bindings.set(name, [
4306
+ var compileOpenApiDocument = (entry, inputDocument, options = {}) => {
4307
+ let owned = inputDocument;
4308
+ const take = () => {
4309
+ const input = owned;
4310
+ owned = void 0;
4311
+ if (input === void 0) fail2("invalid_document", "This API definition was already compiled.");
4312
+ return input;
4313
+ };
4314
+ return Effect_exports.tryPromise({
4315
+ try: async () => {
4316
+ const document = await openApiDocument(take());
4317
+ const { spec } = document;
4318
+ const schemes = { ...options.securitySchemes ?? spec.components?.securitySchemes };
4319
+ const bindings = /* @__PURE__ */ new Map();
4320
+ const oauth = [];
4321
+ for (const [name, source] of Object.entries(schemes)) {
4322
+ const scheme = document.resolve(source);
4323
+ if (scheme.type === "http" && scheme.scheme === "bearer" || scheme.type === "apiKey" && (scheme.in === "header" || scheme.in === "query" || scheme.in === "cookie") && typeof scheme.name === "string") {
4324
+ bindings.set(name, [
4325
+ {
4326
+ scheme: name,
4327
+ field: "token",
4328
+ part: "value",
4329
+ prefix: ""
4330
+ }
4331
+ ]);
4332
+ } else if (scheme.type === "http" && scheme.scheme === "basic") {
4333
+ bindings.set(name, [
4334
+ { scheme: name, field: "username", part: "username", prefix: "" },
4335
+ { scheme: name, field: "password", part: "password", prefix: "" }
4336
+ ]);
4337
+ } else if (scheme.type === "oauth2") {
4338
+ const code = record2(scheme.flows).authorizationCode;
4339
+ if (code !== void 0) {
4340
+ const flow = record2(code);
4341
+ if (typeof flow.authorizationUrl === "string" && typeof flow.tokenUrl === "string")
4342
+ oauth.push({
4343
+ name,
4344
+ config: entry.oauthDiscoveryUrl === void 0 ? {
4345
+ authorizationUrl: absolute(
4346
+ new URL(flow.authorizationUrl, entry.connectUrl).href
4347
+ ),
4348
+ tokenUrl: absolute(new URL(flow.tokenUrl, entry.connectUrl).href),
4349
+ scopes: [
4350
+ ...entry.scopes ?? Object.keys(record2(flow.scopes ?? {}))
4351
+ ].sort()
4352
+ } : { discover: absolute(entry.oauthDiscoveryUrl) }
4353
+ });
4354
+ }
4355
+ }
4356
+ }
4357
+ let fallback = options.fallbackSecurity;
4358
+ if (bindings.size === 0 && Object.keys(schemes).length === 0 && entry.auth?.header !== void 0) {
4359
+ const header = /^([!#$%&'*+.^_`|~A-Za-z0-9-]+):\s*([^{}\r\n]*)\{[A-Za-z0-9_]+\}$/.exec(
4360
+ entry.auth.header
4361
+ );
4362
+ if (!header?.[1] || header[2] === void 0)
4363
+ fail2("auth_helper", "This catalog entry needs a custom authentication helper.");
4364
+ bindings.set("apiKey", [
2319
4365
  {
2320
- scheme: name,
4366
+ scheme: "apiKey",
2321
4367
  field: "token",
2322
4368
  part: "value",
2323
- prefix: ""
4369
+ prefix: header[2]
2324
4370
  }
2325
4371
  ]);
2326
- } else if (scheme.type === "http" && scheme.scheme === "basic") {
2327
- bindings.set(name, [
2328
- { scheme: name, field: "username", part: "username", prefix: "" },
2329
- { scheme: name, field: "password", part: "password", prefix: "" }
2330
- ]);
2331
- } else if (scheme.type === "oauth2") {
2332
- const code = record2(scheme.flows).authorizationCode;
2333
- if (code !== void 0) {
2334
- const flow = record2(code);
2335
- if (typeof flow.authorizationUrl === "string" && typeof flow.tokenUrl === "string")
2336
- oauth.push({
2337
- name,
2338
- config: entry.oauthDiscoveryUrl === void 0 ? {
2339
- authorizationUrl: absolute(
2340
- new URL(flow.authorizationUrl, entry.connectUrl).href
2341
- ),
2342
- tokenUrl: absolute(new URL(flow.tokenUrl, entry.connectUrl).href),
2343
- scopes: [
2344
- ...entry.scopes ?? Object.keys(record2(flow.scopes ?? {}))
2345
- ].sort()
2346
- } : { discover: absolute(entry.oauthDiscoveryUrl) }
2347
- });
2348
- }
4372
+ schemes.apiKey = { type: "apiKey", in: "header", name: header[1] };
4373
+ fallback = [{ apiKey: [] }];
2349
4374
  }
2350
- }
2351
- let fallback = options.fallbackSecurity;
2352
- if (bindings.size === 0 && Object.keys(schemes).length === 0 && entry.auth?.header !== void 0) {
2353
- const header = /^([!#$%&'*+.^_`|~A-Za-z0-9-]+):\s*([^{}\r\n]*)\{[A-Za-z0-9_]+\}$/.exec(
2354
- entry.auth.header
2355
- );
2356
- if (!header?.[1] || header[2] === void 0)
2357
- fail2("auth_helper", "This catalog entry needs a custom authentication helper.");
2358
- bindings.set("apiKey", [
2359
- {
2360
- scheme: "apiKey",
2361
- field: "token",
2362
- part: "value",
2363
- prefix: header[2]
4375
+ if (!fallback && !Object.keys(schemes).length && entry.auth && !["none", "public"].includes(entry.auth.kind))
4376
+ fail2(
4377
+ "auth_missing",
4378
+ "This entry does not declare enough authentication details to generate an app."
4379
+ );
4380
+ const methods = /* @__PURE__ */ new Map();
4381
+ const operations = [];
4382
+ const skipped = /* @__PURE__ */ new Set();
4383
+ const causes = /* @__PURE__ */ new Map();
4384
+ const built = [];
4385
+ const documentServer = spec.servers?.[0];
4386
+ const addresses = /* @__PURE__ */ new Map();
4387
+ const addressOf = (server) => {
4388
+ const key = JSON.stringify([server, documentServer?.variables ?? null]);
4389
+ let known = addresses.get(key);
4390
+ if (known === void 0) {
4391
+ try {
4392
+ known = { address: serverAddress(server, entry.connectUrl, documentServer) };
4393
+ } catch (error) {
4394
+ known = { error };
4395
+ }
4396
+ addresses.set(key, known);
2364
4397
  }
2365
- ]);
2366
- schemes.apiKey = { type: "apiKey", in: "header", name: header[1] };
2367
- fallback = [{ apiKey: [] }];
2368
- }
2369
- if (!fallback && !Object.keys(schemes).length && entry.auth && !["none", "public"].includes(entry.auth.kind))
2370
- fail2(
2371
- "auth_missing",
2372
- "This entry does not declare enough authentication details to generate an app."
4398
+ if ("error" in known) throw known.error;
4399
+ return known.address;
4400
+ };
4401
+ const candidates = Object.entries(spec.paths).flatMap(([path, source]) => {
4402
+ const item = document.resolve(source);
4403
+ return ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"].filter((method) => item[method.toLowerCase()] !== void 0).map((method) => ({ path, item, method }));
4404
+ });
4405
+ if (!candidates.length) fail2("no_operations", "This API does not contain any operations.");
4406
+ const names = planOperationNames(
4407
+ candidates.map(({ path, item, method }) => {
4408
+ const naming = Schema_exports.decodeUnknownOption(OperationNaming)(
4409
+ resolvedOrUndefined(document, item[method.toLowerCase()])
4410
+ ).pipe(Option_exports.getOrUndefined);
4411
+ return {
4412
+ operationId: naming?.operationId,
4413
+ tag: naming?.tags?.find((tag) => tag.trim() !== ""),
4414
+ method,
4415
+ path
4416
+ };
4417
+ })
2373
4418
  );
2374
- const methods = /* @__PURE__ */ new Map();
2375
- const operations = [];
2376
- const skipped = /* @__PURE__ */ new Set();
2377
- const causes = /* @__PURE__ */ new Map();
2378
- const built = [];
2379
- const documentServer = spec.servers?.[0];
2380
- const candidates = Object.entries(spec.paths).flatMap(([path, source]) => {
2381
- const item = document.resolve(source);
2382
- return ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"].filter((method) => item[method.toLowerCase()] !== void 0).map((method) => ({ path, item, method }));
2383
- });
2384
- if (!candidates.length) fail2("no_operations", "This API does not contain any operations.");
2385
- const names = planOperationNames(
2386
- candidates.map(({ path, item, method }) => {
2387
- const naming = Schema_exports.decodeUnknownOption(OperationNaming)(
2388
- resolvedOrUndefined(document, item[method.toLowerCase()])
2389
- ).pipe(Option_exports.getOrUndefined);
2390
- return {
2391
- operationId: naming?.operationId,
2392
- tag: naming?.tags?.find((tag) => tag.trim() !== ""),
2393
- method,
2394
- path
2395
- };
2396
- })
2397
- );
2398
- for (const [index, { path, item, method }] of candidates.entries()) {
2399
- try {
2400
- if (!path.startsWith("/") || path.includes("?") || path.includes("#"))
2401
- fail2("operation_path", "An operation has an invalid API path.");
2402
- const operationMethods = [];
2403
- const resolved2 = document.resolve(record2(item[method.toLowerCase()]));
2404
- const operation = Schema_exports.decodeUnknownSync(Operation)(resolved2);
2405
- const tags = Option_exports.getOrUndefined(
2406
- Schema_exports.decodeUnknownOption(Schema_exports.Array(Schema_exports.NonEmptyString))(resolved2.tags)
2407
- );
2408
- const name = names[index] ?? fail2("operation_path", "An operation has no name.");
2409
- if (built.some((op) => op.operation.name === name))
2410
- fail2(
2411
- "duplicate_operation",
2412
- "The API has duplicate tool names. Update its operation IDs first."
4419
+ for (const [index, { path, item, method }] of candidates.entries()) {
4420
+ if (index % 100 === 99) await yieldToRuntime();
4421
+ try {
4422
+ if (!path.startsWith("/") || path.includes("?") || path.includes("#"))
4423
+ fail2("operation_path", "An operation has an invalid API path.");
4424
+ const operationMethods = [];
4425
+ const resolved2 = document.resolve(record2(item[method.toLowerCase()]));
4426
+ const operation = Schema_exports.decodeUnknownSync(Operation)(resolved2);
4427
+ const tags = Option_exports.getOrUndefined(
4428
+ Schema_exports.decodeUnknownOption(Schema_exports.Array(Schema_exports.NonEmptyString))(resolved2.tags)
2413
4429
  );
2414
- const serverList = operation.servers ?? (Array.isArray(item.servers) ? Schema_exports.decodeUnknownSync(Specification.fields.servers)(item.servers) : void 0) ?? spec.servers;
2415
- const server = serverList?.[0];
2416
- const serverUrl = options.baseUrl ?? server?.url;
2417
- if (serverUrl === void 0)
2418
- fail2("server_missing", "The API has no server URL. Set an API base URL and try again.");
2419
- const baseUrl = serverAddress(
2420
- swagger,
2421
- options.baseUrl === void 0 && server !== void 0 ? server : { url: serverUrl },
2422
- entry.connectUrl,
2423
- documentServer
2424
- );
2425
- const combined = [
2426
- ...Array.isArray(item.parameters) ? item.parameters : [],
2427
- ...operation.parameters ?? []
2428
- ];
2429
- const parameters = /* @__PURE__ */ new Map();
2430
- for (const parameter of combined) {
2431
- const p = Schema_exports.decodeUnknownSync(OpenapiParameter)(document.resolve(record2(parameter)));
2432
- parameters.set(`${p.in}:${p.name}`, p);
2433
- }
2434
- const groups = /* @__PURE__ */ new Map();
2435
- for (const p of parameters.values()) {
2436
- const key = p.in === "header" ? "headers" : p.in;
2437
- const group = groups.get(key) ?? { properties: {}, required: [] };
2438
- const content = p.content === void 0 ? void 0 : Object.values(p.content)[0];
2439
- group.properties[p.name] = p.schema ?? (content === void 0 ? {} : record2(content).schema ?? {});
2440
- if (p.required || p.in === "path") group.required.push(p.name);
2441
- groups.set(key, group);
2442
- }
2443
- const properties = {};
2444
- const required = [];
2445
- for (const [key, group] of groups) {
2446
- properties[key] = (api) => ({
2447
- type: "object",
2448
- properties: Object.fromEntries(
2449
- Object.entries(group.properties).map(([name2, schema2]) => [name2, api(schema2)])
2450
- ),
2451
- required: group.required,
2452
- additionalProperties: false
2453
- });
2454
- if (group.required.length) required.push(key);
2455
- }
2456
- const bodyVariants = [];
2457
- let retainedBody;
2458
- if (operation.requestBody) {
2459
- const request = Schema_exports.decodeUnknownSync(OpenapiRequestBody)(
2460
- document.resolve(operation.requestBody)
4430
+ const name = names[index] ?? fail2("operation_path", "An operation has no name.");
4431
+ if (built.some((op) => op.operation.name === name))
4432
+ fail2(
4433
+ "duplicate_operation",
4434
+ "The API has duplicate tool names. Update its operation IDs first."
4435
+ );
4436
+ const serverList = operation.servers ?? (Array.isArray(item.servers) ? Schema_exports.decodeUnknownSync(Specification.fields.servers)(item.servers) : void 0) ?? spec.servers;
4437
+ const server = serverList?.[0];
4438
+ const serverUrl = options.baseUrl ?? server?.url;
4439
+ if (serverUrl === void 0)
4440
+ fail2("server_missing", "The API has no server URL. Set an API base URL and try again.");
4441
+ const baseUrl = addressOf(
4442
+ options.baseUrl === void 0 && server !== void 0 ? server : { url: serverUrl }
2461
4443
  );
2462
- const retainedContent = {};
2463
- for (const [contentType, content] of Object.entries(request.content)) {
2464
- const kind = openapiMediaKind(contentType);
2465
- const schema2 = document.resolve(content.schema ?? {});
2466
- const declared = content.schema ?? {};
2467
- const retainedFiles = {};
2468
- let inputSchema = kind === "binary" ? () => binaryInput : kind === "text" ? () => ({ type: "string" }) : (api) => api(declared);
2469
- if (kind === "multipart") {
2470
- const fields = { ...record2(schema2.properties ?? {}) };
2471
- const files = {};
2472
- for (const [key, field] of Object.entries(fields)) {
2473
- const shape = document.resolve(record2(field));
2474
- if (isOpenapiFileSchema(shape)) {
2475
- delete fields[key];
2476
- files[key] = binaryInput;
2477
- retainedFiles[key] = shape;
4444
+ const combined = [
4445
+ ...Array.isArray(item.parameters) ? item.parameters : [],
4446
+ ...operation.parameters ?? []
4447
+ ];
4448
+ const parameters = /* @__PURE__ */ new Map();
4449
+ for (const parameter of combined) {
4450
+ const p = Schema_exports.decodeUnknownSync(OpenapiParameter)(document.resolve(record2(parameter)));
4451
+ parameters.set(`${p.in}:${p.name}`, p);
4452
+ }
4453
+ const groups = /* @__PURE__ */ new Map();
4454
+ for (const p of parameters.values()) {
4455
+ const key = p.in === "header" ? "headers" : p.in;
4456
+ const group = groups.get(key) ?? { properties: {}, required: [] };
4457
+ const content = p.content === void 0 ? void 0 : Object.values(p.content)[0];
4458
+ group.properties[p.name] = p.schema ?? (content === void 0 ? {} : record2(content).schema ?? {});
4459
+ if (p.required || p.in === "path") group.required.push(p.name);
4460
+ groups.set(key, group);
4461
+ }
4462
+ const properties = {};
4463
+ const required = [];
4464
+ for (const [key, group] of groups) {
4465
+ properties[key] = (api) => ({
4466
+ type: "object",
4467
+ properties: Object.fromEntries(
4468
+ Object.entries(group.properties).map(([name2, schema2]) => [name2, api(schema2)])
4469
+ ),
4470
+ required: group.required,
4471
+ additionalProperties: false
4472
+ });
4473
+ if (group.required.length) required.push(key);
4474
+ }
4475
+ const bodyVariants = [];
4476
+ let retainedBody;
4477
+ if (operation.requestBody) {
4478
+ const request = Schema_exports.decodeUnknownSync(OpenapiRequestBody)(
4479
+ document.resolve(operation.requestBody)
4480
+ );
4481
+ const retainedContent = {};
4482
+ for (const [contentType, content] of Object.entries(request.content)) {
4483
+ const kind = openapiMediaKind(contentType);
4484
+ const schema2 = document.resolve(content.schema ?? {});
4485
+ const declared = content.schema ?? {};
4486
+ const retainedFiles = {};
4487
+ let inputSchema = kind === "binary" ? () => binaryInput : kind === "text" ? () => ({ type: "string" }) : (api) => api(declared);
4488
+ if (kind === "multipart") {
4489
+ const fields = { ...record2(schema2.properties ?? {}) };
4490
+ const files = {};
4491
+ for (const [key, field] of Object.entries(fields)) {
4492
+ const shape = document.resolve(record2(field));
4493
+ if (isOpenapiFileSchema(shape)) {
4494
+ delete fields[key];
4495
+ files[key] = binaryInput;
4496
+ retainedFiles[key] = shape;
4497
+ }
2478
4498
  }
2479
- }
2480
- const form = schema2;
2481
- inputSchema = (api) => {
2482
- const converted = api({ ...form, properties: fields });
2483
- return {
2484
- ...converted,
2485
- properties: { ...record2(converted.properties ?? {}), ...files }
4499
+ const form = schema2;
4500
+ inputSchema = (api) => {
4501
+ const converted = api({ ...form, properties: fields });
4502
+ return {
4503
+ ...converted,
4504
+ properties: { ...record2(converted.properties ?? {}), ...files }
4505
+ };
2486
4506
  };
4507
+ }
4508
+ retainedContent[contentType] = {
4509
+ ...content.encoding === void 0 ? {} : { encoding: content.encoding },
4510
+ ...Object.keys(retainedFiles).length ? { schema: { type: "object", properties: retainedFiles } } : {}
2487
4511
  };
4512
+ const first = bodyVariants.length === 0;
4513
+ bodyVariants.push((api) => ({
4514
+ properties: { contentType: { enum: [contentType] }, body: inputSchema(api) },
4515
+ ...first ? {} : { required: ["contentType"] }
4516
+ }));
2488
4517
  }
2489
- retainedContent[contentType] = {
2490
- ...content.encoding === void 0 ? {} : { encoding: content.encoding },
2491
- ...Object.keys(retainedFiles).length ? { schema: { type: "object", properties: retainedFiles } } : {}
2492
- };
2493
- const first = bodyVariants.length === 0;
2494
- bodyVariants.push((api) => ({
2495
- properties: { contentType: { enum: [contentType] }, body: inputSchema(api) },
2496
- ...first ? {} : { required: ["contentType"] }
2497
- }));
4518
+ retainedBody = { ...request, content: retainedContent };
4519
+ if (!bodyVariants.length)
4520
+ fail2("request_body", `Tool ${name} has no request media types.`);
4521
+ properties.body = () => ({});
4522
+ properties.contentType = () => ({
4523
+ type: "string",
4524
+ enum: Object.keys(request.content),
4525
+ description: "Request media type. Defaults to the first declared type."
4526
+ });
4527
+ if (request.required) required.push("body");
4528
+ }
4529
+ const security = operation.security ?? spec.security ?? fallback ?? [];
4530
+ for (const requirement of security) {
4531
+ const keys = Object.keys(requirement).sort();
4532
+ if (!keys.length) continue;
4533
+ if (!keys.every((key) => bindings.has(key))) continue;
4534
+ const parts = keys.flatMap((key) => bindings.get(key) ?? []);
4535
+ const methodName = bindings.size === 1 && keys.length === 1 ? "apiKey" : keys.join("_and_");
4536
+ operationMethods.push({
4537
+ name: methodName,
4538
+ label: parts.length === 1 ? "API key" : keys.join(" + "),
4539
+ bindings: parts.map((part) => ({
4540
+ ...part,
4541
+ field: keys.length === 1 ? part.field : `${identifier(part.scheme)}_${part.field}`
4542
+ }))
4543
+ });
4544
+ }
4545
+ const input = document.schema((api) => ({
4546
+ type: "object",
4547
+ properties: Object.fromEntries(
4548
+ Object.entries(properties).map(([key, shape]) => [key, shape(api)])
4549
+ ),
4550
+ required,
4551
+ ...bodyVariants.length ? { anyOf: bodyVariants.map((variant) => variant(api)) } : {},
4552
+ additionalProperties: false
4553
+ }));
4554
+ try {
4555
+ jsonSchema(input);
4556
+ } catch {
4557
+ fail2(
4558
+ "input_schema",
4559
+ `Tool ${name} has an input schema this importer cannot preserve yet.`
4560
+ );
2498
4561
  }
2499
- retainedBody = { ...request, content: retainedContent };
2500
- if (!bodyVariants.length)
2501
- fail2("request_body", `Tool ${name} has no request media types.`);
2502
- properties.body = () => ({});
2503
- properties.contentType = () => ({
2504
- type: "string",
2505
- enum: Object.keys(request.content),
2506
- description: "Request media type. Defaults to the first declared type."
4562
+ const outputSchema = responseSchema(document, operation, method);
4563
+ const streaming = Object.values(operation.responses ?? {}).some((response) => {
4564
+ const content = errorContent(document, response);
4565
+ return content !== void 0 && Object.hasOwn(record2(content), "text/event-stream");
2507
4566
  });
2508
- if (request.required) required.push("body");
2509
- }
2510
- const security = operation.security ?? spec.security ?? fallback ?? [];
2511
- for (const requirement of security) {
2512
- const keys = Object.keys(requirement).sort();
2513
- if (!keys.length) continue;
2514
- if (!keys.every((key) => bindings.has(key))) continue;
2515
- const parts = keys.flatMap((key) => bindings.get(key) ?? []);
2516
- const methodName = bindings.size === 1 && keys.length === 1 ? "apiKey" : keys.join("_and_");
2517
- operationMethods.push({
2518
- name: methodName,
2519
- label: parts.length === 1 ? "API key" : keys.join(" + "),
2520
- bindings: parts.map((part) => ({
2521
- ...part,
2522
- field: keys.length === 1 ? part.field : `${identifier(part.scheme)}_${part.field}`
2523
- }))
4567
+ built.push({
4568
+ methods: operationMethods,
4569
+ operation: {
4570
+ ...streaming ? { streaming: true } : {},
4571
+ ...tags === void 0 || tags.length === 0 ? {} : { tags },
4572
+ name,
4573
+ ...operation.operationId === void 0 ? {} : { operationId: operation.operationId },
4574
+ description: operation.summary ?? operation.description ?? name,
4575
+ method,
4576
+ path,
4577
+ baseUrl,
4578
+ openapi: spec.openapi,
4579
+ securitySchemes: Object.fromEntries(
4580
+ [...new Set(security.flatMap(Object.keys))].map((key) => [
4581
+ key,
4582
+ schemes[key] ?? fail2("auth_method", "A security requirement names a missing scheme.")
4583
+ ])
4584
+ ),
4585
+ request: {
4586
+ parameters: [...parameters.values()],
4587
+ ...retainedBody === void 0 ? {} : { requestBody: retainedBody },
4588
+ security,
4589
+ responses: Object.fromEntries(
4590
+ Object.entries(operation.responses ?? {}).flatMap(([status, response]) => {
4591
+ const content = errorContent(document, response);
4592
+ return content === void 0 ? [] : [
4593
+ [
4594
+ status,
4595
+ {
4596
+ content: Object.fromEntries(
4597
+ Object.keys(record2(content)).map((type) => [type, {}])
4598
+ )
4599
+ }
4600
+ ]
4601
+ ];
4602
+ })
4603
+ )
4604
+ },
4605
+ input,
4606
+ ...outputSchema === void 0 ? {} : { outputSchema },
4607
+ errorResponses: errorResponses(document, operation)
4608
+ }
2524
4609
  });
4610
+ } catch (error) {
4611
+ if (!(error instanceof OpenapiCompileError) && !Schema_exports.isSchemaError(error)) throw error;
4612
+ const code = error instanceof OpenapiCompileError ? error.code : "invalid_document";
4613
+ if (error instanceof OpenapiCompileError && !causes.has(code)) causes.set(code, error);
4614
+ skipped.add(code);
2525
4615
  }
2526
- const input = document.schema((api) => ({
2527
- type: "object",
2528
- properties: Object.fromEntries(
2529
- Object.entries(properties).map(([key, shape]) => [key, shape(api)])
2530
- ),
2531
- required,
2532
- ...bodyVariants.length ? { anyOf: bodyVariants.map((variant) => variant(api)) } : {},
2533
- additionalProperties: false
2534
- }));
2535
- try {
2536
- jsonSchema(input);
2537
- } catch {
2538
- fail2(
2539
- "input_schema",
2540
- `Tool ${name} has an input schema this importer cannot preserve yet.`
2541
- );
2542
- }
2543
- const outputSchema = responseSchema(document, operation, method);
2544
- const streaming = Object.values(operation.responses ?? {}).some((response) => {
2545
- const content = errorContent(document, response);
2546
- return content !== void 0 && Object.hasOwn(record2(content), "text/event-stream");
2547
- });
2548
- built.push({
2549
- methods: operationMethods,
2550
- operation: {
2551
- ...streaming ? { streaming: true } : {},
2552
- ...tags === void 0 || tags.length === 0 ? {} : { tags },
2553
- name,
2554
- ...operation.operationId === void 0 ? {} : { operationId: operation.operationId },
2555
- description: operation.summary ?? operation.description ?? name,
2556
- method,
2557
- path,
2558
- baseUrl,
2559
- openapi: spec.openapi,
2560
- securitySchemes: Object.fromEntries(
2561
- [...new Set(security.flatMap(Object.keys))].map((key) => [
2562
- key,
2563
- schemes[key] ?? fail2("auth_method", "A security requirement names a missing scheme.")
2564
- ])
2565
- ),
2566
- request: {
2567
- parameters: [...parameters.values()],
2568
- ...retainedBody === void 0 ? {} : { requestBody: retainedBody },
2569
- security,
2570
- responses: Object.fromEntries(
2571
- Object.entries(operation.responses ?? {}).flatMap(([status, response]) => {
2572
- const content = errorContent(document, response);
2573
- return content === void 0 ? [] : [
2574
- [
2575
- status,
2576
- {
2577
- content: Object.fromEntries(
2578
- Object.keys(record2(content)).map((type) => [type, {}])
2579
- )
2580
- }
2581
- ]
2582
- ];
2583
- })
2584
- )
2585
- },
2586
- input,
2587
- ...outputSchema === void 0 ? {} : { outputSchema },
2588
- errorResponses: errorResponses(document, operation)
2589
- }
2590
- });
4616
+ }
4617
+ const counts = /* @__PURE__ */ new Map();
4618
+ for (const { operation } of built) {
4619
+ const origin = new URL(operation.baseUrl).origin;
4620
+ counts.set(origin, (counts.get(origin) ?? 0) + 1);
4621
+ }
4622
+ let documentOrigin;
4623
+ try {
4624
+ if (documentServer !== void 0)
4625
+ documentOrigin = new URL(serverAddress(documentServer, entry.connectUrl)).origin;
2591
4626
  } catch (error) {
2592
- if (!(error instanceof OpenapiCompileError) && !Schema_exports.isSchemaError(error)) throw error;
2593
- const code = error instanceof OpenapiCompileError ? error.code : "invalid_document";
2594
- if (error instanceof OpenapiCompileError && !causes.has(code)) causes.set(code, error);
2595
- skipped.add(code);
4627
+ if (!(error instanceof OpenapiCompileError)) throw error;
2596
4628
  }
2597
- }
2598
- const counts = /* @__PURE__ */ new Map();
2599
- for (const { operation } of built) {
2600
- const origin = new URL(operation.baseUrl).origin;
2601
- counts.set(origin, (counts.get(origin) ?? 0) + 1);
2602
- }
2603
- let documentOrigin;
2604
- try {
2605
- if (documentServer !== void 0)
2606
- documentOrigin = new URL(serverAddress(swagger, documentServer, entry.connectUrl)).origin;
2607
- } catch (error) {
2608
- if (!(error instanceof OpenapiCompileError)) throw error;
2609
- }
2610
- let pinnedOrigin = options.allowedOrigin;
2611
- for (const [origin, count] of options.allowedOrigin === void 0 ? counts : []) {
2612
- const best = pinnedOrigin === void 0 ? 0 : counts.get(pinnedOrigin) ?? 0;
2613
- if (count > best || count === best && origin === documentOrigin) pinnedOrigin = origin;
2614
- }
2615
- for (const { operation, methods: operationMethods } of built) {
2616
- if (new URL(operation.baseUrl).origin !== pinnedOrigin) {
2617
- skipped.add("multiple_hosts");
2618
- continue;
4629
+ let pinnedOrigin = options.allowedOrigin;
4630
+ for (const [origin, count] of options.allowedOrigin === void 0 ? counts : []) {
4631
+ const best = pinnedOrigin === void 0 ? 0 : counts.get(pinnedOrigin) ?? 0;
4632
+ if (count > best || count === best && origin === documentOrigin) pinnedOrigin = origin;
2619
4633
  }
2620
- operations.push(operation);
2621
- for (const method of operationMethods) methods.set(method.name, method);
2622
- }
2623
- if (!operations.length) {
2624
- const [only, ...others] = causes.values();
2625
- if (only !== void 0 && others.length === 0 && [...skipped].every((reason) => reason === only.code))
2626
- throw only;
2627
- fail2(
2628
- "no_supported_operations",
2629
- "Executor cannot import any operation in this API definition."
2630
- );
2631
- }
2632
- if (!operations.some(
2633
- (operation) => operation.streaming !== true && (operation.request.security.length === 0 || operation.request.security.some((requirement) => {
2634
- const keys = Object.keys(requirement);
2635
- return keys.every((key) => bindings.has(key)) || keys.length === 1 && oauth.some((method) => method.name === keys[0]);
2636
- }))
2637
- ))
2638
- fail2(
2639
- "no_supported_operations",
2640
- "This API has no operations supported by the available authentication and response transports."
2641
- );
2642
- return {
2643
- operations,
2644
- definitions: Object.fromEntries(document.definitions),
2645
- methods: Object.fromEntries(
2646
- [...methods.values()].map((method) => [method.name, method.bindings])
2647
- ),
2648
- secrets: [...methods.values()],
2649
- oauth,
2650
- schemes,
2651
- pinnedOrigin,
2652
- fallback
2653
- };
2654
- },
2655
- catch: (error) => error instanceof OpenapiCompileError ? error : new OpenapiCompileError({
2656
- code: "invalid_document",
2657
- reason: "This API definition could not be read. It may contain unsupported OpenAPI features."
2658
- })
2659
- });
4634
+ for (const { operation, methods: operationMethods } of built) {
4635
+ if (new URL(operation.baseUrl).origin !== pinnedOrigin) {
4636
+ skipped.add("multiple_hosts");
4637
+ continue;
4638
+ }
4639
+ operations.push(operation);
4640
+ for (const method of operationMethods) methods.set(method.name, method);
4641
+ }
4642
+ if (!operations.length) {
4643
+ const [only, ...others] = causes.values();
4644
+ if (only !== void 0 && others.length === 0 && [...skipped].every((reason) => reason === only.code))
4645
+ throw only;
4646
+ fail2(
4647
+ "no_supported_operations",
4648
+ "Executor cannot import any operation in this API definition."
4649
+ );
4650
+ }
4651
+ if (!operations.some(
4652
+ (operation) => operation.streaming !== true && (operation.request.security.length === 0 || operation.request.security.some((requirement) => {
4653
+ const keys = Object.keys(requirement);
4654
+ return keys.every((key) => bindings.has(key)) || keys.length === 1 && oauth.some((method) => method.name === keys[0]);
4655
+ }))
4656
+ ))
4657
+ fail2(
4658
+ "no_supported_operations",
4659
+ "This API has no operations supported by the available authentication and response transports."
4660
+ );
4661
+ return {
4662
+ operations,
4663
+ definitions: Object.fromEntries(document.definitions),
4664
+ methods: Object.fromEntries(
4665
+ [...methods.values()].map((method) => [method.name, method.bindings])
4666
+ ),
4667
+ secrets: [...methods.values()],
4668
+ oauth,
4669
+ schemes,
4670
+ pinnedOrigin,
4671
+ fallback
4672
+ };
4673
+ },
4674
+ catch: (error) => error instanceof OpenapiCompileError ? error : new OpenapiCompileError({
4675
+ code: "invalid_document",
4676
+ reason: "This API definition could not be read. It may contain unsupported OpenAPI features."
4677
+ })
4678
+ });
4679
+ };
2660
4680
 
2661
4681
  // src/implementation/openapi-source.ts
2662
4682
  var Manifest = Schema_exports.Struct({
2663
4683
  revision: Schema_exports.String,
2664
- pages: Schema_exports.Number,
4684
+ summaries: Schema_exports.Number,
4685
+ operations: Schema_exports.Number,
4686
+ definitions: Schema_exports.Number,
2665
4687
  meta: Schema_exports.optionalKey(RouterMeta)
2666
4688
  });
4689
+ var OperationSummary = Schema_exports.Struct({
4690
+ name: OpenapiOperation.fields.name,
4691
+ operationId: OpenapiOperation.fields.operationId,
4692
+ description: OpenapiOperation.fields.description,
4693
+ method: OpenapiOperation.fields.method,
4694
+ request: Schema_exports.Struct({ security: OpenapiOperation.fields.request.fields.security }),
4695
+ streaming: OpenapiOperation.fields.streaming,
4696
+ tags: OpenapiOperation.fields.tags
4697
+ });
4698
+ var summaryOf = (operation) => ({
4699
+ name: operation.name,
4700
+ ...operation.operationId === void 0 ? {} : { operationId: operation.operationId },
4701
+ description: operation.description,
4702
+ method: operation.method,
4703
+ request: { security: operation.request.security },
4704
+ ...operation.streaming === void 0 ? {} : { streaming: operation.streaming },
4705
+ ...operation.tags === void 0 ? {} : { tags: operation.tags }
4706
+ });
4707
+ var Summaries = Schema_exports.Array(OperationSummary);
4708
+ var Bucket = Schema_exports.Record(Schema_exports.String, Schema_exports.Unknown);
4709
+ var bucketBytes = 64e3;
4710
+ var bucketLimit = 15e5;
4711
+ var summaryPageBytes = 1e6;
4712
+ var bucketOf = (name, count) => {
4713
+ let hash2 = 2166136261;
4714
+ for (let index = 0; index < name.length; index++) {
4715
+ hash2 ^= name.charCodeAt(index);
4716
+ hash2 = Math.imul(hash2, 16777619);
4717
+ }
4718
+ return (hash2 >>> 0) % count;
4719
+ };
4720
+ var bucketize = (entries) => {
4721
+ const sized = entries.map(
4722
+ ([name, value]) => [name, value, JSON.stringify(value).length]
4723
+ );
4724
+ const total = sized.reduce((sum, [, , bytes2]) => sum + bytes2, 0);
4725
+ for (let count = Math.max(1, Math.ceil(total / bucketBytes)); ; count *= 2) {
4726
+ const buckets = Array.from({ length: count }, () => ({
4727
+ values: {},
4728
+ size: 0,
4729
+ bytes: 0
4730
+ }));
4731
+ for (const [name, value, bytes2] of sized) {
4732
+ const bucket = buckets[bucketOf(name, count)];
4733
+ if (bucket === void 0) continue;
4734
+ bucket.values[name] = value;
4735
+ bucket.size++;
4736
+ bucket.bytes += bytes2;
4737
+ }
4738
+ if (count >= sized.length || buckets.every((bucket) => bucket.bytes <= bucketLimit || bucket.size === 1))
4739
+ return buckets.map((bucket) => bucket.values);
4740
+ }
4741
+ };
4742
+ var paginate = (values) => {
4743
+ const pages = [[]];
4744
+ let bytes2 = 0;
4745
+ for (const value of values) {
4746
+ const size = JSON.stringify(value).length;
4747
+ const page = pages[pages.length - 1];
4748
+ if (page !== void 0 && page.length > 0 && bytes2 + size > summaryPageBytes) {
4749
+ pages.push([value]);
4750
+ bytes2 = size;
4751
+ } else {
4752
+ page?.push(value);
4753
+ bytes2 += size;
4754
+ }
4755
+ }
4756
+ return pages;
4757
+ };
2667
4758
  var DocumentInfo = Schema_exports.Struct({
2668
4759
  info: Schema_exports.optionalKey(
2669
4760
  Schema_exports.Struct({
@@ -2696,14 +4787,41 @@ var documentMeta = (document) => {
2696
4787
  };
2697
4788
  return Object.keys(meta).length === 0 ? void 0 : meta;
2698
4789
  };
2699
- var Names = Schema_exports.Array(Schema_exports.String);
2700
- var StoredEntry = Schema_exports.fromJsonString(Schema_exports.Struct({ value: JsonValue }));
4790
+ var partText = wrap(Schema_exports.String, false);
4791
+ var base64 = (bytes2) => {
4792
+ let binary = "";
4793
+ for (let index = 0; index < bytes2.length; index += 32768)
4794
+ binary += String.fromCharCode(...bytes2.subarray(index, index + 32768));
4795
+ return btoa(binary);
4796
+ };
4797
+ var gzip = (text) => invoke(
4798
+ async () => base64(
4799
+ new Uint8Array(
4800
+ await new Response(
4801
+ new Blob([text]).stream().pipeThrough(new CompressionStream("gzip"))
4802
+ ).arrayBuffer()
4803
+ )
4804
+ )
4805
+ );
4806
+ var gunzip = (stored2) => Effect_exports.tryPromise({
4807
+ try: () => new Response(
4808
+ new Blob([Uint8Array.from(atob(stored2), (char) => char.charCodeAt(0))]).stream().pipeThrough(new DecompressionStream("gzip"))
4809
+ ).text(),
4810
+ catch: invalid
4811
+ });
4812
+ var decodeText = (decoder) => (text) => Effect_exports.try({ try: () => JSON.parse(text), catch: invalid }).pipe(
4813
+ Effect_exports.flatMap((value) => Schema_exports.decodeUnknownEffect(decoder)(value))
4814
+ );
2701
4815
  var schema = (decoder) => wrap(decoder, false);
2702
4816
  var invoke = (work) => Effect_exports.tryPromise({ try: work, catch: (error) => error });
2703
4817
  var invalid = () => new OpenapiError({ reason: "invalid_definition" });
2704
- var pageSize = 64;
2705
- var format = "openapi-v2";
2706
- var sha256 = (text) => invoke(() => crypto.subtle.digest("SHA-256", new TextEncoder().encode(text))).pipe(
4818
+ var format = "openapi-v3";
4819
+ var writeEntries = cacheLimits.batchEntries;
4820
+ var writeBytes = cacheLimits.batchBytes - 5e5;
4821
+ var readParts = Math.floor(cacheLimits.batchBytes / bucketLimit);
4822
+ var sha256Json = (value) => invoke(
4823
+ () => crypto.subtle.digest("SHA-256", new TextEncoder().encode(JSON.stringify(value)))
4824
+ ).pipe(
2707
4825
  Effect_exports.map(
2708
4826
  (hash2) => Array.from(new Uint8Array(hash2), (byte) => byte.toString(16).padStart(2, "0")).join("")
2709
4827
  )
@@ -2779,6 +4897,35 @@ function patchOpenapi(root, patches) {
2779
4897
  }
2780
4898
  return result;
2781
4899
  }
4900
+ var expandedNodes = (root, limit) => {
4901
+ const sizes = /* @__PURE__ */ new Map();
4902
+ const size = (value) => {
4903
+ if (typeof value !== "object" || value === null) return 0;
4904
+ const known = sizes.get(value);
4905
+ if (known !== void 0) return known;
4906
+ let total2 = 1;
4907
+ for (const child of Array.isArray(value) ? value : Object.values(value)) {
4908
+ total2 += size(child);
4909
+ if (total2 > limit) break;
4910
+ }
4911
+ sizes.set(value, total2);
4912
+ return total2;
4913
+ };
4914
+ const total = size(root);
4915
+ return total > limit ? void 0 : { total, distinct: sizes.size };
4916
+ };
4917
+ var parseYaml = (text) => {
4918
+ try {
4919
+ const value = load(text, { schema: CORE_SCHEMA, maxAliases: 100 });
4920
+ const nodes = expandedNodes(value, 1e7);
4921
+ if (nodes !== void 0) {
4922
+ if (nodes.total === nodes.distinct) return value;
4923
+ if (nodes.total <= nodes.distinct * 10 + 1e5) return JSON.parse(JSON.stringify(value));
4924
+ }
4925
+ } catch {
4926
+ }
4927
+ return JSON.parse(JSON.stringify(parse(text)));
4928
+ };
2782
4929
  var download = (url, context) => Effect_exports.gen(function* () {
2783
4930
  const response = yield* invoke(
2784
4931
  () => context.fetch(url, { signal: context.signal, redirect: "manual" })
@@ -2805,7 +4952,7 @@ var download = (url, context) => Effect_exports.gen(function* () {
2805
4952
  );
2806
4953
  return yield* Effect_exports.try({
2807
4954
  try: () => Schema_exports.decodeUnknownSync(JsonObject)(
2808
- text.trimStart().startsWith("{") ? JSON.parse(text) : parse(text)
4955
+ text.trimStart().startsWith("{") ? JSON.parse(text) : parseYaml(text)
2809
4956
  ),
2810
4957
  catch: invalid
2811
4958
  });
@@ -2843,12 +4990,28 @@ var liveOpenapiRouter = (options) => {
2843
4990
  kind,
2844
4991
  name
2845
4992
  ];
2846
- const refresh = (context) => Effect_exports.gen(function* () {
2847
- const raw = "url" in options.source ? yield* download(options.source.url, context) : options.source.document;
2848
- const document = patchOpenapi(raw, options.patches);
4993
+ const compile = (context) => Effect_exports.gen(function* () {
4994
+ let document = patchOpenapi(
4995
+ "url" in options.source ? yield* download(options.source.url, context) : (
4996
+ // A copy the compilation can own, as a tree.
4997
+ Schema_exports.decodeUnknownSync(JsonObject)(
4998
+ JSON.parse(JSON.stringify(options.source.document))
4999
+ )
5000
+ ),
5001
+ options.patches
5002
+ );
5003
+ yield* Effect_exports.promise(yieldToRuntime);
5004
+ const revision = yield* sha256Json([format, yield* sourceId, document]);
5005
+ const meta = documentMeta(document);
5006
+ const handOver = () => {
5007
+ const owned = document;
5008
+ document = void 0;
5009
+ if (owned === void 0) throw new Error("The document was already handed over.");
5010
+ return owned;
5011
+ };
2849
5012
  const compiled = yield* compileOpenApiDocument(
2850
5013
  { name: "API", ..."url" in options.source ? { connectUrl: options.source.url } : {} },
2851
- document,
5014
+ handOver(),
2852
5015
  {
2853
5016
  allowedOrigin: options.allowedOrigin,
2854
5017
  securitySchemes: options.securitySchemes,
@@ -2856,51 +5019,57 @@ var liveOpenapiRouter = (options) => {
2856
5019
  ...options.baseUrl === void 0 ? {} : { baseUrl: options.baseUrl }
2857
5020
  }
2858
5021
  );
2859
- const revision = yield* sha256(JSON.stringify([format, yield* sourceId, document]));
2860
- const names = compiled.operations.map((operation) => operation.name);
5022
+ return { revision, meta, compiled };
5023
+ });
5024
+ const serialize = (context) => Effect_exports.gen(function* () {
5025
+ const { revision, meta, compiled } = yield* compile(context);
5026
+ yield* Effect_exports.promise(yieldToRuntime);
5027
+ const summaries = paginate(compiled.operations.map(summaryOf));
5028
+ const operations = bucketize(
5029
+ compiled.operations.map((operation) => [operation.name, operation])
5030
+ );
5031
+ const definitions = bucketize(Object.entries(compiled.definitions));
2861
5032
  const parts = [
2862
- ...compiled.operations.map((operation) => ({
2863
- kind: "operation",
2864
- name: operation.name,
2865
- value: operation
2866
- })),
2867
- ...Object.entries(compiled.definitions).map(([name, value]) => ({
2868
- kind: "definition",
2869
- name,
2870
- value
2871
- }))
5033
+ ...summaries.map((value, name) => ({ kind: "summaries", name, value })),
5034
+ ...operations.map((value, name) => ({ kind: "operations", name, value })),
5035
+ ...definitions.map((value, name) => ({ kind: "definitions", name, value }))
2872
5036
  ];
2873
- const pages = Math.ceil(names.length / pageSize);
2874
- for (let page = 0; page < pages; page++)
2875
- parts.push({
2876
- kind: "names",
2877
- name: page,
2878
- value: names.slice(page * pageSize, (page + 1) * pageSize)
2879
- });
2880
5037
  const batches = [];
2881
5038
  let batch = [];
2882
5039
  let size = 0;
2883
5040
  const retained = /* @__PURE__ */ new Map();
2884
5041
  let retainedBytes = 0;
2885
- for (const part of parts) {
2886
- const entry = { key: partKey(revision, part.kind, part.name), value: part.value };
2887
- const text = JSON.stringify(entry);
2888
- const bytes2 = new TextEncoder().encode(text).byteLength;
2889
- if (batch.length && (batch.length >= 64 || size + bytes2 > 4e6)) {
5042
+ for (const [index, part] of parts.entries()) {
5043
+ if (index % 32 === 31) yield* Effect_exports.promise(yieldToRuntime);
5044
+ const text = JSON.stringify(part.value);
5045
+ const entry = { key: partKey(revision, part.kind, part.name), value: yield* gzip(text) };
5046
+ const bytes2 = new TextEncoder().encode(JSON.stringify(entry)).byteLength;
5047
+ if (batch.length && (batch.length >= writeEntries || size + bytes2 > writeBytes)) {
2890
5048
  batches.push({ entries: batch, bytes: size });
2891
5049
  batch = [];
2892
5050
  size = 0;
2893
5051
  }
2894
5052
  batch.push(entry);
2895
5053
  size += bytes2;
2896
- retainedBytes += bytes2;
2897
- if (retainedBytes <= 8e6)
2898
- retained.set(
2899
- storedPart(part.kind, part.name),
2900
- Schema_exports.decodeUnknownSync(StoredEntry)(text).value
2901
- );
5054
+ retainedBytes += text.length;
5055
+ if (retainedBytes <= 8e6) retained.set(storedPart(part.kind, part.name), text);
2902
5056
  }
2903
5057
  if (batch.length) batches.push({ entries: batch, bytes: size });
5058
+ return {
5059
+ manifest: {
5060
+ revision,
5061
+ summaries: summaries.length,
5062
+ operations: operations.length,
5063
+ definitions: definitions.length,
5064
+ ...meta === void 0 ? {} : { meta }
5065
+ },
5066
+ batches,
5067
+ retained,
5068
+ retainedBytes
5069
+ };
5070
+ });
5071
+ const refresh = (context) => Effect_exports.gen(function* () {
5072
+ const { manifest, batches, retained, retainedBytes } = yield* serialize(context);
2904
5073
  yield* Effect_exports.forEach(
2905
5074
  batches,
2906
5075
  ({ entries, bytes: bytes2 }, index) => fromPromise(context.cache.write)(entries, retention).pipe(
@@ -2918,9 +5087,8 @@ var liveOpenapiRouter = (options) => {
2918
5087
  discard: true
2919
5088
  }
2920
5089
  );
2921
- retain(revision, retained, retainedBytes);
2922
- const meta = documentMeta(document);
2923
- return { revision, pages, ...meta === void 0 ? {} : { meta } };
5090
+ retain(manifest.revision, retained, retainedBytes);
5091
+ return manifest;
2924
5092
  });
2925
5093
  let reading;
2926
5094
  const current = Effect_exports.suspend(() => {
@@ -2947,54 +5115,101 @@ var liveOpenapiRouter = (options) => {
2947
5115
  });
2948
5116
  const read = (revision, kind, names, decoder) => {
2949
5117
  const retained = stored.get(revision);
2950
- return retained === void 0 ? fromPromise(options.cache.readMany)(
2951
- names.map((name) => partKey(revision, kind, name)),
2952
- schema(decoder)
2953
- ) : Effect_exports.forEach(names, (name) => {
2954
- const value = retained.parts.get(storedPart(kind, name));
2955
- return value === void 0 ? Effect_exports.succeed(void 0) : Schema_exports.decodeUnknownEffect(decoder)(value);
2956
- });
5118
+ const decode = decodeText(decoder);
5119
+ if (retained !== void 0)
5120
+ return Effect_exports.forEach(names, (name) => {
5121
+ const text = retained.parts.get(storedPart(kind, name));
5122
+ return text === void 0 ? Effect_exports.succeed(void 0) : decode(text);
5123
+ });
5124
+ const groups = Array.from(
5125
+ { length: Math.ceil(names.length / readParts) },
5126
+ (_, group) => names.slice(group * readParts, (group + 1) * readParts)
5127
+ );
5128
+ return Effect_exports.forEach(
5129
+ groups,
5130
+ (group) => fromPromise(options.cache.readMany)(
5131
+ group.map((name) => partKey(revision, kind, name)),
5132
+ partText
5133
+ ).pipe(
5134
+ Effect_exports.flatMap(
5135
+ (stored2) => Effect_exports.forEach(
5136
+ stored2,
5137
+ (value) => value === void 0 ? Effect_exports.succeed(void 0) : gunzip(value).pipe(Effect_exports.flatMap(decode))
5138
+ )
5139
+ )
5140
+ ),
5141
+ { concurrency: partConcurrency }
5142
+ ).pipe(Effect_exports.map((values) => values.flat()));
2957
5143
  };
2958
- const namesFor = (manifest) => Effect_exports.gen(function* () {
2959
- const names = [];
2960
- for (let page = 0; page < manifest.pages; page += pageSize) {
2961
- const pages = yield* read(
2962
- manifest.revision,
2963
- "names",
2964
- Array.from({ length: Math.min(pageSize, manifest.pages - page) }, (_, i) => page + i),
2965
- Names
2966
- );
2967
- for (const values of pages) {
2968
- if (values === void 0) return void 0;
2969
- names.push(...values);
2970
- }
5144
+ const range = (count) => Array.from({ length: count }, (_, index) => index);
5145
+ const summariesFor = (manifest) => Effect_exports.gen(function* () {
5146
+ const pages = yield* read(
5147
+ manifest.revision,
5148
+ "summaries",
5149
+ range(manifest.summaries),
5150
+ Summaries
5151
+ );
5152
+ const summaries = [];
5153
+ for (const page of pages) {
5154
+ if (page === void 0) return void 0;
5155
+ summaries.push(...page);
5156
+ }
5157
+ return summaries;
5158
+ });
5159
+ const operationFor = (manifest, name) => Effect_exports.gen(function* () {
5160
+ const [bucket] = yield* read(
5161
+ manifest.revision,
5162
+ "operations",
5163
+ [bucketOf(name, manifest.operations)],
5164
+ Bucket
5165
+ );
5166
+ if (bucket === void 0) return void 0;
5167
+ const value = Object.hasOwn(bucket, name) ? bucket[name] : void 0;
5168
+ return {
5169
+ value: value === void 0 ? void 0 : yield* Schema_exports.decodeUnknownEffect(OpenapiOperation)(value)
5170
+ };
5171
+ });
5172
+ const operationsFor = (manifest) => Effect_exports.gen(function* () {
5173
+ const summaries = yield* summariesFor(manifest);
5174
+ if (summaries === void 0) return void 0;
5175
+ const buckets = yield* read(
5176
+ manifest.revision,
5177
+ "operations",
5178
+ range(manifest.operations),
5179
+ Bucket
5180
+ );
5181
+ const all = [];
5182
+ for (const { name } of summaries) {
5183
+ const bucket = buckets[bucketOf(name, manifest.operations)];
5184
+ const value = bucket !== void 0 && Object.hasOwn(bucket, name) ? bucket[name] : void 0;
5185
+ if (value === void 0) return void 0;
5186
+ all.push(yield* Schema_exports.decodeUnknownEffect(OpenapiOperation)(value));
2971
5187
  }
2972
- return names;
5188
+ return all;
2973
5189
  });
2974
- const definitionsFor = (revision, operation) => Effect_exports.gen(function* () {
5190
+ const definitionsFor = (manifest, root) => Effect_exports.gen(function* () {
2975
5191
  const definitions = {};
2976
- const seen = /* @__PURE__ */ new Set();
2977
- let pending = [...references(operation)];
5192
+ const buckets = /* @__PURE__ */ new Map();
5193
+ let pending = [...references(root)];
2978
5194
  while (pending.length) {
2979
- const names = [...new Set(pending.splice(0, pageSize * partConcurrency))].filter(
2980
- (name) => !seen.has(name)
2981
- );
2982
- names.forEach((name) => seen.add(name));
2983
- if (!names.length) continue;
2984
- const values = (yield* Effect_exports.forEach(
2985
- Array.from(
2986
- { length: Math.ceil(names.length / pageSize) },
2987
- (_, page) => names.slice(page * pageSize, (page + 1) * pageSize)
2988
- ),
2989
- (batch) => read(revision, "definition", batch, JsonObject),
2990
- { concurrency: partConcurrency }
2991
- )).flat();
2992
- for (let i = 0; i < names.length; i++) {
2993
- const name = names[i];
2994
- const value = values[i];
2995
- if (name === void 0 || value === void 0) return void 0;
2996
- definitions[name] = value;
2997
- pending.push(...references(value));
5195
+ const names = [...new Set(pending)].filter((name) => !Object.hasOwn(definitions, name));
5196
+ pending = [];
5197
+ const missing = [
5198
+ ...new Set(names.map((name) => bucketOf(name, manifest.definitions)))
5199
+ ].filter((bucket) => !buckets.has(bucket));
5200
+ const values = yield* read(manifest.revision, "definitions", missing, Bucket);
5201
+ for (const [index, bucket] of missing.entries()) {
5202
+ const value = values[index];
5203
+ if (value === void 0) return void 0;
5204
+ buckets.set(bucket, value);
5205
+ }
5206
+ for (const name of names) {
5207
+ const bucket = buckets.get(bucketOf(name, manifest.definitions));
5208
+ const value = bucket !== void 0 && Object.hasOwn(bucket, name) ? bucket[name] : void 0;
5209
+ if (value === void 0) return void 0;
5210
+ const definition = yield* Schema_exports.decodeUnknownEffect(JsonObject)(value);
5211
+ definitions[name] = definition;
5212
+ pending.push(...references(definition));
2998
5213
  }
2999
5214
  }
3000
5215
  return definitions;
@@ -3011,26 +5226,6 @@ var liveOpenapiRouter = (options) => {
3011
5226
  return Object.hasOwn(kinds, key) ? kinds[key] ?? "mutation" : ["GET", "HEAD", "OPTIONS"].includes(op.method) ? "query" : "mutation";
3012
5227
  };
3013
5228
  const readOnly = (op) => kindOf(op) === "query";
3014
- const operationsFor = (manifest) => Effect_exports.gen(function* () {
3015
- const names = yield* namesFor(manifest);
3016
- if (names === void 0) return void 0;
3017
- const pages = yield* Effect_exports.forEach(
3018
- Array.from(
3019
- { length: Math.ceil(names.length / pageSize) },
3020
- (_, page) => names.slice(page * pageSize, (page + 1) * pageSize)
3021
- ),
3022
- (batch) => read(manifest.revision, "operation", batch, OpenapiOperation),
3023
- { concurrency: partConcurrency }
3024
- );
3025
- const all = [];
3026
- for (const operations of pages) {
3027
- for (const operation of operations) {
3028
- if (operation === void 0) return void 0;
3029
- all.push(operation);
3030
- }
3031
- }
3032
- return all;
3033
- });
3034
5229
  const summarize = (operation) => ({
3035
5230
  name: operation.name,
3036
5231
  description: operation.description,
@@ -3055,15 +5250,16 @@ var liveOpenapiRouter = (options) => {
3055
5250
  meta: () => current.pipe(Effect_exports.map((manifest) => manifest.meta ?? {})),
3056
5251
  resolve: (name) => withRevision(
3057
5252
  (manifest) => Effect_exports.gen(function* () {
3058
- const raw = name;
3059
- const memoKey = `${manifest.revision}/${defaultedNames}/${raw}`;
5253
+ const memoKey = `${manifest.revision}/${defaultedNames}/${name}`;
3060
5254
  const memo = resolved.get(memoKey);
3061
- const operation = memo?.operation ?? (yield* read(manifest.revision, "operation", [raw], OpenapiOperation))[0];
5255
+ let operation = memo?.operation;
3062
5256
  if (operation === void 0) {
3063
- const names = yield* namesFor(manifest);
3064
- return names === void 0 || names.includes(raw) ? void 0 : { value: void 0 };
5257
+ const found = yield* operationFor(manifest, name);
5258
+ if (found === void 0) return void 0;
5259
+ if (found.value === void 0) return { value: void 0 };
5260
+ operation = found.value;
3065
5261
  }
3066
- const definitions = memo?.definitions ?? (yield* definitionsFor(manifest.revision, operation));
5262
+ const definitions = memo?.definitions ?? (yield* definitionsFor(manifest, operation));
3067
5263
  if (definitions === void 0) return void 0;
3068
5264
  const schemas = memo?.schemas ?? (yield* prepareOpenapiOperation(operation, definitions, options.parameterDefaults));
3069
5265
  if (memo === void 0) remember(memoKey, { operation, definitions, schemas });
@@ -3074,7 +5270,7 @@ var liveOpenapiRouter = (options) => {
3074
5270
  const declarations = protocolOperations(tools, {
3075
5271
  [operation.name]: kindOf(operation)
3076
5272
  });
3077
- const declaration = Object.hasOwn(declarations, raw) ? declarations[raw] : void 0;
5273
+ const declaration = Object.hasOwn(declarations, name) ? declarations[name] : void 0;
3078
5274
  return { value: declaration === void 0 ? void 0 : nativeOperation(declaration) };
3079
5275
  })
3080
5276
  ),
@@ -3082,7 +5278,7 @@ var liveOpenapiRouter = (options) => {
3082
5278
  (manifest) => Effect_exports.gen(function* () {
3083
5279
  const all = yield* operationsFor(manifest);
3084
5280
  if (all === void 0) return void 0;
3085
- const definitions = yield* definitionsFor(manifest.revision, all);
5281
+ const definitions = yield* definitionsFor(manifest, all);
3086
5282
  if (definitions === void 0) return void 0;
3087
5283
  const bundle = bundler(definitions);
3088
5284
  const request = createRequest(options);
@@ -3093,7 +5289,7 @@ var liveOpenapiRouter = (options) => {
3093
5289
  ),
3094
5290
  summaries: () => withRevision(
3095
5291
  (manifest) => Effect_exports.gen(function* () {
3096
- const all = yield* operationsFor(manifest);
5292
+ const all = yield* summariesFor(manifest);
3097
5293
  if (all === void 0) return void 0;
3098
5294
  const request = createRequest(options);
3099
5295
  return {
@@ -3103,20 +5299,13 @@ var liveOpenapiRouter = (options) => {
3103
5299
  ),
3104
5300
  describe: (name) => withRevision(
3105
5301
  (manifest) => Effect_exports.gen(function* () {
3106
- const raw = name;
3107
- const operation = (yield* read(
3108
- manifest.revision,
3109
- "operation",
3110
- [raw],
3111
- OpenapiOperation
3112
- ))[0];
3113
- if (operation === void 0) {
3114
- const names = yield* namesFor(manifest);
3115
- return names === void 0 || names.includes(raw) ? void 0 : { value: void 0 };
3116
- }
5302
+ const found = yield* operationFor(manifest, name);
5303
+ if (found === void 0) return void 0;
5304
+ if (found.value === void 0) return { value: void 0 };
5305
+ const operation = found.value;
3117
5306
  if (!createRequest(options).available(operation, options.account))
3118
5307
  return { value: void 0 };
3119
- const definitions = yield* definitionsFor(manifest.revision, operation);
5308
+ const definitions = yield* definitionsFor(manifest, operation);
3120
5309
  if (definitions === void 0) return void 0;
3121
5310
  return { value: describe(operation, bundler(definitions)) };
3122
5311
  })
@@ -3142,3 +5331,8 @@ export {
3142
5331
  openapiMediaKind,
3143
5332
  openapiRouter
3144
5333
  };
5334
+ /*! Bundled license information:
5335
+
5336
+ js-yaml/dist/js-yaml.mjs:
5337
+ (*! js-yaml 5.4.2 https://github.com/nodeca/js-yaml @license MIT *)
5338
+ */