@liautaud/typezod 1.0.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Romain Liautaud
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,91 @@
1
+ # typezod
2
+
3
+ Zod-like DSL for comparing TypeScript compiler types against
4
+ user-defined schemas.
5
+
6
+ ## Why?
7
+
8
+ Writing type-aware ESLint rules (or codemods, code generators, etc.) means
9
+ working with the TypeScript compiler's `ts.Type` objects. Checking whether
10
+ a type matches a specific schema quickly turns into verbose, repetitive
11
+ calls to `checker.isTypeAssignableTo()`, `type.getProperty()`, and friends.
12
+
13
+ This library lets you **declare** the types you care about with a concise,
14
+ Zod-inspired API and then ask "is this compiler type assignable to my
15
+ schema?" in a single call.
16
+
17
+ ## Usage
18
+
19
+ ```typescript
20
+ import { t, isAssignableTo, type SchemaContext } from "@liautaud/typezod";
21
+
22
+ // Define schemas for the types you want to check against.
23
+ const Rectangle = t.object({
24
+ x: t.number(),
25
+ y: t.number(),
26
+ width: t.number(),
27
+ height: t.number(),
28
+ });
29
+
30
+ const ElectronWindow = t.fromModule("/electron/", "BaseWindow");
31
+
32
+ // Inside a typescript-eslint rule's `create()` function, build a context
33
+ // from the parser services and use `isAssignableTo` to check types.
34
+ const checker = parserServices.program.getTypeChecker();
35
+ const ctx: SchemaContext = { checker, program: parserServices.program };
36
+
37
+ if (isAssignableTo(ctx, objectType, ElectronWindow)) {
38
+ if (!isAssignableTo(ctx, argType, Rectangle)) {
39
+ context.report({ ... });
40
+ }
41
+ }
42
+ ```
43
+
44
+ ## API
45
+
46
+ ### `isAssignableTo(ctx, type, schema)`
47
+
48
+ Returns `true` if the given `ts.Type` is assignable to the type represented
49
+ by the schema.
50
+
51
+ ### `SchemaContext`
52
+
53
+ The context object passed to `isAssignableTo`. Contains a `checker`
54
+ (required) and an optional `program` (only needed for `t.fromModule()`).
55
+
56
+ ### Primitives
57
+
58
+ | Builder | Description |
59
+ | ---------------- | ------------------------------ |
60
+ | `t.string()` | Represents the `string` type |
61
+ | `t.number()` | Represents the `number` type |
62
+ | `t.boolean()` | Represents the `boolean` type |
63
+ | `t.void()` | Represents the `void` type |
64
+ | `t.undefined()` | Represents the `undefined` type|
65
+ | `t.null()` | Represents the `null` type |
66
+ | `t.any()` | Accepts any type |
67
+ | `t.unknown()` | Accepts any type |
68
+
69
+ ### Combinators
70
+
71
+ | Builder | Description |
72
+ | -------------------------- | ---------------------------------------------------------------- |
73
+ | `t.object(shape)` | Represents an object with the given shape (structural subtyping) |
74
+ | `t.array(element)` | Represents an array whose element satisfies the given schema |
75
+ | `t.union(...schemas)` | Represents a union of the given schemas |
76
+ | `t.intersection(...schemas)` | Represents an intersection of the given schemas |
77
+
78
+ ### Advanced
79
+
80
+ | Builder | Description |
81
+ | --------------------------------------- | ------------------------------------------------------- |
82
+ | `t.fromModule(pathPattern, exportName)` | Represents a type exported from a module in the program |
83
+ | `t.custom(fn)` | Escape hatch for arbitrary predicates |
84
+
85
+ ### Modifiers
86
+
87
+ | Modifier | Description |
88
+ | ------------- | ----------------------------------------------------------------- |
89
+ | `.optional()` | Inside `t.object()`, allows the property to be absent or optional |
90
+ | `.nullable()` | Also accepts `null` |
91
+ | `.nullish()` | Also accepts `null \| undefined` |
@@ -0,0 +1,176 @@
1
+ import { Program, Type, TypeChecker } from "typescript";
2
+
3
+ //#region src/index.d.ts
4
+
5
+ /**
6
+ * Context required by all schema checks. The `program` field is only needed
7
+ * for schemas that resolve types from external modules ({@link t.fromModule}).
8
+ */
9
+ type SchemaContext = {
10
+ checker: TypeChecker;
11
+ program?: Program;
12
+ };
13
+ type AcceptsFn = (type: Type, ctx: SchemaContext) => boolean;
14
+ /**
15
+ * A type schema that checks whether a TypeScript compiler type is assignable
16
+ * to the type represented by the schema.
17
+ *
18
+ * Obtain instances through the {@link t} builder, never instantiate directly.
19
+ */
20
+ declare class TypeSchema {
21
+ /** @internal */
22
+ readonly _accepts: AcceptsFn;
23
+ /** @internal */
24
+ readonly _isOptional: boolean;
25
+ /** @internal */
26
+ constructor(accepts: AcceptsFn, isOptional?: boolean);
27
+ /**
28
+ * Marks this schema as optional when used as a property in {@link t.object}.
29
+ * An optional property may be absent from the type or carry the TypeScript
30
+ * `Optional` symbol flag.
31
+ *
32
+ * @example
33
+ * ```typescript
34
+ * const Shape = t.object({
35
+ * label: t.string().optional(),
36
+ * });
37
+ * ```
38
+ */
39
+ optional(): TypeSchema;
40
+ /**
41
+ * Wraps this schema to also accept `null`.
42
+ *
43
+ * @example
44
+ * ```typescript
45
+ * const MaybeNumber = t.number().nullable(); // number | null
46
+ * ```
47
+ */
48
+ nullable(): TypeSchema;
49
+ /**
50
+ * Wraps this schema to also accept `null` and `undefined`.
51
+ *
52
+ * @example
53
+ * ```typescript
54
+ * const MaybeNumber = t.number().nullish(); // number | null | undefined
55
+ * ```
56
+ */
57
+ nullish(): TypeSchema;
58
+ }
59
+ /**
60
+ * Schema builder namespace.
61
+ */
62
+ declare const t: {
63
+ /** Represents the `number` type. */
64
+ number: () => TypeSchema;
65
+ /** Represents the `string` type. */
66
+ string: () => TypeSchema;
67
+ /** Represents the `boolean` type. */
68
+ boolean: () => TypeSchema;
69
+ /** Represents the `void` type. */
70
+ void: () => TypeSchema;
71
+ /** Represents the `undefined` type. */
72
+ undefined: () => TypeSchema;
73
+ /** Represents the `null` type. */
74
+ null: () => TypeSchema;
75
+ /**
76
+ * Represents the `any` type. Useful as a placeholder in object schemas when
77
+ * you care about a property's existence but not its type.
78
+ */
79
+ any: () => TypeSchema;
80
+ /**
81
+ * Represents the `unknown` type. Semantically identical to `t.any()` as a
82
+ * predicate, but communicates intent differently in your schema.
83
+ */
84
+ unknown: () => TypeSchema;
85
+ /**
86
+ * Represents an object type with the specified shape. Each property must be
87
+ * present and non-optional unless its schema was marked `.optional()`.
88
+ *
89
+ * Extra properties are allowed (structural subtyping), consistent with
90
+ * TypeScript's own assignability rules.
91
+ *
92
+ * @example
93
+ * ```typescript
94
+ * const Point = t.object({
95
+ * x: t.number(),
96
+ * y: t.number(),
97
+ * label: t.string().optional(),
98
+ * });
99
+ * ```
100
+ */
101
+ object: (shape: Record<string, TypeSchema>) => TypeSchema;
102
+ /**
103
+ * Represents an array type whose element type satisfies the given schema.
104
+ * Checks for a numeric index signature, so it also covers tuples and other
105
+ * numerically-indexed types.
106
+ *
107
+ * @example
108
+ * ```typescript
109
+ * const NumberArray = t.array(t.number());
110
+ * ```
111
+ */
112
+ array: (element: TypeSchema) => TypeSchema;
113
+ /**
114
+ * Represents a union of the given schemas. For union source types, every
115
+ * constituent must individually satisfy at least one member schema.
116
+ *
117
+ * @example
118
+ * ```typescript
119
+ * const StringOrNumber = t.union(t.string(), t.number());
120
+ * ```
121
+ */
122
+ union: (...members: TypeSchema[]) => TypeSchema;
123
+ /**
124
+ * Represents an intersection of the given schemas. The type must satisfy
125
+ * every member schema simultaneously.
126
+ *
127
+ * @example
128
+ * ```typescript
129
+ * const NamedAndAged = t.intersection(
130
+ * t.object({ name: t.string() }),
131
+ * t.object({ age: t.number() }),
132
+ * );
133
+ * ```
134
+ */
135
+ intersection: (...members: TypeSchema[]) => TypeSchema;
136
+ /**
137
+ * Represents a type exported from a module in the program. Resolves a genuine
138
+ * `ts.Type` and delegates to `checker.isTypeAssignableTo()`, so it handles
139
+ * nominal class hierarchies correctly.
140
+ *
141
+ * Resolved types are cached per `TypeChecker` instance (via a `WeakMap`) so
142
+ * repeated calls across files do not re-scan source files.
143
+ *
144
+ * Requires `program` in the {@link SchemaContext}.
145
+ *
146
+ * @param modulePathPattern Substring matched against source-file paths.
147
+ * @param exportName The exported type, class or interface name.
148
+ *
149
+ * @example
150
+ * ```typescript
151
+ * const BaseWindow = t.fromModule("/electron/", "BaseWindow");
152
+ * const Buffer = t.fromModule("@types/node", "Buffer");
153
+ * ```
154
+ */
155
+ fromModule: (modulePathPattern: string, exportName: string) => TypeSchema;
156
+ /**
157
+ * Escape hatch for arbitrary predicates that the DSL cannot express directly.
158
+ *
159
+ * @example
160
+ * ```typescript
161
+ * const HasLengthProp = t.custom((type) =>
162
+ * type.getProperty("length") != null,
163
+ * );
164
+ * ```
165
+ */
166
+ custom: (predicate: AcceptsFn) => TypeSchema;
167
+ };
168
+ /**
169
+ * Returns `true` if the given TypeScript type is assignable to the schema–in
170
+ * other words, if `type extends T` with `T` the TypeScript type represented
171
+ * by the schema.
172
+ */
173
+ declare function isAssignableTo(ctx: SchemaContext, type: Type, schema: TypeSchema): boolean;
174
+ //#endregion
175
+ export { SchemaContext, TypeSchema, isAssignableTo, t };
176
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/index.ts"],"sourcesContent":[],"mappings":";;;;;;AAQA;;AACW,KADC,aAAA,GACD;EAAW,OACV,EADD,WACC;EAAO,OAAA,CAAA,EAAP,OAAO;AACjB,CAAA;KAEG,SAAA,GAAS,CAAA,IAAA,EAAU,IAAV,EAAA,GAAA,EAAqB,aAArB,EAAA,GAAA,OAAA;;;AAAkC;AAQhD;;;AAQuB,cARV,UAAA,CAQU;EAAS;EAiBR,SAYV,QAAA,EAnCO,SAmCP;EAAU;EAYD,SAAA,WAAA,EAAA,OAAA;EAaV;EA+MZ,WAAA,CAAA,OAAA,EArQsB,SAqQtB,EAAA,UAAA,CAAA,EAAA,OAAA;EAAA;;;;;;;;;;;;EAjH4B,QAAG,CAAA,CAAA,EAnIlB,UAmIkB;EAAU;;;;;;;AAgHE;EAQ5B,QAAA,CAAA,CAAA,EA/OF,UA+OgB;EAAA;;;;AAGV;;;;aAtOP;;;;;cAaA;;gBAEC;;gBAMA;;iBAMC;;cAMH;;mBAMK;;cAML;;;;;aASD;;;;;iBAMI;;;;;;;;;;;;;;;;;kBAkBG,eAAe,gBAAc;;;;;;;;;;;mBA6B5B,eAAa;;;;;;;;;;sBAgBV,iBAAe;;;;;;;;;;;;;6BAsBR,iBAAe;;;;;;;;;;;;;;;;;;;;iEAsBmB;;;;;;;;;;;sBAoDzC,cAAY;;;;;;;iBAQlB,cAAA,MACT,qBACC,cACE"}
package/dist/index.js ADDED
@@ -0,0 +1,127 @@
1
+ //#region src/index.ts
2
+ const TS_SYMBOL_FLAGS_OPTIONAL = 16777216;
3
+ /**
4
+ * A type schema that checks whether a TypeScript compiler type is assignable
5
+ * to the type represented by the schema.
6
+ *
7
+ * Obtain instances through the {@link t} builder, never instantiate directly.
8
+ */
9
+ var TypeSchema = class TypeSchema {
10
+ /** @internal */
11
+ _accepts;
12
+ /** @internal */
13
+ _isOptional;
14
+ /** @internal */
15
+ constructor(accepts, isOptional = false) {
16
+ this._accepts = accepts;
17
+ this._isOptional = isOptional;
18
+ }
19
+ /**
20
+ * Marks this schema as optional when used as a property in {@link t.object}.
21
+ * An optional property may be absent from the type or carry the TypeScript
22
+ * `Optional` symbol flag.
23
+ *
24
+ * @example
25
+ * ```typescript
26
+ * const Shape = t.object({
27
+ * label: t.string().optional(),
28
+ * });
29
+ * ```
30
+ */
31
+ optional() {
32
+ return new TypeSchema(t.union(this, t.undefined())._accepts, true);
33
+ }
34
+ /**
35
+ * Wraps this schema to also accept `null`.
36
+ *
37
+ * @example
38
+ * ```typescript
39
+ * const MaybeNumber = t.number().nullable(); // number | null
40
+ * ```
41
+ */
42
+ nullable() {
43
+ return t.union(this, t.null());
44
+ }
45
+ /**
46
+ * Wraps this schema to also accept `null` and `undefined`.
47
+ *
48
+ * @example
49
+ * ```typescript
50
+ * const MaybeNumber = t.number().nullish(); // number | null | undefined
51
+ * ```
52
+ */
53
+ nullish() {
54
+ return this.nullable().optional();
55
+ }
56
+ };
57
+ const schema = (check) => new TypeSchema(check);
58
+ const moduleTypeCache = new WeakMap();
59
+ /**
60
+ * Schema builder namespace.
61
+ */
62
+ const t = {
63
+ number: () => schema((type, { checker }) => checker.isTypeAssignableTo(type, checker.getNumberType())),
64
+ string: () => schema((type, { checker }) => checker.isTypeAssignableTo(type, checker.getStringType())),
65
+ boolean: () => schema((type, { checker }) => checker.isTypeAssignableTo(type, checker.getBooleanType())),
66
+ void: () => schema((type, { checker }) => checker.isTypeAssignableTo(type, checker.getVoidType())),
67
+ undefined: () => schema((type, { checker }) => checker.isTypeAssignableTo(type, checker.getUndefinedType())),
68
+ null: () => schema((type, { checker }) => checker.isTypeAssignableTo(type, checker.getNullType())),
69
+ any: () => schema(() => true),
70
+ unknown: () => schema(() => true),
71
+ object: (shape) => schema((type, ctx) => Object.entries(shape).every(([key, propSchema]) => {
72
+ const propSymbol = type.getProperty(key);
73
+ if (!propSymbol) return propSchema._isOptional;
74
+ if (!propSchema._isOptional && (propSymbol.flags & TS_SYMBOL_FLAGS_OPTIONAL) !== 0) return false;
75
+ const propType = ctx.checker.getTypeOfSymbol(propSymbol);
76
+ return propSchema._accepts(propType, ctx);
77
+ })),
78
+ array: (element) => schema((type, ctx) => {
79
+ const indexType = type.getNumberIndexType();
80
+ if (!indexType) return false;
81
+ return element._accepts(indexType, ctx);
82
+ }),
83
+ union: (...members) => schema((type, ctx) => {
84
+ if (type.isUnion()) return type.types.every((member) => members.some((m) => m._accepts(member, ctx)));
85
+ return members.some((m) => m._accepts(type, ctx));
86
+ }),
87
+ intersection: (...members) => schema((type, ctx) => members.every((m) => m._accepts(type, ctx))),
88
+ fromModule: (modulePathPattern, exportName) => schema((type, { checker, program }) => {
89
+ if (!program) throw new Error("t.fromModule() requires `program` in the SchemaContext.");
90
+ let cache = moduleTypeCache.get(checker);
91
+ if (!cache) {
92
+ cache = new Map();
93
+ moduleTypeCache.set(checker, cache);
94
+ }
95
+ const cacheKey = JSON.stringify([modulePathPattern, exportName]);
96
+ if (!cache.has(cacheKey)) {
97
+ let resolved = null;
98
+ for (const sourceFile of program.getSourceFiles()) {
99
+ if (!sourceFile.fileName.includes(modulePathPattern)) continue;
100
+ const moduleSymbol = checker.getSymbolAtLocation(sourceFile);
101
+ if (!moduleSymbol) continue;
102
+ const exportSymbol = checker.getExportsOfModule(moduleSymbol).find((s) => s.getName() === exportName);
103
+ if (exportSymbol) {
104
+ resolved = checker.getDeclaredTypeOfSymbol(exportSymbol);
105
+ break;
106
+ }
107
+ }
108
+ cache.set(cacheKey, resolved);
109
+ }
110
+ const targetType = cache.get(cacheKey);
111
+ if (targetType == null) throw new Error(`t.fromModule(): could not resolve export "${exportName}" from any module matching "${modulePathPattern}".`);
112
+ return checker.isTypeAssignableTo(type, targetType);
113
+ }),
114
+ custom: (predicate) => schema(predicate)
115
+ };
116
+ /**
117
+ * Returns `true` if the given TypeScript type is assignable to the schema–in
118
+ * other words, if `type extends T` with `T` the TypeScript type represented
119
+ * by the schema.
120
+ */
121
+ function isAssignableTo(ctx, type, schema$1) {
122
+ return schema$1._accepts(type, ctx);
123
+ }
124
+
125
+ //#endregion
126
+ export { TypeSchema, isAssignableTo, t };
127
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["accepts: AcceptsFn","check: AcceptsFn","shape: Record<string, TypeSchema>","element: TypeSchema","modulePathPattern: string","exportName: string","resolved: Type | null","predicate: AcceptsFn","ctx: SchemaContext","type: Type","schema: TypeSchema"],"sources":["../src/index.ts"],"sourcesContent":["import type { TypeChecker, Type, Program, SymbolFlags } from \"typescript\";\n\nconst TS_SYMBOL_FLAGS_OPTIONAL = 16777216 satisfies SymbolFlags.Optional;\n\n/**\n * Context required by all schema checks. The `program` field is only needed\n * for schemas that resolve types from external modules ({@link t.fromModule}).\n */\nexport type SchemaContext = {\n checker: TypeChecker;\n program?: Program;\n};\n\ntype AcceptsFn = (type: Type, ctx: SchemaContext) => boolean;\n\n/**\n * A type schema that checks whether a TypeScript compiler type is assignable\n * to the type represented by the schema.\n *\n * Obtain instances through the {@link t} builder, never instantiate directly.\n */\nexport class TypeSchema {\n /** @internal */\n readonly _accepts: AcceptsFn;\n\n /** @internal */\n readonly _isOptional: boolean;\n\n /** @internal */\n constructor(accepts: AcceptsFn, isOptional = false) {\n this._accepts = accepts;\n this._isOptional = isOptional;\n }\n\n /**\n * Marks this schema as optional when used as a property in {@link t.object}.\n * An optional property may be absent from the type or carry the TypeScript\n * `Optional` symbol flag.\n *\n * @example\n * ```typescript\n * const Shape = t.object({\n * label: t.string().optional(),\n * });\n * ```\n */\n optional(): TypeSchema {\n return new TypeSchema(t.union(this, t.undefined())._accepts, true);\n }\n\n /**\n * Wraps this schema to also accept `null`.\n *\n * @example\n * ```typescript\n * const MaybeNumber = t.number().nullable(); // number | null\n * ```\n */\n nullable(): TypeSchema {\n return t.union(this, t.null());\n }\n\n /**\n * Wraps this schema to also accept `null` and `undefined`.\n *\n * @example\n * ```typescript\n * const MaybeNumber = t.number().nullish(); // number | null | undefined\n * ```\n */\n nullish(): TypeSchema {\n return this.nullable().optional();\n }\n}\n\nconst schema = (check: AcceptsFn): TypeSchema => new TypeSchema(check);\n\n// Per-checker cache for `t.fromModule()` resolved types.\nconst moduleTypeCache = new WeakMap<TypeChecker, Map<string, Type | null>>();\n\n/**\n * Schema builder namespace.\n */\nexport const t = {\n /** Represents the `number` type. */\n number: (): TypeSchema =>\n schema((type, { checker }) =>\n checker.isTypeAssignableTo(type, checker.getNumberType())\n ),\n\n /** Represents the `string` type. */\n string: (): TypeSchema =>\n schema((type, { checker }) =>\n checker.isTypeAssignableTo(type, checker.getStringType())\n ),\n\n /** Represents the `boolean` type. */\n boolean: (): TypeSchema =>\n schema((type, { checker }) =>\n checker.isTypeAssignableTo(type, checker.getBooleanType())\n ),\n\n /** Represents the `void` type. */\n void: (): TypeSchema =>\n schema((type, { checker }) =>\n checker.isTypeAssignableTo(type, checker.getVoidType())\n ),\n\n /** Represents the `undefined` type. */\n undefined: (): TypeSchema =>\n schema((type, { checker }) =>\n checker.isTypeAssignableTo(type, checker.getUndefinedType())\n ),\n\n /** Represents the `null` type. */\n null: (): TypeSchema =>\n schema((type, { checker }) =>\n checker.isTypeAssignableTo(type, checker.getNullType())\n ),\n\n /**\n * Represents the `any` type. Useful as a placeholder in object schemas when\n * you care about a property's existence but not its type.\n */\n any: (): TypeSchema => schema(() => true),\n\n /**\n * Represents the `unknown` type. Semantically identical to `t.any()` as a\n * predicate, but communicates intent differently in your schema.\n */\n unknown: (): TypeSchema => schema(() => true),\n\n /**\n * Represents an object type with the specified shape. Each property must be\n * present and non-optional unless its schema was marked `.optional()`.\n *\n * Extra properties are allowed (structural subtyping), consistent with\n * TypeScript's own assignability rules.\n *\n * @example\n * ```typescript\n * const Point = t.object({\n * x: t.number(),\n * y: t.number(),\n * label: t.string().optional(),\n * });\n * ```\n */\n object: (shape: Record<string, TypeSchema>): TypeSchema =>\n schema((type, ctx) =>\n Object.entries(shape).every(([key, propSchema]) => {\n const propSymbol = type.getProperty(key);\n\n if (!propSymbol) return propSchema._isOptional;\n\n if (\n !propSchema._isOptional &&\n (propSymbol.flags & TS_SYMBOL_FLAGS_OPTIONAL) !== 0\n ) {\n return false;\n }\n\n const propType = ctx.checker.getTypeOfSymbol(propSymbol);\n return propSchema._accepts(propType, ctx);\n })\n ),\n\n /**\n * Represents an array type whose element type satisfies the given schema.\n * Checks for a numeric index signature, so it also covers tuples and other\n * numerically-indexed types.\n *\n * @example\n * ```typescript\n * const NumberArray = t.array(t.number());\n * ```\n */\n array: (element: TypeSchema): TypeSchema =>\n schema((type, ctx) => {\n const indexType = type.getNumberIndexType();\n if (!indexType) return false;\n return element._accepts(indexType, ctx);\n }),\n\n /**\n * Represents a union of the given schemas. For union source types, every\n * constituent must individually satisfy at least one member schema.\n *\n * @example\n * ```typescript\n * const StringOrNumber = t.union(t.string(), t.number());\n * ```\n */\n union: (...members: TypeSchema[]): TypeSchema =>\n schema((type, ctx) => {\n if (type.isUnion()) {\n return type.types.every((member) =>\n members.some((m) => m._accepts(member, ctx))\n );\n }\n return members.some((m) => m._accepts(type, ctx));\n }),\n\n /**\n * Represents an intersection of the given schemas. The type must satisfy\n * every member schema simultaneously.\n *\n * @example\n * ```typescript\n * const NamedAndAged = t.intersection(\n * t.object({ name: t.string() }),\n * t.object({ age: t.number() }),\n * );\n * ```\n */\n intersection: (...members: TypeSchema[]): TypeSchema =>\n schema((type, ctx) => members.every((m) => m._accepts(type, ctx))),\n\n /**\n * Represents a type exported from a module in the program. Resolves a genuine\n * `ts.Type` and delegates to `checker.isTypeAssignableTo()`, so it handles\n * nominal class hierarchies correctly.\n *\n * Resolved types are cached per `TypeChecker` instance (via a `WeakMap`) so\n * repeated calls across files do not re-scan source files.\n *\n * Requires `program` in the {@link SchemaContext}.\n *\n * @param modulePathPattern Substring matched against source-file paths.\n * @param exportName The exported type, class or interface name.\n *\n * @example\n * ```typescript\n * const BaseWindow = t.fromModule(\"/electron/\", \"BaseWindow\");\n * const Buffer = t.fromModule(\"@types/node\", \"Buffer\");\n * ```\n */\n fromModule: (modulePathPattern: string, exportName: string): TypeSchema =>\n schema((type, { checker, program }) => {\n if (!program) {\n throw new Error(\n \"t.fromModule() requires `program` in the SchemaContext.\"\n );\n }\n\n let cache = moduleTypeCache.get(checker);\n if (!cache) {\n cache = new Map();\n moduleTypeCache.set(checker, cache);\n }\n\n const cacheKey = JSON.stringify([modulePathPattern, exportName]);\n\n if (!cache.has(cacheKey)) {\n let resolved: Type | null = null;\n for (const sourceFile of program.getSourceFiles()) {\n if (!sourceFile.fileName.includes(modulePathPattern)) continue;\n const moduleSymbol = checker.getSymbolAtLocation(sourceFile);\n if (!moduleSymbol) continue;\n const exportSymbol = checker\n .getExportsOfModule(moduleSymbol)\n .find((s) => s.getName() === exportName);\n if (exportSymbol) {\n resolved = checker.getDeclaredTypeOfSymbol(exportSymbol);\n break;\n }\n }\n cache.set(cacheKey, resolved);\n }\n\n const targetType = cache.get(cacheKey);\n if (targetType == null) {\n throw new Error(\n `t.fromModule(): could not resolve export \"${exportName}\" from any module matching \"${modulePathPattern}\".`\n );\n }\n return checker.isTypeAssignableTo(type, targetType);\n }),\n\n /**\n * Escape hatch for arbitrary predicates that the DSL cannot express directly.\n *\n * @example\n * ```typescript\n * const HasLengthProp = t.custom((type) =>\n * type.getProperty(\"length\") != null,\n * );\n * ```\n */\n custom: (predicate: AcceptsFn): TypeSchema => schema(predicate),\n};\n\n/**\n * Returns `true` if the given TypeScript type is assignable to the schema–in\n * other words, if `type extends T` with `T` the TypeScript type represented\n * by the schema.\n */\nexport function isAssignableTo(\n ctx: SchemaContext,\n type: Type,\n schema: TypeSchema\n): boolean {\n return schema._accepts(type, ctx);\n}\n"],"mappings":";AAEA,MAAM,2BAA2B;;;;;;;AAmBjC,IAAa,aAAb,MAAa,WAAW;;CAEtB,AAAS;;CAGT,AAAS;;CAGT,YAAYA,SAAoB,aAAa,OAAO;AAClD,OAAK,WAAW;AAChB,OAAK,cAAc;CACpB;;;;;;;;;;;;;CAcD,WAAuB;AACrB,SAAO,IAAI,WAAW,EAAE,MAAM,MAAM,EAAE,WAAW,CAAC,CAAC,UAAU;CAC9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,IAAI,UAAU,SAAS;EAC9B;EAED,MAAM,aAAa,MAAM,IAAI,SAAS;AACtC,MAAI,cAAc,KAChB,OAAM,IAAI,OACP,4CAA4C,WAAW,8BAA8B,kBAAkB;AAG5G,SAAO,QAAQ,mBAAmB,MAAM,WAAW;CACpD,EAAC;CAYJ,QAAQ,CAACC,cAAqC,OAAO,UAAU;AAChE;;;;;;AAOD,SAAgB,eACdC,KACAC,MACAC,UACS;AACT,QAAO,SAAO,SAAS,MAAM,IAAI;AAClC"}
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@liautaud/typezod",
3
+ "version": "1.0.0",
4
+ "description": "Zod-like DSL for comparing TypeScript compiler types against user-defined schemas",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "Romain Liautaud",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/liautaud/typezod.git"
11
+ },
12
+ "keywords": [
13
+ "typescript",
14
+ "type-checking",
15
+ "type-aware-linting",
16
+ "typescript-eslint",
17
+ "zod"
18
+ ],
19
+ "exports": {
20
+ ".": {
21
+ "import": "./dist/index.mjs",
22
+ "types": "./dist/index.d.mts"
23
+ }
24
+ },
25
+ "main": "./dist/index.mjs",
26
+ "types": "./dist/index.d.mts",
27
+ "files": [
28
+ "dist"
29
+ ],
30
+ "publishConfig": {
31
+ "provenance": true
32
+ },
33
+ "scripts": {
34
+ "build": "tsdown",
35
+ "typecheck": "tsc --noEmit",
36
+ "test": "vitest run",
37
+ "prepublishOnly": "npm test && npm run build"
38
+ },
39
+ "peerDependencies": {
40
+ "typescript": ">=5.0.0"
41
+ },
42
+ "devDependencies": {
43
+ "tsdown": "^0.11.9",
44
+ "typescript": "^5.9.3",
45
+ "vitest": "^3.2.4"
46
+ }
47
+ }