tsrx-typegen 0.2.2 → 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
@@ -1,55 +1,21 @@
1
1
  # tsrx-typegen
2
2
 
3
- Generate declaration files for packages that export `.tsrx` modules. The
4
- command uses the consuming package's TypeScript and tsrx compiler, then maps
5
- source-extension imports in the emitted declarations to JavaScript module
6
- specifiers.
7
-
8
- ```sh
9
- pnpm exec tsrx-typegen --target octane
10
- ```
3
+ Generate `.d.ts` declaration files for packages that export `.tsrx` modules.
4
+ Use it when publishing an Octane/tsrx component package: it runs the consuming
5
+ package's own TypeScript and tsrx compiler, then rewrites source-extension
6
+ imports in the emitted declarations to JavaScript module specifiers.
11
7
 
12
8
  Install `tsrx-typegen` as a development tool alongside `typescript` and
13
- `@tsrx/typescript-plugin`. Each target in `tsrx-typegen.json` names its
14
- renderer, project config, declaration output directory, and public subpaths.
15
- The project config selects source variants and enables `declaration`,
16
- `emitDeclarationOnly`, and `noEmit: false`. The target's `renderer` is checked
17
- against `compilerOptions.jsxImportSource` when TypeScript sets it; the project
18
- config continues to select the actual tsrx compiler and platform.
9
+ `@tsrx/typescript-plugin`, then run it against a named target:
19
10
 
20
11
  ```sh
21
- pnpm exec tsrx-typegen --target octane
22
- pnpm exec tsrx-typegen --project tsconfig.types.json --check
23
- pnpm exec tsrx-typegen --pack-check
12
+ pnpm exec tsrx-typegen --target octane # generate declarations
13
+ pnpm exec tsrx-typegen --target octane --check # verify output is fresh
14
+ pnpm exec tsrx-typegen --pack-check # validate the packed tarball
24
15
  ```
25
16
 
26
- Generation writes only TypeScript declaration files under the config's `outDir` and records
27
- which files it owns in `.tsrx-typegen-manifest.json`. Check mode emits to a
28
- temporary directory and compares the result with those owned files. It reports
29
- missing or stale output, unresolved `.tsrx` references, and code export paths
30
- without declaration targets. It refuses to overwrite an unmanaged declaration
31
- and removes stale files only when the manifest says it owns them. Same-name
32
- sources such as `Button.ts` and `Button.tsrx` need separate target configs or an
33
- explicit declaration override. Case-only source renames replace the prior
34
- manifest-owned declaration, including on case-insensitive filesystems; manual
35
- declarations remain protected.
36
-
37
- ```sh
38
- pnpm exec tsrx-typegen --target octane --check
39
- ```
40
-
41
- Treat the output directory, including its ownership manifest, as generated
42
- build artifacts: ignore it in Git, formatting, and linting. Keep handwritten
43
- declarations and override sources outside that directory. Include the output
44
- directory in the package's `files` list so ignored declarations still ship in
45
- the tarball. Generate before local consumer typechecks, and regenerate in
46
- `prepack` before validating the package. Workspaces that resolve generated
47
- types directly also need generation during setup and refreshes during
48
- development; this repository's workflow is documented in
49
- [Develop against generated declarations](../../docs/notes/toolchain-notes.md#develop-against-generated-declarations).
50
-
51
- `--project` selects the target whose project path matches. Use `--target` to
52
- select a named target directly. A target can look like this:
17
+ Each target in `tsrx-typegen.json` names its renderer, project config,
18
+ declaration output directory, and public subpaths:
53
19
 
54
20
  ```json
55
21
  {
@@ -61,7 +27,7 @@ select a named target directly. A target can look like this:
61
27
  "entrypoints": {
62
28
  ".": {
63
29
  "source": "src/index.ts",
64
- "runtime": "./dist/index.js",
30
+ "runtime": "./src/index.ts",
65
31
  "types": "./types/generated/index.d.ts"
66
32
  }
67
33
  }
@@ -70,6 +36,41 @@ select a named target directly. A target can look like this:
70
36
  }
71
37
  ```
72
38
 
39
+ The project config selects source variants and enables `declaration`,
40
+ `emitDeclarationOnly`, and `noEmit: false`. The target's `renderer` is checked
41
+ against `compilerOptions.jsxImportSource` when TypeScript sets it; the project
42
+ config continues to select the actual tsrx compiler and platform. `--project`
43
+ selects the target whose project path matches; `--target` selects a named
44
+ target directly.
45
+
46
+ ## What generation writes and checks
47
+
48
+ Generation writes only TypeScript declaration files under the config's
49
+ `outDir` and records which files it owns in `.tsrx-typegen-manifest.json`.
50
+ Declaration inputs included by the project under `rootDir` are copied beside
51
+ emitted declarations, with the same import rewriting and freshness checks.
52
+ Check mode emits to a temporary directory and compares the result with those
53
+ owned files. It reports missing or stale output, unresolved `.tsrx`
54
+ references, and code export paths without declaration targets. It refuses to
55
+ overwrite an unmanaged declaration and removes stale files only when the
56
+ manifest says it owns them. Same-name sources such as `Button.ts` and
57
+ `Button.tsrx` need separate target configs or an explicit declaration
58
+ override. Case-only source renames replace the prior manifest-owned
59
+ declaration, including on case-insensitive filesystems; manual declarations
60
+ remain protected.
61
+
62
+ Treat the output directory, including its ownership manifest, as generated
63
+ build artifacts: ignore it in Git, formatting, and linting. Keep handwritten
64
+ declarations and override sources outside that directory. Include the output
65
+ directory in the package's `files` list so ignored declarations still ship in
66
+ the tarball. Generate before local consumer typechecks, and regenerate in
67
+ `prepack` before validating the package. Workspaces that resolve generated
68
+ types directly also need generation during setup and refreshes during
69
+ development; this repository's workflow is documented in
70
+ [Develop against generated declarations](../../.agents/docs/notes/toolchain-notes.md#develop-against-generated-declarations).
71
+
72
+ ## Overrides and import rewriting
73
+
73
74
  Keep exceptional signatures in handwritten declaration sources outside the
74
75
  generated directory, then map their generated output path explicitly:
75
76
 
@@ -86,30 +87,50 @@ manifest; check mode detects edits to either the source mapping or generated
86
87
  copy. Override declarations must use publishable module specifiers and may not
87
88
  reference `.tsrx` files.
88
89
 
89
- ```sh
90
- pnpm exec tsrx-typegen --target octane --check
91
- ```
92
-
93
90
  Relative imports between generated declarations receive runtime extensions
94
91
  from the source map, including extensionless imports. This supports NodeNext
95
- consumers as well as bundler resolution without requiring `allowArbitraryExtensions`.
92
+ consumers as well as bundler resolution without requiring
93
+ `allowArbitraryExtensions`. A plain TypeScript consumer then imports the
94
+ package normally:
96
95
 
97
96
  ```ts
98
- // Plain TypeScript consumer of the package whose exports are configured above.
99
97
  import { Button } from 'my-component-library'
98
+ ```
99
+
100
+ The `.js` specifiers inside declarations resolve to sibling `.d.ts` files
101
+ through TypeScript's extension substitution. They do not require a JavaScript
102
+ package build. Keep runtime exports pointed at authored source and type exports
103
+ pointed at declarations:
100
104
 
101
- // Button is a component exported by your library's src/index.ts.
102
- export { Button }
105
+ ```json
106
+ {
107
+ "exports": {
108
+ ".": {
109
+ "types": "./types/generated/index.d.ts",
110
+ "default": "./src/index.ts"
111
+ },
112
+ "./*": {
113
+ "types": "./types/generated/*.d.ts",
114
+ "default": "./src/*"
115
+ }
116
+ },
117
+ "files": ["src", "types"]
118
+ }
103
119
  ```
104
120
 
121
+ Keep wildcard runtime targets extensionless so the app bundler can select
122
+ `.web.ts`, `.ios.ts`, or `.web.tsrx` siblings. The declaration wildcard uses
123
+ the same module stem, and the pack check verifies each source variant has its
124
+ matching declaration.
125
+
105
126
  Use separate target records and project configs when public signatures differ.
106
- Each config must select the same source variants as its runtime build.
127
+ Each config must select the source variants exposed by its runtime exports.
107
128
  `runtime` records the published runtime path or condition map, while `types`
108
- records the declaration path. The CLI does not edit `package.json`; export maps
109
- remain package-owned. The default source-extension mapping is `.tsrx`, `.tsx`,
110
- and `.ts` to `.js`, with `.mts` to `.mjs` and `.cts` to `.cjs`. Packages with
111
- another runtime layout can override these mappings in `sourceExtensions` at
112
- the target or root level.
129
+ records the declaration path. The CLI does not edit `package.json`; export
130
+ maps remain package-owned. The default source-extension mapping is `.tsrx`,
131
+ `.tsx`, and `.ts` to `.js`, with `.mts` to `.mjs` and `.cts` to `.cjs`.
132
+ Packages with another runtime layout can override these mappings in
133
+ `sourceExtensions` at the target or root level:
113
134
 
114
135
  ```json
115
136
  {
@@ -123,17 +144,12 @@ Use `--pack-check` before publishing. It checks every configured target unless
123
144
  `--target` narrows the selection, packs a temporary tarball with lifecycle
124
145
  scripts disabled, and verifies that package and `publishConfig` export paths
125
146
  exist in the tarball. It also compares runtime and declaration value exports
126
- and checks that relative declaration references resolve inside the package and
127
- bare package imports are declared dependencies or peers. The command needs
147
+ and checks that relative declaration references resolve to declarations inside
148
+ the package and bare package imports are declared dependencies or peers. The command needs
128
149
  `pnpm` and the system `tar` utility. It checks package structure; keep a plain
129
150
  TypeScript consumer test for the module-resolution modes and public prop
130
151
  contracts your package supports.
131
152
 
132
- ```sh
133
- pnpm exec tsrx-typegen --pack-check
134
- pnpm exec tsrx-typegen --pack-check --target octane
135
- ```
136
-
137
153
  A target with `"emit": false` exists only to drive packed-package
138
154
  verification. Packages whose declarations are handwritten or produced by
139
155
  another tool declare one so `--pack-check` skips generation and freshness
@@ -153,7 +169,7 @@ for source-published packages, the `.ts` source itself.
153
169
  "entrypoints": {
154
170
  ".": {
155
171
  "source": "src/index.ts",
156
- "runtime": "./dist/index.js",
172
+ "runtime": "./src/index.ts",
157
173
  "types": "./types/index.d.ts"
158
174
  }
159
175
  }
@@ -168,8 +184,7 @@ Run the same gate from `prepack` so `pnpm pack` and publication share it:
168
184
  {
169
185
  "scripts": {
170
186
  "typegen": "tsrx-typegen --target octane",
171
- "build": "vite build && pnpm typegen",
172
- "prepack": "pnpm build && tsrx-typegen --pack-check"
187
+ "prepack": "pnpm typegen && tsrx-typegen --pack-check"
173
188
  }
174
189
  }
175
190
  ```
@@ -182,9 +197,11 @@ that declaration gate fails.
182
197
  pnpm exec xplat doctor
183
198
  ```
184
199
 
200
+ ## Backend and inference
201
+
185
202
  The first supported backend is the classic `tsrx-tsc` path with TypeScript
186
- 5.9.x. TypeScript 7 content-mapper output needs upstream declaration naming and
187
- specifier support before it can replace this backend. Generation rejects
203
+ 5.9.x. TypeScript 7 content-mapper output needs upstream declaration naming
204
+ and specifier support before it can replace this backend. Generation rejects
188
205
  compiler errors; editor-only partial transforms are not used.
189
206
 
190
207
  This tool preserves TypeScript's declaration inference. Keep exported helpers,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tsrx-typegen",
3
- "version": "0.2.2",
3
+ "version": "0.3.0",
4
4
  "description": "Generate consumer-ready TypeScript declarations for TSRX libraries",
5
5
  "keywords": [
6
6
  "build-tool",
package/src/cli.mjs CHANGED
@@ -529,7 +529,7 @@ function rewriteDeclaration(ts, path, outputDir, extensions, generatedFiles, run
529
529
 
530
530
  const declaration = relative(outputDir, target)
531
531
  const runtimeExtension = runtimeByDeclaration.get(declaration) ?? '.js'
532
- const isIndex = /[\\/]index\.d\.[cm]?ts$/.test(target)
532
+ const isIndex = dirname(target) === targetStem
533
533
  const baseSpecifier = specifier.endsWith('/') ? specifier.slice(0, -1) : specifier
534
534
  replacement = isIndex
535
535
  ? `${baseSpecifier}/index${runtimeExtension}`
@@ -746,8 +746,8 @@ function verifyPublicTypes(projectRoot, generated, outDir, target, sourceOutputs
746
746
  if (target && exportsMap && typeof exportsMap === 'object') {
747
747
  const configuredSubpaths = new Set(Object.keys(target.entrypoints))
748
748
  for (const [subpath, mapping] of Object.entries(exportsMap)) {
749
- const runtimeTargets = stringsIn(mapping).filter((entry) =>
750
- /\.(?:[cm]?[jt]sx?|tsrx)$/.test(entry),
749
+ const runtimeTargets = stringsIn(mapping).filter(
750
+ (entry) => !extname(entry) || /\.(?:[cm]?[jt]sx?|tsrx)$/.test(entry),
751
751
  )
752
752
 
753
753
  if (runtimeTargets.length && !configuredSubpaths.has(subpath)) {
@@ -794,8 +794,8 @@ function verifyPublicTypes(projectRoot, generated, outDir, target, sourceOutputs
794
794
 
795
795
  if (exportsMap && typeof exportsMap === 'object') {
796
796
  for (const [subpath, mapping] of Object.entries(exportsMap)) {
797
- const runtimeTargets = stringsIn(mapping).filter((target) =>
798
- /\.(?:[cm]?[jt]sx?|tsrx)$/.test(target),
797
+ const runtimeTargets = stringsIn(mapping).filter(
798
+ (target) => !extname(target) || /\.(?:[cm]?[jt]sx?|tsrx)$/.test(target),
799
799
  )
800
800
 
801
801
  if (!runtimeTargets.length) {
@@ -925,6 +925,23 @@ function runTarget(projectRoot, args) {
925
925
  return false
926
926
  }
927
927
 
928
+ // TypeScript does not emit declaration inputs. Preserve included, local
929
+ // declarations beside emitted modules so their references remain closed.
930
+ for (const source of fileNames) {
931
+ if (!/\.d\.[cm]?ts$/.test(source) || !pathInside(rootDir, source)) {
932
+ continue
933
+ }
934
+
935
+ const declaration = relative(rootDir, source)
936
+ if (sourceOutputs.has(declaration)) {
937
+ continue
938
+ }
939
+
940
+ const output = join(outputDir, declaration)
941
+ mkdirSync(dirname(output), { recursive: true })
942
+ writeFileSync(output, readFileSync(source))
943
+ }
944
+
928
945
  const generated = normalizeOutput(ts, outputDir, sourceExtensions, runtimeByDeclaration)
929
946
  const managedOverrides = applyOverrides(ts, projectRoot, outDir, generated, overrides)
930
947
  verifySourceDeclarations(generated, sourceOutputs)
@@ -50,7 +50,7 @@ const stringsIn = (value) => {
50
50
  }
51
51
 
52
52
  const codeTarget = (target) =>
53
- /\.(?:[cm]?[jt]sx?|tsrx)$/.test(target) && !/\.d\.[cm]?ts$/.test(target)
53
+ (!extname(target) || /\.(?:[cm]?[jt]sx?|tsrx)$/.test(target)) && !/\.d\.[cm]?ts$/.test(target)
54
54
 
55
55
  function exportBranches(exportsMap, fallbackTypes = []) {
56
56
  const branches = []
@@ -58,7 +58,11 @@ function exportBranches(exportsMap, fallbackTypes = []) {
58
58
  const visit = (value, inheritedTypes) => {
59
59
  if (typeof value === 'string') {
60
60
  if (codeTarget(value)) {
61
- branches.push({ subpath, runtime: value, types: inheritedTypes })
61
+ branches.push({
62
+ subpath,
63
+ runtime: value,
64
+ types: inheritedTypes.length ? inheritedTypes : fallbackTypes,
65
+ })
62
66
  }
63
67
 
64
68
  return
@@ -68,15 +72,20 @@ function exportBranches(exportsMap, fallbackTypes = []) {
68
72
  return
69
73
  }
70
74
 
71
- const types = Object.hasOwn(value, 'types') ? stringsIn(value.types) : inheritedTypes
75
+ // An earlier condition cannot use a later sibling's type fallback.
76
+ let types = inheritedTypes
72
77
  for (const [condition, child] of Object.entries(value)) {
73
- if (condition !== 'types') {
78
+ if (condition === 'types') {
79
+ if (!types.length) {
80
+ types = stringsIn(child)
81
+ }
82
+ } else {
74
83
  visit(child, types)
75
84
  }
76
85
  }
77
86
  }
78
87
 
79
- visit(mapping, fallbackTypes)
88
+ visit(mapping, [])
80
89
  }
81
90
 
82
91
  return branches
@@ -104,11 +113,12 @@ function packageFiles(root) {
104
113
  }
105
114
 
106
115
  function expandTarget(target, files, packageRoot) {
107
- if (!target.includes('*')) {
116
+ const extensionless = !extname(target)
117
+ if (!target.includes('*') && !extensionless) {
108
118
  return [{ path: target, capture: undefined }]
109
119
  }
110
120
 
111
- if ((target.match(/\*/g) ?? []).length !== 1) {
121
+ if ((target.match(/\*/g) ?? []).length > 1) {
112
122
  throw new Error(`packed export target uses more than one wildcard: ${target}`)
113
123
  }
114
124
 
@@ -118,19 +128,31 @@ function expandTarget(target, files, packageRoot) {
118
128
 
119
129
  const pattern = target.slice(2)
120
130
  const marker = pattern.indexOf('*')
121
- const prefix = pattern.slice(0, marker)
122
- const suffix = pattern.slice(marker + 1)
131
+ const prefix = marker === -1 ? pattern : pattern.slice(0, marker)
132
+ const suffix = marker === -1 ? '' : pattern.slice(marker + 1)
123
133
  const matches = files.flatMap((file) => {
124
134
  const path = relative(packageRoot, file).replaceAll('\\', '/')
135
+ // Extensionless source exports let the app choose platform siblings.
136
+ // Their wildcard captures are module stems, not source extensions.
137
+ if (!codeTarget(path) || (extensionless && !extname(path))) {
138
+ return []
139
+ }
140
+
141
+ const matchedPath = extensionless ? path.slice(0, -extname(path).length) : path
125
142
  if (
126
- !path.startsWith(prefix) ||
127
- !path.endsWith(suffix) ||
128
- path.length < prefix.length + suffix.length
143
+ !matchedPath.startsWith(prefix) ||
144
+ !matchedPath.endsWith(suffix) ||
145
+ matchedPath.length < prefix.length + suffix.length ||
146
+ (marker === -1 && matchedPath !== pattern)
129
147
  ) {
130
148
  return []
131
149
  }
132
150
 
133
- const capture = path.slice(prefix.length, path.length - suffix.length)
151
+ const capture =
152
+ marker === -1
153
+ ? undefined
154
+ : matchedPath.slice(prefix.length, matchedPath.length - suffix.length)
155
+
134
156
  return [{ path: `./${path}`, capture }]
135
157
  })
136
158
 
@@ -163,13 +185,11 @@ function packedPath(packageRoot, target) {
163
185
  function sourceFile(ts, file) {
164
186
  const extension = extname(file).toLowerCase()
165
187
  const scriptKind =
166
- extension === '.tsx'
188
+ extension === '.tsx' || extension === '.tsrx'
167
189
  ? ts.ScriptKind.TSX
168
190
  : extension === '.jsx'
169
191
  ? ts.ScriptKind.JSX
170
- : extension === '.tsrx'
171
- ? ts.ScriptKind.Deferred
172
- : ts.ScriptKind.TS
192
+ : ts.ScriptKind.TS
173
193
 
174
194
  return ts.createSourceFile(
175
195
  file,
@@ -337,7 +357,21 @@ function compilerExports(ts, program, file, cache = new Map(), pending = new Set
337
357
  // Subtract names whose only export edges are type-only.
338
358
  const typeOnly = new Set()
339
359
  for (const statement of source.statements) {
340
- if (!ts.isExportDeclaration(statement) || !statement.isTypeOnly) {
360
+ if (!ts.isExportDeclaration(statement)) {
361
+ continue
362
+ }
363
+
364
+ if (statement.exportClause && ts.isNamedExports(statement.exportClause)) {
365
+ for (const element of statement.exportClause.elements) {
366
+ if (statement.isTypeOnly || element.isTypeOnly) {
367
+ typeOnly.add(element.name.text)
368
+ }
369
+ }
370
+
371
+ continue
372
+ }
373
+
374
+ if (!statement.isTypeOnly) {
341
375
  continue
342
376
  }
343
377
 
@@ -392,6 +426,20 @@ function moduleResolutionOptions(ts) {
392
426
  allowImportingTsExtensions: true,
393
427
  module: ts.ModuleKind.NodeNext,
394
428
  moduleResolution: ts.ModuleResolutionKind.NodeNext,
429
+ // Same precedence as repository typecheck/typegen programs
430
+ // (packages/cli tsconfig-envs.mjs PLATFORM_MODULE_SUFFIXES):
431
+ // extensionless first, then every platform suffix.
432
+ moduleSuffixes: [
433
+ '',
434
+ '.web',
435
+ '.ios',
436
+ '.android',
437
+ '.mobile',
438
+ '.native',
439
+ '.macos',
440
+ '.linux',
441
+ '.windows',
442
+ ],
395
443
  noEmit: true,
396
444
  skipLibCheck: true,
397
445
  target: ts.ScriptTarget.Latest,
@@ -421,6 +469,10 @@ function verifyDeclarationClosure(ts, packageRoot, files, manifest, failures) {
421
469
  )
422
470
  } else if (!pathInside(packageRoot, resolve(resolved.resolvedFileName))) {
423
471
  failures.push(`${relative(packageRoot, file)} resolves ${specifier} outside the package`)
472
+ } else if (!/\.d\.[cm]?ts$/.test(resolved.resolvedFileName)) {
473
+ failures.push(
474
+ `${relative(packageRoot, file)} resolves ${specifier} to implementation source; publish its declaration`,
475
+ )
424
476
  }
425
477
 
426
478
  continue