@rpc-dart/trpc-adapter 0.1.4 → 0.3.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
@@ -31,13 +31,14 @@ pnpm add @rpc-dart/trpc-adapter
31
31
  ## Usage
32
32
 
33
33
  ```typescript
34
- import { extractTrpcContract } from '@rpc-dart/trpc-adapter';
34
+ import { extractContract } from '@rpc-dart/trpc-adapter';
35
35
 
36
- const { contract, diagnostics } = await extractTrpcContract({
37
- entry: './src/trpc/router.ts',
36
+ const { ir, diagnostics } = await extractContract({
37
+ tsconfigPath: './tsconfig.json',
38
+ entryFile: './src/trpc/router.ts',
38
39
  exportName: 'appRouter',
39
- transformer: 'superjson',
40
- unknownPolicy: 'fail',
40
+ protocol: { kind: 'trpc', version: '11', transformer: 'superjson' },
41
+ policies: { unserializablePolicy: 'error' }, // 'warn-dynamic' | 'skip-procedure'
41
42
  });
42
43
  ```
43
44
 
@@ -1,40 +1 @@
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
- }
1
+ export { TypeClassificationError, TypeClassifier, pascal, type UnserializablePolicy } from '@rpc-dart/core';
package/dist/classify.js CHANGED
@@ -1,360 +1 @@
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
- }
1
+ export { TypeClassificationError, TypeClassifier, pascal } from '@rpc-dart/core';
package/dist/extract.js CHANGED
@@ -1,10 +1,11 @@
1
+ import { readFileSync } from 'node:fs';
1
2
  import path from 'node:path';
2
3
  import * as ts from 'typescript';
3
- import { assembleContract, ExtractionFailure, } from '@rpc-dart/core';
4
- import { entryImportPath, buildHarness, harnessFileName, pathAlias } from './harness.js';
4
+ import { assembleContract, ExtractionFailure, TypeClassificationError, TypeClassifier, entryImportPath, harnessFileName, neutralizeOptions, overlayHost, pascal, pathAlias, resolutionKind, typeFromAlias, } from '@rpc-dart/core';
5
+ import { buildHarness } from './harness.js';
5
6
  import { probeRouter } from './probe.js';
6
- import { pascal, TypeClassificationError, TypeClassifier } from './classify.js';
7
- const GENERATOR = { name: 'rpc-dart', version: '0.1.0' };
7
+ const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf-8'));
8
+ const GENERATOR = { name: 'rpc-dart', version: pkg.version };
8
9
  export async function extractContract(options) {
9
10
  const tsconfigDir = path.dirname(options.tsconfigPath);
10
11
  const entryAbsolute = path.resolve(tsconfigDir, options.entryFile);
@@ -38,34 +39,14 @@ export async function extractContract(options) {
38
39
  }
39
40
  const parsed = ts.parseJsonConfigFileContent(configFile.config, ts.sys, tsconfigDir);
40
41
  // 3. Virtual harness over the public inference utilities, one alias pair per path.
41
- const resolution = parsed.options.moduleResolution === ts.ModuleResolutionKind.Node16
42
- ? 'node16'
43
- : parsed.options.moduleResolution === ts.ModuleResolutionKind.NodeNext
44
- ? 'nodenext'
45
- : undefined;
42
+ const resolution = resolutionKind(ts, parsed.options.moduleResolution);
43
+ const subscriptionPaths = new Set(probePaths.filter((p) => p.kind === 'subscription').map((p) => p.path));
46
44
  const harnessPath = path.join(tsconfigDir, harnessFileName());
47
- const harnessSource = buildHarness(entryImportPath(tsconfigDir, entryAbsolute, resolution), options.exportName, probePaths.map((p) => p.path));
45
+ const harnessSource = buildHarness(entryImportPath(tsconfigDir, entryAbsolute, resolution), options.exportName, probePaths.map((p) => p.path), subscriptionPaths);
48
46
  // 4. Program under the user's own tsconfig, harness overlaid in memory.
49
- // Extraction-neutral overrides: the in-memory program exists only to
50
- // answer type queries on the harness, so build/lint-only flags are
51
- // neutralized regardless of the user's tsconfig — they would otherwise
52
- // reject the synthetic harness (rootDir, composite emit rules) or surface
53
- // lint-only semantic errors (noUnusedLocals/noUnusedParameters,
54
- // isolatedDeclarations) that have nothing to do with contract extraction.
55
- const extractionOptions = {
56
- ...parsed.options,
57
- noEmit: true,
58
- declaration: false,
59
- declarationMap: false,
60
- composite: false,
61
- incremental: false,
62
- isolatedDeclarations: false,
63
- noUnusedLocals: false,
64
- noUnusedParameters: false,
65
- rootDir: undefined,
66
- };
47
+ const extractionOptions = neutralizeOptions(parsed.options);
67
48
  const baseHost = ts.createCompilerHost(extractionOptions, true);
68
- const host = overlayHost(baseHost, harnessPath, harnessSource);
49
+ const host = overlayHost(ts, baseHost, harnessPath, harnessSource);
69
50
  const program = ts.createProgram({
70
51
  rootNames: [harnessPath, ...parsed.fileNames],
71
52
  options: extractionOptions,
@@ -106,8 +87,8 @@ export async function extractContract(options) {
106
87
  const entries = [];
107
88
  for (const p of probePaths) {
108
89
  classifier.currentProcedure = p.path;
109
- const inputType = typeFromAlias(harnessSf, checker, pathAlias(p.path, 'in'));
110
- const outputType = typeFromAlias(harnessSf, checker, pathAlias(p.path, 'out'));
90
+ const inputType = typeFromAlias(ts, harnessSf, checker, pathAlias(p.path, 'in'));
91
+ const outputType = typeFromAlias(ts, harnessSf, checker, pathAlias(p.path, 'out'));
111
92
  if (outputType === undefined) {
112
93
  diagnostics.push({
113
94
  code: 'RPCDART0106',
@@ -151,6 +132,13 @@ export async function extractContract(options) {
151
132
  access: p.meta['access'] === 'authenticated' ? 'authenticated' : 'public',
152
133
  extra: {},
153
134
  };
135
+ if (p.kind === 'subscription') {
136
+ // `tracked()` yields resolve to a true literal via the harness; without
137
+ // tracked events the client cannot resume, so the flag stays false.
138
+ const trackedType = typeFromAlias(ts, harnessSf, checker, pathAlias(p.path, 'tracked'));
139
+ meta.extra['supportsLastEventId'] =
140
+ trackedType !== undefined && checker.typeToString(trackedType) === 'true';
141
+ }
154
142
  entries.push({ path: p.path, kind: p.kind, input, output, meta, docs: null });
155
143
  }
156
144
  classifier.currentProcedure = undefined;
@@ -162,7 +150,7 @@ export async function extractContract(options) {
162
150
  entryFile: options.entryFile,
163
151
  exportName: options.exportName,
164
152
  tsconfigFile: options.tsconfigPath,
165
- adapterVersion: '0.1.0',
153
+ adapterVersion: pkg.version,
166
154
  },
167
155
  entries,
168
156
  });
@@ -171,34 +159,3 @@ export async function extractContract(options) {
171
159
  function isVoidish(type) {
172
160
  return ((type.flags & (ts.TypeFlags.Void | ts.TypeFlags.Undefined | ts.TypeFlags.Never)) !== 0);
173
161
  }
174
- function typeFromAlias(sourceFile, checker, name) {
175
- for (const statement of sourceFile.statements) {
176
- if (ts.isTypeAliasDeclaration(statement) && statement.name.text === name) {
177
- return checker.getTypeFromTypeNode(statement.type);
178
- }
179
- }
180
- return undefined;
181
- }
182
- function overlayHost(base, harnessPath, harnessSource) {
183
- const cache = new Map();
184
- return {
185
- ...base,
186
- fileExists(name) {
187
- return name === harnessPath || base.fileExists(name);
188
- },
189
- readFile(name) {
190
- return name === harnessPath ? harnessSource : base.readFile(name);
191
- },
192
- getSourceFile(name, languageVersion, onError, shouldCreate) {
193
- if (name === harnessPath) {
194
- const cached = cache.get(name);
195
- if (cached)
196
- return cached;
197
- const sf = ts.createSourceFile(name, harnessSource, languageVersion, true);
198
- cache.set(name, sf);
199
- return sf;
200
- }
201
- return base.getSourceFile(name, languageVersion, onError, shouldCreate);
202
- },
203
- };
204
- }
package/dist/harness.d.ts CHANGED
@@ -1,17 +1,2 @@
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
- /**
12
- * './router.ts' -> './router' (bundler-style), or explicit extensions under
13
- * node16/nodenext resolution, where extensionless relative imports are
14
- * illegal (TS5097) and the TS-standard specifiers (.js/.mjs/.cjs) resolve to
15
- * the .ts/.mts/.cts sources with or without allowImportingTsExtensions.
16
- */
17
- export declare function entryImportPath(tsconfigDir: string, entryAbsolute: string, resolution?: 'node16' | 'nodenext'): string;
1
+ export { entryImportPath, harnessFileName, pathAlias, type HarnessAliasRole } from '@rpc-dart/core';
2
+ export declare function buildHarness(entryImportPath: string, exportName: string, paths: string[], subscriptionPaths?: ReadonlySet<string>): string;
package/dist/harness.js CHANGED
@@ -1,25 +1,32 @@
1
1
  /**
2
- * Virtual type-harness generation.
2
+ * Virtual type-harness generation (tRPC-specific).
3
3
  * The harness imports ONLY the user's router and tRPC's public inference
4
4
  * utilities - never private internals. Per-path aliases force indexed-access
5
5
  * evaluation so deep conditional/mapped types resolve concretely, and make
6
6
  * per-procedure failures point at exactly one line.
7
+ *
8
+ * Subscription procedures get an extra unwrap layer: tRPC v11 subscription
9
+ * outputs are `AsyncGenerator<Y>` / `AsyncIterable<Y>` / `Observable<Y>` and
10
+ * tracked generators wrap each yield in `TrackedEnvelope<T>` ([id, data,
11
+ * symbol]), so the aliases resolve straight to the streamed item type Y.
7
12
  */
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) {
13
+ import { pathAlias } from '@rpc-dart/core';
14
+ export { entryImportPath, harnessFileName, pathAlias } from '@rpc-dart/core';
15
+ export function buildHarness(entryImportPath, exportName, paths, subscriptionPaths = new Set()) {
16
16
  const aliases = paths
17
17
  .map((p) => {
18
18
  const access = p
19
19
  .split('.')
20
20
  .map((s) => `[${JSON.stringify(s)}]`)
21
21
  .join('');
22
- return `export type ${pathAlias(p, 'in')} = __rpc_dart_inputs${access};\nexport type ${pathAlias(p, 'out')} = __rpc_dart_outputs${access};`;
22
+ const lines = [`export type ${pathAlias(p, 'in')} = __rpc_dart_inputs${access};`];
23
+ if (subscriptionPaths.has(p)) {
24
+ lines.push(`export type ${pathAlias(p, 'out')} = __rpc_dart_unwrap_item<__rpc_dart_outputs${access}>;`, `export type ${pathAlias(p, 'tracked')} = __rpc_dart_is_tracked<__rpc_dart_outputs${access}>;`);
25
+ }
26
+ else {
27
+ lines.push(`export type ${pathAlias(p, 'out')} = __rpc_dart_outputs${access};`);
28
+ }
29
+ return lines.join('\n');
23
30
  })
24
31
  .join('\n');
25
32
  return `import type { ${exportName} } from ${JSON.stringify(entryImportPath)};
@@ -29,24 +36,24 @@ type __rpc_dart_router = typeof ${exportName};
29
36
  export type __rpc_dart_inputs = inferRouterInputs<__rpc_dart_router>;
30
37
  export type __rpc_dart_outputs = inferRouterOutputs<__rpc_dart_router>;
31
38
 
39
+ type __rpc_dart_unwrap_item<T> =
40
+ T extends { subscribe(observer: infer O): unknown }
41
+ ? O extends { next(value: infer Y): void } ? __rpc_dart_unwrap_tracked<Y> : never
42
+ : T extends AsyncIterable<infer Y> ? __rpc_dart_unwrap_tracked<Y> : T;
43
+ // tRPC v11 hands clients tracked events as either the branded tuple
44
+ // TrackedEnvelope<T> = [id, T, symbol] or its TrackedData<T> = { id, data }
45
+ // projection; both reduce to the payload T.
46
+ type __rpc_dart_unwrap_tracked<Y> =
47
+ Y extends readonly [string, infer D, symbol]
48
+ ? D
49
+ : Y extends { id: string; data: infer D } ? D : Y;
50
+ type __rpc_dart_is_tracked<T> =
51
+ T extends AsyncIterable<infer Y>
52
+ ? Y extends readonly [string, unknown, symbol]
53
+ ? true
54
+ : Y extends { id: string; data: unknown } ? true : false
55
+ : false;
56
+
32
57
  ${aliases}
33
58
  `;
34
59
  }
35
- /**
36
- * './router.ts' -> './router' (bundler-style), or explicit extensions under
37
- * node16/nodenext resolution, where extensionless relative imports are
38
- * illegal (TS5097) and the TS-standard specifiers (.js/.mjs/.cjs) resolve to
39
- * the .ts/.mts/.cts sources with or without allowImportingTsExtensions.
40
- */
41
- export function entryImportPath(tsconfigDir, entryAbsolute, resolution) {
42
- const rel = relative(tsconfigDir, entryAbsolute);
43
- const specifier = resolution === undefined
44
- ? rel.replace(/\.(mts|cts|tsx?)$/, '')
45
- : rel
46
- .replace(/\.tsx$/, '.js')
47
- .replace(/\.mts$/, '.mjs')
48
- .replace(/\.cts$/, '.cjs')
49
- .replace(/\.ts$/, '.js');
50
- return specifier.startsWith('.') ? specifier : `./${specifier}`;
51
- }
52
- import { relative } from 'node:path';
package/dist/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  export { extractContract, type ExtractOptions, type ExtractPolicies, type ExtractResult, } from './extract.js';
2
- export { TypeClassificationError, pascal } from './classify.js';
2
+ export { TypeClassificationError, pascal } from '@rpc-dart/core';
3
3
  export { ProbeError, probeRouter, type ProbePath } from './probe.js';
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
1
  export { extractContract, } from './extract.js';
2
- export { TypeClassificationError, pascal } from './classify.js';
2
+ export { TypeClassificationError, pascal } from '@rpc-dart/core';
3
3
  export { ProbeError, probeRouter } from './probe.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rpc-dart/trpc-adapter",
3
- "version": "0.1.4",
3
+ "version": "0.3.0",
4
4
  "description": "tRPC v11 extraction adapter: route probe, inference harness, and Contract IR normalizer.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -9,7 +9,7 @@
9
9
  "dist"
10
10
  ],
11
11
  "dependencies": {
12
- "@rpc-dart/core": "0.1.4",
12
+ "@rpc-dart/core": "0.3.0",
13
13
  "jiti": "^2.6.0",
14
14
  "typescript": "^5.9.0"
15
15
  },