@rpc-dart/trpc-adapter 0.0.0-stage → 0.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 rpc-dart contributors
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 CHANGED
@@ -1,3 +1,17 @@
1
- # Temporary Holding Version
1
+ # @rpc-dart/trpc-adapter
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ tRPC v11 extraction adapter: route probe, inference harness, Contract IR normalizer.
4
+
5
+ Part of the [rpc-dart](https://github.com/rpc-dart/rpc-dart) monorepo — end-to-end type safety for tRPC v11 backends consumed from Dart and Flutter.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install @rpc-dart/trpc-adapter
11
+ ```
12
+
13
+ See the [documentation](../../docs/README.md) for the full CLI reference, concepts, and guides.
14
+
15
+ ## License
16
+
17
+ MIT — see [LICENSE](./LICENSE).
@@ -0,0 +1,40 @@
1
+ import type * as tsTypes from 'typescript';
2
+ import type { FieldDef, TypeRef } from '@rpc-dart/core';
3
+ import type { RpcDartDiagnostic } from '@rpc-dart/core';
4
+ export declare class TypeClassificationError extends Error {
5
+ readonly diagnostic: RpcDartDiagnostic;
6
+ constructor(diagnostic: RpcDartDiagnostic);
7
+ }
8
+ export declare function pascal(input: string): string;
9
+ /**
10
+ * TypeChecker type -> Contract IR TypeDef. Field optionality/nullability is
11
+ * decided here (undefined -> optional, null -> nullable) so the emitter never
12
+ * sees unions for optionality.
13
+ *
14
+ * Recursive types are handled with an in-progress stack: re-entering a type
15
+ * currently being classified yields a transient selfRef that the assembler
16
+ * resolves into a forward $ref.
17
+ */
18
+ export type UnserializablePolicy = 'error' | 'warn-dynamic' | 'skip-procedure';
19
+ export declare class TypeClassifier {
20
+ private readonly ts;
21
+ private readonly checker;
22
+ private readonly unserializablePolicy;
23
+ private readonly cache;
24
+ private readonly inProgress;
25
+ private readonly stack;
26
+ currentProcedure: string | undefined;
27
+ /** Warnings recorded when per-field warn-dynamic downgrades occur. */
28
+ readonly collectedDiagnostics: RpcDartDiagnostic[];
29
+ constructor(ts: typeof tsTypes, checker: tsTypes.TypeChecker, unserializablePolicy?: UnserializablePolicy);
30
+ classifyProperty(symbol: tsTypes.Symbol, parentName: string): FieldDef;
31
+ classify(type: tsTypes.Type, nameHint: string): TypeRef;
32
+ private classifyUncached;
33
+ private classifyUnion;
34
+ private tryDiscriminatedUnion;
35
+ private classifyObject;
36
+ private locationOf;
37
+ private isOptional;
38
+ private stripNullish;
39
+ private typeArgument;
40
+ }
@@ -0,0 +1,360 @@
1
+ export class TypeClassificationError extends Error {
2
+ diagnostic;
3
+ constructor(diagnostic) {
4
+ super(`${diagnostic.code}: ${diagnostic.message}`);
5
+ this.name = 'TypeClassificationError';
6
+ this.diagnostic = diagnostic;
7
+ }
8
+ }
9
+ export function pascal(input) {
10
+ return input
11
+ .split(/[.\-_]/)
12
+ .filter((s) => s.length > 0)
13
+ .map((s) => s.charAt(0).toUpperCase() + s.slice(1))
14
+ .join('');
15
+ }
16
+ function fail(code, message, hint, context = {}) {
17
+ return new TypeClassificationError({
18
+ code,
19
+ severity: 'error',
20
+ message,
21
+ procedurePath: context.procedurePath,
22
+ file: context.file,
23
+ line: context.line,
24
+ column: context.column,
25
+ hint,
26
+ });
27
+ }
28
+ export class TypeClassifier {
29
+ ts;
30
+ checker;
31
+ unserializablePolicy;
32
+ cache = new Map();
33
+ inProgress = new Set();
34
+ stack = [];
35
+ currentProcedure;
36
+ /** Warnings recorded when per-field warn-dynamic downgrades occur. */
37
+ collectedDiagnostics = [];
38
+ constructor(ts, checker, unserializablePolicy = 'error') {
39
+ this.ts = ts;
40
+ this.checker = checker;
41
+ this.unserializablePolicy = unserializablePolicy;
42
+ }
43
+ classifyProperty(symbol, parentName) {
44
+ const name = symbol.getName();
45
+ const declared = this.checker.getTypeOfSymbol(symbol);
46
+ const optional = this.isOptional(symbol, declared);
47
+ const { stripped, nullable } = this.stripNullish(declared);
48
+ let type;
49
+ try {
50
+ type = this.classify(stripped, `${parentName}${pascal(name)}`);
51
+ }
52
+ catch (error) {
53
+ if (error instanceof TypeClassificationError) {
54
+ if (error.diagnostic.file === undefined) {
55
+ const location = this.locationOf(symbol);
56
+ if (location) {
57
+ error.diagnostic.file = location.file;
58
+ error.diagnostic.line = location.line;
59
+ error.diagnostic.column = location.column;
60
+ }
61
+ }
62
+ // Per-field warn-dynamic: downgrade only this offending field to an
63
+ // unknown (JsonValue) type and record the warning; siblings stay
64
+ // strongly typed.
65
+ if (this.unserializablePolicy === 'warn-dynamic' && error.diagnostic.code === 'RPCDART0201') {
66
+ error.diagnostic.severity = 'warning';
67
+ this.collectedDiagnostics.push(error.diagnostic);
68
+ return { name, wireName: name, type: { kind: 'unknown' }, optional, nullable };
69
+ }
70
+ }
71
+ throw error;
72
+ }
73
+ return { name, wireName: name, type, optional, nullable };
74
+ }
75
+ classify(type, nameHint) {
76
+ const cached = this.cache.get(type);
77
+ if (cached)
78
+ return cached;
79
+ if (this.inProgress.has(type)) {
80
+ // Recursion: the enclosing named type will resolve this marker.
81
+ return { kind: 'selfRef', name: this.stack[this.stack.length - 1] ?? nameHint };
82
+ }
83
+ this.inProgress.add(type);
84
+ try {
85
+ const def = this.classifyUncached(type, nameHint);
86
+ this.cache.set(type, def);
87
+ return def;
88
+ }
89
+ finally {
90
+ this.inProgress.delete(type);
91
+ }
92
+ }
93
+ classifyUncached(type, nameHint) {
94
+ const ts = this.ts;
95
+ const flags = type.flags;
96
+ if (flags & ts.TypeFlags.String)
97
+ return 'string';
98
+ if (flags & ts.TypeFlags.Number)
99
+ return 'number';
100
+ if (flags & ts.TypeFlags.Boolean)
101
+ return 'boolean';
102
+ if (flags & ts.TypeFlags.BigInt)
103
+ return 'BigInt';
104
+ if (flags & ts.TypeFlags.Void)
105
+ return 'void';
106
+ if (flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown))
107
+ return { kind: 'unknown' };
108
+ if (flags & ts.TypeFlags.Null || flags & ts.TypeFlags.Undefined)
109
+ return { kind: 'unknown' };
110
+ if (flags & (ts.TypeFlags.StringLiteral | ts.TypeFlags.NumberLiteral)) {
111
+ return { kind: 'literal', value: type.value };
112
+ }
113
+ if (flags & ts.TypeFlags.BooleanLiteral) {
114
+ const intrinsic = type.intrinsicName;
115
+ return { kind: 'literal', value: intrinsic === 'true' };
116
+ }
117
+ if (type.isUnion())
118
+ return this.classifyUnion(type, nameHint);
119
+ if (flags & ts.TypeFlags.Intersection) {
120
+ // Branded/nominal types (string & BRAND<'X'>) are intersections whose
121
+ // phantom members carry only `__@`-prefixed symbol properties; the
122
+ // real payload is the first non-phantom member.
123
+ const members = type.types;
124
+ const nonPhantom = members.filter((member) => {
125
+ const apparent = this.checker.getApparentType(member);
126
+ if (!(apparent.flags & this.ts.TypeFlags.Object))
127
+ return true;
128
+ const props = this.checker.getPropertiesOfType(apparent);
129
+ return props.length > 0 && props.some((p2) => !p2.getName().startsWith('__@'));
130
+ });
131
+ if (nonPhantom.length >= 1) {
132
+ return this.classify(nonPhantom[0], nameHint);
133
+ }
134
+ throw fail('RPCDART0201', `cannot classify intersection at ${nameHint}`, 'simplify the intersection type', {
135
+ procedurePath: this.currentProcedure,
136
+ });
137
+ }
138
+ if (flags & ts.TypeFlags.Object) {
139
+ const symbol = type.getSymbol() ?? type.aliasSymbol;
140
+ const symbolName = symbol ? symbol.getName() : '';
141
+ if (symbolName === 'Date')
142
+ return 'Date';
143
+ if (symbolName === 'Function') {
144
+ throw fail('RPCDART0201', `unserializable type Function at ${nameHint}`, 'remove the field from the schema, or set unserializablePolicy in the generator config', { procedurePath: this.currentProcedure });
145
+ }
146
+ if (symbolName === 'Promise') {
147
+ throw fail('RPCDART0201', `unserializable type Promise at ${nameHint} (async values cannot cross the wire)`, 'await the promise inside the resolver and return its resolved type', { procedurePath: this.currentProcedure });
148
+ }
149
+ if (symbolName === 'Symbol') {
150
+ throw fail('RPCDART0201', `unserializable type Symbol at ${nameHint}`, 'use a string identifier instead', {
151
+ procedurePath: this.currentProcedure,
152
+ });
153
+ }
154
+ if (symbolName === 'RegExp') {
155
+ throw fail('RPCDART0201', `unserializable type RegExp at ${nameHint}`, 'serialize as a string pattern instead', {
156
+ procedurePath: this.currentProcedure,
157
+ });
158
+ }
159
+ if (symbolName === 'Set') {
160
+ const element = this.checker.getIndexTypeOfType(type, this.ts.IndexKind.Number) ??
161
+ this.typeArgument(type, 0);
162
+ if (!element) {
163
+ throw fail('RPCDART0201', `Set without a type argument at ${nameHint}`, 'give Set an explicit element type', {
164
+ procedurePath: this.currentProcedure,
165
+ });
166
+ }
167
+ return { kind: 'set', element: this.classify(element, `${nameHint}Item`) };
168
+ }
169
+ if (symbolName === 'Map') {
170
+ const key = this.typeArgument(type, 0);
171
+ const value = this.typeArgument(type, 1);
172
+ if (!key || !value) {
173
+ throw fail('RPCDART0201', `Map without type arguments at ${nameHint}`, 'give Map explicit key and value types', {
174
+ procedurePath: this.currentProcedure,
175
+ });
176
+ }
177
+ const keyType = this.classify(key, `${nameHint}Key`);
178
+ if (typeof keyType !== 'string') {
179
+ throw fail('RPCDART0203', `unmappable map key type at ${nameHint}`, 'use string or enum keys', {
180
+ procedurePath: this.currentProcedure,
181
+ });
182
+ }
183
+ return {
184
+ kind: 'record',
185
+ keyType,
186
+ valueType: this.classify(value, `${nameHint}Value`),
187
+ };
188
+ }
189
+ if (this.checker.isArrayType(type) || symbolName === 'ReadonlyArray') {
190
+ const element = this.checker.getIndexTypeOfType(type, this.ts.IndexKind.Number) ??
191
+ this.typeArgument(type, 0);
192
+ if (!element) {
193
+ throw fail('RPCDART0201', `array without element at ${nameHint}`, 'give the array an explicit element type', {
194
+ procedurePath: this.currentProcedure,
195
+ });
196
+ }
197
+ return { kind: 'list', element: this.classify(element, `${nameHint}Item`) };
198
+ }
199
+ if (this.checker.isTupleType(type)) {
200
+ const args = type.typeArguments ?? [];
201
+ return { kind: 'tuple', items: args.map((a, i) => this.classify(a, `${nameHint}${i}`)) };
202
+ }
203
+ const props = this.checker.getPropertiesOfType(type);
204
+ const indexInfos = this.checker.getIndexInfosOfType(type);
205
+ if (props.length === 0 && this.checker.getSignaturesOfType(type, this.ts.SignatureKind.Call).length > 0) {
206
+ // Anonymous function types (e.g. z.function() inference) carry no
207
+ // Function symbol but are equally unserializable.
208
+ throw fail('RPCDART0201', `unserializable function type at ${nameHint}`, 'remove the field from the schema, or set unserializablePolicy in the generator config', {
209
+ procedurePath: this.currentProcedure,
210
+ });
211
+ }
212
+ if (props.length === 0 && indexInfos.length > 0) {
213
+ const info = indexInfos[0];
214
+ if (!info.keyType) {
215
+ throw fail('RPCDART0203', `record key type missing at ${nameHint}`, 'use string keys', {
216
+ procedurePath: this.currentProcedure,
217
+ });
218
+ }
219
+ const keyType = this.classify(info.keyType, `${nameHint}Key`);
220
+ if (typeof keyType !== 'string') {
221
+ throw fail('RPCDART0203', `unmappable record key type at ${nameHint}`, 'use string or enum keys', {
222
+ procedurePath: this.currentProcedure,
223
+ });
224
+ }
225
+ const kind = keyType === 'string' ? this.ts.IndexKind.String : this.ts.IndexKind.Number;
226
+ const valueType = this.checker.getIndexTypeOfType(type, kind);
227
+ if (!valueType) {
228
+ throw fail('RPCDART0203', `record value type missing at ${nameHint}`, 'give the record a value type', {
229
+ procedurePath: this.currentProcedure,
230
+ });
231
+ }
232
+ return {
233
+ kind: 'record',
234
+ keyType,
235
+ valueType: this.classify(valueType, `${nameHint}Value`),
236
+ };
237
+ }
238
+ if (props.length > 0) {
239
+ this.stack.push(nameHint);
240
+ try {
241
+ return this.classifyObject(type, nameHint);
242
+ }
243
+ finally {
244
+ this.stack.pop();
245
+ }
246
+ }
247
+ }
248
+ throw fail('RPCDART0201', `cannot classify type at ${nameHint}`, 'simplify the type or use a schema primitive', {
249
+ procedurePath: this.currentProcedure,
250
+ });
251
+ }
252
+ classifyUnion(type, nameHint) {
253
+ const members = type.types.filter((t) => !(t.flags & (this.ts.TypeFlags.Null | this.ts.TypeFlags.Undefined)));
254
+ if (members.length === 0)
255
+ return { kind: 'unknown' };
256
+ const allLiterals = members.every((t) => (t.flags & (this.ts.TypeFlags.StringLiteral | this.ts.TypeFlags.NumberLiteral)) !== 0);
257
+ if (allLiterals) {
258
+ const values = [
259
+ ...new Set(members.map((t) => t.value)),
260
+ ].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
261
+ const def = { kind: 'enum', name: nameHint, values };
262
+ return def;
263
+ }
264
+ const du = this.tryDiscriminatedUnion(members, nameHint);
265
+ if (du)
266
+ return du;
267
+ if (members.length === 1)
268
+ return this.classify(members[0], nameHint);
269
+ throw fail('RPCDART0202', `non-discriminated object union at ${nameHint}`, 'add a literal discriminator field (z.discriminatedUnion) or widen to a single shape', { procedurePath: this.currentProcedure });
270
+ }
271
+ tryDiscriminatedUnion(members, nameHint) {
272
+ const propsPerMember = [];
273
+ for (const member of members) {
274
+ if (!(member.flags & this.ts.TypeFlags.Object))
275
+ return null;
276
+ const resolved = this.checker.getApparentType(member);
277
+ const props = this.checker.getPropertiesOfType(resolved);
278
+ if (props.length === 0)
279
+ return null;
280
+ const map = new Map(props.map((s) => [s.getName(), s]));
281
+ propsPerMember.push(map);
282
+ }
283
+ const first = propsPerMember[0];
284
+ for (const [tagField] of first) {
285
+ const tags = [];
286
+ let viable = true;
287
+ for (const map of propsPerMember) {
288
+ const sym = map.get(tagField);
289
+ if (!sym) {
290
+ viable = false;
291
+ break;
292
+ }
293
+ const t = this.checker.getTypeOfSymbol(sym);
294
+ if (!(t.flags & (this.ts.TypeFlags.StringLiteral | this.ts.TypeFlags.NumberLiteral))) {
295
+ viable = false;
296
+ break;
297
+ }
298
+ tags.push(t.value);
299
+ }
300
+ if (!viable)
301
+ continue;
302
+ if (new Set(tags.map((t) => `${t}`)).size !== tags.length)
303
+ continue;
304
+ const variants = members.map((member, i) => ({
305
+ tag: tags[i],
306
+ object: this.classify(member, `${nameHint}${pascal(String(tags[i]))}`),
307
+ }));
308
+ variants.sort((a, b) => (String(a.tag) < String(b.tag) ? -1 : String(a.tag) > String(b.tag) ? 1 : 0));
309
+ return { kind: 'discriminatedUnion', name: nameHint, tagField, variants };
310
+ }
311
+ return null;
312
+ }
313
+ classifyObject(type, name) {
314
+ const props = this.checker.getPropertiesOfType(type);
315
+ const fields = props.map((sym) => this.classifyProperty(sym, name));
316
+ fields.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
317
+ return { kind: 'object', name, fields };
318
+ }
319
+ locationOf(symbol) {
320
+ const declaration = symbol.valueDeclaration ?? symbol.declarations?.[0];
321
+ if (!declaration)
322
+ return null;
323
+ const sourceFile = declaration.getSourceFile();
324
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(declaration.getStart());
325
+ return { file: sourceFile.fileName, line: line + 1, column: character + 1 };
326
+ }
327
+ isOptional(symbol, declared) {
328
+ if ((symbol.flags & this.ts.SymbolFlags.Optional) !== 0)
329
+ return true;
330
+ const question = (symbol.declarations ?? []).some((d) => 'questionToken' in d && d.questionToken !== undefined);
331
+ if (question)
332
+ return true;
333
+ if (declared.isUnion()) {
334
+ return declared.types.some((t) => (t.flags & this.ts.TypeFlags.Undefined) !== 0);
335
+ }
336
+ return false;
337
+ }
338
+ stripNullish(type) {
339
+ if (!type.isUnion())
340
+ return { stripped: type, nullable: false };
341
+ const hasNull = type.types.some((t) => (t.flags & this.ts.TypeFlags.Null) !== 0);
342
+ const hasUndefined = type.types.some((t) => (t.flags & this.ts.TypeFlags.Undefined) !== 0);
343
+ if (!hasNull && !hasUndefined)
344
+ return { stripped: type, nullable: false };
345
+ const rest = type.types.filter((t) => !(t.flags & (this.ts.TypeFlags.Null | this.ts.TypeFlags.Undefined)));
346
+ if (rest.length === 0)
347
+ return { stripped: type, nullable: hasNull };
348
+ if (rest.length === 1)
349
+ return { stripped: rest[0], nullable: hasNull };
350
+ // Multiple value members plus a nullish member cannot be rebuilt without
351
+ // a public checker union API - surface it rather than guessing.
352
+ throw fail('RPCDART0201', 'union with value members and nullish members cannot be decoded', 'restructure the union', {
353
+ procedurePath: this.currentProcedure,
354
+ });
355
+ }
356
+ typeArgument(type, index) {
357
+ const args = type.typeArguments;
358
+ return args ? args[index] : undefined;
359
+ }
360
+ }
@@ -0,0 +1,21 @@
1
+ import { type ContractIR, type RpcDartDiagnostic } from '@rpc-dart/core';
2
+ export interface ExtractPolicies {
3
+ /** Default: 'error'. 'warn-dynamic' emits unknown + records; 'skip-procedure' drops the procedure. */
4
+ unserializablePolicy?: 'error' | 'warn-dynamic' | 'skip-procedure';
5
+ }
6
+ export interface ExtractOptions {
7
+ tsconfigPath: string;
8
+ entryFile: string;
9
+ exportName: string;
10
+ protocol: {
11
+ kind: 'trpc' | 'orpc';
12
+ version: string;
13
+ transformer: 'superjson' | 'json';
14
+ };
15
+ policies?: ExtractPolicies;
16
+ }
17
+ export interface ExtractResult {
18
+ ir: ContractIR;
19
+ diagnostics: RpcDartDiagnostic[];
20
+ }
21
+ export declare function extractContract(options: ExtractOptions): Promise<ExtractResult>;
@@ -0,0 +1,179 @@
1
+ import path from 'node:path';
2
+ import * as ts from 'typescript';
3
+ import { assembleContract, ExtractionFailure, } from '@rpc-dart/core';
4
+ import { entryImportPath, buildHarness, harnessFileName, pathAlias } from './harness.js';
5
+ import { probeRouter } from './probe.js';
6
+ import { pascal, TypeClassificationError, TypeClassifier } from './classify.js';
7
+ const GENERATOR = { name: 'rpc-dart', version: '0.1.0' };
8
+ export async function extractContract(options) {
9
+ const tsconfigDir = path.dirname(options.tsconfigPath);
10
+ const entryAbsolute = path.resolve(tsconfigDir, options.entryFile);
11
+ const diagnostics = [];
12
+ // 1. Runtime probe: kinds + meta, sorted paths.
13
+ let probePaths;
14
+ try {
15
+ probePaths = await probeRouter(entryAbsolute, options.exportName);
16
+ }
17
+ catch (error) {
18
+ diagnostics.push({
19
+ code: 'RPCDART0102',
20
+ severity: 'error',
21
+ message: error.message,
22
+ hint: 'export the router as a const and make sure the module evaluates cleanly',
23
+ });
24
+ throw new ExtractionFailure(diagnostics);
25
+ }
26
+ // 2. Virtual harness over the public inference utilities, one alias pair per path.
27
+ const harnessPath = path.join(tsconfigDir, harnessFileName());
28
+ const harnessSource = buildHarness(entryImportPath(tsconfigDir, entryAbsolute), options.exportName, probePaths.map((p) => p.path));
29
+ // 3. Program under the user's own tsconfig, harness overlaid in memory.
30
+ const configFile = ts.readConfigFile(options.tsconfigPath, ts.sys.readFile);
31
+ if (configFile.error) {
32
+ diagnostics.push({
33
+ code: 'RPCDART0103',
34
+ severity: 'error',
35
+ message: `tsconfig failed to parse: ${ts.flattenDiagnosticMessageText(configFile.error.messageText, ' ')}`,
36
+ file: options.tsconfigPath,
37
+ hint: 'make sure tsconfig.json is valid JSON with the compiler options your project needs',
38
+ });
39
+ throw new ExtractionFailure(diagnostics);
40
+ }
41
+ const parsed = ts.parseJsonConfigFileContent(configFile.config, ts.sys, tsconfigDir);
42
+ const baseHost = ts.createCompilerHost(parsed.options, true);
43
+ const host = overlayHost(baseHost, harnessPath, harnessSource);
44
+ const program = ts.createProgram({
45
+ rootNames: [harnessPath, ...parsed.fileNames],
46
+ options: parsed.options,
47
+ host,
48
+ });
49
+ const harnessSf = program.getSourceFile(harnessPath);
50
+ if (!harnessSf)
51
+ throw new ExtractionFailure([{
52
+ code: 'RPCDART0105',
53
+ severity: 'error',
54
+ message: 'harness missing from program',
55
+ }]);
56
+ const programDiagnostics = [
57
+ ...program.getSyntacticDiagnostics(),
58
+ ...program.getSemanticDiagnostics(),
59
+ ];
60
+ if (programDiagnostics.length > 0) {
61
+ for (const d of programDiagnostics.slice(0, 10)) {
62
+ const file = d.file ? path.basename(d.file.fileName) : undefined;
63
+ const pos = d.file && d.start !== undefined ? d.file.getLineAndCharacterOfPosition(d.start) : null;
64
+ diagnostics.push({
65
+ code: 'RPCDART0105',
66
+ severity: 'error',
67
+ message: ts.flattenDiagnosticMessageText(d.messageText, ' '),
68
+ file: d.file?.fileName,
69
+ line: pos ? pos.line + 1 : undefined,
70
+ column: pos ? pos.character + 1 : undefined,
71
+ hint: 'fix the TypeScript error; error types silently corrupt generated bindings',
72
+ });
73
+ void file;
74
+ }
75
+ throw new ExtractionFailure(diagnostics);
76
+ }
77
+ // 4. Resolve per-procedure input/output through per-path harness aliases.
78
+ const checker = program.getTypeChecker();
79
+ const unserializablePolicy = options.policies?.unserializablePolicy ?? 'error';
80
+ const classifier = new TypeClassifier(ts, checker, unserializablePolicy === 'warn-dynamic' ? 'warn-dynamic' : 'error');
81
+ const entries = [];
82
+ for (const p of probePaths) {
83
+ classifier.currentProcedure = p.path;
84
+ const inputType = typeFromAlias(harnessSf, checker, pathAlias(p.path, 'in'));
85
+ const outputType = typeFromAlias(harnessSf, checker, pathAlias(p.path, 'out'));
86
+ if (outputType === undefined) {
87
+ diagnostics.push({
88
+ code: 'RPCDART0106',
89
+ severity: 'error',
90
+ message: `no output type resolved for procedure "${p.path}"`,
91
+ procedurePath: p.path,
92
+ hint: 'make sure the procedure returns a value',
93
+ });
94
+ throw new ExtractionFailure(diagnostics);
95
+ }
96
+ let input;
97
+ let output;
98
+ try {
99
+ input =
100
+ inputType === undefined || isVoidish(inputType)
101
+ ? null
102
+ : classifier.classify(inputType, `${pascal(p.path)}Input`);
103
+ output = classifier.classify(outputType, `${pascal(p.path)}Output`);
104
+ diagnostics.push(...classifier.collectedDiagnostics);
105
+ }
106
+ catch (error) {
107
+ if (!(error instanceof TypeClassificationError)) {
108
+ throw error;
109
+ }
110
+ const diagnostic = error.diagnostic;
111
+ diagnostics.push(diagnostic);
112
+ if (unserializablePolicy === 'skip-procedure') {
113
+ diagnostic.severity = 'warning';
114
+ continue;
115
+ }
116
+ if (unserializablePolicy === 'warn-dynamic') {
117
+ diagnostic.severity = 'warning';
118
+ input = null;
119
+ output = { kind: 'unknown' };
120
+ }
121
+ else {
122
+ throw new ExtractionFailure(diagnostics);
123
+ }
124
+ }
125
+ const meta = {
126
+ access: p.meta['access'] === 'authenticated' ? 'authenticated' : 'public',
127
+ extra: {},
128
+ };
129
+ entries.push({ path: p.path, kind: p.kind, input, output, meta, docs: null });
130
+ }
131
+ classifier.currentProcedure = undefined;
132
+ // 5. Assemble, dedup, name, hash.
133
+ const ir = assembleContract({
134
+ generator: { ...GENERATOR },
135
+ protocol: options.protocol,
136
+ source: {
137
+ entryFile: options.entryFile,
138
+ exportName: options.exportName,
139
+ tsconfigFile: options.tsconfigPath,
140
+ adapterVersion: '0.1.0',
141
+ },
142
+ entries,
143
+ });
144
+ return { ir, diagnostics };
145
+ }
146
+ function isVoidish(type) {
147
+ return ((type.flags & (ts.TypeFlags.Void | ts.TypeFlags.Undefined | ts.TypeFlags.Never)) !== 0);
148
+ }
149
+ function typeFromAlias(sourceFile, checker, name) {
150
+ for (const statement of sourceFile.statements) {
151
+ if (ts.isTypeAliasDeclaration(statement) && statement.name.text === name) {
152
+ return checker.getTypeFromTypeNode(statement.type);
153
+ }
154
+ }
155
+ return undefined;
156
+ }
157
+ function overlayHost(base, harnessPath, harnessSource) {
158
+ const cache = new Map();
159
+ return {
160
+ ...base,
161
+ fileExists(name) {
162
+ return name === harnessPath || base.fileExists(name);
163
+ },
164
+ readFile(name) {
165
+ return name === harnessPath ? harnessSource : base.readFile(name);
166
+ },
167
+ getSourceFile(name, languageVersion, onError, shouldCreate) {
168
+ if (name === harnessPath) {
169
+ const cached = cache.get(name);
170
+ if (cached)
171
+ return cached;
172
+ const sf = ts.createSourceFile(name, harnessSource, languageVersion, true);
173
+ cache.set(name, sf);
174
+ return sf;
175
+ }
176
+ return base.getSourceFile(name, languageVersion, onError, shouldCreate);
177
+ },
178
+ };
179
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Virtual type-harness generation.
3
+ * The harness imports ONLY the user's router and tRPC's public inference
4
+ * utilities - never private internals. Per-path aliases force indexed-access
5
+ * evaluation so deep conditional/mapped types resolve concretely, and make
6
+ * per-procedure failures point at exactly one line.
7
+ */
8
+ export declare function harnessFileName(): string;
9
+ export declare function pathAlias(path: string, role: 'in' | 'out'): string;
10
+ export declare function buildHarness(entryImportPath: string, exportName: string, paths: string[]): string;
11
+ /** './router.ts' -> './router' (extensionless relative import for the harness). */
12
+ export declare function entryImportPath(tsconfigDir: string, entryAbsolute: string): string;
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Virtual type-harness generation.
3
+ * The harness imports ONLY the user's router and tRPC's public inference
4
+ * utilities - never private internals. Per-path aliases force indexed-access
5
+ * evaluation so deep conditional/mapped types resolve concretely, and make
6
+ * per-procedure failures point at exactly one line.
7
+ */
8
+ export function harnessFileName() {
9
+ return '__rpc_dart_harness__.ts';
10
+ }
11
+ export function pathAlias(path, role) {
12
+ const segments = path.split('.').map((s) => s.replace(/[^A-Za-z0-9_]/g, '_'));
13
+ return ['__p', ...segments, role].join('_');
14
+ }
15
+ export function buildHarness(entryImportPath, exportName, paths) {
16
+ const aliases = paths
17
+ .map((p) => {
18
+ const access = p
19
+ .split('.')
20
+ .map((s) => `[${JSON.stringify(s)}]`)
21
+ .join('');
22
+ return `export type ${pathAlias(p, 'in')} = __rpc_dart_inputs${access};\nexport type ${pathAlias(p, 'out')} = __rpc_dart_outputs${access};`;
23
+ })
24
+ .join('\n');
25
+ return `import type { ${exportName} } from ${JSON.stringify(entryImportPath)};
26
+ import type { inferRouterInputs, inferRouterOutputs } from '@trpc/server/unstable-core-do-not-import';
27
+
28
+ type __rpc_dart_router = typeof ${exportName};
29
+ export type __rpc_dart_inputs = inferRouterInputs<__rpc_dart_router>;
30
+ export type __rpc_dart_outputs = inferRouterOutputs<__rpc_dart_router>;
31
+
32
+ ${aliases}
33
+ `;
34
+ }
35
+ /** './router.ts' -> './router' (extensionless relative import for the harness). */
36
+ export function entryImportPath(tsconfigDir, entryAbsolute) {
37
+ const rel = relative(tsconfigDir, entryAbsolute).replace(/\.ts$/, '');
38
+ return rel.startsWith('.') ? rel : `./${rel}`;
39
+ }
40
+ import { relative } from 'node:path';
@@ -0,0 +1,3 @@
1
+ export { extractContract, type ExtractOptions, type ExtractPolicies, type ExtractResult, } from './extract.js';
2
+ export { TypeClassificationError, pascal } from './classify.js';
3
+ export { ProbeError, probeRouter, type ProbePath } from './probe.js';
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { extractContract, } from './extract.js';
2
+ export { TypeClassificationError, pascal } from './classify.js';
3
+ export { ProbeError, probeRouter } from './probe.js';
@@ -0,0 +1,15 @@
1
+ export type ProcedureKind = 'query' | 'mutation' | 'subscription';
2
+ export interface ProbePath {
3
+ path: string;
4
+ kind: ProcedureKind;
5
+ meta: Record<string, unknown>;
6
+ }
7
+ export declare class ProbeError extends Error {
8
+ }
9
+ /**
10
+ * Runtime metadata probe: imports the router module in an isolated require
11
+ * cache and walks the router record for procedure kinds and .meta() values.
12
+ * Every access is feature-tested; failures throw ProbeError with context
13
+ * rather than returning wrong kinds.
14
+ */
15
+ export declare function probeRouter(entryAbsolute: string, exportName: string): Promise<ProbePath[]>;
package/dist/probe.js ADDED
@@ -0,0 +1,108 @@
1
+ import { createJiti } from 'jiti';
2
+ export class ProbeError extends Error {
3
+ }
4
+ /**
5
+ * Runtime metadata probe: imports the router module in an isolated require
6
+ * cache and walks the router record for procedure kinds and .meta() values.
7
+ * Every access is feature-tested; failures throw ProbeError with context
8
+ * rather than returning wrong kinds.
9
+ */
10
+ export async function probeRouter(entryAbsolute, exportName) {
11
+ const jiti = createJiti(entryAbsolute, { fsCache: false, moduleCache: false });
12
+ const mod = (await jiti.import(entryAbsolute));
13
+ const router = mod[exportName];
14
+ if (!router || typeof router !== 'object') {
15
+ throw new ProbeError(`export "${exportName}" not found or not a router in ${entryAbsolute}`);
16
+ }
17
+ const out = [];
18
+ walk(router, [], out);
19
+ if (out.length === 0) {
20
+ throw new ProbeError(`no procedures discovered under "${exportName}"`);
21
+ }
22
+ return out.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
23
+ }
24
+ function walk(node, prefix, out) {
25
+ const def = readDef(node);
26
+ if (!def)
27
+ return;
28
+ // tRPC v11 routers expose a flat procedures map keyed by full dot-path.
29
+ const flat = readFlatProcedures(def);
30
+ if (flat) {
31
+ for (const key of Object.keys(flat).sort()) {
32
+ const procDef = readDef(flat[key]);
33
+ if (!procDef)
34
+ continue;
35
+ const kind = readKind(procDef);
36
+ if (!kind)
37
+ continue;
38
+ const meta = procDef['meta'];
39
+ out.push({
40
+ path: key,
41
+ kind,
42
+ meta: meta && typeof meta === 'object' ? meta : {},
43
+ });
44
+ }
45
+ return;
46
+ }
47
+ // Fallback shape: nested record of routers/procedures (v10-style).
48
+ const record = readRecord(def);
49
+ if (record) {
50
+ for (const key of Object.keys(record).sort()) {
51
+ walk(record[key], [...prefix, key], out);
52
+ }
53
+ return;
54
+ }
55
+ const kind = readKind(def);
56
+ if (!kind)
57
+ return;
58
+ const meta = def['meta'];
59
+ out.push({
60
+ path: prefix.join('.'),
61
+ kind,
62
+ meta: meta && typeof meta === 'object' ? meta : {},
63
+ });
64
+ }
65
+ function readFlatProcedures(def) {
66
+ const value = def['procedures'];
67
+ if (!value || typeof value !== 'object' || Array.isArray(value))
68
+ return null;
69
+ const entries = Object.entries(value);
70
+ if (entries.length === 0)
71
+ return null;
72
+ // Flat map entries are procedures (leaf _defs with a kind), regardless of
73
+ // whether the key carries a dot (top-level procedures do not).
74
+ const isFlat = entries.every(([, v]) => {
75
+ const procDef = readDef(v);
76
+ return procDef !== null && readKind(procDef) !== null;
77
+ });
78
+ return isFlat ? value : null;
79
+ }
80
+ function readDef(node) {
81
+ const def = node?._def;
82
+ return def && typeof def === 'object' ? def : null;
83
+ }
84
+ function readRecord(def) {
85
+ for (const key of ['record', 'procedures']) {
86
+ const value = def[key];
87
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
88
+ const keys = Object.keys(value);
89
+ if (keys.length > 0)
90
+ return value;
91
+ if (key === 'record')
92
+ return value; // empty router
93
+ }
94
+ }
95
+ return null;
96
+ }
97
+ function readKind(def) {
98
+ const type = def['type'];
99
+ if (type === 'query' || type === 'mutation' || type === 'subscription')
100
+ return type;
101
+ if (def['query'] !== undefined)
102
+ return 'query';
103
+ if (def['mutation'] !== undefined)
104
+ return 'mutation';
105
+ if (def['subscription'] !== undefined)
106
+ return 'subscription';
107
+ return null;
108
+ }
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "@rpc-dart/trpc-adapter",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "files": [
8
+ "dist"
9
+ ],
10
+ "dependencies": {
11
+ "@rpc-dart/core": "0.1.0",
12
+ "jiti": "^2.6.0",
13
+ "typescript": "^5.9.0"
14
+ },
15
+ "devDependencies": {
16
+ "vitest": "^3.2.0",
17
+ "@types/node": "^24.0.0"
18
+ },
19
+ "license": "MIT",
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/rpc-dart/rpc-dart.git"
23
+ },
24
+ "homepage": "https://github.com/rpc-dart/rpc-dart#readme",
25
+ "keywords": [
26
+ "trpc",
27
+ "typescript",
28
+ "typechecker",
29
+ "extraction"
30
+ ],
31
+ "scripts": {
32
+ "build": "tsc -p tsconfig.build.json",
33
+ "typecheck": "tsc -p tsconfig.json --noEmit",
34
+ "test": "vitest run --passWithNoTests"
35
+ }
6
36
  }