arktype 2.0.0-dev.25 → 2.0.0-dev.26

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.
@@ -1,4 +1,4 @@
1
- import { type keyError } from "@arktype/util";
1
+ import { type keyError, type WhiteSpaceToken } from "@arktype/util";
2
2
  import { writeUnexpectedCharacterMessage } from "./string/shift/operator/operator.js";
3
3
  import { Scanner } from "./string/shift/scanner.js";
4
4
  export type GenericDeclaration<name extends string = string, params extends string = string> = `${name}<${params}>`;
@@ -9,7 +9,7 @@ export declare const parseGenericParams: (def: string) => string[];
9
9
  export type parseGenericParams<def extends string> = _parseParams<def, "", []> extends infer result extends string[] ? "" extends result[number] ? GenericParamsParseError<emptyGenericParameterMessage> : result : never;
10
10
  export declare const emptyGenericParameterMessage = "An empty string is not a valid generic parameter name";
11
11
  export type emptyGenericParameterMessage = typeof emptyGenericParameterMessage;
12
- type _parseParams<unscanned extends string, param extends string, result extends string[]> = unscanned extends `${infer lookahead}${infer nextUnscanned}` ? lookahead extends "," ? _parseParams<nextUnscanned, "", [...result, param]> : lookahead extends Scanner.WhiteSpaceToken ? param extends "" ? _parseParams<Scanner.skipWhitespace<nextUnscanned>, "", result> : Scanner.skipWhitespace<nextUnscanned> extends (`${infer nextNonWhitespace}${infer rest}`) ? nextNonWhitespace extends "," ? _parseParams<rest, "", [...result, param]> : GenericParamsParseError<writeUnexpectedCharacterMessage<nextNonWhitespace, ",">> : [
12
+ type _parseParams<unscanned extends string, param extends string, result extends string[]> = unscanned extends `${infer lookahead}${infer nextUnscanned}` ? lookahead extends "," ? _parseParams<nextUnscanned, "", [...result, param]> : lookahead extends WhiteSpaceToken ? param extends "" ? _parseParams<Scanner.skipWhitespace<nextUnscanned>, "", result> : Scanner.skipWhitespace<nextUnscanned> extends (`${infer nextNonWhitespace}${infer rest}`) ? nextNonWhitespace extends "," ? _parseParams<rest, "", [...result, param]> : GenericParamsParseError<writeUnexpectedCharacterMessage<nextNonWhitespace, ",">> : [
13
13
  ...result,
14
14
  param
15
15
  ] : _parseParams<nextUnscanned, `${param}${lookahead}`, result> : param extends "" ? result : [...result, param];
@@ -1,12 +1,9 @@
1
- import { type BaseRoot, type DateLiteral, type Default, type distillOut, type of, type UndeclaredKeyBehavior, type writeInvalidPropertyKeyMessage } from "@arktype/schema";
2
- import { type anyOrNever, type BigintLiteral, type Dict, type ErrorMessage, type Key, type keyError, type merge, type NumberLiteral, type show } from "@arktype/util";
1
+ import { type BaseRoot, type Default, type DefaultableAst, type IndexNode, type of, type OptionalNode, type RequiredNode, type UndeclaredKeyBehavior, type writeInvalidPropertyKeyMessage } from "@arktype/schema";
2
+ import { type anyOrNever, type Dict, type ErrorMessage, type EscapeToken, type Key, type keyError, type listable, type merge, type show } from "@arktype/util";
3
3
  import type { ParseContext } from "../scope.js";
4
4
  import type { inferDefinition, validateDefinition } from "./definition.js";
5
5
  import type { astToString } from "./semantic/utils.js";
6
6
  import type { validateString } from "./semantic/validate.js";
7
- import type { StringLiteral } from "./string/shift/operand/enclosed.js";
8
- import { Scanner } from "./string/shift/scanner.js";
9
- import type { inferString } from "./string/string.js";
10
7
  export declare const parseObjectLiteral: (def: Dict, ctx: ParseContext) => BaseRoot;
11
8
  export declare const writeInvalidUndeclaredBehaviorMessage: (actual: unknown) => string;
12
9
  export declare const nonLeadingSpreadError = "Spread operator may only be used as the first key in an object";
@@ -15,14 +12,20 @@ export type inferObjectLiteral<def extends object, $, args> = show<"..." extends
15
12
  * Infers the contents of an object literal, ignoring a spread definition
16
13
  */
17
14
  type _inferObjectLiteral<def extends object, $, args> = {
18
- -readonly [k in keyof def as nonOptionalKeyFrom<k, $, args>]: def[k] extends (DefaultValueTuple<infer baseDef, infer defaultValue>) ? def[k] extends anyOrNever ? def[k] : (In?: inferDefinition<baseDef, $, args>) => Default<defaultValue> : def[k] extends DefaultValueString<infer baseDef, infer defaultDef> ? (In?: inferDefinition<baseDef, $, args>) => Default<inferDefinition<defaultDef, $, args>> : inferDefinition<def[k], $, args>;
15
+ -readonly [k in keyof def as nonOptionalKeyFrom<k, $, args>]: def[k] extends (DefaultValueTuple<infer baseDef, infer defaultValue>) ? def[k] extends anyOrNever ? def[k] : (In?: inferDefinition<baseDef, $, args>) => Default<defaultValue> : inferDefinition<def[k], $, args>;
19
16
  } & {
20
17
  -readonly [k in keyof def as optionalKeyFrom<k>]?: inferDefinition<def[k], $, args>;
21
18
  };
22
19
  export type validateObjectLiteral<def, $, args> = {
23
20
  [k in keyof def]: k extends IndexKey<infer indexDef> ? validateString<indexDef, $, args> extends ErrorMessage<infer message> ? keyError<message> : inferDefinition<indexDef, $, args> extends (PropertyKey | of<PropertyKey, {}>) ? validateDefinition<def[k], $, args> : keyError<writeInvalidPropertyKeyMessage<indexDef>> : k extends "..." ? inferDefinition<def[k], $, args> extends object ? validateDefinition<def[k], $, args> : keyError<writeInvalidSpreadTypeMessage<astToString<def[k]>>> : k extends "+" ? UndeclaredKeyBehavior : validateDefaultableValue<def, k, $, args>;
24
21
  };
25
- type validateDefaultableValue<def, k extends keyof def, $, args> = def[k] extends DefaultValueTuple ? validateDefaultValueTuple<def[k], k, $, args> : def[k] extends DefaultValueString ? validateDefaultValueString<def[k], k, $, args> : validateDefinition<def[k], $, args>;
22
+ type validateDefaultableValue<def, k extends keyof def, $, args> = def[k] extends DefaultValueTuple ? validateDefaultValueTuple<def[k], k, $, args> : validateDefinition<def[k], $, args> extends def[k] ? [
23
+ inferDefinition<def[k], $, args>,
24
+ parseKey<k>["kind"]
25
+ ] extends ([
26
+ DefaultableAst,
27
+ Exclude<ParsedKeyKind, "required">
28
+ ]) ? ErrorMessage<invalidDefaultKeyKindMessage> : validateDefinition<def[k], $, args> : validateDefinition<def[k], $, args>;
26
29
  type DefaultValueTuple<baseDef = unknown, defaultValue = unknown> = readonly [
27
30
  baseDef,
28
31
  "=",
@@ -33,17 +36,11 @@ type validateDefaultValueTuple<def extends DefaultValueTuple, k extends Property
33
36
  "=",
34
37
  inferDefinition<def[0], $, args>
35
38
  ] : ErrorMessage<invalidDefaultKeyKindMessage>;
36
- type DefaultValueString<baseDef extends string = string, defaultDef extends UnitLiteral = UnitLiteral> = `${baseDef}${typeof defaultValueStringOperator}${defaultDef}`;
37
- declare const defaultValueStringOperator = " = ";
38
- type validateDefaultValueString<def extends DefaultValueString, k extends PropertyKey, $, args> = def extends DefaultValueString<infer baseDef, infer defaultDef> ? parseKey<k>["kind"] extends "required" ? validateDefinition<baseDef, $, args> extends (infer e extends ErrorMessage) ? e : [
39
- distillOut<inferString<baseDef, {}, args>>,
40
- distillOut<inferString<defaultDef, {}, args>>
41
- ] extends [infer base, infer defaultValue] ? defaultValue extends base ? def : ErrorMessage<`${defaultDef} is not assignable to ${baseDef}`> : never : ErrorMessage<invalidDefaultKeyKindMessage> : never;
42
- type nonOptionalKeyFrom<k, $, args> = parseKey<k> extends PreparsedKey<"required", infer inner> ? inner : parseKey<k> extends PreparsedKey<"index", infer inner> ? Extract<inferDefinition<inner, $, args>, Key> : never;
39
+ type nonOptionalKeyFrom<k, $, args> = parseKey<k> extends PreparsedKey<"required", infer inner> ? inner : parseKey<k> extends PreparsedKey<"index", infer inner> ? inferDefinition<inner, $, args> extends infer t extends Key ? t : never : never;
43
40
  type optionalKeyFrom<k> = parseKey<k> extends PreparsedKey<"optional", infer inner> ? inner : never;
44
- type PreparsedKey<kind extends ParsedKeyKind = ParsedKeyKind, inner extends Key = Key> = {
41
+ type PreparsedKey<kind extends ParsedKeyKind = ParsedKeyKind, key extends Key = Key> = {
45
42
  kind: kind;
46
- key: inner;
43
+ key: key;
47
44
  };
48
45
  declare namespace PreparsedKey {
49
46
  type from<t extends PreparsedKey> = t;
@@ -51,23 +48,20 @@ declare namespace PreparsedKey {
51
48
  type ParsedKeyKind = "required" | "optional" | "index" | MetaKey;
52
49
  export type MetaKey = "..." | "+";
53
50
  export type IndexKey<def extends string = string> = `[${def}]`;
54
- interface PreparsedEntry extends PreparsedKey {
55
- value: unknown;
56
- default: unknown;
57
- }
58
- declare const unitLiteralKeywords: {
59
- readonly null: null;
60
- readonly undefined: undefined;
61
- readonly true: true;
62
- readonly false: false;
51
+ export type ParsedEntry = ParsedUndeclaredEntry | ParsedSpreadEntry | RequiredNode | OptionalNode | IndexNode;
52
+ export type ParsedUndeclaredEntry = {
53
+ kind: "undeclared";
54
+ behavior: UndeclaredKeyBehavior;
55
+ };
56
+ export type ParsedSpreadEntry = {
57
+ kind: "spread";
58
+ node: BaseRoot;
63
59
  };
64
- type UnitLiteralKeyword = keyof typeof unitLiteralKeywords;
65
- export type UnitLiteral = StringLiteral | BigintLiteral | NumberLiteral | DateLiteral | UnitLiteralKeyword;
66
- export declare const parseEntry: (key: Key, value: unknown) => PreparsedEntry;
60
+ export declare const parseEntry: (key: Key, value: unknown, ctx: ParseContext) => listable<ParsedEntry>;
67
61
  export declare const invalidDefaultKeyKindMessage = "Only required keys may specify default values, e.g. { value: 'number = 0' }";
68
62
  export type invalidDefaultKeyKindMessage = typeof invalidDefaultKeyKindMessage;
69
63
  declare const parseKey: (key: Key) => PreparsedKey;
70
- type parseKey<k> = k extends `${infer inner}?` ? inner extends `${infer baseName}${Scanner.EscapeToken}` ? PreparsedKey.from<{
64
+ type parseKey<k> = k extends `${infer inner}?` ? inner extends `${infer baseName}${EscapeToken}` ? PreparsedKey.from<{
71
65
  kind: "required";
72
66
  key: `${baseName}?`;
73
67
  }> : PreparsedKey.from<{
@@ -76,7 +70,7 @@ type parseKey<k> = k extends `${infer inner}?` ? inner extends `${infer baseName
76
70
  }> : k extends MetaKey ? PreparsedKey.from<{
77
71
  kind: k;
78
72
  key: k;
79
- }> : k extends `${Scanner.EscapeToken}${infer escapedMeta extends MetaKey}` ? PreparsedKey.from<{
73
+ }> : k extends `${EscapeToken}${infer escapedMeta extends MetaKey}` ? PreparsedKey.from<{
80
74
  kind: "required";
81
75
  key: escapedMeta;
82
76
  }> : k extends IndexKey<infer def> ? PreparsedKey.from<{
@@ -84,7 +78,7 @@ type parseKey<k> = k extends `${infer inner}?` ? inner extends `${infer baseName
84
78
  key: def;
85
79
  }> : PreparsedKey.from<{
86
80
  kind: "required";
87
- key: k extends (`${Scanner.EscapeToken}${infer escapedIndexKey extends IndexKey}`) ? escapedIndexKey : k extends Key ? k : `${k & number}`;
81
+ key: k extends `${EscapeToken}${infer escapedIndexKey extends IndexKey}` ? escapedIndexKey : k extends Key ? k : `${k & number}`;
88
82
  }>;
89
83
  export declare const writeInvalidSpreadTypeMessage: <def extends string>(def: def) => writeInvalidSpreadTypeMessage<def>;
90
84
  type writeInvalidSpreadTypeMessage<def extends string> = `Spread operand must resolve to an object literal type (was ${def})`;
@@ -1,6 +1,6 @@
1
1
  import { ArkErrors, normalizeIndex } from "@arktype/schema";
2
- import { anchoredRegex, append, deanchoredSource, integerLikeMatcher, isArray, keysOf, numberLikeMatcher, printable, stringAndSymbolicEntriesOf, throwInternalError, throwParseError, tryParseWellFormedBigint, tryParseWellFormedNumber, unset } from "@arktype/util";
3
- import { Scanner } from "./string/shift/scanner.js";
2
+ import { append, escapeToken, isArray, printable, stringAndSymbolicEntriesOf, throwParseError } from "@arktype/util";
3
+ import { writeUnassignableDefaultValueMessage } from "./semantic/default.js";
4
4
  export const parseObjectLiteral = (def, ctx) => {
5
5
  let spread;
6
6
  const structure = {};
@@ -8,53 +8,25 @@ export const parseObjectLiteral = (def, ctx) => {
8
8
  // because to match JS behavior any keys before the spread are overwritten
9
9
  // by the values in the target object, so there'd be no useful purpose in having it
10
10
  // anywhere except for the beginning.
11
- const parsedEntries = stringAndSymbolicEntriesOf(def).map(entry => parseEntry(entry[0], entry[1]));
12
- if (parsedEntries[0]?.kind === "...") {
11
+ const parsedEntries = stringAndSymbolicEntriesOf(def).flatMap(entry => parseEntry(entry[0], entry[1], ctx));
12
+ if (parsedEntries[0]?.kind === "spread") {
13
13
  // remove the spread entry so we can iterate over the remaining entries
14
14
  // expecting non-spread entries
15
15
  const spreadEntry = parsedEntries.shift();
16
- const spreadNode = ctx.$.parse(spreadEntry.value, ctx);
17
- if (!spreadNode.hasKind("intersection") || !spreadNode.structure) {
18
- return throwParseError(writeInvalidSpreadTypeMessage(typeof spreadEntry.value === "string" ?
19
- spreadEntry.value
20
- : printable(spreadEntry.value)));
16
+ if (!spreadEntry.node.hasKind("intersection") ||
17
+ !spreadEntry.node.structure) {
18
+ return throwParseError(writeInvalidSpreadTypeMessage(typeof spreadEntry.node.expression));
21
19
  }
22
- spread = spreadNode.structure;
20
+ spread = spreadEntry.node.structure;
23
21
  }
24
22
  for (const entry of parsedEntries) {
25
- if (entry.kind === "...")
23
+ if (entry.kind === "spread")
26
24
  return throwParseError(nonLeadingSpreadError);
27
- if (entry.kind === "+") {
28
- if (entry.value !== "reject" &&
29
- entry.value !== "delete" &&
30
- entry.value !== "ignore")
31
- throwParseError(writeInvalidUndeclaredBehaviorMessage(entry.value));
32
- structure.undeclared = entry.value;
25
+ if (entry.kind === "undeclared") {
26
+ structure.undeclared = entry.behavior;
33
27
  continue;
34
28
  }
35
- if (entry.kind === "index") {
36
- // handle key parsing first to match type behavior
37
- const key = ctx.$.parse(entry.key, ctx);
38
- const value = ctx.$.parse(entry.value, ctx);
39
- const normalizedSignature = normalizeIndex(key, value, ctx.$);
40
- if (normalizedSignature.required) {
41
- structure.required = append(structure.required, normalizedSignature.required);
42
- }
43
- if (normalizedSignature.index)
44
- structure.index = append(structure.index, normalizedSignature.index);
45
- }
46
- else {
47
- const value = ctx.$.parse(entry.value, ctx);
48
- const inner = { key: entry.key, value };
49
- if (entry.default !== unset) {
50
- const out = value.traverse(entry.default);
51
- if (out instanceof ArkErrors)
52
- throwParseError(`Default value at ${printable(entry.key)} ${out}`);
53
- value.assert(entry.default);
54
- inner.default = entry.default;
55
- }
56
- structure[entry.kind] = append(structure[entry.kind], inner);
57
- }
29
+ structure[entry.kind] = append(structure[entry.kind], entry);
58
30
  }
59
31
  const structureNode = ctx.$.node("structure", structure);
60
32
  return ctx.$.schema({
@@ -64,87 +36,50 @@ export const parseObjectLiteral = (def, ctx) => {
64
36
  };
65
37
  export const writeInvalidUndeclaredBehaviorMessage = (actual) => `Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${printable(actual)})`;
66
38
  export const nonLeadingSpreadError = "Spread operator may only be used as the first key in an object";
67
- const defaultValueStringOperator = " = ";
68
- const unitLiteralKeywords = {
69
- null: null,
70
- undefined,
71
- true: true,
72
- false: false
73
- };
74
- /** Matches a single or double-quoted date or string literal */
75
- const stringLiteral = anchoredRegex(/(?:"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/);
76
- /** Matches a definition including a valid default value expression */
77
- const defaultExpressionMatcher = new RegExp(`^(?<baseDef>[\\s\\S]*) = (` +
78
- `(?<string>${deanchoredSource(stringLiteral)})` +
79
- `|(?<date>d${deanchoredSource(stringLiteral)})` +
80
- `|(?<bigint>${deanchoredSource(integerLikeMatcher)}n)` +
81
- `|(?<number>${deanchoredSource(numberLikeMatcher)})` +
82
- `|(?<keyword>${keysOf(unitLiteralKeywords).join("|")})` +
83
- `)$`);
84
- const parsePossibleDefaultExpression = (s) => {
85
- const result = defaultExpressionMatcher.exec(s);
86
- return result && result.groups;
87
- };
88
- export const parseEntry = (key, value) => {
39
+ export const parseEntry = (key, value, ctx) => {
89
40
  const parsedKey = parseKey(key);
90
- if (isArray(value) && value[1] === "=") {
41
+ if (parsedKey.kind === "+") {
42
+ if (value !== "reject" && value !== "delete" && value !== "ignore")
43
+ throwParseError(writeInvalidUndeclaredBehaviorMessage(value));
44
+ return { kind: "undeclared", behavior: value };
45
+ }
46
+ if (parsedKey.kind === "...")
47
+ return { kind: "spread", node: ctx.$.parse(value, ctx) };
48
+ const parsedValue = isArray(value) && value[1] === "=" ?
49
+ [ctx.$.parse(value[0], ctx), "=", value[2]]
50
+ : ctx.$.parse(value, ctx, true);
51
+ if (isArray(parsedValue)) {
91
52
  if (parsedKey.kind !== "required")
92
53
  throwParseError(invalidDefaultKeyKindMessage);
93
- return {
94
- kind: "optional",
54
+ const out = parsedValue[0].traverse(parsedValue[2]);
55
+ if (out instanceof ArkErrors) {
56
+ throwParseError(writeUnassignableDefaultValueMessage(printable(parsedKey.key), out.message));
57
+ }
58
+ return ctx.$.node("optional", {
95
59
  key: parsedKey.key,
96
- value: value[0],
97
- default: value[2]
98
- };
99
- }
100
- // if a string includes " = ", it might have a default value,
101
- // but it could also be a string literal like "' = '"
102
- if (typeof value === "string" && value.includes(defaultValueStringOperator)) {
103
- const result = parsePossibleDefaultExpression(value);
104
- if (result)
105
- return parseDefaultValueStringExpression(parsedKey, result);
106
- }
107
- return {
108
- kind: parsedKey.kind,
109
- key: parsedKey.key,
110
- value,
111
- default: unset
112
- };
113
- };
114
- const parseDefaultValueStringExpression = (parsedKey, match) => {
115
- if (parsedKey.kind !== "required")
116
- throwParseError(invalidDefaultKeyKindMessage);
117
- let defaultValue;
118
- if (match.keyword)
119
- defaultValue = unitLiteralKeywords[match.keyword];
120
- else if (match.string)
121
- defaultValue = match.string.slice(1, -1);
122
- else if (match.number) {
123
- defaultValue = tryParseWellFormedNumber(match.number, {
124
- errorOnFail: true
60
+ value: parsedValue[0],
61
+ default: parsedValue[2]
125
62
  });
126
63
  }
127
- else if (match.date)
128
- defaultValue = new Date(match.date);
129
- else if (match.bigint) {
130
- defaultValue =
131
- tryParseWellFormedBigint(match.bigint) ??
132
- throwInternalError(`Unexpected default bigint parse result ${match.bigint}`);
64
+ if (parsedKey.kind === "index") {
65
+ const signature = ctx.$.parse(parsedKey.key, ctx);
66
+ const normalized = normalizeIndex(signature, parsedValue, ctx.$);
67
+ return (normalized.index ?
68
+ normalized.required ?
69
+ [normalized.index, ...normalized.required]
70
+ : normalized.index
71
+ : normalized.required ?? []);
133
72
  }
134
- else
135
- throwInternalError(`Unexpected default expression parse result ${match}`);
136
- return {
137
- kind: "optional",
73
+ return ctx.$.node(parsedKey.kind, {
138
74
  key: parsedKey.key,
139
- value: match.baseDef,
140
- default: defaultValue
141
- };
75
+ value: parsedValue
76
+ });
142
77
  };
143
78
  // single quote use here is better for TypeScript's inlined error to avoid escapes
144
79
  export const invalidDefaultKeyKindMessage = `Only required keys may specify default values, e.g. { value: 'number = 0' }`;
145
80
  const parseKey = (key) => typeof key === "symbol" ? { kind: "required", key }
146
81
  : key.at(-1) === "?" ?
147
- key.at(-2) === Scanner.escapeToken ?
82
+ key.at(-2) === escapeToken ?
148
83
  { kind: "required", key: `${key.slice(0, -2)}?` }
149
84
  : {
150
85
  kind: "optional",
@@ -152,13 +87,14 @@ const parseKey = (key) => typeof key === "symbol" ? { kind: "required", key }
152
87
  }
153
88
  : key[0] === "[" && key.at(-1) === "]" ?
154
89
  { kind: "index", key: key.slice(1, -1) }
155
- : key[0] === Scanner.escapeToken && key[1] === "[" && key.at(-1) === "]" ?
90
+ : key[0] === escapeToken && key[1] === "[" && key.at(-1) === "]" ?
156
91
  { kind: "required", key: key.slice(1) }
157
- : key === "..." || key === "+" ? { kind: key, key }
158
- : {
159
- kind: "required",
160
- key: key === "\\..." ? "..."
161
- : key === "\\+" ? "+"
162
- : key
163
- };
92
+ : key === "..." ? { kind: key, key }
93
+ : key === "+" ? { kind: key, key }
94
+ : {
95
+ kind: "required",
96
+ key: key === "\\..." ? "..."
97
+ : key === "\\+" ? "+"
98
+ : key
99
+ };
164
100
  export const writeInvalidSpreadTypeMessage = (def) => `Spread operand must resolve to an object literal type (was ${def})`;
@@ -0,0 +1,8 @@
1
+ import type { ErrorMessage } from "@arktype/util";
2
+ import type { UnitLiteral } from "../string/shift/operator/default.js";
3
+ import type { inferAstOut, inferTerminal } from "./infer.js";
4
+ import type { astToString } from "./utils.js";
5
+ import type { validateAst } from "./validate.js";
6
+ export type validateDefault<baseAst, unitLiteral extends UnitLiteral, $, args> = validateAst<baseAst, $, args> extends infer e extends ErrorMessage ? e : inferTerminal<unitLiteral, $, args> extends inferAstOut<baseAst, $, args> ? undefined : ErrorMessage<writeUnassignableDefaultValueMessage<astToString<baseAst>, unitLiteral>>;
7
+ export declare const writeUnassignableDefaultValueMessage: <key extends string, message extends string>(key: key, message: message) => string;
8
+ export type writeUnassignableDefaultValueMessage<baseDef extends string, defaultValue extends string> = `Default value ${defaultValue} is not assignable to ${baseDef}`;
@@ -0,0 +1 @@
1
+ export const writeUnassignableDefaultValueMessage = (key, message) => `Default value at ${key} ${message}`;
@@ -1,4 +1,4 @@
1
- import type { Date, DateLiteral, GenericProps, LimitLiteral, RegexLiteral, constrain, distillIn, inferIntersection, normalizeLimit, string } from "@arktype/schema";
1
+ import type { Date, DateLiteral, Default, GenericProps, LimitLiteral, RegexLiteral, constrain, distillIn, distillOut, inferIntersection, normalizeLimit, string } from "@arktype/schema";
2
2
  import type { BigintLiteral, array } from "@arktype/util";
3
3
  import type { UnparsedScope, resolve, tryInferSubmoduleReference } from "../../scope.js";
4
4
  import type { inferDefinition } from "../definition.js";
@@ -6,11 +6,12 @@ import type { Comparator, MinComparator } from "../string/reduce/shared.js";
6
6
  import type { StringLiteral } from "../string/shift/operand/enclosed.js";
7
7
  export type inferAstRoot<ast, $, args> = inferConstrainableAst<ast, $, args>;
8
8
  export type inferAstIn<ast, $, args> = distillIn<inferAstRoot<ast, $, args>>;
9
+ export type inferAstOut<ast, $, args> = distillOut<inferAstRoot<ast, $, args>>;
9
10
  export type inferConstrainableAst<ast, $, args> = ast extends array ? inferExpression<ast, $, args> : ast extends string ? inferTerminal<ast, $, args> : never;
10
11
  export type GenericInstantiationAst<generic extends GenericProps = GenericProps, argAsts extends unknown[] = unknown[]> = [generic, "<>", argAsts];
11
12
  export type inferExpression<ast extends array, $, args> = ast extends GenericInstantiationAst<infer generic, infer argAsts> ? inferDefinition<generic["def"], generic["$"]["t"] extends UnparsedScope ? $ : generic["$"]["t"], {
12
13
  [i in keyof generic["params"] & `${number}` as generic["params"][i]]: inferConstrainableAst<argAsts[i & keyof argAsts], $, args>;
13
- }> : ast[1] extends "[]" ? inferConstrainableAst<ast[0], $, args>[] : ast[1] extends "|" ? inferConstrainableAst<ast[0], $, args> | inferConstrainableAst<ast[2], $, args> : ast[1] extends "&" ? inferIntersection<inferConstrainableAst<ast[0], $, args>, inferConstrainableAst<ast[2], $, args>> : ast[1] extends Comparator ? ast[0] extends LimitLiteral ? constrainBound<inferConstrainableAst<ast[2], $, args>, ast[1], ast[0]> : constrainBound<inferConstrainableAst<ast[0], $, args>, ast[1], ast[2]> : ast[1] extends "%" ? constrain<inferConstrainableAst<ast[0], $, args>, "divisor", ast[2] & number> : ast[0] extends "keyof" ? keyof inferConstrainableAst<ast[1], $, args> : never;
14
+ }> : ast[1] extends "[]" ? inferConstrainableAst<ast[0], $, args>[] : ast[1] extends "|" ? inferConstrainableAst<ast[0], $, args> | inferConstrainableAst<ast[2], $, args> : ast[1] extends "&" ? inferIntersection<inferConstrainableAst<ast[0], $, args>, inferConstrainableAst<ast[2], $, args>> : ast[1] extends "=" ? inferTerminal<ast[2] & string, $, args> extends infer defaultValue ? (In?: inferConstrainableAst<ast[0], $, args>) => Default<defaultValue> : never : ast[1] extends Comparator ? ast[0] extends LimitLiteral ? constrainBound<inferConstrainableAst<ast[2], $, args>, ast[1], ast[0]> : constrainBound<inferConstrainableAst<ast[0], $, args>, ast[1], ast[2]> : ast[1] extends "%" ? constrain<inferConstrainableAst<ast[0], $, args>, "divisor", ast[2] & number> : ast[0] extends "keyof" ? keyof inferConstrainableAst<ast[1], $, args> : never;
14
15
  export type constrainBound<constrainableIn, comparator extends Comparator, limit> = distillIn<constrainableIn> extends infer In ? comparator extends "==" ? In extends number ? limit : In extends Date ? Date.literal<normalizeLimit<limit>> : constrain<constrainableIn, "exactLength", limit & number> : constrain<constrainableIn, In extends number ? comparator extends MinComparator ? "min" : "max" : In extends string | array ? comparator extends MinComparator ? "minLength" : "maxLength" : comparator extends MinComparator ? "after" : "before", {
15
16
  rule: normalizeLimit<limit>;
16
17
  exclusive: comparator extends ">" | "<" ? true : false;
@@ -2,12 +2,14 @@ import type { arkKind, GenericProps, PrivateDeclaration, writeMissingSubmoduleAc
2
2
  import type { anyOrNever, BigintLiteral, charsAfterFirst, Completion, ErrorMessage, writeMalformedNumericLiteralMessage } from "@arktype/util";
3
3
  import type { Comparator } from "../string/reduce/shared.js";
4
4
  import type { writeInvalidGenericArgsMessage } from "../string/shift/operand/genericArgs.js";
5
+ import type { UnitLiteral } from "../string/shift/operator/default.js";
5
6
  import type { parseString } from "../string/string.js";
6
7
  import type { validateRange } from "./bounds.js";
8
+ import type { validateDefault } from "./default.js";
7
9
  import type { validateDivisor } from "./divisor.js";
8
10
  import type { GenericInstantiationAst, InfixExpression, PostfixExpression } from "./infer.js";
9
11
  import type { astToString } from "./utils.js";
10
- export type validateAst<ast, $, args> = ast extends string ? validateStringAst<ast, $> : ast extends PostfixExpression<infer operator, infer operand> ? operator extends "[]" ? validateAst<operand, $, args> : never : ast extends InfixExpression<infer operator, infer l, infer r> ? operator extends "&" | "|" ? validateInfix<ast, $, args> : operator extends Comparator ? validateRange<l, operator, r, $, args> : operator extends "%" ? validateDivisor<l, $, args> : undefined : ast extends readonly ["keyof", infer operand] ? validateAst<operand, $, args> : ast extends GenericInstantiationAst ? validateGenericArgs<ast[2], $, args> : ErrorMessage<writeUnexpectedExpressionMessage<astToString<ast>>> & {
12
+ export type validateAst<ast, $, args> = ast extends string ? validateStringAst<ast, $> : ast extends PostfixExpression<infer operator, infer operand> ? operator extends "[]" ? validateAst<operand, $, args> : never : ast extends InfixExpression<infer operator, infer l, infer r> ? operator extends "&" | "|" ? validateInfix<ast, $, args> : operator extends Comparator ? validateRange<l, operator, r, $, args> : operator extends "%" ? validateDivisor<l, $, args> : undefined : ast extends (readonly [infer baseAst, "=", infer unitLiteral extends UnitLiteral]) ? validateDefault<baseAst, unitLiteral, $, args> : ast extends readonly ["keyof", infer operand] ? validateAst<operand, $, args> : ast extends GenericInstantiationAst ? validateGenericArgs<ast[2], $, args> : ErrorMessage<writeUnexpectedExpressionMessage<astToString<ast>>> & {
11
13
  ast: ast;
12
14
  };
13
15
  type writeUnexpectedExpressionMessage<expression extends string> = `Unexpectedly failed to parse the expression resulting from ${expression}`;
@@ -13,12 +13,13 @@ type BranchState = {
13
13
  export type DynamicStateWithRoot = requireKeys<DynamicState, "root">;
14
14
  export declare class DynamicState {
15
15
  readonly ctx: ParseContext;
16
+ readonly defaultable: boolean;
16
17
  readonly scanner: Scanner;
17
18
  root: BaseRoot<any> | undefined;
18
19
  branches: BranchState;
19
20
  finalizer: Scanner.FinalizingLookahead | undefined;
20
21
  groups: BranchState[];
21
- constructor(def: string, ctx: ParseContext);
22
+ constructor(def: string, ctx: ParseContext, defaultable: boolean);
22
23
  error(message: string): never;
23
24
  hasRoot(): this is DynamicStateWithRoot;
24
25
  setRoot(root: BaseRoot): void;
@@ -6,6 +6,7 @@ import { parseUntilFinalizer } from "../string.js";
6
6
  import { invertedComparators, minComparators, writeMultipleLeftBoundsMessage, writeOpenRangeMessage, writeUnclosedGroupMessage, writeUnmatchedGroupCloseMessage, writeUnpairableComparatorMessage } from "./shared.js";
7
7
  export class DynamicState {
8
8
  ctx;
9
+ defaultable;
9
10
  scanner;
10
11
  // set root type to `any` so that all constraints can be applied
11
12
  root;
@@ -17,8 +18,9 @@ export class DynamicState {
17
18
  };
18
19
  finalizer;
19
20
  groups = [];
20
- constructor(def, ctx) {
21
+ constructor(def, ctx, defaultable) {
21
22
  this.ctx = ctx;
23
+ this.defaultable = defaultable;
22
24
  this.scanner = new Scanner(def);
23
25
  }
24
26
  error(message) {
@@ -102,7 +104,7 @@ export class DynamicState {
102
104
  this.root = undefined;
103
105
  }
104
106
  parseUntilFinalizer() {
105
- return parseUntilFinalizer(new DynamicState(this.scanner.unscanned, this.ctx));
107
+ return parseUntilFinalizer(new DynamicState(this.scanner.unscanned, this.ctx, false));
106
108
  }
107
109
  parseOperator() {
108
110
  return parseOperator(this);
@@ -1,8 +1,9 @@
1
+ import { type WhiteSpaceToken } from "@arktype/util";
1
2
  import type { DynamicState } from "../../reduce/dynamic.js";
2
3
  import type { StaticState, state } from "../../reduce/static.js";
3
4
  import type { BaseCompletions } from "../../string.js";
4
- import { Scanner } from "../scanner.js";
5
+ import type { Scanner } from "../scanner.js";
5
6
  import { parseEnclosed, type EnclosingQuote, type EnclosingStartToken } from "./enclosed.js";
6
7
  import { parseUnenclosed } from "./unenclosed.js";
7
8
  export declare const parseOperand: (s: DynamicState) => void;
8
- export type parseOperand<s extends StaticState, $, args> = s["unscanned"] extends Scanner.shift<infer lookahead, infer unscanned> ? lookahead extends "(" ? state.reduceGroupOpen<s, unscanned> : lookahead extends EnclosingStartToken ? parseEnclosed<s, lookahead, unscanned> : lookahead extends Scanner.WhiteSpaceToken ? parseOperand<state.scanTo<s, unscanned>, $, args> : lookahead extends "d" ? unscanned extends (Scanner.shift<infer enclosing extends EnclosingQuote, infer nextUnscanned>) ? parseEnclosed<s, `d${enclosing}`, nextUnscanned> : parseUnenclosed<s, $, args> : parseUnenclosed<s, $, args> : state.completion<`${s["scanned"]}${BaseCompletions<$, args>}`>;
9
+ export type parseOperand<s extends StaticState, $, args> = s["unscanned"] extends Scanner.shift<infer lookahead, infer unscanned> ? lookahead extends "(" ? state.reduceGroupOpen<s, unscanned> : lookahead extends EnclosingStartToken ? parseEnclosed<s, lookahead, unscanned> : lookahead extends WhiteSpaceToken ? parseOperand<state.scanTo<s, unscanned>, $, args> : lookahead extends "d" ? unscanned extends (Scanner.shift<infer enclosing extends EnclosingQuote, infer nextUnscanned>) ? parseEnclosed<s, `d${enclosing}`, nextUnscanned> : parseUnenclosed<s, $, args> : parseUnenclosed<s, $, args> : state.completion<`${s["scanned"]}${BaseCompletions<$, args>}`>;
@@ -1,11 +1,10 @@
1
- import { Scanner } from "../scanner.js";
1
+ import { whiteSpaceTokens } from "@arktype/util";
2
2
  import { enclosingChar, enclosingQuote, parseEnclosed } from "./enclosed.js";
3
3
  import { parseUnenclosed, writeMissingOperandMessage } from "./unenclosed.js";
4
4
  export const parseOperand = (s) => s.scanner.lookahead === "" ? s.error(writeMissingOperandMessage(s))
5
5
  : s.scanner.lookahead === "(" ? s.shiftedByOne().reduceGroupOpen()
6
6
  : s.scanner.lookaheadIsIn(enclosingChar) ? parseEnclosed(s, s.scanner.shift())
7
- : s.scanner.lookaheadIsIn(Scanner.whiteSpaceTokens) ?
8
- parseOperand(s.shiftedByOne())
7
+ : s.scanner.lookaheadIsIn(whiteSpaceTokens) ? parseOperand(s.shiftedByOne())
9
8
  : s.scanner.lookahead === "d" ?
10
9
  s.scanner.nextLookahead in enclosingQuote ?
11
10
  parseEnclosed(s, `${s.scanner.shift()}${s.scanner.shift()}`)
@@ -16,11 +16,9 @@ type OneCharComparator = keyof typeof oneCharComparators;
16
16
  export type ComparatorStartChar = Comparator extends `${infer char}${string}` ? char : never;
17
17
  export declare const comparatorStartChars: keySet<ComparatorStartChar>;
18
18
  declare const shiftComparator: (s: DynamicState, start: ComparatorStartChar) => Comparator;
19
- type shiftComparator<start extends ComparatorStartChar, unscanned extends string> = unscanned extends `=${infer nextUnscanned}` ? [`${start}=`, nextUnscanned] : start extends OneCharComparator ? [start, unscanned] : state.error<singleEqualsMessage>;
19
+ type shiftComparator<start extends ComparatorStartChar, unscanned extends string> = unscanned extends `=${infer nextUnscanned}` ? [`${start}=`, nextUnscanned] : [start & OneCharComparator, unscanned];
20
20
  export declare const writeIncompatibleRangeMessage: (l: BoundKind, r: BoundKind) => string;
21
21
  export declare const getBoundKinds: (comparator: Comparator, limit: LimitLiteral, root: BaseRoot, boundKind: BoundExpressionKind) => BoundKind[];
22
- export declare const singleEqualsMessage = "= is not valid here. Default values must be specified on objects like { isAdmin: 'boolean = false' }";
23
- type singleEqualsMessage = typeof singleEqualsMessage;
24
22
  export declare const parseRightBound: (s: DynamicStateWithRoot, comparator: Comparator) => void;
25
23
  export type parseRightBound<s extends StaticState, comparator extends Comparator, $, args> = parseOperand<s, $, args> extends infer nextState extends StaticState ? nextState["root"] extends `${infer limit extends LimitLiteral}` ? s["branches"]["leftBound"] extends {} ? comparator extends MaxComparator ? state.reduceRange<s, s["branches"]["leftBound"]["limit"], s["branches"]["leftBound"]["comparator"], comparator, limit, nextState["unscanned"]> : state.error<writeUnpairableComparatorMessage<comparator>> : state.reduceSingleBound<s, comparator, limit, nextState["unscanned"]> : state.error<writeInvalidLimitMessage<comparator, astToString<nextState["root"]>, "right">> : never;
26
24
  export declare const writeInvalidLimitMessage: <comparator extends Comparator, limit extends string | number, boundKind extends BoundExpressionKind>(comparator: comparator, limit: limit, boundKind: boundKind) => writeInvalidLimitMessage<comparator, limit, boundKind>;
@@ -28,9 +28,9 @@ export const comparatorStartChars = {
28
28
  ">": 1,
29
29
  "=": 1
30
30
  };
31
- const shiftComparator = (s, start) => s.scanner.lookaheadIs("=") ? `${start}${s.scanner.shift()}`
32
- : isKeyOf(start, oneCharComparators) ? start
33
- : s.error(singleEqualsMessage);
31
+ const shiftComparator = (s, start) => s.scanner.lookaheadIs("=") ?
32
+ `${start}${s.scanner.shift()}`
33
+ : start;
34
34
  export const writeIncompatibleRangeMessage = (l, r) => `Bound kinds ${l} and ${r} are incompatible`;
35
35
  export const getBoundKinds = (comparator, limit, root, boundKind) => {
36
36
  if (root.extends(tsKeywords.number)) {
@@ -57,7 +57,6 @@ export const getBoundKinds = (comparator, limit, root, boundKind) => {
57
57
  }
58
58
  return throwParseError(writeUnboundableMessage(root.expression));
59
59
  };
60
- export const singleEqualsMessage = `= is not valid here. Default values must be specified on objects like { isAdmin: 'boolean = false' }`;
61
60
  const openLeftBoundToRoot = (leftBound) => ({
62
61
  rule: isDateLiteral(leftBound.limit) ?
63
62
  extractDateLiteralSource(leftBound.limit)
@@ -0,0 +1,24 @@
1
+ import type { BaseRoot, DateLiteral } from "@arktype/schema";
2
+ import { type BigintLiteral, type ErrorMessage, type NumberLiteral, type trim } from "@arktype/util";
3
+ import type { DynamicStateWithRoot } from "../../reduce/dynamic.js";
4
+ import type { StringLiteral } from "../operand/enclosed.js";
5
+ declare const unitLiteralKeywords: {
6
+ readonly null: null;
7
+ readonly undefined: undefined;
8
+ readonly true: true;
9
+ readonly false: false;
10
+ };
11
+ type UnitLiteralKeyword = keyof typeof unitLiteralKeywords;
12
+ export type UnitLiteral = StringLiteral | BigintLiteral | NumberLiteral | DateLiteral | UnitLiteralKeyword;
13
+ export type ParsedDefault = [BaseRoot, "=", unknown];
14
+ export declare const parseDefault: (s: DynamicStateWithRoot) => ParsedDefault;
15
+ export type parseDefault<root, unscanned extends string> = trim<unscanned> extends infer defaultValue extends UnitLiteral ? [
16
+ root,
17
+ "=",
18
+ defaultValue
19
+ ] : ErrorMessage<writeNonLiteralDefaultMessage<trim<unscanned>>>;
20
+ export declare const writeNonLiteralDefaultMessage: <defaultDef extends string>(defaultDef: defaultDef) => writeNonLiteralDefaultMessage<defaultDef>;
21
+ export type writeNonLiteralDefaultMessage<defaultDef extends string> = `Default value '${defaultDef}' must a literal value`;
22
+ export declare const shallowDefaultMessage = "Default values must be specified on objects like { isAdmin: 'boolean = false' }";
23
+ export type shallowDefaultMessage = typeof shallowDefaultMessage;
24
+ export {};
@@ -0,0 +1,23 @@
1
+ import { throwParseError } from "@arktype/util";
2
+ const unitLiteralKeywords = {
3
+ null: null,
4
+ undefined,
5
+ true: true,
6
+ false: false
7
+ };
8
+ export const parseDefault = (s) => {
9
+ if (!s.defaultable)
10
+ return throwParseError(shallowDefaultMessage);
11
+ // store the node that will be bounded
12
+ const baseNode = s.unsetRoot();
13
+ s.parseOperand();
14
+ const defaultNode = s.unsetRoot();
15
+ // after parsing the next operand, use the locations to get the
16
+ // token from which it was parsed
17
+ if (!defaultNode.hasKind("unit"))
18
+ return s.error(writeNonLiteralDefaultMessage(defaultNode.expression));
19
+ // assignability is checked in parseEntries
20
+ return [baseNode, "=", defaultNode.unit];
21
+ };
22
+ export const writeNonLiteralDefaultMessage = (defaultDef) => `Default value '${defaultDef}' must a literal value`;
23
+ export const shallowDefaultMessage = `Default values must be specified on objects like { isAdmin: 'boolean = false' }`;
@@ -1,10 +1,11 @@
1
+ import { type WhiteSpaceToken } from "@arktype/util";
1
2
  import type { DynamicStateWithRoot } from "../../reduce/dynamic.js";
2
3
  import type { StaticState, state } from "../../reduce/static.js";
3
4
  import { Scanner } from "../scanner.js";
4
5
  import { parseBound, type ComparatorStartChar } from "./bounds.js";
5
6
  import { parseDivisor } from "./divisor.js";
6
7
  export declare const parseOperator: (s: DynamicStateWithRoot) => void;
7
- export type parseOperator<s extends StaticState, $, args> = s["unscanned"] extends Scanner.shift<infer lookahead, infer unscanned> ? lookahead extends "[" ? unscanned extends Scanner.shift<"]", infer nextUnscanned> ? state.setRoot<s, [s["root"], "[]"], nextUnscanned> : state.error<incompleteArrayTokenMessage> : lookahead extends "|" | "&" ? state.reduceBranch<s, lookahead, unscanned> : lookahead extends ")" ? state.finalizeGroup<s, unscanned> : Scanner.lookaheadIsFinalizing<lookahead, unscanned> extends true ? state.finalize<state.scanTo<s, unscanned>, lookahead & Scanner.FinalizingLookahead> : lookahead extends ComparatorStartChar ? parseBound<s, lookahead, unscanned, $, args> : lookahead extends "%" ? parseDivisor<s, unscanned> : lookahead extends Scanner.WhiteSpaceToken ? parseOperator<state.scanTo<s, unscanned>, $, args> : state.error<writeUnexpectedCharacterMessage<lookahead>> : state.finalize<s, "">;
8
+ export type parseOperator<s extends StaticState, $, args> = s["unscanned"] extends Scanner.shift<infer lookahead, infer unscanned> ? lookahead extends "[" ? unscanned extends Scanner.shift<"]", infer nextUnscanned> ? state.setRoot<s, [s["root"], "[]"], nextUnscanned> : state.error<incompleteArrayTokenMessage> : lookahead extends "|" | "&" ? state.reduceBranch<s, lookahead, unscanned> : lookahead extends ")" ? state.finalizeGroup<s, unscanned> : Scanner.lookaheadIsFinalizing<lookahead, unscanned> extends true ? state.finalize<state.scanTo<s, unscanned>, lookahead & Scanner.FinalizingLookahead> : lookahead extends ComparatorStartChar ? parseBound<s, lookahead, unscanned, $, args> : lookahead extends "%" ? parseDivisor<s, unscanned> : lookahead extends WhiteSpaceToken ? parseOperator<state.scanTo<s, unscanned>, $, args> : state.error<writeUnexpectedCharacterMessage<lookahead>> : state.finalize<s, "">;
8
9
  export declare const writeUnexpectedCharacterMessage: <char extends string, shouldBe extends string>(char: char, shouldBe?: shouldBe) => writeUnexpectedCharacterMessage<char, shouldBe>;
9
10
  export type writeUnexpectedCharacterMessage<char extends string, shouldBe extends string = ""> = `'${char}' is not allowed here${shouldBe extends "" ? "" : ` (should be ${shouldBe})`}`;
10
11
  export declare const incompleteArrayTokenMessage = "Missing expected ']'";
@@ -1,4 +1,4 @@
1
- import { type Dict } from "@arktype/util";
1
+ import { type Dict, type EscapeToken, type WhiteSpaceToken } from "@arktype/util";
2
2
  import type { Comparator } from "../reduce/shared.js";
3
3
  export declare class Scanner<lookahead extends string = string> {
4
4
  private chars;
@@ -45,21 +45,14 @@ export declare namespace Scanner {
45
45
  readonly ">": true;
46
46
  readonly ",": true;
47
47
  readonly "": true;
48
+ readonly "=": true;
48
49
  };
49
50
  type FinalizingLookahead = keyof typeof finalizingLookaheads;
50
51
  type InfixToken = Comparator | "|" | "&" | "%" | ":" | "=>";
51
52
  type PostfixToken = "[]";
52
53
  type OperatorToken = InfixToken | PostfixToken;
53
- const escapeToken = "\\";
54
- type EscapeToken = typeof escapeToken;
55
- const whiteSpaceTokens: {
56
- readonly " ": true;
57
- readonly "\n": true;
58
- readonly "\t": true;
59
- };
60
- type WhiteSpaceToken = keyof typeof whiteSpaceTokens;
61
- const lookaheadIsFinalizing: (lookahead: string, unscanned: string) => lookahead is ">" | ",";
62
- type lookaheadIsFinalizing<lookahead extends string, unscanned extends string> = lookahead extends ">" ? unscanned extends `=${infer nextUnscanned}` ? nextUnscanned extends `=${string}` ? true : false : Scanner.skipWhitespace<unscanned> extends ("" | `${TerminatingChar}${string}`) ? true : false : lookahead extends "," ? true : false;
54
+ const lookaheadIsFinalizing: (lookahead: string, unscanned: string) => lookahead is ">" | "," | "=";
55
+ type lookaheadIsFinalizing<lookahead extends string, unscanned extends string> = lookahead extends ">" ? unscanned extends `=${infer nextUnscanned}` ? nextUnscanned extends `=${string}` ? true : false : Scanner.skipWhitespace<unscanned> extends ("" | `${TerminatingChar}${string}`) ? true : false : lookahead extends "=" ? unscanned extends `=${string}` ? false : true : lookahead extends "," ? true : false;
63
56
  type shift<lookahead extends string, unscanned extends string> = `${lookahead}${unscanned}`;
64
57
  type shiftUntil<unscanned extends string, terminator extends string, scanned extends string = ""> = unscanned extends shift<infer lookahead, infer nextUnscanned> ? lookahead extends terminator ? scanned extends `${infer base}${EscapeToken}` ? shiftUntil<nextUnscanned, terminator, `${base}${lookahead}`> : [scanned, unscanned] : shiftUntil<nextUnscanned, terminator, `${scanned}${lookahead}`> : [scanned, ""];
65
58
  type shiftUntilNot<unscanned extends string, nonTerminator extends string, scanned extends string = ""> = unscanned extends shift<infer lookahead, infer nextUnscanned> ? lookahead extends nonTerminator ? shiftUntilNot<nextUnscanned, nonTerminator, `${scanned}${lookahead}`> : [scanned, unscanned] : [scanned, ""];
@@ -1,4 +1,4 @@
1
- import { isKeyOf } from "@arktype/util";
1
+ import { escapeToken, isKeyOf, whiteSpaceTokens } from "@arktype/util";
2
2
  export class Scanner {
3
3
  chars;
4
4
  i;
@@ -23,7 +23,7 @@ export class Scanner {
23
23
  let shifted = "";
24
24
  while (this.lookahead) {
25
25
  if (condition(this, shifted)) {
26
- if (shifted[shifted.length - 1] === Scanner.escapeToken)
26
+ if (shifted[shifted.length - 1] === escapeToken)
27
27
  shifted = shifted.slice(0, -1);
28
28
  else
29
29
  break;
@@ -63,7 +63,7 @@ export class Scanner {
63
63
  }
64
64
  (function (Scanner) {
65
65
  Scanner.lookaheadIsTerminator = (scanner) => scanner.lookahead in Scanner.terminatingChars;
66
- Scanner.lookaheadIsNotWhitespace = (scanner) => !(scanner.lookahead in Scanner.whiteSpaceTokens);
66
+ Scanner.lookaheadIsNotWhitespace = (scanner) => !(scanner.lookahead in whiteSpaceTokens);
67
67
  Scanner.terminatingChars = {
68
68
  "<": true,
69
69
  ">": true,
@@ -79,13 +79,8 @@ export class Scanner {
79
79
  Scanner.finalizingLookaheads = {
80
80
  ">": true,
81
81
  ",": true,
82
- "": true
83
- };
84
- Scanner.escapeToken = "\\";
85
- Scanner.whiteSpaceTokens = {
86
- " ": true,
87
- "\n": true,
88
- "\t": true
82
+ "": true,
83
+ "=": true
89
84
  };
90
85
  Scanner.lookaheadIsFinalizing = (lookahead, unscanned) => lookahead === ">" ?
91
86
  unscanned[0] === "=" ?
@@ -95,6 +90,9 @@ export class Scanner {
95
90
  // if > is the end of a generic instantiation, the next token will be an operator or the end of the string
96
91
  : unscanned.trimStart() === "" ||
97
92
  isKeyOf(unscanned.trimStart()[0], Scanner.terminatingChars)
98
- // if the lookahead is a finalizing token but not >, it's unambiguously a finalizer (currently just ",")
99
- : lookahead === ",";
93
+ // "=" is a finalizer on its own (representing a default value),
94
+ // but not with a second "=" (an equality comparator)
95
+ : lookahead === "=" ? unscanned[0] !== "="
96
+ // ","" is unambiguously a finalizer
97
+ : lookahead === ",";
100
98
  })(Scanner || (Scanner = {}));
@@ -3,8 +3,9 @@ import { type ErrorMessage } from "@arktype/util";
3
3
  import type { inferAstRoot } from "../semantic/infer.js";
4
4
  import type { DynamicState, DynamicStateWithRoot } from "./reduce/dynamic.js";
5
5
  import type { StringifiablePrefixOperator } from "./reduce/shared.js";
6
- import type { StaticState, state } from "./reduce/static.js";
6
+ import type { state, StaticState } from "./reduce/static.js";
7
7
  import type { parseOperand } from "./shift/operand/operand.js";
8
+ import { parseDefault, type ParsedDefault } from "./shift/operator/default.js";
8
9
  import { writeUnexpectedCharacterMessage, type parseOperator } from "./shift/operator/operator.js";
9
10
  /**
10
11
  * Try to parse the definition from right to left using the most common syntax.
@@ -16,11 +17,12 @@ export type parseString<def extends string, $, args> = def extends keyof $ ? def
16
17
  ] : fullStringParse<state.initialize<def>, $, args> : fullStringParse<state.initialize<def>, $, args>;
17
18
  export type inferString<def extends string, $, args> = inferAstRoot<parseString<def, $, args>, $, args>;
18
19
  export type BaseCompletions<$, args, otherSuggestions extends string = never> = resolvableReferenceIn<$> | resolvableReferenceIn<ArkEnv.$> | (keyof args & string) | StringifiablePrefixOperator | otherSuggestions;
19
- export declare const fullStringParse: (s: DynamicState) => BaseRoot;
20
+ export type StringParseResult = BaseRoot | ParsedDefault;
21
+ export declare const fullStringParse: (s: DynamicState) => StringParseResult;
20
22
  type fullStringParse<s extends StaticState, $, args> = extractFinalizedResult<parseUntilFinalizer<s, $, args>>;
21
23
  export declare const parseUntilFinalizer: (s: DynamicState) => DynamicStateWithRoot;
22
24
  export type parseUntilFinalizer<s extends StaticState, $, args> = s["finalizer"] extends undefined ? parseUntilFinalizer<next<s, $, args>, $, args> : s;
23
25
  declare const next: (s: DynamicState) => void;
24
26
  type next<s extends StaticState, $, args> = s["root"] extends undefined ? parseOperand<s, $, args> : parseOperator<s, $, args>;
25
- export type extractFinalizedResult<s extends StaticState> = s["finalizer"] extends ErrorMessage ? s["finalizer"] : s["finalizer"] extends "" ? s["root"] : state.error<writeUnexpectedCharacterMessage<`${s["finalizer"]}`>>;
27
+ export type extractFinalizedResult<s extends StaticState> = s["finalizer"] extends "" ? s["root"] : s["finalizer"] extends ErrorMessage ? s["finalizer"] : s["finalizer"] extends "=" ? parseDefault<s["root"], s["unscanned"]> : state.error<writeUnexpectedCharacterMessage<`${s["finalizer"]}`>>;
26
28
  export {};
@@ -1,11 +1,14 @@
1
1
  import { throwInternalError, throwParseError } from "@arktype/util";
2
+ import { parseDefault } from "./shift/operator/default.js";
2
3
  import { writeUnexpectedCharacterMessage } from "./shift/operator/operator.js";
3
4
  export const fullStringParse = (s) => {
4
5
  s.parseOperand();
5
- const result = parseUntilFinalizer(s).root;
6
+ let result = parseUntilFinalizer(s).root;
6
7
  if (!result) {
7
8
  return throwInternalError(`Root was unexpectedly unset after parsing string '${s.scanner.scanned}'`);
8
9
  }
10
+ if (s.finalizer === "=")
11
+ result = parseDefault(s);
9
12
  s.scanner.shiftUntilNonWhitespace();
10
13
  if (s.scanner.lookahead) {
11
14
  // throw a parse error if non-whitespace characters made it here without being parsed
@@ -84,7 +84,7 @@ const appendSpreadBranch = (base, branch) => {
84
84
  const spread = branch.firstReferenceOfKind("sequence");
85
85
  if (!spread) {
86
86
  // the only array with no sequence reference is unknown[]
87
- return appendElement(base, "variadic", tsKeywords.unknown);
87
+ return appendElement(base, "variadic", tsKeywords.unknown.internal);
88
88
  }
89
89
  spread.prefix.forEach(node => appendElement(base, "required", node));
90
90
  spread.optionals.forEach(node => appendElement(base, "optional", node));
package/out/scope.d.ts CHANGED
@@ -5,6 +5,7 @@ import { type MatchParser } from "./match.js";
5
5
  import type { Module } from "./module.js";
6
6
  import { type inferDefinition, type validateDefinition } from "./parser/definition.js";
7
7
  import { parseGenericParams, type GenericDeclaration, type GenericParamsParseError } from "./parser/generic.js";
8
+ import type { ParsedDefault } from "./parser/string/shift/operator/default.js";
8
9
  import { RawTypeParser, type DeclarationParser, type DefinitionParser, type Type, type TypeParser } from "./type.js";
9
10
  export type ScopeParser = <const def>(def: validateScope<def>, config?: ArkConfig) => Scope<inferScope<def>>;
10
11
  export type validateScope<def> = {
@@ -65,8 +66,8 @@ export declare class RawScope<$ extends RawRootResolutions = RawRootResolutions>
65
66
  define: (def: unknown) => unknown;
66
67
  preparseRoot(def: unknown): unknown;
67
68
  parseRoot(def: unknown): BaseRoot;
68
- parse(def: unknown, ctx: ParseContext): BaseRoot;
69
- parseString(def: string, ctx: ParseContext): BaseRoot;
69
+ parse<defaultable extends boolean = false>(def: unknown, ctx: ParseContext, defaultable?: defaultable): BaseRoot | (defaultable extends false ? never : ParsedDefault);
70
+ parseString<defaultable extends boolean>(def: string, ctx: ParseContext, defaultable: defaultable): BaseRoot | (defaultable extends false ? never : ParsedDefault);
70
71
  }
71
72
  export declare const writeShallowCycleErrorMessage: (name: string, seen: string[]) => string;
72
73
  export type ParsedScopeKey = {
package/out/scope.js CHANGED
@@ -84,26 +84,32 @@ let RawScope = (() => {
84
84
  args: {}
85
85
  }).bindScope(this);
86
86
  }
87
- parse(def, ctx) {
87
+ parse(def, ctx, defaultable = false) {
88
88
  if (typeof def === "string") {
89
89
  if (ctx.args && Object.keys(ctx.args).every(k => !def.includes(k))) {
90
90
  // we can only rely on the cache if there are no contextual
91
91
  // resolutions like "this" or generic args
92
- return this.parseString(def, ctx);
92
+ return this.parseString(def, ctx, defaultable);
93
93
  }
94
- if (!this.parseCache[def])
95
- this.parseCache[def] = this.parseString(def, ctx);
96
- return this.parseCache[def];
94
+ const contextKey = `${def}${defaultable}`;
95
+ if (!this.parseCache[contextKey])
96
+ this.parseCache[contextKey] = this.parseString(def, ctx, defaultable);
97
+ return this.parseCache[contextKey];
97
98
  }
98
99
  return hasDomain(def, "object") ?
99
100
  parseObject(def, ctx)
100
101
  : throwParseError(writeBadDefinitionTypeMessage(domainOf(def)));
101
102
  }
102
- parseString(def, ctx) {
103
- return (this.maybeResolveRoot(def) ??
104
- ((def.endsWith("[]") &&
105
- this.maybeResolveRoot(def.slice(0, -2))?.array()) ||
106
- fullStringParse(new DynamicState(def, ctx))));
103
+ parseString(def, ctx, defaultable) {
104
+ const aliasResolution = this.maybeResolveRoot(def);
105
+ if (aliasResolution)
106
+ return aliasResolution;
107
+ const aliasArrayResolution = def.endsWith("[]") ?
108
+ this.maybeResolveRoot(def.slice(0, -2))?.array()
109
+ : undefined;
110
+ if (aliasArrayResolution)
111
+ return aliasArrayResolution;
112
+ return fullStringParse(new DynamicState(def, ctx, defaultable));
107
113
  }
108
114
  };
109
115
  })();
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "arktype",
3
3
  "description": "TypeScript's 1:1 validator, optimized from editor to runtime",
4
- "version": "2.0.0-dev.25",
4
+ "version": "2.0.0-dev.26",
5
5
  "license": "MIT",
6
6
  "author": {
7
7
  "name": "David Blass",
@@ -24,8 +24,8 @@
24
24
  "out"
25
25
  ],
26
26
  "dependencies": {
27
- "@arktype/util": "0.0.50",
28
- "@arktype/schema": "0.1.17"
27
+ "@arktype/util": "0.0.51",
28
+ "@arktype/schema": "0.1.18"
29
29
  },
30
30
  "scripts": {
31
31
  "build": "tsx ../repo/build.ts",