arktype 0.5.1 → 1.0.0-alpha

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 (93) hide show
  1. package/README.md +1 -1
  2. package/dist/api.cjs +4 -2
  3. package/dist/api.d.ts +1 -1
  4. package/dist/api.mjs +1 -1
  5. package/dist/cjs/nodes/branch.js +3 -3
  6. package/dist/cjs/nodes/compose.js +4 -4
  7. package/dist/cjs/nodes/discriminate.js +2 -2
  8. package/dist/cjs/nodes/node.js +33 -30
  9. package/dist/cjs/nodes/predicate.js +1 -7
  10. package/dist/cjs/nodes/rules/props.js +39 -0
  11. package/dist/cjs/nodes/rules/rules.js +5 -2
  12. package/dist/cjs/parse/ast/config.js +13 -0
  13. package/dist/cjs/parse/ast/distributableFunction.js +2 -2
  14. package/dist/cjs/parse/ast/keyof.js +1 -1
  15. package/dist/cjs/parse/ast/morph.js +4 -3
  16. package/dist/cjs/parse/ast/narrow.js +8 -1
  17. package/dist/cjs/{nodes/infer.js → parse/ast/node.js} +0 -0
  18. package/dist/cjs/parse/ast/tuple.js +2 -1
  19. package/dist/cjs/parse/definition.js +2 -2
  20. package/dist/cjs/parse/string/reduce/dynamic.js +2 -2
  21. package/dist/cjs/parse/string/shift/operand/unenclosed.js +1 -1
  22. package/dist/cjs/parse/string/string.js +3 -3
  23. package/dist/cjs/scopes/{standard.js → ark.js} +9 -8
  24. package/dist/cjs/scopes/expressions.js +9 -9
  25. package/dist/cjs/scopes/scope.js +73 -75
  26. package/dist/cjs/scopes/type.js +24 -38
  27. package/dist/cjs/scopes/validation/creditCard.js +47 -0
  28. package/dist/cjs/scopes/validation/date.js +63 -0
  29. package/dist/cjs/scopes/validation/validation.js +95 -0
  30. package/dist/cjs/traverse/problems.js +48 -19
  31. package/dist/cjs/traverse/traverse.js +80 -25
  32. package/dist/cjs/utils/generics.js +16 -0
  33. package/dist/cjs/utils/serialize.js +29 -53
  34. package/dist/mjs/nodes/branch.js +2 -2
  35. package/dist/mjs/nodes/compose.js +5 -5
  36. package/dist/mjs/nodes/discriminate.js +2 -2
  37. package/dist/mjs/nodes/node.js +31 -31
  38. package/dist/mjs/nodes/predicate.js +1 -6
  39. package/dist/mjs/nodes/rules/props.js +39 -0
  40. package/dist/mjs/nodes/rules/rules.js +5 -2
  41. package/dist/mjs/parse/ast/config.js +5 -0
  42. package/dist/mjs/parse/ast/distributableFunction.js +2 -2
  43. package/dist/mjs/parse/ast/keyof.js +1 -1
  44. package/dist/mjs/parse/ast/morph.js +5 -4
  45. package/dist/mjs/parse/ast/narrow.js +9 -2
  46. package/dist/mjs/{nodes/infer.js → parse/ast/node.js} +0 -0
  47. package/dist/mjs/parse/ast/tuple.js +2 -1
  48. package/dist/mjs/parse/definition.js +2 -2
  49. package/dist/mjs/parse/string/reduce/dynamic.js +2 -2
  50. package/dist/mjs/parse/string/shift/operand/unenclosed.js +1 -1
  51. package/dist/mjs/parse/string/string.js +3 -3
  52. package/dist/mjs/scopes/{standard.js → ark.js} +8 -7
  53. package/dist/mjs/scopes/expressions.js +9 -9
  54. package/dist/mjs/scopes/scope.js +70 -76
  55. package/dist/mjs/scopes/type.js +22 -38
  56. package/dist/mjs/scopes/validation/creditCard.js +34 -0
  57. package/dist/mjs/scopes/validation/date.js +49 -0
  58. package/dist/mjs/scopes/validation/validation.js +81 -0
  59. package/dist/mjs/traverse/problems.js +45 -18
  60. package/dist/mjs/traverse/traverse.js +82 -27
  61. package/dist/mjs/utils/generics.js +11 -0
  62. package/dist/mjs/utils/serialize.js +29 -52
  63. package/dist/tsconfig.temp.tsbuildinfo +1 -1
  64. package/dist/types/nodes/branch.d.ts +8 -6
  65. package/dist/types/nodes/node.d.ts +24 -12
  66. package/dist/types/nodes/predicate.d.ts +4 -8
  67. package/dist/types/nodes/rules/props.d.ts +23 -8
  68. package/dist/types/nodes/rules/rules.d.ts +2 -2
  69. package/dist/types/parse/ast/ast.d.ts +1 -1
  70. package/dist/types/parse/ast/config.d.ts +10 -0
  71. package/dist/types/parse/ast/distributableFunction.d.ts +1 -1
  72. package/dist/types/parse/ast/morph.d.ts +2 -2
  73. package/dist/types/parse/ast/narrow.d.ts +1 -1
  74. package/dist/types/{nodes/infer.d.ts → parse/ast/node.d.ts} +14 -14
  75. package/dist/types/parse/ast/tuple.d.ts +8 -7
  76. package/dist/types/parse/definition.d.ts +2 -2
  77. package/dist/types/parse/string/reduce/dynamic.d.ts +5 -5
  78. package/dist/types/parse/string/string.d.ts +3 -3
  79. package/dist/types/scopes/{standard.d.ts → ark.d.ts} +15 -86
  80. package/dist/types/scopes/expressions.d.ts +3 -3
  81. package/dist/types/scopes/scope.d.ts +24 -11
  82. package/dist/types/scopes/type.d.ts +37 -20
  83. package/dist/types/scopes/validation/creditCard.d.ts +2 -0
  84. package/dist/types/scopes/validation/date.d.ts +23 -0
  85. package/dist/types/scopes/validation/validation.d.ts +28 -0
  86. package/dist/types/traverse/problems.d.ts +14 -8
  87. package/dist/types/traverse/traverse.d.ts +18 -3
  88. package/dist/types/utils/generics.d.ts +10 -5
  89. package/dist/types/utils/serialize.d.ts +0 -1
  90. package/package.json +2 -2
  91. package/dist/cjs/scopes/validation.js +0 -79
  92. package/dist/mjs/scopes/validation.js +0 -66
  93. package/dist/types/scopes/validation.d.ts +0 -25
@@ -65,6 +65,11 @@ const propKeysIntersection = composeKeyedIntersection((propKey, l, r, context)=>
65
65
  onEmpty: "bubble"
66
66
  });
67
67
  export const flattenProps = (entries, props, ctx)=>{
68
+ const keyConfig = ctx.type.config?.keys ?? ctx.type.scope.config.keys;
69
+ return keyConfig === "loose" ? flattenLooseProps(entries, props, ctx) : flattenPropsRecord(keyConfig, entries, props, ctx);
70
+ };
71
+ const flattenLooseProps = (entries, props, ctx)=>{
72
+ // if we don't care about extraneous keys, flatten props so we can iterate over the definitions directly
68
73
  for(const k in props){
69
74
  const prop = props[k];
70
75
  ctx.path.push(k);
@@ -101,3 +106,37 @@ export const flattenProps = (entries, props, ctx)=>{
101
106
  ctx.path.pop();
102
107
  }
103
108
  };
109
+ const flattenPropsRecord = (kind, entries, props, ctx)=>{
110
+ const result = {
111
+ required: {},
112
+ optional: {}
113
+ };
114
+ // if we need to keep track of extraneous keys, either to add problems or
115
+ // remove them, store the props as a Record to optimize for presence
116
+ // checking as we iterate over the data
117
+ for(const k in props){
118
+ const prop = props[k];
119
+ ctx.path.push(k);
120
+ if (k === mappedKeys.index) {
121
+ result.index = flattenNode(propToNode(prop), ctx);
122
+ } else if (isOptional(prop)) {
123
+ result.optional[k] = flattenNode(prop[1], ctx);
124
+ } else if (isPrerequisite(prop)) {
125
+ // we still have to push prerequisite props as normal entries so they can be checked first
126
+ entries.push([
127
+ "prerequisiteProp",
128
+ [
129
+ k,
130
+ flattenNode(prop[1], ctx)
131
+ ]
132
+ ]);
133
+ } else {
134
+ result.required[k] = flattenNode(prop, ctx);
135
+ }
136
+ ctx.path.pop();
137
+ }
138
+ entries.push([
139
+ `${kind}Props`,
140
+ result
141
+ ]);
142
+ };
@@ -69,8 +69,9 @@ const ruleFlatteners = {
69
69
  }
70
70
  };
71
71
  export const precedenceMap = {
72
+ // Config: Applies before any checks
73
+ config: -1,
72
74
  // Critical: No other checks are performed if these fail
73
- config: 0,
74
75
  domain: 0,
75
76
  value: 0,
76
77
  domains: 0,
@@ -87,6 +88,8 @@ export const precedenceMap = {
87
88
  // is invalid
88
89
  prerequisiteProp: 2,
89
90
  // Deep: Performed if all shallow checks pass, even if one or more deep checks fail
91
+ distilledProps: 3,
92
+ strictProps: 3,
90
93
  requiredProp: 3,
91
94
  optionalProp: 3,
92
95
  indexProp: 3,
@@ -95,7 +98,7 @@ export const precedenceMap = {
95
98
  // Morph: Only performed if all validation passes
96
99
  morph: 5
97
100
  };
98
- export const literalSatisfiesRules = (data, rules, state)=>!state.type.meta.scope.type([
101
+ export const literalSatisfiesRules = (data, rules, state)=>!state.type.scope.type([
99
102
  "node",
100
103
  {
101
104
  [state.domain]: rules
@@ -0,0 +1,5 @@
1
+ import { parseDefinition } from "../definition.js";
2
+ export const parseConfigTuple = (def, ctx)=>({
3
+ node: ctx.type.scope.resolveTypeNode(parseDefinition(def[0], ctx)),
4
+ config: def[2]
5
+ });
@@ -3,8 +3,8 @@ import { throwParseError } from "../../utils/errors.js";
3
3
  import { objectKeysOf } from "../../utils/generics.js";
4
4
  import { stringify } from "../../utils/serialize.js";
5
5
  export const writeMalformedDistributableFunctionMessage = (def)=>`Expected a Function or Record<Domain, Function> operand (${stringify(def)} was invalid)`;
6
- export const distributeFunctionToNode = (distributableFunction, inputNode, ctx, ruleKey)=>{
7
- const domains = objectKeysOf(ctx.type.meta.scope.resolveNode(inputNode));
6
+ export const distributeFunctionToNode = (distributableFunction, node, ctx, ruleKey)=>{
7
+ const domains = objectKeysOf(node);
8
8
  if (!hasDomain(distributableFunction, "object")) {
9
9
  return throwParseError(writeMalformedDistributableFunctionMessage(distributableFunction));
10
10
  }
@@ -21,7 +21,7 @@ const arrayIndexNumberBranch = deepFreeze({
21
21
  divisor: 1
22
22
  });
23
23
  export const parseKeyOfTuple = (def, ctx)=>{
24
- const resolution = ctx.type.meta.scope.resolveNode(parseDefinition(def[1], ctx));
24
+ const resolution = ctx.type.scope.resolveNode(parseDefinition(def[1], ctx));
25
25
  const predicateKeys = objectKeysOf(resolution).map((domain)=>keysOfPredicate(domain, resolution[domain]));
26
26
  const sharedKeys = sharedKeysOf(predicateKeys);
27
27
  if (!sharedKeys.length) {
@@ -1,4 +1,4 @@
1
- import { isMorphBranch } from "../../nodes/branch.js";
1
+ import { isTransformationBranch } from "../../nodes/branch.js";
2
2
  import { throwInternalError, throwParseError } from "../../utils/errors.js";
3
3
  import { isArray } from "../../utils/objectKinds.js";
4
4
  import { stringify } from "../../utils/serialize.js";
@@ -7,9 +7,10 @@ export const parseMorphTuple = (def, ctx)=>{
7
7
  if (typeof def[2] !== "function") {
8
8
  return throwParseError(writeMalformedMorphExpressionMessage(def[2]));
9
9
  }
10
- const resolution = ctx.type.meta.scope.resolveNode(parseDefinition(def[0], ctx));
10
+ const node = parseDefinition(def[0], ctx);
11
+ const resolution = ctx.type.scope.resolveTypeNode(node);
11
12
  const morph = def[2];
12
- ctx.type.meta.includesMorph = true;
13
+ ctx.type.includesMorph = true;
13
14
  let domain;
14
15
  const result = {};
15
16
  for(domain in resolution){
@@ -27,7 +28,7 @@ export const parseMorphTuple = (def, ctx)=>{
27
28
  }
28
29
  return result;
29
30
  };
30
- const applyMorph = (branch, morph)=>isMorphBranch(branch) ? {
31
+ const applyMorph = (branch, morph)=>isTransformationBranch(branch) ? {
31
32
  ...branch,
32
33
  morph: branch.morph ? Array.isArray(branch.morph) ? [
33
34
  ...branch.morph,
@@ -1,7 +1,14 @@
1
- import { rootIntersection } from "../../nodes/node.js";
1
+ import { isConfigNode, rootIntersection } from "../../nodes/node.js";
2
2
  import { parseDefinition } from "../definition.js";
3
3
  import { distributeFunctionToNode } from "./distributableFunction.js";
4
4
  export const parseNarrowTuple = (def, ctx)=>{
5
5
  const inputNode = parseDefinition(def[0], ctx);
6
- return rootIntersection(inputNode, distributeFunctionToNode(def[2], inputNode, ctx, "narrow"), ctx.type);
6
+ const resolution = ctx.type.scope.resolveNode(inputNode);
7
+ const hasConfig = isConfigNode(resolution);
8
+ const typeNode = hasConfig ? resolution.node : resolution;
9
+ const result = rootIntersection(inputNode, distributeFunctionToNode(def[2], typeNode, ctx, "narrow"), ctx.type);
10
+ return hasConfig ? {
11
+ config: resolution.config,
12
+ node: result
13
+ } : result;
7
14
  };
File without changes
@@ -3,6 +3,7 @@ import { domainOf } from "../../utils/domains.js";
3
3
  import { throwParseError } from "../../utils/errors.js";
4
4
  import { parseDefinition } from "../definition.js";
5
5
  import { writeMissingRightOperandMessage } from "../string/shift/operand/unenclosed.js";
6
+ import { parseConfigTuple } from "./config.js";
6
7
  import { parseKeyOfTuple } from "./keyof.js";
7
8
  import { parseMorphTuple } from "./morph.js";
8
9
  import { parseNarrowTuple } from "./narrow.js";
@@ -55,7 +56,7 @@ const indexOneParsers = {
55
56
  "[]": parseArrayTuple,
56
57
  "=>": parseNarrowTuple,
57
58
  "|>": parseMorphTuple,
58
- ":": ()=>({})
59
+ ":": parseConfigTuple
59
60
  };
60
61
  const prefixParsers = {
61
62
  keyof: parseKeyOfTuple,
@@ -28,12 +28,12 @@ export const parseDefinition = (def, ctx)=>{
28
28
  };
29
29
  case "Function":
30
30
  if (isType(def)) {
31
- return def.node;
31
+ return ctx.type.scope.addAnonymousTypeReference(def, ctx);
32
32
  }
33
33
  if (isThunk(def)) {
34
34
  const returned = def();
35
35
  if (isType(returned)) {
36
- return returned.node;
36
+ return ctx.type.scope.addAnonymousTypeReference(returned, ctx);
37
37
  }
38
38
  }
39
39
  return throwParseError(writeBadDefinitionTypeMessage("Function"));
@@ -14,7 +14,7 @@ export class DynamicState {
14
14
  }
15
15
  resolveRoot() {
16
16
  this.assertHasRoot();
17
- return this.ctx.type.meta.scope.resolveNode(this.root);
17
+ return this.ctx.type.scope.resolveTypeNode(this.root);
18
18
  }
19
19
  rootToString() {
20
20
  this.assertHasRoot();
@@ -22,7 +22,7 @@ export class DynamicState {
22
22
  }
23
23
  ejectRootIfLimit() {
24
24
  this.assertHasRoot();
25
- const resolution = typeof this.root === "string" ? this.ctx.type.meta.scope.resolveNode(this.root) : this.root;
25
+ const resolution = typeof this.root === "string" ? this.ctx.type.scope.resolveNode(this.root) : this.root;
26
26
  if (isLiteralNode(resolution, "number")) {
27
27
  const limit = resolution.number.value;
28
28
  this.root = undefined;
@@ -4,7 +4,7 @@ export const parseUnenclosed = (s)=>{
4
4
  s.setRoot(unenclosedToNode(s, token));
5
5
  };
6
6
  const unenclosedToNode = (s, token)=>{
7
- if (s.ctx.type.meta.scope.addReferenceIfResolvable(token, s.ctx)) {
7
+ if (s.ctx.type.scope.addParsedReferenceIfResolvable(token, s.ctx)) {
8
8
  return token;
9
9
  }
10
10
  return maybeParseUnenclosedLiteral(token) ?? s.error(token === "" ? writeMissingOperandMessage(s) : writeUnresolvableMessage(token));
@@ -2,14 +2,14 @@ import { toArrayNode } from "../../nodes/node.js";
2
2
  import { DynamicState } from "./reduce/dynamic.js";
3
3
  import { parseOperand } from "./shift/operand/operand.js";
4
4
  import { parseOperator } from "./shift/operator/operator.js";
5
- export const parseString = (def, ctx)=>ctx.type.meta.scope.parseCache.get(def) ?? ctx.type.meta.scope.parseCache.set(def, maybeNaiveParse(def, ctx) ?? fullStringParse(def, ctx));
5
+ export const parseString = (def, ctx)=>ctx.type.scope.parseCache.get(def) ?? ctx.type.scope.parseCache.set(def, maybeNaiveParse(def, ctx) ?? fullStringParse(def, ctx));
6
6
  export const maybeNaiveParse = (def, ctx)=>{
7
- if (ctx.type.meta.scope.addReferenceIfResolvable(def, ctx)) {
7
+ if (ctx.type.scope.addParsedReferenceIfResolvable(def, ctx)) {
8
8
  return def;
9
9
  }
10
10
  if (def.endsWith("[]")) {
11
11
  const elementDef = def.slice(0, -2);
12
- if (ctx.type.meta.scope.addReferenceIfResolvable(def, ctx)) {
12
+ if (ctx.type.scope.addParsedReferenceIfResolvable(def, ctx)) {
13
13
  return toArrayNode(elementDef);
14
14
  }
15
15
  }
@@ -1,8 +1,8 @@
1
1
  import { jsObjects, jsObjectsScope } from "./jsObjects.js";
2
- import { scope } from "./scope.js";
2
+ import { rootScope, scope } from "./scope.js";
3
3
  import { tsKeywords, tsKeywordsScope } from "./tsKeywords.js";
4
- import { validation, validationScope } from "./validation.js";
5
- export const standardScope = scope({}, {
4
+ import { validation, validationScope } from "./validation/validation.js";
5
+ export const arkscope = scope({}, {
6
6
  name: "standard",
7
7
  includes: [
8
8
  tsKeywords,
@@ -11,17 +11,18 @@ export const standardScope = scope({}, {
11
11
  ],
12
12
  standard: false
13
13
  });
14
- export const standard = standardScope.compile();
14
+ export const ark = arkscope.compile();
15
15
  export const scopes = {
16
+ root: rootScope,
16
17
  tsKeywords: tsKeywordsScope,
17
18
  jsObjects: jsObjectsScope,
18
19
  validation: validationScope,
19
- standard: standardScope
20
+ ark: arkscope
20
21
  };
21
22
  export const spaces = {
22
23
  tsKeywords,
23
24
  jsObjects,
24
25
  validation,
25
- standard
26
+ ark
26
27
  };
27
- export const type = scopes.standard.type;
28
+ export const type = arkscope.type;
@@ -1,9 +1,9 @@
1
- import { scopes } from "./standard.js";
2
- export const intersection = scopes.standard.intersection;
3
- export const union = scopes.standard.union;
4
- export const arrayOf = scopes.standard.arrayOf;
5
- export const keyOf = scopes.standard.keyOf;
6
- export const instanceOf = scopes.standard.instanceOf;
7
- export const valueOf = scopes.standard.valueOf;
8
- export const narrow = scopes.standard.narrow;
9
- export const morph = scopes.standard.morph;
1
+ import { scopes } from "./ark.js";
2
+ export const intersection = scopes.ark.intersection;
3
+ export const union = scopes.ark.union;
4
+ export const arrayOf = scopes.ark.arrayOf;
5
+ export const keyOf = scopes.ark.keyOf;
6
+ export const instanceOf = scopes.ark.instanceOf;
7
+ export const valueOf = scopes.ark.valueOf;
8
+ export const narrow = scopes.ark.narrow;
9
+ export const morph = scopes.ark.morph;
@@ -19,29 +19,6 @@ function _classApplyDescriptorSet(receiver, descriptor, value) {
19
19
  descriptor.value = value;
20
20
  }
21
21
  }
22
- function _classApplyDescriptorUpdate(receiver, descriptor) {
23
- if (descriptor.set) {
24
- if (!descriptor.get) {
25
- throw new TypeError("attempted to read set only private field");
26
- }
27
- if (!("__destrWrapper" in descriptor)) {
28
- descriptor.__destrWrapper = {
29
- set value (v){
30
- descriptor.set.call(receiver, v);
31
- },
32
- get value () {
33
- return descriptor.get.call(receiver);
34
- }
35
- };
36
- }
37
- return descriptor.__destrWrapper;
38
- } else {
39
- if (!descriptor.writable) {
40
- throw new TypeError("attempted to set read only private field");
41
- }
42
- return descriptor;
43
- }
44
- }
45
22
  function _classExtractFieldDescriptor(receiver, privateMap, action) {
46
23
  if (!privateMap.has(receiver)) {
47
24
  throw new TypeError("attempted to " + action + " private field on non-instance");
@@ -61,10 +38,6 @@ function _classPrivateFieldSet(receiver, privateMap, value) {
61
38
  _classApplyDescriptorSet(receiver, descriptor, value);
62
39
  return value;
63
40
  }
64
- function _classPrivateFieldUpdate(receiver, privateMap) {
65
- var descriptor = _classExtractFieldDescriptor(receiver, privateMap, "update");
66
- return _classApplyDescriptorUpdate(receiver, descriptor);
67
- }
68
41
  function _classPrivateMethodGet(receiver, privateSet, fn) {
69
42
  if (!privateSet.has(receiver)) {
70
43
  throw new TypeError("attempted to get private field on non-instance");
@@ -75,22 +48,38 @@ function _classPrivateMethodInit(obj, privateSet) {
75
48
  _checkPrivateRedeclaration(obj, privateSet);
76
49
  privateSet.add(obj);
77
50
  }
78
- var _ctx_type_meta;
79
- import { flattenType } from "../nodes/node.js";
51
+ var _ctx_type, _ctx_type1;
52
+ import { flattenType, isConfigNode } from "../nodes/node.js";
80
53
  import { parseDefinition } from "../parse/definition.js";
54
+ import { compileProblemWriters } from "../traverse/problems.js";
81
55
  import { chainableNoOpProxy } from "../utils/chainableNoOpProxy.js";
82
56
  import { throwInternalError, throwParseError } from "../utils/errors.js";
83
57
  import { deepFreeze } from "../utils/freeze.js";
58
+ import { hasKeys } from "../utils/generics.js";
84
59
  import { Path } from "../utils/paths.js";
85
60
  import { Cache, FreezingCache } from "./cache.js";
86
61
  import { initializeType } from "./type.js";
62
+ export const compileScopeOptions = (opts)=>({
63
+ codes: compileProblemWriters(opts.codes),
64
+ keys: opts.keys ?? "loose"
65
+ });
87
66
  let anonymousScopeCount = 0;
88
67
  const scopeRegistry = {};
89
68
  const spaceRegistry = {};
90
- var _resolutions = /*#__PURE__*/ new WeakMap(), _exports = /*#__PURE__*/ new WeakMap(), _anonymousTypeCount = /*#__PURE__*/ new WeakMap(), _register = /*#__PURE__*/ new WeakSet(), _cacheSpaces = /*#__PURE__*/ new WeakSet(), _initializeContext = /*#__PURE__*/ new WeakSet(), _resolveRecurse = /*#__PURE__*/ new WeakSet();
69
+ export const isConfigTuple = (def)=>Array.isArray(def) && def[1] === ":";
70
+ var _resolutions = /*#__PURE__*/ new WeakMap(), _exports = /*#__PURE__*/ new WeakMap(), _register = /*#__PURE__*/ new WeakSet(), _cacheSpaces = /*#__PURE__*/ new WeakSet(), _initializeContext = /*#__PURE__*/ new WeakSet(), _resolveRecurse = /*#__PURE__*/ new WeakSet();
91
71
  export class Scope {
92
- createAnonymousTypeSuffix() {
93
- return ++_classPrivateFieldUpdate(this, _anonymousTypeCount).value;
72
+ getAnonymousQualifiedName(base) {
73
+ let increment = 0;
74
+ let id = base;
75
+ while(this.isResolvable(id)){
76
+ id = `${base}${increment++}`;
77
+ }
78
+ return `${this.name}.${id}`;
79
+ }
80
+ addAnonymousTypeReference(referencedType, ctx) {
81
+ (_ctx_type = ctx.type).includesMorph || (_ctx_type.includesMorph = referencedType.includesMorph);
82
+ return referencedType.node;
94
83
  }
95
84
  get infer() {
96
85
  return chainableNoOpProxy;
@@ -104,24 +93,32 @@ export class Scope {
104
93
  }
105
94
  return _classPrivateFieldGet(this, _exports).root;
106
95
  }
107
- addReferenceIfResolvable(name, ctx) {
108
- const resolution = _classPrivateMethodGet(this, _resolveRecurse, resolveRecurse).call(this, name, "undefined", []);
96
+ addParsedReferenceIfResolvable(name, ctx) {
97
+ const resolution = _classPrivateMethodGet(this, _resolveRecurse, resolveRecurse).call(this, name, "undefined", [
98
+ name
99
+ ]);
109
100
  if (!resolution) {
110
101
  return false;
111
102
  }
112
- (_ctx_type_meta = ctx.type.meta).includesMorph || (_ctx_type_meta.includesMorph = resolution.meta.includesMorph);
103
+ (_ctx_type1 = ctx.type).includesMorph || (_ctx_type1.includesMorph = resolution.includesMorph);
113
104
  return true;
114
105
  }
115
106
  resolve(name) {
116
- return _classPrivateMethodGet(this, _resolveRecurse, resolveRecurse).call(this, name, "throw", []);
107
+ return _classPrivateMethodGet(this, _resolveRecurse, resolveRecurse).call(this, name, "throw", [
108
+ name
109
+ ]);
117
110
  }
118
111
  resolveNode(node) {
119
- if (typeof node === "object") {
120
- return node;
121
- }
122
- return this.resolveNode(this.resolve(node).node);
112
+ return typeof node === "string" ? this.resolveNode(this.resolve(node).node) : node;
113
+ }
114
+ resolveTypeNode(node) {
115
+ const resolution = this.resolveNode(node);
116
+ return isConfigNode(resolution) ? resolution.node : resolution;
123
117
  }
124
- constructor(aliases, opts){
118
+ isResolvable(name) {
119
+ return _classPrivateFieldGet(this, _resolutions).has(name) || this.aliases[name];
120
+ }
121
+ constructor(aliases, opts = {}){
125
122
  _classPrivateMethodInit(this, _register);
126
123
  _classPrivateMethodInit(this, _cacheSpaces);
127
124
  _classPrivateMethodInit(this, _initializeContext);
@@ -134,16 +131,10 @@ export class Scope {
134
131
  writable: true,
135
132
  value: void 0
136
133
  });
137
- _classPrivateFieldInit(this, _anonymousTypeCount, {
138
- writable: true,
139
- value: void 0
140
- });
141
134
  this.aliases = aliases;
142
- this.opts = opts;
143
135
  this.parseCache = new FreezingCache();
144
136
  _classPrivateFieldSet(this, _resolutions, new Cache());
145
137
  _classPrivateFieldSet(this, _exports, new Cache());
146
- _classPrivateFieldSet(this, _anonymousTypeCount, 0);
147
138
  this.expressions = {
148
139
  intersection: (l, r, opts)=>this.type([
149
140
  l,
@@ -163,7 +154,7 @@ export class Scope {
163
154
  "keyof",
164
155
  def
165
156
  ], opts),
166
- fromNode: (def, opts)=>this.type([
157
+ node: (def, opts)=>this.type([
167
158
  "node",
168
159
  def
169
160
  ], opts),
@@ -194,17 +185,18 @@ export class Scope {
194
185
  this.instanceOf = this.expressions.instanceOf;
195
186
  this.narrow = this.expressions.narrow;
196
187
  this.morph = this.expressions.morph;
197
- this.type = Object.assign((def, opts = {})=>{
198
- if (opts.name && this.aliases[opts.name]) {
199
- return throwParseError(writeDuplicateAliasesMessage(opts.name));
200
- }
201
- const result = initializeType(def, opts, this);
202
- const ctx = _classPrivateMethodGet(this, _initializeContext, initializeContext).call(this, result);
203
- result.node = this.resolveNode(parseDefinition(def, ctx));
204
- result.flat = flattenType(result);
205
- return result;
188
+ this.type = Object.assign((def, config = {})=>{
189
+ const t = initializeType("λtype", def, config, this);
190
+ const ctx = _classPrivateMethodGet(this, _initializeContext, initializeContext).call(this, t);
191
+ const root = parseDefinition(def, ctx);
192
+ t.node = deepFreeze(hasKeys(config) ? {
193
+ config,
194
+ node: this.resolveTypeNode(root)
195
+ } : root);
196
+ t.flat = deepFreeze(flattenType(t));
197
+ return t;
206
198
  }, {
207
- from: this.expressions.fromNode
199
+ from: this.expressions.node
208
200
  });
209
201
  this.name = _classPrivateMethodGet(this, _register, register).call(this, opts);
210
202
  if (opts.standard !== false) {
@@ -218,9 +210,7 @@ export class Scope {
218
210
  if (opts.includes) {
219
211
  _classPrivateMethodGet(this, _cacheSpaces, cacheSpaces).call(this, opts.includes, "includes");
220
212
  }
221
- if (opts.config) {
222
- this.config = opts.config;
223
- }
213
+ this.config = compileScopeOptions(opts);
224
214
  }
225
215
  }
226
216
  function register(opts) {
@@ -252,28 +242,32 @@ function resolveRecurse(name, onUnresolvable, seen) {
252
242
  if (maybeCacheResult) {
253
243
  return maybeCacheResult;
254
244
  }
255
- if (!this.aliases[name]) {
245
+ const aliasDef = this.aliases[name];
246
+ if (!aliasDef) {
256
247
  return onUnresolvable === "throw" ? throwInternalError(`Unexpectedly failed to resolve alias '${name}'`) : undefined;
257
248
  }
258
- const type = initializeType(this.aliases[name], {
259
- name
260
- }, this);
261
- _classPrivateFieldGet(this, _resolutions).set(name, type);
262
- _classPrivateFieldGet(this, _exports).set(name, type);
263
- const ctx = _classPrivateMethodGet(this, _initializeContext, initializeContext).call(this, type);
264
- let resolution = parseDefinition(type.meta.definition, ctx);
265
- if (typeof resolution === "string") {
266
- if (seen.includes(resolution)) {
249
+ const t = initializeType(name, aliasDef, {}, this);
250
+ const ctx = _classPrivateMethodGet(this, _initializeContext, initializeContext).call(this, t);
251
+ _classPrivateFieldGet(this, _resolutions).set(name, t);
252
+ _classPrivateFieldGet(this, _exports).set(name, t);
253
+ let node = parseDefinition(aliasDef, ctx);
254
+ if (typeof node === "string") {
255
+ if (seen.includes(node)) {
267
256
  return throwParseError(writeShallowCycleErrorMessage(name, seen));
268
257
  }
269
- seen.push(resolution);
270
- resolution = _classPrivateMethodGet(this, _resolveRecurse, resolveRecurse).call(this, resolution, "throw", seen).node;
258
+ seen.push(node);
259
+ node = _classPrivateMethodGet(this, _resolveRecurse, resolveRecurse).call(this, node, "throw", seen).node;
271
260
  }
272
- type.node = deepFreeze(resolution);
273
- type.flat = deepFreeze(flattenType(type));
274
- return type;
261
+ t.node = deepFreeze(node);
262
+ t.flat = deepFreeze(flattenType(t));
263
+ return t;
275
264
  }
276
265
  export const scope = (aliases, opts = {})=>new Scope(aliases, opts);
266
+ export const rootScope = scope({}, {
267
+ name: "root",
268
+ standard: false
269
+ });
270
+ export const rootType = rootScope.type;
277
271
  export const writeShallowCycleErrorMessage = (name, seen)=>`Alias '${name}' has a shallow resolution cycle: ${[
278
272
  ...seen,
279
273
  name
@@ -1,26 +1,16 @@
1
1
  import { TraversalState, traverse } from "../traverse/traverse.js";
2
2
  import { chainableNoOpProxy } from "../utils/chainableNoOpProxy.js";
3
- import { hasKeys } from "../utils/generics.js";
4
- const compileTypeConfig = (opts)=>{
5
- if (opts === undefined) {
6
- return;
7
- }
8
- const { name , ...config } = opts;
9
- if (hasKeys(config)) {
10
- return config;
11
- }
12
- };
13
- export const initializeType = (definition, opts, scope)=>{
14
- const name = opts?.name ?? "type";
15
- const config = compileTypeConfig(opts);
16
- const meta = {
17
- name,
18
- id: `${scope.name}.${opts?.name ? name : `type${scope.createAnonymousTypeSuffix()}`}`,
19
- definition,
20
- scope,
21
- config,
22
- includesMorph: false
23
- };
3
+ import { composeNamed, getNominalId } from "../utils/generics.js";
4
+ export const initializeType = (name, definition, config, scope)=>{
5
+ const namedTraverse = composeNamed((data)=>{
6
+ const state = new TraversalState(data, t);
7
+ traverse(t.flat, state);
8
+ return state.problems.count ? {
9
+ problems: state.problems
10
+ } : {
11
+ data: state.data
12
+ };
13
+ }, name);
24
14
  const root = {
25
15
  // temporarily initialize node/flat to aliases that will be included in
26
16
  // the final type in case of cyclic resolutions
@@ -31,23 +21,17 @@ export const initializeType = (definition, opts, scope)=>{
31
21
  name
32
22
  ]
33
23
  ],
34
- meta,
35
- infer: chainableNoOpProxy
24
+ allows: (data)=>!namedTraverse(data).problems,
25
+ infer: chainableNoOpProxy,
26
+ qualifiedName: isAnonymousName(name) ? scope.getAnonymousQualifiedName(name) : `${scope.name}.${name}`,
27
+ definition,
28
+ scope,
29
+ includesMorph: false,
30
+ config
36
31
  };
37
- // dynamically assign a name to the primary traversal function
38
- const namedTraverse = {
39
- [name]: (data)=>{
40
- const state = new TraversalState(data, type);
41
- return traverse(type.flat, state) ? {
42
- data: state.data
43
- } : {
44
- problems: state.problems
45
- };
46
- }
47
- }[name];
48
- // we need to assign this to a variable before returning so we can reference
49
- // it in namedTraverse
50
- const type = Object.assign(namedTraverse, root);
51
- return type;
32
+ const t = Object.assign(namedTraverse, root);
33
+ return t;
52
34
  };
53
35
  export const isType = (value)=>value?.infer === chainableNoOpProxy;
36
+ export const isCheckResult = (value)=>getNominalId(value) !== undefined;
37
+ export const isAnonymousName = (name)=>name[0] === "λ";
@@ -0,0 +1,34 @@
1
+ import { rootType } from "../scope.js";
2
+ // https://github.com/validatorjs/validator.js/blob/master/src/lib/isLuhnNumber.js
3
+ export const isLuhnValid = (creditCardInput)=>{
4
+ const sanitized = creditCardInput.replace(/[- ]+/g, "");
5
+ let sum = 0;
6
+ let digit;
7
+ let tmpNum;
8
+ let shouldDouble;
9
+ for(let i = sanitized.length - 1; i >= 0; i--){
10
+ digit = sanitized.substring(i, i + 1);
11
+ tmpNum = parseInt(digit, 10);
12
+ if (shouldDouble) {
13
+ tmpNum *= 2;
14
+ if (tmpNum >= 10) {
15
+ sum += tmpNum % 10 + 1;
16
+ } else {
17
+ sum += tmpNum;
18
+ }
19
+ } else {
20
+ sum += tmpNum;
21
+ }
22
+ shouldDouble = !shouldDouble;
23
+ }
24
+ return !!(sum % 10 === 0 ? sanitized : false);
25
+ };
26
+ // https://github.com/validatorjs/validator.js/blob/master/src/lib/isCreditCard.js
27
+ const creditCardMatcher = /^(?:4[0-9]{12}(?:[0-9]{3,6})?|5[1-5][0-9]{14}|(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|6(?:011|5[0-9][0-9])[0-9]{12,15}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11}|6[27][0-9]{14}|^(81[0-9]{14,17}))$/;
28
+ export const creditCard = rootType([
29
+ creditCardMatcher,
30
+ "=>",
31
+ (s, problems)=>isLuhnValid(s) || !problems.mustBe("a valid credit card number")
32
+ ], {
33
+ mustBe: "a valid credit card number"
34
+ });