arktype 2.0.3 → 2.1.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.
@@ -22,10 +22,14 @@ export const stringInteger = Scope.module({
22
22
  },
23
23
  declaredOut: intrinsic.integer
24
24
  })
25
+ }, {
26
+ name: "string.integer"
25
27
  });
26
28
  const base64 = Scope.module({
27
29
  root: regexStringNode(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/, "base64-encoded"),
28
30
  url: regexStringNode(/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2}(?:==|%3D%3D)?|[A-Za-z0-9_-]{3}(?:=|%3D)?)?$/, "base64url-encoded")
31
+ }, {
32
+ name: "string.base64"
29
33
  });
30
34
  const preformattedCapitalize = regexStringNode(/^[A-Z].*$/, "capitalized");
31
35
  export const capitalize = Scope.module({
@@ -35,6 +39,8 @@ export const capitalize = Scope.module({
35
39
  declaredOut: preformattedCapitalize
36
40
  }),
37
41
  preformatted: preformattedCapitalize
42
+ }, {
43
+ name: "string.capitalize"
38
44
  });
39
45
  // https://github.com/validatorjs/validator.js/blob/master/src/lib/isLuhnNumber.js
40
46
  export const isLuhnValid = (creditCardInput) => {
@@ -139,6 +145,8 @@ const epoch = Scope.module({
139
145
  morphs: (s) => new Date(s),
140
146
  declaredOut: intrinsic.Date
141
147
  })
148
+ }, {
149
+ name: "string.date.epoch"
142
150
  });
143
151
  const isoRoot = regexStringNode(iso8601Matcher, "an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection");
144
152
  const iso = Scope.module({
@@ -148,6 +156,8 @@ const iso = Scope.module({
148
156
  morphs: (s) => new Date(s),
149
157
  declaredOut: intrinsic.Date
150
158
  })
159
+ }, {
160
+ name: "string.date.iso"
151
161
  });
152
162
  export const stringDate = Scope.module({
153
163
  root: parsableDate,
@@ -164,6 +174,8 @@ export const stringDate = Scope.module({
164
174
  }),
165
175
  iso,
166
176
  epoch
177
+ }, {
178
+ name: "string.date"
167
179
  });
168
180
  const email = regexStringNode(
169
181
  // https://www.regular-expressions.info/email.html
@@ -188,6 +200,8 @@ export const ip = Scope.module({
188
200
  root: ["v4 | v6", "@", "an IP address"],
189
201
  v4: regexStringNode(ipv4Matcher, "an IPv4 address"),
190
202
  v6: regexStringNode(ipv6Matcher, "an IPv6 address")
203
+ }, {
204
+ name: "string.ip"
191
205
  });
192
206
  const jsonStringDescription = "a JSON string";
193
207
  export const writeJsonSyntaxErrorProblem = (error) => {
@@ -196,6 +210,7 @@ export const writeJsonSyntaxErrorProblem = (error) => {
196
210
  return `must be ${jsonStringDescription} (${error})`;
197
211
  };
198
212
  const jsonRoot = rootSchema({
213
+ meta: jsonStringDescription,
199
214
  domain: "string",
200
215
  predicate: {
201
216
  meta: jsonStringDescription,
@@ -236,10 +251,13 @@ const parseJson = (s, ctx) => {
236
251
  export const json = Scope.module({
237
252
  root: jsonRoot,
238
253
  parse: rootSchema({
254
+ meta: "safe JSON string parser",
239
255
  in: "string",
240
256
  morphs: parseJson,
241
- declaredOut: intrinsic.json
257
+ declaredOut: intrinsic.jsonObject
242
258
  })
259
+ }, {
260
+ name: "string.json"
243
261
  });
244
262
  const preformattedLower = regexStringNode(/^[a-z]*$/, "only lowercase letters");
245
263
  const lower = Scope.module({
@@ -249,6 +267,8 @@ const lower = Scope.module({
249
267
  declaredOut: preformattedLower
250
268
  }),
251
269
  preformatted: preformattedLower
270
+ }, {
271
+ name: "string.lower"
252
272
  });
253
273
  export const normalizedForms = ["NFC", "NFD", "NFKC", "NFKD"];
254
274
  const preformattedNodes = flatMorph(normalizedForms, (i, form) => [
@@ -270,18 +290,26 @@ const normalizeNodes = flatMorph(normalizedForms, (i, form) => [
270
290
  export const NFC = Scope.module({
271
291
  root: normalizeNodes.NFC,
272
292
  preformatted: preformattedNodes.NFC
293
+ }, {
294
+ name: "string.normalize.NFC"
273
295
  });
274
296
  export const NFD = Scope.module({
275
297
  root: normalizeNodes.NFD,
276
298
  preformatted: preformattedNodes.NFD
299
+ }, {
300
+ name: "string.normalize.NFD"
277
301
  });
278
302
  export const NFKC = Scope.module({
279
303
  root: normalizeNodes.NFKC,
280
304
  preformatted: preformattedNodes.NFKC
305
+ }, {
306
+ name: "string.normalize.NFKC"
281
307
  });
282
308
  export const NFKD = Scope.module({
283
309
  root: normalizeNodes.NFKD,
284
310
  preformatted: preformattedNodes.NFKD
311
+ }, {
312
+ name: "string.normalize.NFKD"
285
313
  });
286
314
  export const normalize = Scope.module({
287
315
  root: "NFC",
@@ -289,6 +317,8 @@ export const normalize = Scope.module({
289
317
  NFD,
290
318
  NFKC,
291
319
  NFKD
320
+ }, {
321
+ name: "string.normalize"
292
322
  });
293
323
  const numericRoot = regexStringNode(numericStringMatcher, "a well-formed numeric string");
294
324
  export const numeric = Scope.module({
@@ -298,6 +328,8 @@ export const numeric = Scope.module({
298
328
  morphs: (s) => Number.parseFloat(s),
299
329
  declaredOut: intrinsic.number
300
330
  })
331
+ }, {
332
+ name: "string.numeric"
301
333
  });
302
334
  // https://semver.org/
303
335
  const semverMatcher = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;
@@ -312,6 +344,8 @@ const trim = Scope.module({
312
344
  declaredOut: preformattedTrim
313
345
  }),
314
346
  preformatted: preformattedTrim
347
+ }, {
348
+ name: "string.trim"
315
349
  });
316
350
  const preformattedUpper = regexStringNode(/^[A-Z]*$/, "only uppercase letters");
317
351
  const upper = Scope.module({
@@ -321,6 +355,8 @@ const upper = Scope.module({
321
355
  declaredOut: preformattedUpper
322
356
  }),
323
357
  preformatted: preformattedUpper
358
+ }, {
359
+ name: "string.upper"
324
360
  });
325
361
  const isParsableUrl = (s) => {
326
362
  if (URL.canParse)
@@ -356,6 +392,8 @@ export const url = Scope.module({
356
392
  },
357
393
  declaredOut: rootSchema(URL)
358
394
  })
395
+ }, {
396
+ name: "string.url"
359
397
  });
360
398
  // Based on https://github.com/validatorjs/validator.js/blob/master/src/lib/isUUID.js
361
399
  export const uuid = Scope.module({
@@ -373,6 +411,8 @@ export const uuid = Scope.module({
373
411
  v6: regexStringNode(/^[0-9a-f]{8}-[0-9a-f]{4}-6[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i, "a UUIDv6"),
374
412
  v7: regexStringNode(/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i, "a UUIDv7"),
375
413
  v8: regexStringNode(/^[0-9a-f]{8}-[0-9a-f]{4}-8[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i, "a UUIDv8")
414
+ }, {
415
+ name: "string.uuid"
376
416
  });
377
417
  export const string = Scope.module({
378
418
  root: intrinsic.string,
@@ -395,4 +435,6 @@ export const string = Scope.module({
395
435
  upper,
396
436
  url,
397
437
  uuid
438
+ }, {
439
+ name: "string"
398
440
  });
@@ -18,18 +18,24 @@ export const arkTsKeywords = Scope.module({
18
18
  export const unknown = Scope.module({
19
19
  root: intrinsic.unknown,
20
20
  any: intrinsic.unknown
21
+ }, {
22
+ name: "unknown"
21
23
  });
22
24
  export const json = Scope.module({
23
- root: intrinsic.json,
25
+ root: intrinsic.jsonObject,
24
26
  stringify: node("morph", {
25
- in: intrinsic.json,
27
+ in: intrinsic.jsonObject,
26
28
  morphs: (data) => JSON.stringify(data),
27
29
  declaredOut: intrinsic.string
28
30
  })
31
+ }, {
32
+ name: "object.json"
29
33
  });
30
34
  export const object = Scope.module({
31
35
  root: intrinsic.object,
32
36
  json
37
+ }, {
38
+ name: "object"
33
39
  });
34
40
  class RecordHkt extends Hkt {
35
41
  description = "a generic type that instantiates an object from a single index signature and corresponding value type";
package/out/match.d.ts ADDED
@@ -0,0 +1,119 @@
1
+ import { type ArkErrors, type BaseRoot, type Morph } from "@ark/schema";
2
+ import { Callable, type conform, type ErrorMessage, type ErrorType, type isDisjoint, type Key, type numericStringKeyOf, type propValueOf, type unionToTuple } from "@ark/util";
3
+ import type { distill, Out } from "./attributes.ts";
4
+ import type { type } from "./keywords/keywords.ts";
5
+ import type { Inferred } from "./methods/base.ts";
6
+ import type { BaseCompletions } from "./parser/string.ts";
7
+ import type { InternalScope } from "./scope.ts";
8
+ type MatchParserContext<input = unknown> = {
9
+ cases: Morph[];
10
+ $: unknown;
11
+ input: input;
12
+ key: PropertyKey | null;
13
+ };
14
+ declare namespace ctx {
15
+ type from<ctx extends MatchParserContext> = ctx;
16
+ type init<$, input = unknown> = from<{
17
+ cases: [];
18
+ $: $;
19
+ input: input;
20
+ key: null;
21
+ }>;
22
+ type atKey<ctx extends MatchParserContext, key extends string> = from<{
23
+ cases: ctx["cases"];
24
+ $: ctx["$"];
25
+ input: ctx["input"];
26
+ key: key;
27
+ }>;
28
+ }
29
+ export interface MatchParser<$> extends CaseMatchParser<ctx.init<$>> {
30
+ in<const def>(def: type.validate<def, $>): ChainableMatchParser<ctx.init<$, type.infer<def, $>>>;
31
+ in<const typedInput = never>(...args: [typedInput] extends [never] ? [
32
+ ErrorMessage<"from requires a definition or type argument (from('string') or from<string>())">
33
+ ] : []): ChainableMatchParser<ctx.init<$, typedInput>>;
34
+ in<const def>(def: type.validate<def, $>): ChainableMatchParser<ctx.init<$, type.infer<def, $>>>;
35
+ case: CaseParser<ctx.init<$>>;
36
+ at: AtParser<ctx.init<$>>;
37
+ }
38
+ type addCasesToContext<ctx extends MatchParserContext, cases extends unknown[]> = cases extends Morph[] ? ctx.from<{
39
+ $: ctx["$"];
40
+ input: ctx["input"];
41
+ cases: [...ctx["cases"], ...cases];
42
+ key: ctx["key"];
43
+ }> : never;
44
+ type addDefaultToContext<ctx extends MatchParserContext, defaultCase extends DefaultCase<ctx>> = ctx.from<{
45
+ $: ctx["$"];
46
+ input: defaultCase extends "never" ? Morph.In<ctx["cases"][number]> : ctx["input"];
47
+ cases: defaultCase extends Morph ? [...ctx["cases"], defaultCase] : defaultCase extends "never" | "assert" ? ctx["cases"] : [...ctx["cases"], (In: ctx["input"]) => ArkErrors];
48
+ key: ctx["key"];
49
+ }>;
50
+ type casesToMorphTuple<cases, ctx extends MatchParserContext> = unionToTuple<propValueOf<{
51
+ [def in Exclude<keyof cases, "default">]: cases[def] extends (Morph<never, infer o>) ? (In: inferCaseArg<def extends number ? `${number}` : def, ctx, "in">) => o : never;
52
+ }>>;
53
+ type addCasesToParser<cases, ctx extends MatchParserContext> = cases extends {
54
+ default: infer defaultDef extends DefaultCase<ctx>;
55
+ } ? finalizeMatchParser<addCasesToContext<ctx, casesToMorphTuple<cases, ctx>>, defaultDef> : ChainableMatchParser<addCasesToContext<ctx, casesToMorphTuple<cases, ctx>>>;
56
+ type inferCaseArg<def, ctx extends MatchParserContext, endpoint extends "in" | "out"> = _finalizeCaseArg<ctx["key"] extends PropertyKey ? {
57
+ [k in ctx["key"]]: type.infer<def, ctx["$"]>;
58
+ } : type.infer<def, ctx["$"]>, ctx, endpoint>;
59
+ type _finalizeCaseArg<t, ctx extends MatchParserContext, endpoint extends "in" | "out"> = [
60
+ distill<t, "in">,
61
+ distill<t, endpoint>
62
+ ] extends [infer i, infer result] ? i extends ctx["input"] ? result : Extract<ctx["input"], i> extends never ? result : Extract<ctx["input"], result> : never;
63
+ type CaseParser<ctx extends MatchParserContext> = <const def, ret>(def: type.validate<def, ctx["$"]>, resolve: (In: inferCaseArg<def, ctx, "out">) => ret) => ChainableMatchParser<addCasesToContext<ctx, [(In: inferCaseArg<def, ctx, "in">) => ret]>>;
64
+ type validateKey<key extends Key, ctx extends MatchParserContext> = ctx["key"] extends Key ? ErrorMessage<doubleAtMessage> : ctx["cases"]["length"] extends 0 ? keyof ctx["input"] extends never ? key : conform<key, keyof ctx["input"]> : ErrorMessage<chainedAtMessage>;
65
+ interface AtParser<ctx extends MatchParserContext> {
66
+ <const key extends string>(key: validateKey<key, ctx>): ChainableMatchParser<ctx.atKey<ctx, key>>;
67
+ <const key extends string, const cases, ctxAtKey extends MatchParserContext = ctx.atKey<ctx, key>>(key: validateKey<key, ctx>, cases: cases extends validateCases<cases, ctxAtKey> ? cases : errorCases<cases, ctxAtKey>): addCasesToParser<cases, ctxAtKey>;
68
+ }
69
+ interface ChainableMatchParser<ctx extends MatchParserContext> {
70
+ case: CaseParser<ctx>;
71
+ match: CaseMatchParser<ctx>;
72
+ default: DefaultMethod<ctx>;
73
+ at: AtParser<ctx>;
74
+ }
75
+ export type DefaultCaseKeyword = "never" | "assert" | "reject";
76
+ type DefaultCase<ctx extends MatchParserContext = MatchParserContext<any>> = DefaultCaseKeyword | Morph<ctx["input"]>;
77
+ type DefaultMethod<ctx extends MatchParserContext> = <const def extends DefaultCase<ctx>>(def: def) => finalizeMatchParser<ctx, def>;
78
+ type validateCases<cases, ctx extends MatchParserContext> = {
79
+ [def in keyof cases | BaseCompletions<ctx["$"], {}, "default">]?: def extends "default" ? DefaultCase<ctx> : def extends number ? (In: inferCaseArg<`${def}`, ctx, "out">) => unknown : def extends type.validate<def, ctx["$"]> ? (In: inferCaseArg<def, ctx, "out">) => unknown : type.validate<def, ctx["$"]>;
80
+ };
81
+ type errorCases<cases, ctx extends MatchParserContext> = {
82
+ [def in keyof cases]?: def extends "default" ? DefaultCase<ctx> : def extends number ? (In: inferCaseArg<`${def}`, ctx, "out">) => unknown : def extends type.validate<def, ctx["$"]> ? (In: inferCaseArg<def, ctx, "out">) => unknown : ErrorType<type.validate<def, ctx["$"]>>;
83
+ } & {
84
+ [k in BaseCompletions<ctx["$"], {}>]?: (In: inferCaseArg<k, ctx, "out">) => unknown;
85
+ } & {
86
+ default?: DefaultCase<ctx>;
87
+ };
88
+ export type CaseMatchParser<ctx extends MatchParserContext> = <const cases>(def: cases extends validateCases<cases, ctx> ? cases : errorCases<cases, ctx>) => addCasesToParser<cases, ctx>;
89
+ type finalizeMatchParser<ctx extends MatchParserContext, defaultCase extends DefaultCase<ctx>> = addDefaultToContext<ctx, defaultCase> extends (infer ctx extends MatchParserContext) ? Match<ctx["input"], ctx["cases"]> : never;
90
+ export interface Match<In = any, cases extends Morph[] = Morph[]> extends Inferred<(In: Morph.In<cases[number]>) => Out<ReturnType<cases[number]>>> {
91
+ <const data extends In>(data: data): {
92
+ [i in numericStringKeyOf<cases>]: isDisjoint<data, Morph.In<cases[i]>> extends true ? never : Morph.Out<cases[i]>;
93
+ }[numericStringKeyOf<cases>];
94
+ }
95
+ export declare class InternalMatchParser extends Callable<InternalCaseParserFn> {
96
+ $: InternalScope;
97
+ constructor($: InternalScope);
98
+ in(): InternalChainedMatchParser;
99
+ at(key: Key, cases?: InternalCases): InternalChainedMatchParser | Match;
100
+ case(when: unknown, then: Morph): InternalChainedMatchParser;
101
+ }
102
+ type InternalCases = Record<string, Morph | DefaultCase>;
103
+ type InternalCaseParserFn = (cases: InternalCases) => InternalChainedMatchParser | Match;
104
+ export declare class InternalChainedMatchParser extends Callable<InternalCaseParserFn> {
105
+ $: InternalScope;
106
+ protected key: Key | undefined;
107
+ protected branches: BaseRoot[];
108
+ constructor($: InternalScope);
109
+ at(key: Key, cases?: InternalCases): InternalChainedMatchParser | Match;
110
+ case(def: unknown, resolver: Morph): InternalChainedMatchParser;
111
+ match(cases: InternalCases): InternalChainedMatchParser | Match;
112
+ default(defaultCase: DefaultCase): Match;
113
+ }
114
+ export declare const throwOnDefault: ArkErrors.Handler;
115
+ export declare const chainedAtMessage = "A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')";
116
+ export type chainedAtMessage = typeof chainedAtMessage;
117
+ export declare const doubleAtMessage = "At most one key matcher may be specified per expression";
118
+ export type doubleAtMessage = typeof doubleAtMessage;
119
+ export {};
package/out/match.js ADDED
@@ -0,0 +1,77 @@
1
+ import { intrinsic } from "@ark/schema";
2
+ import { Callable, domainOf, throwParseError } from "@ark/util";
3
+ export class InternalMatchParser extends Callable {
4
+ $;
5
+ constructor($) {
6
+ super((...args) => new InternalChainedMatchParser($)(...args), {
7
+ bind: $
8
+ });
9
+ this.$ = $;
10
+ }
11
+ in() {
12
+ return new InternalChainedMatchParser(this.$);
13
+ }
14
+ at(key, cases) {
15
+ return new InternalChainedMatchParser(this.$).at(key, cases);
16
+ }
17
+ case(when, then) {
18
+ return new InternalChainedMatchParser(this.$).case(when, then);
19
+ }
20
+ }
21
+ export class InternalChainedMatchParser extends Callable {
22
+ $;
23
+ key;
24
+ branches = [];
25
+ constructor($) {
26
+ super(cases => {
27
+ const entries = Object.entries(cases);
28
+ for (let i = 0; i < entries.length; i++) {
29
+ const [k, v] = entries[i];
30
+ if (k === "default") {
31
+ if (i !== entries.length - 1) {
32
+ throwParseError(`default may only be specified as the last key of a switch definition`);
33
+ }
34
+ return this.default(v);
35
+ }
36
+ if (typeof v !== "function") {
37
+ return throwParseError(`Value for case "${k}" must be a function (was ${domainOf(v)})`);
38
+ }
39
+ this.case(k, v);
40
+ }
41
+ return this;
42
+ });
43
+ this.$ = $;
44
+ }
45
+ at(key, cases) {
46
+ if (this.key)
47
+ throwParseError(doubleAtMessage);
48
+ if (this.branches.length)
49
+ throwParseError(chainedAtMessage);
50
+ this.key = key;
51
+ return cases ? this.match(cases) : this;
52
+ }
53
+ case(def, resolver) {
54
+ const wrappableDef = this.key ? { [this.key]: def } : def;
55
+ const branch = this.$.parse(wrappableDef).pipe(resolver);
56
+ this.branches.push(branch);
57
+ return this;
58
+ }
59
+ match(cases) {
60
+ return this(cases);
61
+ }
62
+ default(defaultCase) {
63
+ if (typeof defaultCase === "function")
64
+ this.case(intrinsic.unknown, defaultCase);
65
+ const schema = {
66
+ branches: this.branches,
67
+ ordered: true
68
+ };
69
+ if (defaultCase === "never" || defaultCase === "assert")
70
+ schema.meta = { onFail: throwOnDefault };
71
+ const matcher = this.$.finalize(this.$.node("union", schema));
72
+ return matcher;
73
+ }
74
+ }
75
+ export const throwOnDefault = errors => errors.throw();
76
+ export const chainedAtMessage = `A key matcher must be specified before the first case i.e. match.at('foo') or match.in<object>().at('bar')`;
77
+ export const doubleAtMessage = `At most one key matcher may be specified per expression`;
@@ -1,13 +1,13 @@
1
- import type { ArkErrors, BaseRoot, Disjoint, JsonSchema, MetaSchema, Morph, Predicate, StandardSchemaV1, UndeclaredKeyBehavior } from "@ark/schema";
1
+ import type { BaseRoot, Disjoint, JsonSchema, Morph, Predicate, StandardSchemaV1, UndeclaredKeyBehavior } from "@ark/schema";
2
2
  import type { anyOrNever, array, Callable, ErrorMessage, inferred, JsonStructure, unset } from "@ark/util";
3
- import type { defaultFor, distill, inferIntersection, inferMorphOut, inferPipes, InferredMorph, Out, To } from "../attributes.ts";
4
- import type { ArkAmbient } from "../config.ts";
3
+ import type { defaultFor, distill, inferIntersection, inferMorphOut, inferPipe, inferPipes, InferredMorph, Out, To } from "../attributes.ts";
4
+ import type { ArkAmbient, TypeMetaInput } from "../config.ts";
5
5
  import type { type } from "../keywords/keywords.ts";
6
6
  import type { Scope } from "../scope.ts";
7
7
  import type { ArrayType } from "./array.ts";
8
8
  import type { instantiateType } from "./instantiate.ts";
9
9
  /** @ts-ignore cast variance */
10
- interface Type<out t = unknown, $ = {}> extends Callable<(data: unknown) => distill.Out<t> | ArkErrors> {
10
+ export interface Inferred<out t = unknown, $ = {}> {
11
11
  internal: BaseRoot;
12
12
  [inferred]: t;
13
13
  /**
@@ -174,7 +174,7 @@ interface Type<out t = unknown, $ = {}> extends Callable<(data: unknown) => dist
174
174
  * // error message at root is affected, leading to a misleading description
175
175
  * const nonObject = notOddBox(null) // must be not odd (was null)
176
176
  */
177
- configure(meta: MetaSchema): this;
177
+ configure<meta extends TypeMetaInput>(meta: meta): this;
178
178
  /**
179
179
  * #### add description to shallow references
180
180
  *
@@ -252,16 +252,6 @@ interface Type<out t = unknown, $ = {}> extends Callable<(data: unknown) => dist
252
252
  * const baseOut = base.out
253
253
  */
254
254
  get out(): instantiateType<this["inferIntrospectableOut"], $>;
255
- /**
256
- * #### cast the way this is inferred
257
- *
258
- * 🥸 inference-only function that does nothing runtime
259
- *
260
- * @example
261
- * // Type<`LEEEEEEEE${string}ROY`>
262
- * const leeroy = type(/^LE{8,}ROY$/).as<`LEEEEEEEE${string}ROY`>()
263
- */
264
- as<castTo = unset>(...args: validateChainedAsArgs<castTo>): instantiateType<castTo, $>;
265
255
  /**
266
256
  * #### add a compile-time brand to output
267
257
  *
@@ -274,27 +264,7 @@ interface Type<out t = unknown, $ = {}> extends Callable<(data: unknown) => dist
274
264
  * // Brand<string, "palindrome">
275
265
  * const out = palindrome.assert("racecar")
276
266
  */
277
- brand<const name extends string, r = type.brand<t, name>>(name: name): instantiateType<r, $>;
278
- /**
279
- * #### intersect the parsed Type, throwing if the result is unsatisfiable
280
- *
281
- * @example
282
- * // Type<{ foo: number; bar: string }>
283
- * const t = type({ foo: "number" }).and({ bar: "string" })
284
- * // ParseError: Intersection at foo of number and string results in an unsatisfiable type
285
- * const bad = type({ foo: "number" }).and({ foo: "string" })
286
- */
287
- and<const def, r = type.infer<def, $>>(def: type.validate<def, $>): instantiateType<inferIntersection<t, r>, $>;
288
- /**
289
- * #### union with the parsed Type
290
- *
291
- * ⚠️ a union that could apply different morphs to the same data is a ParseError ([docs](https://arktype.io/docs/expressions/union-morphs))
292
- *
293
- * @example
294
- * // Type<string | { box: string }>
295
- * const t = type("string").or({ box: "string" })
296
- */
297
- or<const def, r = type.infer<def, $>>(def: type.validate<def, $>): instantiateType<t | r, $>;
267
+ brand<const name extends string, r = instantiateType<type.brand<t, name>, $>>(name: name): r extends infer _ ? _ : never;
298
268
  /**
299
269
  * #### an array of this
300
270
  *
@@ -345,11 +315,13 @@ interface Type<out t = unknown, $ = {}> extends Callable<(data: unknown) => dist
345
315
  * s.endsWith("Z")
346
316
  * )
347
317
  */
348
- filter<narrowed extends this["inferIn"] = never, r = [narrowed] extends [never] ? t : t extends InferredMorph<any, infer o> ? (In: narrowed) => o : narrowed>(predicate: Predicate.Castable<this["inferIn"], narrowed>): instantiateType<r, $>;
318
+ filter<narrowed extends this["inferIn"] = never, r = instantiateType<[
319
+ narrowed
320
+ ] extends [never] ? t : t extends InferredMorph<any, infer o> ? (In: narrowed) => o : narrowed, $>>(predicate: Predicate.Castable<this["inferIn"], narrowed>): r extends infer _ ? _ : never;
349
321
  /**
350
322
  * #### apply a predicate function to output
351
323
  *
352
- * ✅ go-to fallback for validation not composable via built-in types and operators
324
+ * ✅ go-to fallback for validation not composable via builtin types and operators
353
325
  * ✅ runs after all other validators and morphs, if present
354
326
  * 🥸 {@link https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates | Type predicates} can be used as casts
355
327
  *
@@ -362,13 +334,62 @@ interface Type<out t = unknown, $ = {}> extends Callable<(data: unknown) => dist
362
334
  * // Type<`${string}.tsx`>
363
335
  * const withPredicate = type("string").narrow((s): s is `${string}.tsx` => /\.tsx?$/.test(s))
364
336
  */
365
- narrow<narrowed extends this["infer"] = never, r = [narrowed] extends [never] ? t : t extends InferredMorph<infer i, infer o> ? o extends To ? (In: i) => To<narrowed> : (In: i) => Out<narrowed> : narrowed>(predicate: Predicate.Castable<this["infer"], narrowed>): instantiateType<r, $>;
337
+ narrow<narrowed extends this["infer"] = never, r = instantiateType<[
338
+ narrowed
339
+ ] extends [never] ? t : t extends InferredMorph<infer i, infer o> ? o extends To ? (In: i) => To<narrowed> : (In: i) => Out<narrowed> : narrowed, $>>(predicate: Predicate.Castable<this["infer"], narrowed>): r extends infer _ ? _ : never;
366
340
  /**
367
- * Morph this `Type` through a chain of morphs.
368
- * @example const dedupe = type('string[]').pipe(a => Array.from(new Set(a)))
369
- * @example type({codes: 'string.numeric[]'}).pipe(obj => obj.codes).to('string.numeric.parse[]')
341
+ * #### pipe output through arbitrary transformations or other Types
342
+ *
343
+ * @example
344
+ * const user = type({ name: "string" })
345
+ *
346
+ * // parse a string and validate that the result as a user
347
+ * const parseUser = type("string").pipe(s => JSON.parse(s), user)
370
348
  */
371
349
  pipe: ChainedPipe<t, $>;
350
+ /**
351
+ * #### parse a definition as an output validator
352
+ *
353
+ * 🔗 `to({ name: "string" })` is equivalent to `.pipe(type({ name: "string" }))`
354
+ *
355
+ * @example
356
+ * // parse a string and validate that the result as a user
357
+ * const parseUser = type("string").pipe(s => JSON.parse(s)).to({ name: "string" })
358
+ */
359
+ to<const def, r = instantiateType<inferPipe<t, type.infer<def, $>>, $>>(def: type.validate<def, $>): r extends infer _ ? _ : never;
360
+ }
361
+ /** @ts-ignore cast variance */
362
+ interface Type<out t = unknown, $ = {}> extends Callable<(data: unknown) => distill.Out<t> | ArkEnv.onFail>, Inferred<t, $> {
363
+ /**
364
+ * #### cast the way this is inferred
365
+ *
366
+ * 🥸 inference-only function that does nothing runtime
367
+ *
368
+ * @example
369
+ * // Type<`LEEEEEEEE${string}ROY`>
370
+ * const leeroy = type(/^LE{8,}ROY$/).as<`LEEEEEEEE${string}ROY`>()
371
+ */
372
+ as<castTo = unset>(...args: validateChainedAsArgs<castTo>): instantiateType<castTo, $>;
373
+ /**
374
+ * #### intersect the parsed Type, throwing if the result is unsatisfiable
375
+ *
376
+ * @example
377
+ * // Type<{ foo: number; bar: string }>
378
+ * const t = type({ foo: "number" }).and({ bar: "string" })
379
+ * // ParseError: Intersection at foo of number and string results in an unsatisfiable type
380
+ * const bad = type({ foo: "number" }).and({ foo: "string" })
381
+ */
382
+ and<const def, r = instantiateType<inferIntersection<t, type.infer<def, $>>, $>>(def: type.validate<def, $>): r extends infer _ ? _ : never;
383
+ /**
384
+ * #### union with the parsed Type
385
+ *
386
+ * ⚠️ a union that could apply different morphs to the same data is a ParseError ([docs](https://arktype.io/docs/expressions/union-morphs))
387
+ *
388
+ * @example
389
+ * // Type<string | { box: string }>
390
+ * const t = type("string").or({ box: "string" })
391
+ */
392
+ or<const def, r = instantiateType<t | type.infer<def, $>, $>>(def: type.validate<def, $>): r extends infer _ ? _ : never;
372
393
  /**
373
394
  * #### intersect the parsed Type, returning an introspectable {@link Disjoint} if the result is unsatisfiable
374
395
  *
@@ -379,7 +400,7 @@ interface Type<out t = unknown, $ = {}> extends Callable<(data: unknown) => dist
379
400
  * // logs "Intersection of > 10 and < 5 results in an unsatisfiable type"
380
401
  * if (bad instanceof Disjoint) console.log(`${bad.summary}`)
381
402
  */
382
- intersect<const def, r = type.infer<def, $>>(def: type.validate<def, $>): instantiateType<inferIntersection<t, r>, $> | Disjoint;
403
+ intersect<const def, r = instantiateType<inferIntersection<t, type.infer<def, $>>, $>>(def: type.validate<def, $>): r extends infer _ ? _ | Disjoint : never;
383
404
  /**
384
405
  * #### check if the parsed Type's constraints are identical
385
406
  *
@@ -407,7 +428,7 @@ interface Type<out t = unknown, $ = {}> extends Callable<(data: unknown) => dist
407
428
  * // Type<0.5> | undefined
408
429
  * const ez = n.ifEquals("0.5")
409
430
  */
410
- ifEquals<const def, r = type.infer<def, $>>(def: type.validate<def, $>): instantiateType<r, $> | undefined;
431
+ ifEquals<const def, r = type.instantiate<def, $>>(def: type.validate<def, $>): r extends infer _ ? _ | undefined : never;
411
432
  /**
412
433
  * #### check if this is a subtype of the parsed Type
413
434
  *
@@ -429,7 +450,7 @@ interface Type<out t = unknown, $ = {}> extends Callable<(data: unknown) => dist
429
450
  * const n = type(Math.random() > 0.5 ? "true" : "0") // Type<0 | true>
430
451
  * const ez = n.ifExtends("boolean") // Type<true> | undefined
431
452
  */
432
- ifExtends<const def, r = type.infer<def, $>>(other: type.validate<def, $>): instantiateType<r, $> | undefined;
453
+ ifExtends<const def, r = type.instantiate<def, $>>(other: type.validate<def, $>): r extends infer _ ? _ | undefined : never;
433
454
  /**
434
455
  * #### check if a value could satisfy this and the parsed Type
435
456
  *
@@ -451,7 +472,7 @@ interface Type<out t = unknown, $ = {}> extends Callable<(data: unknown) => dist
451
472
  * // Type<true | 0 | 2>
452
473
  * const t = type("boolean | 0 | 'one' | 2 | bigint").extract("number | 0n | true")
453
474
  */
454
- extract<const def, r = type.infer<def, $>>(r: type.validate<def, $>): instantiateType<Extract<t, r>, $>;
475
+ extract<const def, r = instantiateType<t extends type.infer<def, $> ? t : never, $>>(r: type.validate<def, $>): r extends infer _ extends r ? _ : never;
455
476
  /**
456
477
  * #### exclude branches {@link extend}ing the parsed Type
457
478
  *
@@ -460,7 +481,7 @@ interface Type<out t = unknown, $ = {}> extends Callable<(data: unknown) => dist
460
481
  * // Type<false | 'one' | bigint>
461
482
  * const t = type("boolean | 0 | 'one' | 2 | bigint").exclude("number | 0n | true")
462
483
  */
463
- exclude<const def, r = type.infer<def, $>>(r: type.validate<def, $>): instantiateType<Exclude<t, r>, $>;
484
+ exclude<const def, r = instantiateType<t extends type.infer<def, $> ? never : t, $>>(r: type.validate<def, $>): r extends infer _ ? _ : never;
464
485
  /**
465
486
  * @experimental
466
487
  * Map and optionally reduce branches of a union. Types that are not unions
@@ -497,13 +518,13 @@ interface Type<out t = unknown, $ = {}> extends Callable<(data: unknown) => dist
497
518
  Symbol: never;
498
519
  }
499
520
  interface ChainedPipeSignature<t, $> {
500
- <a extends Morph<distill.Out<t>>, r = instantiateType<inferPipes<t, [a]>, $>>(a: a): NoInfer<r> extends infer result ? result : never;
501
- <a extends Morph<distill.Out<t>>, b extends Morph<inferMorphOut<a>>, r = instantiateType<inferPipes<t, [a, b]>, $>>(a: a, b: b): NoInfer<r> extends infer result ? result : never;
502
- <a extends Morph<distill.Out<t>>, b extends Morph<inferMorphOut<a>>, c extends Morph<inferMorphOut<b>>, r = instantiateType<inferPipes<t, [a, b, c]>, $>>(a: a, b: b, c: c): NoInfer<r> extends infer result ? result : never;
503
- <a extends Morph<distill.Out<t>>, b extends Morph<inferMorphOut<a>>, c extends Morph<inferMorphOut<b>>, d extends Morph<inferMorphOut<c>>, r = instantiateType<inferPipes<t, [a, b, c, d]>, $>>(a: a, b: b, c: c, d: d): NoInfer<r> extends infer result ? result : never;
504
- <a extends Morph<distill.Out<t>>, b extends Morph<inferMorphOut<a>>, c extends Morph<inferMorphOut<b>>, d extends Morph<inferMorphOut<c>>, e extends Morph<inferMorphOut<d>>, r = instantiateType<inferPipes<t, [a, b, c, d, e]>, $>>(a: a, b: b, c: c, d: d, e: e): NoInfer<r> extends infer result ? result : never;
505
- <a extends Morph<distill.Out<t>>, b extends Morph<inferMorphOut<a>>, c extends Morph<inferMorphOut<b>>, d extends Morph<inferMorphOut<c>>, e extends Morph<inferMorphOut<d>>, f extends Morph<inferMorphOut<e>>, r = instantiateType<inferPipes<t, [a, b, c, d, e, f]>, $>>(a: a, b: b, c: c, d: d, e: e, f: f): NoInfer<r> extends infer result ? result : never;
506
- <a extends Morph<distill.Out<t>>, b extends Morph<inferMorphOut<a>>, c extends Morph<inferMorphOut<b>>, d extends Morph<inferMorphOut<c>>, e extends Morph<inferMorphOut<d>>, f extends Morph<inferMorphOut<e>>, g extends Morph<inferMorphOut<f>>, r = instantiateType<inferPipes<t, [a, b, c, d, e, f, g]>, $>>(a: a, b: b, c: c, d: d, e: e, f: f, g: g): NoInfer<r> extends infer result ? result : never;
521
+ <a extends Morph<distill.Out<t>>, r = instantiateType<inferPipes<t, [a]>, $>>(a: a): r extends infer _ ? _ : never;
522
+ <a extends Morph<distill.Out<t>>, b extends Morph<inferMorphOut<a>>, r = instantiateType<inferPipes<t, [a, b]>, $>>(a: a, b: b): r extends infer _ ? _ : never;
523
+ <a extends Morph<distill.Out<t>>, b extends Morph<inferMorphOut<a>>, c extends Morph<inferMorphOut<b>>, r = instantiateType<inferPipes<t, [a, b, c]>, $>>(a: a, b: b, c: c): r extends infer _ ? _ : never;
524
+ <a extends Morph<distill.Out<t>>, b extends Morph<inferMorphOut<a>>, c extends Morph<inferMorphOut<b>>, d extends Morph<inferMorphOut<c>>, r = instantiateType<inferPipes<t, [a, b, c, d]>, $>>(a: a, b: b, c: c, d: d): r extends infer _ ? _ : never;
525
+ <a extends Morph<distill.Out<t>>, b extends Morph<inferMorphOut<a>>, c extends Morph<inferMorphOut<b>>, d extends Morph<inferMorphOut<c>>, e extends Morph<inferMorphOut<d>>, r = instantiateType<inferPipes<t, [a, b, c, d, e]>, $>>(a: a, b: b, c: c, d: d, e: e): r extends infer _ ? _ : never;
526
+ <a extends Morph<distill.Out<t>>, b extends Morph<inferMorphOut<a>>, c extends Morph<inferMorphOut<b>>, d extends Morph<inferMorphOut<c>>, e extends Morph<inferMorphOut<d>>, f extends Morph<inferMorphOut<e>>, r = instantiateType<inferPipes<t, [a, b, c, d, e, f]>, $>>(a: a, b: b, c: c, d: d, e: e, f: f): r extends infer _ ? _ : never;
527
+ <a extends Morph<distill.Out<t>>, b extends Morph<inferMorphOut<a>>, c extends Morph<inferMorphOut<b>>, d extends Morph<inferMorphOut<c>>, e extends Morph<inferMorphOut<d>>, f extends Morph<inferMorphOut<e>>, g extends Morph<inferMorphOut<f>>, r = instantiateType<inferPipes<t, [a, b, c, d, e, f, g]>, $>>(a: a, b: b, c: c, d: d, e: e, f: f, g: g): r extends infer _ ? _ : never;
507
528
  }
508
529
  export interface ChainedPipe<t, $> extends ChainedPipeSignature<t, $> {
509
530
  try: ChainedPipeSignature<t, $>;
@@ -1,17 +1,12 @@
1
1
  import type { anyOrNever, array } from "@ark/util";
2
- import type { InferredMorph } from "../attributes.ts";
3
2
  import type { ArrayType } from "./array.ts";
4
3
  import type { BaseType } from "./base.ts";
5
4
  import type { DateType } from "./date.ts";
6
- import type { MorphType } from "./morph.ts";
7
5
  import type { NumberType } from "./number.ts";
8
6
  import type { ObjectType } from "./object.ts";
9
7
  import type { StringType } from "./string.ts";
10
- export type instantiateType<t, $> = NoInfer<_instantiateType<t, $>> extends infer r ? r : never;
11
- export type _instantiateType<t, $> = [
12
- Extract<t, InferredMorph>
13
- ] extends [anyOrNever] ? [
8
+ export type instantiateType<t, $> = [
14
9
  t
15
- ] extends [anyOrNever] ? BaseType<t, $> : [t] extends [string] ? StringType<t, $> : [t] extends [number] ? NumberType<t, $> : [t] extends [object] ? [
10
+ ] extends [anyOrNever] ? BaseType<t, $> : [t] extends [object] ? [
16
11
  t
17
- ] extends [array] ? ArrayType<t, $> : [t] extends [Date] ? DateType<t, $> : ObjectType<t, $> : BaseType<t, $> : MorphType<t, $>;
12
+ ] extends [array] ? ArrayType<t, $> : [t] extends [Date] ? DateType<t, $> : ObjectType<t, $> : [t] extends [string] ? StringType<t, $> : [t] extends [number] ? NumberType<t, $> : BaseType<t, $>;