@liautaud/typezod 1.0.0 → 2.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/README.md CHANGED
@@ -27,7 +27,7 @@ const Rectangle = t.object({
27
27
  height: t.number(),
28
28
  });
29
29
 
30
- const ElectronWindow = t.fromModule("/electron/", "BaseWindow");
30
+ const ElectronWindow = t.fromModule("electron", "BaseWindow");
31
31
 
32
32
  // Inside a typescript-eslint rule's `create()` function, build a context
33
33
  // from the parser services and use `isAssignableTo` to check types.
@@ -51,36 +51,55 @@ by the schema.
51
51
  ### `SchemaContext`
52
52
 
53
53
  The context object passed to `isAssignableTo`. Contains a `checker`
54
- (required) and an optional `program` (only needed for `t.fromModule()`).
54
+ (always required), a `program` (required when using `t.fromModule()`),
55
+ and a `sourceFile` (required when using `t.fromModule()` with a relative
56
+ module specifier such as `"./foo"` or `"../foo"`).
57
+
58
+ Example for relative module specifiers inside an ESLint rule:
59
+
60
+ ```typescript
61
+ const tsNode = parserServices.esTreeNodeToTSNodeMap.get(node);
62
+ const ctx: SchemaContext = {
63
+ checker: parserServices.program.getTypeChecker(),
64
+ program: parserServices.program,
65
+ sourceFile: tsNode.getSourceFile(),
66
+ };
67
+ ```
55
68
 
56
69
  ### Primitives
57
70
 
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 |
71
+ | Builder | Description |
72
+ | --------------- | ------------------------------- |
73
+ | `t.string()` | Represents the `string` type |
74
+ | `t.number()` | Represents the `number` type |
75
+ | `t.boolean()` | Represents the `boolean` type |
76
+ | `t.void()` | Represents the `void` type |
77
+ | `t.undefined()` | Represents the `undefined` type |
78
+ | `t.null()` | Represents the `null` type |
79
+ | `t.any()` | Accepts any type |
80
+ | `t.unknown()` | Accepts any type |
68
81
 
69
82
  ### Combinators
70
83
 
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 |
84
+ | Builder | Description |
85
+ | ---------------------------- | ---------------------------------------------------------------- |
86
+ | `t.object(shape)` | Represents an object with the given shape (structural subtyping) |
87
+ | `t.array(element)` | Represents an array whose element satisfies the given schema |
88
+ | `t.union(...schemas)` | Represents a union of the given schemas |
89
+ | `t.intersection(...schemas)` | Represents an intersection of the given schemas |
77
90
 
78
91
  ### Advanced
79
92
 
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 |
93
+ | Builder | Description |
94
+ | -------------------------------------- | ------------------------------------------------------- |
95
+ | `t.fromModule(moduleName, exportName)` | Represents a type exported from a module in the program |
96
+ | `t.custom(fn)` | Escape hatch for arbitrary predicates |
97
+
98
+ `t.fromModule()` accepts the same module specifier you'd write in an `import` statement.
99
+ Installed packages (`"typescript"`, `"electron"`), relative paths (`"./types"`,
100
+ `"../shared/types"`), and ambient module declarations (`declare module '...'`) are
101
+ all supported. Relative specifiers require `sourceFile` in the context. Throws if the
102
+ module or export cannot be found.
84
103
 
85
104
  ### Modifiers
86
105
 
@@ -1,14 +1,21 @@
1
- import { Program, Type, TypeChecker } from "typescript";
1
+ import { Program, SourceFile, Type, TypeChecker } from "typescript";
2
2
 
3
3
  //#region src/index.d.ts
4
4
 
5
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}).
6
+ * Context required by all schema checks.
7
+ *
8
+ * `program` is required by schemas that resolve module exports
9
+ * ({@link t.fromModule}).
10
+ *
11
+ * `sourceFile` is only required when resolving relative module specifiers
12
+ * (`"./x"`, `"../x"`) with {@link t.fromModule}. It should be the source file
13
+ * currently being analyzed.
8
14
  */
9
15
  type SchemaContext = {
10
16
  checker: TypeChecker;
11
17
  program?: Program;
18
+ sourceFile?: SourceFile;
12
19
  };
13
20
  type AcceptsFn = (type: Type, ctx: SchemaContext) => boolean;
14
21
  /**
@@ -56,6 +63,12 @@ declare class TypeSchema {
56
63
  */
57
64
  nullish(): TypeSchema;
58
65
  }
66
+ /**
67
+ * Returns `true` if the given TypeScript type is assignable to the schema–in
68
+ * other words, if `type extends T` with `T` the TypeScript type represented
69
+ * by the schema.
70
+ */
71
+ declare function isAssignableTo(ctx: SchemaContext, type: Type, schema: TypeSchema): boolean;
59
72
  /**
60
73
  * Schema builder namespace.
61
74
  */
@@ -134,25 +147,27 @@ declare const t: {
134
147
  */
135
148
  intersection: (...members: TypeSchema[]) => TypeSchema;
136
149
  /**
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.
150
+ * Represents a type exported from a module. Resolves the module using
151
+ * TypeScript's module resolution algorithm, with a fallback to ambient
152
+ * module declarations. Resolved types are cached per `TypeChecker` instance.
140
153
  *
141
- * Resolved types are cached per `TypeChecker` instance (via a `WeakMap`) so
142
- * repeated calls across files do not re-scan source files.
154
+ * Requires `program` in the {@link SchemaContext}. Relative specifiers
155
+ * (`"./x"`, `"../x"`) also require `sourceFile`.
143
156
  *
144
- * Requires `program` in the {@link SchemaContext}.
145
- *
146
- * @param modulePathPattern Substring matched against source-file paths.
157
+ * @param moduleName The module specifier, as in an `import` statement.
147
158
  * @param exportName The exported type, class or interface name.
148
159
  *
149
160
  * @example
150
161
  * ```typescript
151
- * const BaseWindow = t.fromModule("/electron/", "BaseWindow");
152
- * const Buffer = t.fromModule("@types/node", "Buffer");
162
+ * const BaseWindow = t.fromModule("electron", "BaseWindow");
163
+ * const Buffer = t.fromModule("node:buffer", "Buffer");
153
164
  * ```
165
+ *
166
+ * @throws When `program` is missing from the context.
167
+ * @throws When `moduleName` is relative and `sourceFile` is missing.
168
+ * @throws When no export named `exportName` can be resolved from `moduleName`.
154
169
  */
155
- fromModule: (modulePathPattern: string, exportName: string) => TypeSchema;
170
+ fromModule: (moduleName: string, exportName: string) => TypeSchema;
156
171
  /**
157
172
  * Escape hatch for arbitrary predicates that the DSL cannot express directly.
158
173
  *
@@ -165,12 +180,5 @@ declare const t: {
165
180
  */
166
181
  custom: (predicate: AcceptsFn) => TypeSchema;
167
182
  };
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
183
  //#endregion
175
- export { SchemaContext, TypeSchema, isAssignableTo, t };
176
- //# sourceMappingURL=index.d.ts.map
184
+ export { SchemaContext, TypeSchema, isAssignableTo, t };
@@ -1,3 +1,5 @@
1
+ import ts from "typescript";
2
+
1
3
  //#region src/index.ts
2
4
  const TS_SYMBOL_FLAGS_OPTIONAL = 16777216;
3
5
  /**
@@ -55,7 +57,14 @@ var TypeSchema = class TypeSchema {
55
57
  }
56
58
  };
57
59
  const schema = (check) => new TypeSchema(check);
58
- const moduleTypeCache = new WeakMap();
60
+ /**
61
+ * Returns `true` if the given TypeScript type is assignable to the schema–in
62
+ * other words, if `type extends T` with `T` the TypeScript type represented
63
+ * by the schema.
64
+ */
65
+ function isAssignableTo(ctx, type, schema$1) {
66
+ return schema$1._accepts(type, ctx);
67
+ }
59
68
  /**
60
69
  * Schema builder namespace.
61
70
  */
@@ -85,43 +94,56 @@ const t = {
85
94
  return members.some((m) => m._accepts(type, ctx));
86
95
  }),
87
96
  intersection: (...members) => schema((type, ctx) => members.every((m) => m._accepts(type, ctx))),
88
- fromModule: (modulePathPattern, exportName) => schema((type, { checker, program }) => {
97
+ fromModule: (moduleName, exportName) => schema((type, { checker, program, sourceFile }) => {
89
98
  if (!program) throw new Error("t.fromModule() requires `program` in the SchemaContext.");
99
+ const isRelative = moduleName.startsWith("./") || moduleName.startsWith("../");
100
+ if (isRelative && !sourceFile) throw new Error("t.fromModule() requires `sourceFile` in the SchemaContext for relative module specifiers.");
90
101
  let cache = moduleTypeCache.get(checker);
91
102
  if (!cache) {
92
- cache = new Map();
103
+ cache = /* @__PURE__ */ new Map();
93
104
  moduleTypeCache.set(checker, cache);
94
105
  }
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
- }
106
+ const cacheKey = JSON.stringify([
107
+ moduleName,
108
+ exportName,
109
+ isRelative ? sourceFile.fileName : null
110
+ ]);
111
+ if (!cache.has(cacheKey)) cache.set(cacheKey, resolveModuleType(checker, program, moduleName, exportName, sourceFile));
110
112
  const targetType = cache.get(cacheKey);
111
- if (targetType == null) throw new Error(`t.fromModule(): could not resolve export "${exportName}" from any module matching "${modulePathPattern}".`);
113
+ if (targetType == null) throw new Error(`t.fromModule(): could not resolve export "${exportName}" from module "${moduleName}".`);
112
114
  return checker.isTypeAssignableTo(type, targetType);
113
115
  }),
114
116
  custom: (predicate) => schema(predicate)
115
117
  };
118
+ /** Per-checker cache for `t.fromModule()` resolved types. */
119
+ const moduleTypeCache = /* @__PURE__ */ new WeakMap();
116
120
  /**
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.
121
+ * Resolves a module's exported type using TypeScript's module resolution
122
+ * algorithm, with a fallback to ambient module declarations.
123
+ *
124
+ * Returns the resolved `ts.Type`, or `null` if the export cannot be found.
125
+ *
126
+ * @throws When multiple ambient/resolved symbols yield different types for the
127
+ * same export name (ambiguity).
120
128
  */
121
- function isAssignableTo(ctx, type, schema$1) {
122
- return schema$1._accepts(type, ctx);
123
- }
129
+ const resolveModuleType = (checker, program, moduleName, exportName, sourceFile) => {
130
+ const compilerOptions = program.getCompilerOptions();
131
+ const containingFile = sourceFile ? sourceFile.fileName : program.getCurrentDirectory() + "/__typezod__.ts";
132
+ let moduleSymbol;
133
+ const resolved = ts.resolveModuleName(moduleName, containingFile, compilerOptions, ts.sys);
134
+ if (resolved.resolvedModule) {
135
+ const resolvedSf = program.getSourceFile(resolved.resolvedModule.resolvedFileName);
136
+ if (resolvedSf) moduleSymbol = checker.getSymbolAtLocation(resolvedSf);
137
+ }
138
+ if (!moduleSymbol) {
139
+ const quotedName = `"${moduleName}"`;
140
+ moduleSymbol = checker.getAmbientModules().find((s) => s.getName() === quotedName);
141
+ }
142
+ if (!moduleSymbol) return null;
143
+ const exportSymbol = checker.getExportsOfModule(moduleSymbol).find((s) => s.getName() === exportName);
144
+ if (!exportSymbol) return null;
145
+ return checker.getDeclaredTypeOfSymbol(exportSymbol);
146
+ };
124
147
 
125
148
  //#endregion
126
- export { TypeSchema, isAssignableTo, t };
127
- //# sourceMappingURL=index.js.map
149
+ export { TypeSchema, isAssignableTo, t };
package/package.json CHANGED
@@ -1,14 +1,18 @@
1
1
  {
2
2
  "name": "@liautaud/typezod",
3
- "version": "1.0.0",
4
- "description": "Zod-like DSL for comparing TypeScript compiler types against user-defined schemas",
5
3
  "type": "module",
6
- "license": "MIT",
4
+ "version": "2.0.0",
5
+ "description": "Zod-like DSL for comparing TypeScript compiler types against user-defined schemas",
7
6
  "author": "Romain Liautaud",
7
+ "license": "MIT",
8
+ "homepage": "https://github.com/liautaud/typezod#readme",
8
9
  "repository": {
9
10
  "type": "git",
10
11
  "url": "git+https://github.com/liautaud/typezod.git"
11
12
  },
13
+ "bugs": {
14
+ "url": "https://github.com/liautaud/typezod/issues"
15
+ },
12
16
  "keywords": [
13
17
  "typescript",
14
18
  "type-checking",
@@ -32,16 +36,19 @@
32
36
  },
33
37
  "scripts": {
34
38
  "build": "tsdown",
39
+ "dev": "tsdown --watch",
40
+ "test": "vitest",
35
41
  "typecheck": "tsc --noEmit",
36
- "test": "vitest run",
37
42
  "prepublishOnly": "npm test && npm run build"
38
43
  },
39
44
  "peerDependencies": {
40
45
  "typescript": ">=5.0.0"
41
46
  },
42
47
  "devDependencies": {
43
- "tsdown": "^0.11.9",
48
+ "@types/node": "^25.0.3",
49
+ "prettier": "^3.8.1",
50
+ "tsdown": "^0.18.1",
44
51
  "typescript": "^5.9.3",
45
- "vitest": "^3.2.4"
52
+ "vitest": "^4.0.16"
46
53
  }
47
54
  }
@@ -1 +0,0 @@
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.map DELETED
@@ -1 +0,0 @@
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 */\nex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