@depup/typebox 1.3.9-depup.0 → 1.3.14-depup.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/README.md +2 -2
  2. package/build/format/date.d.mts +1 -1
  3. package/build/format/date.mjs +1 -1
  4. package/build/format/date_time.d.mts +2 -2
  5. package/build/format/date_time.mjs +3 -3
  6. package/build/format/email.d.mts +1 -1
  7. package/build/format/email.mjs +2 -2
  8. package/build/format/hostname.mjs +2 -10
  9. package/build/format/idn_email.d.mts +1 -1
  10. package/build/format/idn_email.mjs +3 -3
  11. package/build/format/idn_hostname.d.mts +1 -0
  12. package/build/format/idn_hostname.mjs +3 -11
  13. package/build/format/idna/format/bidi.d.mts +3 -0
  14. package/build/format/idna/format/bidi.mjs +98 -0
  15. package/build/format/idna/format/puny.d.mts +3 -0
  16. package/build/format/idna/format/puny.mjs +144 -0
  17. package/build/format/idna/hostname.d.mts +1 -0
  18. package/build/format/idna/hostname.mjs +16 -0
  19. package/build/format/idna/idn-hostname.d.mts +1 -0
  20. package/build/format/idna/idn-hostname.mjs +23 -0
  21. package/build/format/idna/index.d.mts +2 -0
  22. package/build/format/idna/index.mjs +2 -0
  23. package/build/format/idna/label/ascii.d.mts +1 -0
  24. package/build/format/idna/label/ascii.mjs +9 -0
  25. package/build/format/idna/label/puny.d.mts +1 -0
  26. package/build/format/idna/label/puny.mjs +28 -0
  27. package/build/format/idna/label/unicode.d.mts +1 -0
  28. package/build/format/idna/label/unicode.mjs +106 -0
  29. package/build/format/idna/pattern/pattern.d.mts +30 -0
  30. package/build/format/idna/pattern/pattern.mjs +70 -0
  31. package/build/format/ipv4.d.mts +0 -1
  32. package/build/format/ipv4.mjs +2 -32
  33. package/build/format/ipv6.mjs +2 -61
  34. package/build/format/iri.d.mts +2 -2
  35. package/build/format/iri.mjs +26 -8
  36. package/build/format/iri_reference.d.mts +2 -2
  37. package/build/format/iri_reference.mjs +9 -55
  38. package/build/format/regex.d.mts +1 -2
  39. package/build/format/regex.mjs +2 -6
  40. package/build/format/time.d.mts +2 -2
  41. package/build/format/time.mjs +19 -14
  42. package/build/format/uri.d.mts +1 -1
  43. package/build/format/uri.mjs +3 -130
  44. package/build/format/uri_reference.d.mts +1 -1
  45. package/build/format/uri_reference.mjs +2 -3
  46. package/build/format/uri_template.d.mts +2 -3
  47. package/build/format/uri_template.mjs +4 -5
  48. package/build/format/url.d.mts +3 -3
  49. package/build/format/url.mjs +4 -5
  50. package/build/guard/guard.mjs +2 -2
  51. package/build/guard/string.d.mts +2 -2
  52. package/build/guard/string.mjs +7 -7
  53. package/build/schema/engine/_regexp.d.mts +2 -0
  54. package/build/schema/engine/_regexp.mjs +4 -0
  55. package/build/schema/engine/_stack.mjs +1 -1
  56. package/build/schema/engine/additionalProperties.mjs +4 -3
  57. package/build/schema/engine/pattern.mjs +3 -2
  58. package/build/schema/engine/patternProperties.mjs +4 -3
  59. package/build/schema/engine/schema.mjs +13 -4
  60. package/build/schema/resolve/ref.d.mts +1 -0
  61. package/build/schema/resolve/ref.mjs +13 -3
  62. package/build/schema/types/index.d.mts +0 -2
  63. package/build/schema/types/index.mjs +0 -2
  64. package/build/system/memory/clone.mjs +14 -11
  65. package/build/system/memory/discard.mjs +6 -5
  66. package/build/system/settings/settings.d.mts +9 -0
  67. package/build/system/settings/settings.mjs +2 -0
  68. package/build/type/engine/call/distribute_arguments.d.mts +6 -1
  69. package/build/type/engine/call/distribute_arguments.mjs +16 -3
  70. package/build/type/engine/call/instantiate.mjs +34 -4
  71. package/build/type/engine/evaluate/broaden.d.mts +5 -5
  72. package/build/type/engine/evaluate/broaden.mjs +20 -26
  73. package/build/type/engine/evaluate/compare.d.mts +6 -10
  74. package/build/type/engine/evaluate/compare.mjs +9 -13
  75. package/build/type/engine/evaluate/composite.d.mts +7 -4
  76. package/build/type/engine/evaluate/composite.mjs +12 -19
  77. package/build/type/engine/evaluate/distribute.d.mts +4 -20
  78. package/build/type/engine/evaluate/distribute.mjs +8 -20
  79. package/build/type/engine/evaluate/evaluate.d.mts +4 -4
  80. package/build/type/engine/evaluate/evaluate.mjs +11 -8
  81. package/build/type/engine/evaluate/flatten.d.mts +1 -1
  82. package/build/type/engine/evaluate/flatten.mjs +3 -4
  83. package/build/type/engine/evaluate/narrow.d.mts +17 -2
  84. package/build/type/engine/evaluate/narrow.mjs +26 -6
  85. package/build/type/engine/exclude/operation.mjs +3 -4
  86. package/build/type/engine/extract/operation.d.mts +1 -1
  87. package/build/type/engine/extract/operation.mjs +3 -4
  88. package/build/type/engine/priority/priority.d.mts +2 -2
  89. package/build/type/engine/priority/priority.mjs +3 -4
  90. package/build/type/script/parser.mjs +8 -1
  91. package/changes.json +1 -1
  92. package/package.json +3 -3
  93. package/readme.md +66 -62
  94. package/build/format/_idna.d.mts +0 -2
  95. package/build/format/_idna.mjs +0 -246
  96. package/build/format/_puny.d.mts +0 -1
  97. package/build/format/_puny.mjs +0 -77
  98. package/build/schema/types/contentEncoding.d.mts +0 -9
  99. package/build/schema/types/contentEncoding.mjs +0 -13
  100. package/build/schema/types/contentMediaType.d.mts +0 -9
  101. package/build/schema/types/contentMediaType.mjs +0 -13
@@ -1,6 +1,6 @@
1
1
  /** Returns the number of grapheme clusters in a string */
2
2
  export declare function GraphemeCount(value: string): number;
3
3
  /** Fast check for minimum grapheme length, falls back to full check if needed */
4
- export declare function IsMinLengthFast(value: string, minLength: number): boolean;
4
+ export declare function IsMinLength(value: string, minLength: number): boolean;
5
5
  /** Fast check for maximum grapheme length, falls back to full check if needed */
6
- export declare function IsMaxLengthFast(value: string, maxLength: number): boolean;
6
+ export declare function IsMaxLength(value: string, maxLength: number): boolean;
@@ -67,7 +67,7 @@ function NextGraphemeClusterIndex(value, clusterStart) {
67
67
  // Consume combining marks & variation selectors
68
68
  clusterEnd = ConsumeModifiers(value, clusterEnd);
69
69
  // Handle multi-ZWJ sequences
70
- while (clusterEnd < value.length - 1 && value[clusterEnd] === '\u200D') {
70
+ while (clusterEnd < value.length - 1 && IsZeroWidthJoiner(value.codePointAt(clusterEnd))) {
71
71
  const nextCP = value.codePointAt(clusterEnd + 1);
72
72
  clusterEnd += 1 + CodePointLength(nextCP);
73
73
  clusterEnd = ConsumeModifiers(value, clusterEnd);
@@ -106,7 +106,7 @@ export function GraphemeCount(value) {
106
106
  // IsMinLength
107
107
  // --------------------------------------------------------------------------
108
108
  /** Checks if a string has at least a minimum number of grapheme clusters */
109
- function IsMinLength(value, minLength) {
109
+ function IsMinLengthSegmented(value, minLength) {
110
110
  // ----------------------------------------------------------------
111
111
  // Inaccessible via public interface (review)
112
112
  //
@@ -129,7 +129,7 @@ function IsMinLength(value, minLength) {
129
129
  // IsMaxLength
130
130
  // --------------------------------------------------------------------------
131
131
  /** Checks if a string has at most a maximum number of grapheme clusters */
132
- function IsMaxLength(value, maxLength) {
132
+ function IsMaxLengthSegmented(value, maxLength) {
133
133
  let count = 0;
134
134
  let index = 0;
135
135
  while (index < value.length) {
@@ -144,13 +144,13 @@ function IsMaxLength(value, maxLength) {
144
144
  // IsMinLengthFast
145
145
  // --------------------------------------------------------------------------
146
146
  /** Fast check for minimum grapheme length, falls back to full check if needed */
147
- export function IsMinLengthFast(value, minLength) {
147
+ export function IsMinLength(value, minLength) {
148
148
  if (minLength === 0)
149
149
  return true; // 0-length
150
150
  let index = 0;
151
151
  while (index < value.length) {
152
152
  if (IsGraphemeCodePoint(value.charCodeAt(index))) {
153
- return IsMinLength(value, minLength);
153
+ return IsMinLengthSegmented(value, minLength);
154
154
  }
155
155
  index++;
156
156
  if (index >= minLength)
@@ -162,11 +162,11 @@ export function IsMinLengthFast(value, minLength) {
162
162
  // IsMaxLengthFast
163
163
  // --------------------------------------------------------------------------
164
164
  /** Fast check for maximum grapheme length, falls back to full check if needed */
165
- export function IsMaxLengthFast(value, maxLength) {
165
+ export function IsMaxLength(value, maxLength) {
166
166
  let index = 0;
167
167
  while (index < value.length) {
168
168
  if (IsGraphemeCodePoint(value.charCodeAt(index))) {
169
- return IsMaxLength(value, maxLength);
169
+ return IsMaxLengthSegmented(value, maxLength);
170
170
  }
171
171
  index++;
172
172
  if (index > maxLength)
@@ -0,0 +1,2 @@
1
+ /** Standard RegExp with Unicode */
2
+ export declare function UnicodeRegExp(pattern: string): RegExp;
@@ -0,0 +1,4 @@
1
+ /** Standard RegExp with Unicode */
2
+ export function UnicodeRegExp(pattern) {
3
+ return new RegExp(pattern, 'u');
4
+ }
@@ -22,7 +22,7 @@ export class Stack {
22
22
  // Base
23
23
  // ----------------------------------------------------------------
24
24
  BaseURL() {
25
- return this.ids.reduce((result, schema) => new URL(schema.$id, result), new URL('http://unknown'));
25
+ return this.ids.reduce((result, schema) => new URL(schema.$id, result), Resolve.DefaultBase);
26
26
  }
27
27
  Base() {
28
28
  return this.ids[this.ids.length - 1] ?? this.schema;
@@ -3,6 +3,7 @@ import * as S from '../types/index.mjs';
3
3
  import * as V from './_externals.mjs';
4
4
  import { Unique } from './_unique.mjs';
5
5
  import { AccumulatedErrorContext } from './_context.mjs';
6
+ import { UnicodeRegExp } from './_regexp.mjs';
6
7
  import { EmitGuard as E, Guard as G } from '../../guard/index.mjs';
7
8
  import { BuildSchemaPushStack, CheckSchemaPushStack, ErrorSchemaPushStack } from './schema.mjs';
8
9
  // ------------------------------------------------------------------
@@ -58,7 +59,7 @@ export function BuildAdditionalPropertiesFast(_context, schema, value) {
58
59
  // ------------------------------------------------------------------
59
60
  export function BuildAdditionalPropertiesStandard(stack, context, schema, value) {
60
61
  const [key, _index] = [Unique(), Unique()];
61
- const regexp = V.CreateVariable(new RegExp(GetPropertiesPattern(schema)));
62
+ const regexp = V.CreateVariable(UnicodeRegExp(GetPropertiesPattern(schema)));
62
63
  const isSchema = BuildSchemaPushStack(stack, context, schema.additionalProperties, `${value}[${key}]`);
63
64
  const isKey = E.Call(E.Member(regexp, 'test'), [key]);
64
65
  const addKey = context.AddKey(key);
@@ -78,7 +79,7 @@ export function BuildAdditionalProperties(stack, context, schema, value) {
78
79
  // Check
79
80
  // ------------------------------------------------------------------
80
81
  export function CheckAdditionalProperties(stack, context, schema, value) {
81
- const regexp = new RegExp(GetPropertiesPattern(schema));
82
+ const regexp = UnicodeRegExp(GetPropertiesPattern(schema));
82
83
  const isAdditionalProperties = G.Every(G.Keys(value), 0, (key, _index) => {
83
84
  return regexp.test(key) ||
84
85
  (CheckSchemaPushStack(stack, context, schema.additionalProperties, value[key]) && context.AddKey(key));
@@ -89,7 +90,7 @@ export function CheckAdditionalProperties(stack, context, schema, value) {
89
90
  // Error
90
91
  // ------------------------------------------------------------------
91
92
  export function ErrorAdditionalProperties(stack, context, schemaPath, instancePath, schema, value) {
92
- const regexp = new RegExp(GetPropertiesPattern(schema));
93
+ const regexp = UnicodeRegExp(GetPropertiesPattern(schema));
93
94
  const additionalProperties = [];
94
95
  const isAdditionalProperties = G.EveryAll(G.Keys(value), 0, (key, _index) => {
95
96
  const nextSchemaPath = `${schemaPath}/additionalProperties`;
@@ -1,18 +1,19 @@
1
1
  // deno-fmt-ignore-file
2
2
  import * as Externals from './_externals.mjs';
3
3
  import { Guard as G, EmitGuard as E } from '../../guard/index.mjs';
4
+ import { UnicodeRegExp } from './_regexp.mjs';
4
5
  // ------------------------------------------------------------------
5
6
  // Build
6
7
  // ------------------------------------------------------------------
7
8
  export function BuildPattern(_stack, _context, schema, value) {
8
- const regexp = Externals.CreateVariable(G.IsString(schema.pattern) ? new RegExp(schema.pattern, 'u') : schema.pattern);
9
+ const regexp = Externals.CreateVariable(G.IsString(schema.pattern) ? UnicodeRegExp(schema.pattern) : schema.pattern);
9
10
  return E.Call(E.Member(regexp, 'test'), [value]);
10
11
  }
11
12
  // ------------------------------------------------------------------
12
13
  // Check
13
14
  // ------------------------------------------------------------------
14
15
  export function CheckPattern(_stack, _context, schema, value) {
15
- const regexp = G.IsString(schema.pattern) ? new RegExp(schema.pattern, 'u') : schema.pattern;
16
+ const regexp = G.IsString(schema.pattern) ? UnicodeRegExp(schema.pattern) : schema.pattern;
16
17
  return regexp.test(value);
17
18
  }
18
19
  // ------------------------------------------------------------------
@@ -1,6 +1,7 @@
1
1
  // deno-fmt-ignore-file
2
2
  import * as Externals from './_externals.mjs';
3
3
  import { Unique } from './_unique.mjs';
4
+ import { UnicodeRegExp } from './_regexp.mjs';
4
5
  import { Guard as G, EmitGuard as E } from '../../guard/index.mjs';
5
6
  import { BuildSchemaPushStack, CheckSchemaPushStack, ErrorSchemaPushStack } from './schema.mjs';
6
7
  // ------------------------------------------------------------------
@@ -9,7 +10,7 @@ import { BuildSchemaPushStack, CheckSchemaPushStack, ErrorSchemaPushStack } from
9
10
  export function BuildPatternProperties(stack, context, schema, value) {
10
11
  return E.ReduceAnd(G.Entries(schema.patternProperties).map(([pattern, schema]) => {
11
12
  const [key, prop] = [Unique(), Unique()];
12
- const regexp = Externals.CreateVariable(new RegExp(pattern, 'u'));
13
+ const regexp = Externals.CreateVariable(UnicodeRegExp(pattern));
13
14
  const notKey = E.Not(E.Call(E.Member(regexp, 'test'), [key]));
14
15
  const isSchema = BuildSchemaPushStack(stack, context, schema, prop);
15
16
  const addKey = context.AddKey(key);
@@ -22,7 +23,7 @@ export function BuildPatternProperties(stack, context, schema, value) {
22
23
  // ------------------------------------------------------------------
23
24
  export function CheckPatternProperties(stack, context, schema, value) {
24
25
  return G.Every(G.Entries(schema.patternProperties), 0, ([pattern, schema]) => {
25
- const regexp = new RegExp(pattern, 'u');
26
+ const regexp = UnicodeRegExp(pattern);
26
27
  return G.Every(G.Entries(value), 0, ([key, prop]) => {
27
28
  return !regexp.test(key) || CheckSchemaPushStack(stack, context, schema, prop) && context.AddKey(key);
28
29
  });
@@ -34,7 +35,7 @@ export function CheckPatternProperties(stack, context, schema, value) {
34
35
  export function ErrorPatternProperties(stack, context, schemaPath, instancePath, schema, value) {
35
36
  return G.EveryAll(G.Entries(schema.patternProperties), 0, ([pattern, schema]) => {
36
37
  const nextSchemaPath = `${schemaPath}/patternProperties/${pattern}`;
37
- const regexp = new RegExp(pattern, 'u');
38
+ const regexp = UnicodeRegExp(pattern);
38
39
  return G.EveryAll(G.Entries(value), 0, ([key, value]) => {
39
40
  const nextInstancePath = `${instancePath}/${key}`;
40
41
  const notKey = !regexp.test(key);
@@ -45,12 +45,21 @@ import { BuildUnevaluatedItems, CheckUnevaluatedItems, ErrorUnevaluatedItems } f
45
45
  import { BuildUnevaluatedProperties, CheckUnevaluatedProperties, ErrorUnevaluatedProperties } from './unevaluatedProperties.mjs';
46
46
  import { BuildUniqueItems, CheckUniqueItems, ErrorUniqueItems } from './uniqueItems.mjs';
47
47
  // ----------------------------------------------------------------
48
- // HasTypeName
48
+ // HasTypeName (Optimization)
49
+ //
50
+ // We only consider a schema as having a type name when the schema
51
+ // has a single type string, or when every element in the type
52
+ // array is the same. For a type array, we must treat multi-variant
53
+ // types as unions and therefore can NOT use an optimized forward
54
+ // type check.
55
+ //
49
56
  // ----------------------------------------------------------------
50
57
  function HasTypeName(schema, typename) {
51
- return Schema.IsType(schema) &&
52
- (G.IsArray(schema.type) && G.IsGreaterThan(schema.type.length, 0) && G.Every(schema.type, 0, type => G.IsEqual(type, typename)) ||
53
- G.IsEqual(schema.type, typename));
58
+ return (Schema.IsType(schema) &&
59
+ ((G.IsArray(schema.type) &&
60
+ G.IsGreaterThan(schema.type.length, 0) &&
61
+ G.Every(schema.type, 0, type => G.IsEqual(type, typename))) ||
62
+ G.IsEqual(schema.type, typename)));
54
63
  }
55
64
  // ----------------------------------------------------------------
56
65
  // HasObject
@@ -1,3 +1,4 @@
1
1
  import * as Schema from '../types/index.mjs';
2
+ export declare const DefaultBase: URL;
2
3
  export declare function Ref(schema: Schema.XSchemaObject, ref: string): Schema.XSchema | undefined;
3
4
  export declare function DynamicRef(root: Schema.XSchemaObject, base: Schema.XSchemaObject, dynamicRef: Schema.XDynamicRef, dynamicAnchors: Schema.XDynamicAnchor[]): Schema.XSchema | undefined;
@@ -3,6 +3,10 @@ import { Guard } from '../../guard/index.mjs';
3
3
  import { Pointer } from '../pointer/index.mjs';
4
4
  import * as Schema from '../types/index.mjs';
5
5
  // ------------------------------------------------------------------
6
+ // DefaultBase
7
+ // ------------------------------------------------------------------
8
+ export const DefaultBase = new URL('https://json-schema.org');
9
+ // ------------------------------------------------------------------
6
10
  // Match: Id
7
11
  // ------------------------------------------------------------------
8
12
  function MatchId(schema, base, ref) {
@@ -83,8 +87,15 @@ function FromArray(schema, base, ref) {
83
87
  // ------------------------------------------------------------------
84
88
  // FromObject
85
89
  // ------------------------------------------------------------------
90
+ function SkipProperty(key) {
91
+ // these are explicit data encoded in a schema, they should not
92
+ // be considered valid targets used for de-referencing.
93
+ return Guard.IsEqual(key, 'const') || Guard.IsEqual(key, 'enum');
94
+ }
86
95
  function FromObject(schema, base, ref) {
87
96
  return Guard.Keys(schema).reduce((result, key) => {
97
+ if (SkipProperty(key))
98
+ return result;
88
99
  const match = FromValue(schema[key], base, ref);
89
100
  return !Guard.IsUndefined(match) ? match : result;
90
101
  }, undefined);
@@ -111,8 +122,7 @@ function FromValue(schema, base, ref) {
111
122
  // Ref
112
123
  // ------------------------------------------------------------------
113
124
  export function Ref(schema, ref) {
114
- const defaultBase = new URL('http://unknown/');
115
- const initialBase = Schema.IsId(schema) ? new URL(schema.$id, defaultBase.href) : defaultBase;
125
+ const initialBase = Schema.IsId(schema) ? new URL(schema.$id, DefaultBase.href) : DefaultBase;
116
126
  const initialRef = new URL(ref, initialBase.href);
117
127
  return FromValue(schema, initialBase, initialRef);
118
128
  }
@@ -134,7 +144,7 @@ export function DynamicRef(root, base, dynamicRef, dynamicAnchors) {
134
144
  // Extract the fragment portion of the reference. According to the test suite,
135
145
  // only plain fragment names (e.g., "#foo") trigger the dynamic scope; JSON
136
146
  // Pointer fragments (e.g., "#/definitions/foo") bypass dynamic resolution.
137
- const fragment = new URL(dynamicRef.$dynamicRef, 'http://unknown/').hash;
147
+ const fragment = new URL(dynamicRef.$dynamicRef, DefaultBase).hash;
138
148
  if (fragment.startsWith('#/'))
139
149
  return fragmentTarget;
140
150
  // Search the live dynamic anchor stack for a schema whose $dynamicAnchor matches the
@@ -6,8 +6,6 @@ export * from './anchor.mjs';
6
6
  export * from './anyOf.mjs';
7
7
  export * from './const.mjs';
8
8
  export * from './contains.mjs';
9
- export * from './contentEncoding.mjs';
10
- export * from './contentMediaType.mjs';
11
9
  export * from './default.mjs';
12
10
  export * from './defs.mjs';
13
11
  export * from './dependencies.mjs';
@@ -12,8 +12,6 @@ export * from './anchor.mjs';
12
12
  export * from './anyOf.mjs';
13
13
  export * from './const.mjs';
14
14
  export * from './contains.mjs';
15
- export * from './contentEncoding.mjs';
16
- export * from './contentMediaType.mjs';
17
15
  export * from './default.mjs';
18
16
  export * from './defs.mjs';
19
17
  export * from './dependencies.mjs';
@@ -13,24 +13,27 @@ function FromClassInstance(value) {
13
13
  return value; // atomic
14
14
  }
15
15
  // ------------------------------------------------------------------
16
- // TypeObject
16
+ // SchemaObject
17
17
  //
18
- // Types have non-enumerable properties that MUST be preserved on Clone.
19
- // The following is the optimal path for TypeBox types.
18
+ // Schema objects have non-enumerable properties that MUST be preserved
19
+ // on Clone. The following is the optimal path these objects.
20
20
  // ------------------------------------------------------------------
21
- function IsTypeObject(value) {
21
+ function IsSchemaObject(value) {
22
22
  return (Guard.HasPropertyKey(value, '~kind') ||
23
23
  Guard.HasPropertyKey(value, '~unsafe'));
24
24
  }
25
- function FromTypeObject(value) {
25
+ function FromSchemaObject(value) {
26
26
  const result = {};
27
- const descriptors = Object.getOwnPropertyDescriptors(value);
28
- for (const key of Object.keys(descriptors)) {
27
+ for (const key of Guard.Keys(value)) {
29
28
  if (Guard.IsUnsafePropertyKey(key))
30
29
  continue; // (ignore: prototype-pollution)
31
- const descriptor = descriptors[key];
32
- if (Guard.HasPropertyKey(descriptor, 'value')) {
33
- Object.defineProperty(result, key, { ...descriptor, value: FromValue(descriptor.value) });
30
+ const descriptor = Object.getOwnPropertyDescriptor(value, key); // safe-name!
31
+ descriptor.value = FromValue(descriptor.value);
32
+ if (Guard.IsEqual(descriptor.enumerable, true)) {
33
+ result[key] = descriptor.value;
34
+ }
35
+ else {
36
+ Object.defineProperty(result, key, descriptor);
34
37
  }
35
38
  }
36
39
  return result;
@@ -55,7 +58,7 @@ function FromPlainObject(value) {
55
58
  // ------------------------------------------------------------------
56
59
  function FromObject(value) {
57
60
  return (Guard.IsClassInstance(value) ? FromClassInstance(value) :
58
- IsTypeObject(value) ? FromTypeObject(value) :
61
+ IsSchemaObject(value) ? FromSchemaObject(value) :
59
62
  FromPlainObject(value));
60
63
  }
61
64
  // ------------------------------------------------------------------
@@ -1,17 +1,18 @@
1
1
  // deno-lint-ignore-file no-explicit-any
2
2
  // deno-fmt-ignore-file
3
+ import { Guard } from '../../guard/index.mjs';
3
4
  import { Metrics } from './metrics.mjs';
4
5
  import { Clone } from './clone.mjs';
5
6
  /** Discards multiple property keys from the given object value */
6
7
  export function Discard(value, propertyKeys) {
7
8
  Metrics.discard += 1;
8
9
  const result = {};
9
- const descriptors = Object.getOwnPropertyDescriptors(Clone(value));
10
- const keysToDiscard = new Set(propertyKeys);
11
- for (const key of Object.keys(descriptors)) {
12
- if (keysToDiscard.has(key))
10
+ for (const key of Guard.Keys(value)) {
11
+ if (propertyKeys.includes(key))
13
12
  continue;
14
- Object.defineProperty(result, key, descriptors[key]);
13
+ const descriptor = Object.getOwnPropertyDescriptor(value, key); // safe-name!
14
+ descriptor.value = Clone(descriptor.value);
15
+ Object.defineProperty(result, key, descriptor);
15
16
  }
16
17
  return result;
17
18
  }
@@ -16,6 +16,15 @@ export interface TSettings {
16
16
  * @default 8
17
17
  */
18
18
  maxErrors: number;
19
+ /**
20
+ * Specifies the maximum number of instantiations allowed within a top-level generic instantiation
21
+ * context. This setting can be used to bound generic calls to a fixed count, which can be useful if
22
+ * evaluating string-encoded types originating from untrusted sources. Setting this value to 0 will
23
+ * disallow generics entirely, ensuring type instantiation runs linear.
24
+ *
25
+ * @default 128
26
+ */
27
+ maxInstantiationCount: number;
19
28
  /**
20
29
  * Enables or disables the use of runtime code evaluation to accelerate validation. By default,
21
30
  * TypeBox checks for `unsafe-eval` support in the environment before attempting to evaluate
@@ -3,6 +3,7 @@ import { Guard } from '../../guard/index.mjs';
3
3
  const settings = {
4
4
  immutableTypes: false,
5
5
  maxErrors: 8,
6
+ maxInstantiationCount: 128,
6
7
  useAcceleration: true,
7
8
  exactOptionalPropertyTypes: false,
8
9
  enumerableKind: false,
@@ -13,6 +14,7 @@ const settings = {
13
14
  export function Reset() {
14
15
  settings.immutableTypes = false;
15
16
  settings.maxErrors = 8;
17
+ settings.maxInstantiationCount = 128;
16
18
  settings.useAcceleration = true;
17
19
  settings.exactOptionalPropertyTypes = false;
18
20
  settings.enumerableKind = false;
@@ -1,12 +1,17 @@
1
1
  import { type TSchema } from '../../types/schema.mjs';
2
2
  import { type TUnion } from '../../types/union.mjs';
3
3
  import { type TDeferred } from '../../types/deferred.mjs';
4
+ import { type TEnum, type TEnumValue } from '../../types/enum.mjs';
5
+ import { type TTemplateLiteral } from '../../types/template_literal.mjs';
4
6
  import { type TRef } from '../../types/ref.mjs';
5
7
  import { type TParameter } from '../../types/parameter.mjs';
8
+ import { type TEvaluateTemplateLiteral } from '../evaluate/evaluate.mjs';
9
+ import { type TEvaluateEnum } from '../evaluate/evaluate.mjs';
6
10
  type TCollectDistributionNames<Expression extends TSchema, Result extends string[] = []> = (Expression extends TDeferred<'Conditional', [infer Left extends TSchema, infer _Right extends TSchema, infer True extends TSchema, infer False extends TSchema]> ? Left extends TRef ? TCollectDistributionNames<True, TCollectDistributionNames<False, [...Result, Left['$ref']]>> : TCollectDistributionNames<True, TCollectDistributionNames<False, Result>> : Expression extends TDeferred<'Mapped', [infer _Identifier extends TSchema, infer Type extends TSchema, infer _As extends TSchema, infer _Property extends TSchema]> ? (Type extends TDeferred<'KeyOf', [infer Ref extends TRef]> ? [...Result, Ref['$ref']] : Result) : Result);
7
11
  type TBuildDistributionArray<Parameters extends TParameter[], Names extends string[], Result extends boolean[] = []> = (Parameters extends [infer Left extends TParameter, ...infer Right extends TParameter[]] ? Left['name'] extends Names[number] ? TBuildDistributionArray<Right, Names, [...Result, true]> : TBuildDistributionArray<Right, Names, [...Result, false]> : Result);
8
12
  type TZipDistributionArray<Arguments extends TSchema[], DistributionArray extends boolean[], Result extends [boolean, TSchema][] = []> = (Arguments extends [infer ArgumentLeft extends TSchema, ...infer ArgumentRight extends TSchema[]] ? DistributionArray extends [infer BooleanLeft extends boolean, ...infer BooleanRight extends boolean[]] ? TZipDistributionArray<ArgumentRight, BooleanRight, [...Result, [BooleanLeft, ArgumentLeft]]> : Result : Result);
9
- type TExpand<Type extends TSchema> = (Type extends TUnion<infer Types extends TSchema[]> ? [...Types] : [Type]);
13
+ type TCanonicalArgument<Type extends TSchema> = (Type extends TTemplateLiteral<infer Pattern extends string> ? TEvaluateTemplateLiteral<Pattern> : Type extends TEnum<infer Values extends TEnumValue[]> ? TEvaluateEnum<Values> : Type);
14
+ type TExpand<Argument extends TSchema, CanonicalArgument extends TSchema = TCanonicalArgument<Argument>> = (CanonicalArgument extends TUnion<infer Types extends TSchema[]> ? [...Types] : [CanonicalArgument]);
10
15
  type TAppend<Current extends TSchema[][], Type extends TSchema, Result extends TSchema[][] = []> = (Current extends [infer Left extends TSchema[], ...infer Right extends TSchema[][]] ? TAppend<Right, Type, [...Result, [...Left, Type]]> : Result);
11
16
  type TCross<Current extends TSchema[][], Variants extends TSchema[], Result extends TSchema[][] = []> = (Variants extends [infer Left extends TSchema, ...infer Right extends TSchema[]] ? TCross<Current, Right, [...Result, ...TAppend<Current, Left>]> : Result);
12
17
  type TDistribute<ZippedArguments extends [boolean, TSchema][], Result extends TSchema[][] = [[]]> = (ZippedArguments extends [infer Left extends [boolean, TSchema], ...infer Right extends [boolean, TSchema][]] ? Left[0] extends true ? TDistribute<Right, TCross<Result, TExpand<Left[1]>>> : TDistribute<Right, TCross<Result, [Left[1]]>> : Result);
@@ -2,7 +2,14 @@
2
2
  import { Guard } from '../../../guard/index.mjs';
3
3
  import { IsUnion } from '../../types/union.mjs';
4
4
  import { IsDeferred } from '../../types/deferred.mjs';
5
+ import { IsEnum } from '../../types/enum.mjs';
6
+ import { IsTemplateLiteral } from '../../types/template_literal.mjs';
5
7
  import { IsRef } from '../../types/ref.mjs';
8
+ // ------------------------------------------------------------------
9
+ // Infrastructure
10
+ // ------------------------------------------------------------------
11
+ import { EvaluateTemplateLiteral } from '../evaluate/evaluate.mjs';
12
+ import { EvaluateEnum } from '../evaluate/evaluate.mjs';
6
13
  function CollectDistributionNames(expression, result = []) {
7
14
  return (
8
15
  // Conditional
@@ -21,10 +28,16 @@ function BuildDistributionArray(parameters, names) {
21
28
  function ZipDistributionArray(arguments_, distributionArray, result = []) {
22
29
  return Guard.ShiftLeft(arguments_, (argumentLeft, argumentRight) => Guard.ShiftLeft(distributionArray, (booleanLeft, booleanRight) => ZipDistributionArray(argumentRight, booleanRight, [...result, [booleanLeft, argumentLeft]]), () => result), () => result);
23
30
  }
31
+ function CanonicalArgument(type) {
32
+ return (IsTemplateLiteral(type) ? EvaluateTemplateLiteral(type.pattern) :
33
+ IsEnum(type) ? EvaluateEnum(type.enum) :
34
+ type);
35
+ }
24
36
  function Expand(type) {
25
- return (IsUnion(type)
26
- ? [...type.anyOf]
27
- : [type]);
37
+ const canonicalArgument = CanonicalArgument(type);
38
+ return (IsUnion(canonicalArgument)
39
+ ? [...canonicalArgument.anyOf]
40
+ : [canonicalArgument]);
28
41
  }
29
42
  function Append(current, type) {
30
43
  return current.reduce((result, left) => [...result, [...left, type]], []);
@@ -1,4 +1,5 @@
1
1
  // deno-fmt-ignore-file
2
+ import { Settings } from '../../../system/settings/index.mjs';
2
3
  import { Guard } from '../../../guard/index.mjs';
3
4
  import { CallConstruct } from '../../types/call.mjs';
4
5
  import { Ref } from '../../types/ref.mjs';
@@ -13,6 +14,26 @@ import { State } from '../instantiate.mjs';
13
14
  import { DistributeArguments } from './distribute_arguments.mjs';
14
15
  import { ResolveTarget } from './resolve_target.mjs';
15
16
  import { ResolveArgumentsContext } from './resolve_arguments.mjs';
17
+ // ------------------------------------------------------------------
18
+ // InstantiationGuard
19
+ // ------------------------------------------------------------------
20
+ let instantiationDepth = 0;
21
+ let instantiationCount = 0;
22
+ function InstantiationAssert() {
23
+ if (Guard.IsLessThan(instantiationCount, Settings.Get().maxInstantiationCount))
24
+ return;
25
+ throw Error('Type instantiation is excessively deep and possibly infinite');
26
+ }
27
+ function InstantiationIncrement() {
28
+ InstantiationAssert();
29
+ instantiationCount++;
30
+ instantiationDepth++;
31
+ }
32
+ function InstantiationDecrement() {
33
+ instantiationDepth--;
34
+ if (Guard.IsEqual(instantiationDepth, 0))
35
+ instantiationCount = 0;
36
+ }
16
37
  function Peek(state) {
17
38
  const result = Guard.IsGreaterThan(state.callstack.length, 0) ? state.callstack[state.callstack.length - 1] : '';
18
39
  return result;
@@ -22,12 +43,21 @@ function IsTailCall(state, name) {
22
43
  return result;
23
44
  }
24
45
  function CallDispatch(context, state, target, parameters, expression, arguments_) {
25
- const argumentsContext = ResolveArgumentsContext(context, state, parameters, arguments_);
26
- const returnType = InstantiateType(argumentsContext, State([...state['callstack'], target['$ref']], state['visited']), expression);
27
- return InstantiateType(argumentsContext, State([], []), returnType);
46
+ InstantiationIncrement();
47
+ try {
48
+ const argumentsContext = ResolveArgumentsContext(context, state, parameters, arguments_);
49
+ const returnType = InstantiateType(argumentsContext, State([...state['callstack'], target['$ref']], state['visited']), expression);
50
+ return InstantiateType(argumentsContext, State([], []), returnType);
51
+ }
52
+ finally {
53
+ InstantiationDecrement();
54
+ }
28
55
  }
29
56
  function CallDistributed(context, state, target, parameters, expression, distributedArguments) {
30
- return distributedArguments.reduce((result, arguments_) => [...result, CallDispatch(context, state, target, parameters, expression, arguments_)], []);
57
+ return distributedArguments.reduce((result, arguments_) => {
58
+ const returnType = CallDispatch(context, state, target, parameters, expression, arguments_);
59
+ return [...result, returnType];
60
+ }, []);
31
61
  }
32
62
  function CallImmediate(context, state, target, parameters, expression, arguments_) {
33
63
  const distributedArguments = DistributeArguments(parameters, arguments_, expression);
@@ -2,13 +2,13 @@ import { type TSchema } from '../../types/schema.mjs';
2
2
  import { type TAny } from '../../types/any.mjs';
3
3
  import { type TNever } from '../../types/never.mjs';
4
4
  import { type TObject } from '../../types/object.mjs';
5
- import { type TCompare, ResultRightInside, ResultLeftInside, ResultEqual } from './compare.mjs';
5
+ import { type TUnknown } from '../../types/unknown.mjs';
6
+ import { type TCompare, CompareResultLeftInside, CompareResultEqual, CompareResultDisjoint } from './compare.mjs';
6
7
  import { type TFlatten } from './flatten.mjs';
7
8
  import { type TEvaluateType } from './evaluate.mjs';
8
- type TBroadFilter<Type extends TSchema, Types extends TSchema[], Result extends TSchema[] = []> = (Types extends [infer Left extends TSchema, ...infer Right extends TSchema[]] ? TCompare<Type, Left> extends typeof ResultRightInside ? TBroadFilter<Type, Right, [...Result]> : TBroadFilter<Type, Right, [...Result, Left]> : Result);
9
- type TIsBroadestType<Type extends TSchema, Types extends TSchema[]> = (Types extends [infer Left extends TSchema, ...infer Right extends TSchema[]] ? TCompare<Type, Left> extends typeof ResultLeftInside | typeof ResultEqual ? false : TIsBroadestType<Type, Right> : true);
10
- type TBroadenType<Type extends TSchema, Types extends TSchema[], Evaluated extends TSchema = TEvaluateType<Type>, Result extends TSchema[] = (Evaluated extends TAny ? [Evaluated] : TIsBroadestType<Evaluated, Types> extends true ? [...TBroadFilter<Evaluated, Types>, Evaluated] : Types)> = Result;
11
- type TBroadenTypes<Types extends TSchema[], Result extends TSchema[] = []> = (Types extends [infer Left extends TSchema, ...infer Right extends TSchema[]] ? (Left extends TObject ? TBroadenTypes<Right, [...Result, Left]> : Left extends TNever ? TBroadenTypes<Right, Result> : TBroadenTypes<Right, TBroadenType<Left, Result>>) : Result);
9
+ type TBroadenFilter<Type extends TSchema, Types extends TSchema[], Result extends TSchema[] = [], All extends TSchema[] = Types> = (Types extends [infer Left extends TSchema, ...infer Right extends TSchema[]] ? TCompare<Type, Left> extends typeof CompareResultLeftInside | typeof CompareResultEqual ? All : TCompare<Type, Left> extends typeof CompareResultDisjoint ? TBroadenFilter<Type, Right, [...Result, Left], All> : TBroadenFilter<Type, Right, Result, All> : [...Result, Type]);
10
+ type TBroadenType<Type extends TSchema, Types extends TSchema[], Result extends TSchema[], Evaluated extends TSchema = TEvaluateType<Type>> = (Evaluated extends TAny ? [Evaluated] : Evaluated extends TUnknown ? [Evaluated] : Evaluated extends TNever ? TBroadenTypes<Types, Result> : Evaluated extends TObject ? TBroadenTypes<Types, [...Result, Evaluated]> : TBroadenTypes<Types, TBroadenFilter<Evaluated, Result>>);
11
+ type TBroadenTypes<Types extends TSchema[], Result extends TSchema[] = []> = (Types extends [infer Left extends TSchema, ...infer Right extends TSchema[]] ? TBroadenType<Left, Right, Result> : Result);
12
12
  export type TBroaden<Types extends TSchema[], Broadened extends TSchema[] = TBroadenTypes<Types>, Flattened extends TSchema[] = TFlatten<Broadened>> = Flattened;
13
13
  /** Broadens a set of types and returns either the most broad type, or union or disjoint types. */
14
14
  export declare function Broaden<Types extends TSchema[]>(types: [...Types]): TBroaden<Types>;
@@ -3,37 +3,31 @@ import { Guard } from '../../../guard/index.mjs';
3
3
  import { IsAny } from '../../types/any.mjs';
4
4
  import { IsNever } from '../../types/never.mjs';
5
5
  import { IsObject } from '../../types/object.mjs';
6
- import { Compare, ResultRightInside, ResultLeftInside, ResultEqual } from './compare.mjs';
6
+ import { IsUnknown } from '../../types/unknown.mjs';
7
+ import { Compare, CompareResultLeftInside, CompareResultEqual, CompareResultDisjoint } from './compare.mjs';
7
8
  import { Flatten } from './flatten.mjs';
8
9
  import { EvaluateType } from './evaluate.mjs';
9
- function BroadFilter(type, types) {
10
- return types.filter(left => {
11
- return Compare(type, left) === ResultRightInside
12
- ? false
13
- : true;
14
- });
15
- }
16
- function IsBroadestType(type, types) {
17
- const result = types.some(left => {
18
- const result = Compare(type, left);
19
- return Guard.IsEqual(result, ResultLeftInside) || Guard.IsEqual(result, ResultEqual);
20
- });
21
- return Guard.IsEqual(result, false);
10
+ function BroadenFilter(type, types, result = [], all = types) {
11
+ return Guard.ShiftLeft(types, (left, right) => {
12
+ const compare = Compare(type, left);
13
+ return ((Guard.IsEqual(compare, CompareResultLeftInside) || Guard.IsEqual(compare, CompareResultEqual))
14
+ ? all // Left in set. Return original All set.
15
+ : Guard.IsEqual(compare, CompareResultDisjoint)
16
+ ? BroadenFilter(type, right, [...result, left], all) // Left is disjoint, keep it
17
+ : BroadenFilter(type, right, result, all) // Left in Type, drop it
18
+ );
19
+ }, () => [...result, type]); // Type broadest in set
22
20
  }
23
- function BroadenType(type, types) {
21
+ function BroadenType(type, types, result) {
24
22
  const evaluated = EvaluateType(type);
25
- return (IsAny(evaluated) ? [evaluated] :
26
- IsBroadestType(evaluated, types)
27
- ? [...BroadFilter(evaluated, types), evaluated]
28
- : types);
23
+ return (IsAny(evaluated) ? [evaluated] : // terminate (always the most broad)
24
+ IsUnknown(evaluated) ? [evaluated] : // terminate (always the most broad)
25
+ IsNever(evaluated) ? BroadenTypes(types, result) : // ignored: never is dropped
26
+ IsObject(evaluated) ? BroadenTypes(types, [...result, evaluated]) : // objects are always considered (too expensive to compare)
27
+ BroadenTypes(types, BroadenFilter(evaluated, result)));
29
28
  }
30
- function BroadenTypes(types) {
31
- return types.reduce((result, left) => {
32
- return (IsObject(left) ? [...result, left] : // push
33
- IsNever(left) ? result : // ignore
34
- BroadenType(left, result) // broaden
35
- );
36
- }, []);
29
+ function BroadenTypes(types, result = []) {
30
+ return Guard.ShiftLeft(types, (left, right) => (BroadenType(left, right, result)), () => result);
37
31
  }
38
32
  /** Broadens a set of types and returns either the most broad type, or union or disjoint types. */
39
33
  export function Broaden(types) {
@@ -1,15 +1,11 @@
1
1
  import { type TSchema } from '../../types/index.mjs';
2
- import { type TUnknown } from '../../types/unknown.mjs';
3
2
  import { type TExtends, ExtendsResult } from "../../extends/index.mjs";
4
- export declare const ResultEqual = "equal";
5
- export declare const ResultDisjoint = "disjoint";
6
- export declare const ResultLeftInside = "left-inside";
7
- export declare const ResultRightInside = "right-inside";
8
- export type TCompareResult = typeof ResultEqual | typeof ResultDisjoint | typeof ResultLeftInside | typeof ResultRightInside;
3
+ export declare const CompareResultEqual = 0;
4
+ export declare const CompareResultDisjoint = 1;
5
+ export declare const CompareResultLeftInside = 2;
6
+ export declare const CompareResultRightInside = 3;
7
+ export type TCompareResult = (typeof CompareResultEqual | typeof CompareResultDisjoint | typeof CompareResultLeftInside | typeof CompareResultRightInside);
9
8
  /** Compares left and right types and determines their set relationship */
10
- export type TCompare<Left extends TSchema, Right extends TSchema, Extends extends [ExtendsResult.TResult, ExtendsResult.TResult] = [
11
- Left extends TUnknown ? ExtendsResult.TExtendsFalse : TExtends<{}, Left, Right>,
12
- Left extends TUnknown ? ExtendsResult.TExtendsTrue : TExtends<{}, Right, Left>
13
- ]> = (Extends extends [ExtendsResult.TExtendsTrueLike, ExtendsResult.TExtendsTrueLike] ? typeof ResultEqual : Extends extends [ExtendsResult.TExtendsTrueLike, ExtendsResult.TExtendsFalse] ? typeof ResultLeftInside : Extends extends [ExtendsResult.TExtendsFalse, ExtendsResult.TExtendsTrueLike] ? typeof ResultRightInside : typeof ResultDisjoint);
9
+ export type TCompare<Left extends TSchema, Right extends TSchema, Extends extends [ExtendsResult.TResult, ExtendsResult.TResult] = [TExtends<{}, Left, Right>, TExtends<{}, Right, Left>]> = (Extends extends [ExtendsResult.TExtendsTrueLike, ExtendsResult.TExtendsTrueLike] ? typeof CompareResultEqual : Extends extends [ExtendsResult.TExtendsTrueLike, ExtendsResult.TExtendsFalse] ? typeof CompareResultLeftInside : Extends extends [ExtendsResult.TExtendsFalse, ExtendsResult.TExtendsTrueLike] ? typeof CompareResultRightInside : typeof CompareResultDisjoint);
14
10
  /** Compares left and right types and determines their set relationship. */
15
11
  export declare function Compare<Left extends TSchema, Right extends TSchema>(left: Left, right: Right): TCompare<Left, Right>;