@dunx/transform 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 +201 -0
- package/README.md +84 -0
- package/dist/ast.d.ts +73 -0
- package/dist/deps.d.ts +18 -0
- package/dist/edits.d.ts +11 -0
- package/dist/erased.d.ts +11 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +161 -0
- package/dist/index.js.map +14 -0
- package/dist/plugin.d.ts +13 -0
- package/dist/preload.d.ts +1 -0
- package/dist/preload.js +163 -0
- package/dist/preload.js.map +15 -0
- package/package.json +65 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
# @dunx/transform
|
|
2
|
+
|
|
3
|
+
Load-time transform that lets the dunx container use constructor injection.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
export class UsersService {
|
|
7
|
+
constructor(private readonly repo: UsersRepository) {}
|
|
8
|
+
}
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
No `@Injectable`, no `@Inject`, no `reflect-metadata`, no `experimentalDecorators`.
|
|
12
|
+
|
|
13
|
+
## Setup
|
|
14
|
+
|
|
15
|
+
```toml
|
|
16
|
+
# bunfig.toml
|
|
17
|
+
preload = ["@dunx/transform/preload"]
|
|
18
|
+
|
|
19
|
+
[test]
|
|
20
|
+
preload = ["@dunx/transform/preload"]
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Or with no config file at all:
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
bun --preload @dunx/transform/preload src/main.ts
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
For a production build, pass the plugin to `Bun.build`:
|
|
30
|
+
|
|
31
|
+
```ts
|
|
32
|
+
import { depsPlugin } from '@dunx/transform';
|
|
33
|
+
|
|
34
|
+
await Bun.build({ entrypoints: ['src/main.ts'], plugins: [depsPlugin] });
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## What it does
|
|
38
|
+
|
|
39
|
+
It parses each file with `oxc-parser`, reads every class declaration's constructor
|
|
40
|
+
parameter types, and appends one statement per class:
|
|
41
|
+
|
|
42
|
+
```ts
|
|
43
|
+
Object.defineProperty(UsersService, Symbol.for('dunx.deps'), {
|
|
44
|
+
value: () => [UsersRepository],
|
|
45
|
+
});
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
`@dunx/core` reads that record and resolves the arguments before calling `new`.
|
|
49
|
+
|
|
50
|
+
The record is a **thunk**, so it is evaluated when the container resolves the class
|
|
51
|
+
rather than when the module is defined. A dependency declared later in the file, or
|
|
52
|
+
reached through a circular import, therefore needs no `forwardRef`.
|
|
53
|
+
|
|
54
|
+
Only the appended statement is added — every other byte of the original source is
|
|
55
|
+
preserved, so comments, formatting, and the line numbers in stack traces are
|
|
56
|
+
unchanged.
|
|
57
|
+
|
|
58
|
+
## Parameters it will not guess
|
|
59
|
+
|
|
60
|
+
A parameter whose type names nothing that exists at runtime is recorded as
|
|
61
|
+
`unresolved` together with its original source text, and the container throws at
|
|
62
|
+
boot:
|
|
63
|
+
|
|
64
|
+
```
|
|
65
|
+
UsersService cannot be constructed: parameter 2 (private readonly cfg: AppConfig)
|
|
66
|
+
names nothing that exists at runtime, so there is no token to resolve.
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
That covers a type-only import, an inline `type` specifier, a local `interface` or
|
|
70
|
+
type alias, a class type parameter, a primitive, and a union. Replace the type with
|
|
71
|
+
an abstract class, or bind it with `token()`.
|
|
72
|
+
|
|
73
|
+
Class **expressions** are skipped: `const X = class Inner {}` binds `Inner` only
|
|
74
|
+
inside the class body, so a statement appended after it could not reference the name.
|
|
75
|
+
|
|
76
|
+
## If you forget to register it
|
|
77
|
+
|
|
78
|
+
The container checks `ctor.length` against the recorded dependencies, so a class the
|
|
79
|
+
plugin never saw is a boot error rather than a set of `undefined` fields:
|
|
80
|
+
|
|
81
|
+
```
|
|
82
|
+
UsersController declares 1 constructor parameter(s) but no dependencies were
|
|
83
|
+
recorded for it, so @dunx/transform did not transform UsersController.
|
|
84
|
+
```
|
package/dist/ast.d.ts
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal structural views over oxc's ESTree output — only the node shapes the
|
|
3
|
+
* dependency transform reads. Verified against real `oxc-parser` output.
|
|
4
|
+
*/
|
|
5
|
+
export interface Node {
|
|
6
|
+
readonly type: string;
|
|
7
|
+
readonly start: number;
|
|
8
|
+
readonly end: number;
|
|
9
|
+
}
|
|
10
|
+
export interface Identifier extends Node {
|
|
11
|
+
readonly type: 'Identifier';
|
|
12
|
+
readonly name: string;
|
|
13
|
+
readonly typeAnnotation?: TSTypeAnnotation | null;
|
|
14
|
+
}
|
|
15
|
+
export interface ClassBody extends Node {
|
|
16
|
+
readonly type: 'ClassBody';
|
|
17
|
+
readonly body: readonly Node[];
|
|
18
|
+
}
|
|
19
|
+
/** `ClassDeclaration` and `ClassExpression` share every field read here. */
|
|
20
|
+
export interface ClassNode extends Node {
|
|
21
|
+
readonly id: Identifier | null;
|
|
22
|
+
readonly typeParameters: Node | null;
|
|
23
|
+
readonly body: ClassBody;
|
|
24
|
+
}
|
|
25
|
+
export interface FunctionExpression extends Node {
|
|
26
|
+
readonly params: readonly Node[];
|
|
27
|
+
}
|
|
28
|
+
export interface MethodDefinition extends Node {
|
|
29
|
+
readonly type: 'MethodDefinition';
|
|
30
|
+
readonly key: Node;
|
|
31
|
+
readonly value: FunctionExpression;
|
|
32
|
+
}
|
|
33
|
+
export interface TSParameterProperty extends Node {
|
|
34
|
+
readonly type: 'TSParameterProperty';
|
|
35
|
+
readonly parameter: Node;
|
|
36
|
+
}
|
|
37
|
+
export interface TSTypeAnnotation extends Node {
|
|
38
|
+
readonly type: 'TSTypeAnnotation';
|
|
39
|
+
readonly typeAnnotation: Node;
|
|
40
|
+
}
|
|
41
|
+
export interface TSTypeReference extends Node {
|
|
42
|
+
readonly type: 'TSTypeReference';
|
|
43
|
+
readonly typeName: Node;
|
|
44
|
+
}
|
|
45
|
+
export interface ImportDeclaration extends Node {
|
|
46
|
+
readonly type: 'ImportDeclaration';
|
|
47
|
+
readonly specifiers: readonly Node[];
|
|
48
|
+
readonly importKind: 'value' | 'type';
|
|
49
|
+
}
|
|
50
|
+
export interface ImportSpecifier extends Node {
|
|
51
|
+
readonly type: 'ImportSpecifier';
|
|
52
|
+
readonly local: Identifier;
|
|
53
|
+
readonly importKind: 'value' | 'type';
|
|
54
|
+
}
|
|
55
|
+
export declare const isIdentifier: (node: Node | null | undefined) => node is Identifier;
|
|
56
|
+
export declare const isMethodDefinition: (node: Node | null | undefined) => node is MethodDefinition;
|
|
57
|
+
export declare const isTypeReference: (node: Node | null | undefined) => node is TSTypeReference;
|
|
58
|
+
export declare const isImportDeclaration: (node: Node | null | undefined) => node is ImportDeclaration;
|
|
59
|
+
export declare const isImportSpecifier: (node: Node | null | undefined) => node is ImportSpecifier;
|
|
60
|
+
export declare const isParameterProperty: (node: Node | null | undefined) => node is TSParameterProperty;
|
|
61
|
+
/**
|
|
62
|
+
* Declarations only. A `ClassExpression`'s own name is bound inside the class
|
|
63
|
+
* body, not outside it, so a statement appended after `const X = class Foo {}`
|
|
64
|
+
* could not reference `Foo` — it would be a ReferenceError at load.
|
|
65
|
+
*/
|
|
66
|
+
export declare const isClassDeclaration: (node: Node) => node is ClassNode;
|
|
67
|
+
/**
|
|
68
|
+
* Depth-first over every object in the tree. oxc's ESTree output is a plain
|
|
69
|
+
* object graph with no parent links, so recursing every own value is safe and
|
|
70
|
+
* needs no visitor-key table.
|
|
71
|
+
*/
|
|
72
|
+
export declare const walk: (root: unknown, visit: (node: Node) => void) => void;
|
|
73
|
+
export declare const nameOf: (node: Node | null | undefined) => string | undefined;
|
package/dist/deps.d.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export interface TransformResult {
|
|
2
|
+
readonly code: string;
|
|
3
|
+
readonly changed: boolean;
|
|
4
|
+
/** Classes that received dependency metadata, in source order. */
|
|
5
|
+
readonly annotated: readonly string[];
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Records each class's constructor dependencies, and each decorated field's
|
|
9
|
+
* declared type, as thunks on the class itself.
|
|
10
|
+
*
|
|
11
|
+
* A thunk, not a literal: the body is evaluated when the record is read rather
|
|
12
|
+
* than when the module is defined, so a dependency declared later in the file —
|
|
13
|
+
* or in a circular import — is not a temporal-dead-zone crash. That is what
|
|
14
|
+
* removes the need for Nest's `forwardRef`, and it is also why a class decorator
|
|
15
|
+
* cannot read the field record while it runs: the statement is appended after the
|
|
16
|
+
* class, which is after decoration.
|
|
17
|
+
*/
|
|
18
|
+
export declare const transform: (source: string, filename?: string) => TransformResult;
|
package/dist/edits.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export interface Edit {
|
|
2
|
+
readonly start: number;
|
|
3
|
+
readonly end: number;
|
|
4
|
+
readonly text: string;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Splices edits into the original text rather than reprinting the AST, so
|
|
8
|
+
* everything untouched keeps its exact bytes — comments, formatting, and the
|
|
9
|
+
* line numbers stack traces point at.
|
|
10
|
+
*/
|
|
11
|
+
export declare const applyEdits: (source: string, edits: readonly Edit[]) => string;
|
package/dist/erased.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { type ClassNode, type Node } from './ast.js';
|
|
2
|
+
/**
|
|
3
|
+
* Names that exist only in the type system, so emitting them in a value position
|
|
4
|
+
* would be a `ReferenceError` at runtime. Collected per file: type-only imports,
|
|
5
|
+
* inline `type` specifiers, local interfaces and type aliases.
|
|
6
|
+
*/
|
|
7
|
+
export declare const collectTypeOnlyNames: (program: Node) => ReadonlySet<string>;
|
|
8
|
+
/** A class's own type parameters are erased, so `T` is never a usable token. */
|
|
9
|
+
export declare const collectTypeParameters: (klass: ClassNode) => ReadonlySet<string>;
|
|
10
|
+
/** Every name in this file that a value position cannot use. */
|
|
11
|
+
export declare const erasedNames: (typeOnly: ReadonlySet<string>, klass: ClassNode) => ReadonlySet<string>;
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// src/deps.ts
|
|
3
|
+
import { parseSync } from "oxc-parser";
|
|
4
|
+
|
|
5
|
+
// src/ast.ts
|
|
6
|
+
var guard = (type) => (node) => node?.type === type;
|
|
7
|
+
var isIdentifier = guard("Identifier");
|
|
8
|
+
var isMethodDefinition = guard("MethodDefinition");
|
|
9
|
+
var isTypeReference = guard("TSTypeReference");
|
|
10
|
+
var isImportDeclaration = guard("ImportDeclaration");
|
|
11
|
+
var isImportSpecifier = guard("ImportSpecifier");
|
|
12
|
+
var isParameterProperty = guard("TSParameterProperty");
|
|
13
|
+
var isClassDeclaration = (node) => node.type === "ClassDeclaration";
|
|
14
|
+
var walk = (root, visit) => {
|
|
15
|
+
if (Array.isArray(root)) {
|
|
16
|
+
for (const child of root)
|
|
17
|
+
walk(child, visit);
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
if (root === null || typeof root !== "object")
|
|
21
|
+
return;
|
|
22
|
+
const candidate = root;
|
|
23
|
+
if (typeof candidate.type === "string" && typeof candidate.start === "number" && typeof candidate.end === "number") {
|
|
24
|
+
visit(root);
|
|
25
|
+
}
|
|
26
|
+
for (const child of Object.values(root))
|
|
27
|
+
walk(child, visit);
|
|
28
|
+
};
|
|
29
|
+
var nameOf = (node) => isIdentifier(node) ? node.name : undefined;
|
|
30
|
+
|
|
31
|
+
// src/edits.ts
|
|
32
|
+
var applyEdits = (source, edits) => {
|
|
33
|
+
const sorted = [...edits].sort((left, right) => left.start - right.start || left.end - right.end);
|
|
34
|
+
let out = "";
|
|
35
|
+
let cursor = 0;
|
|
36
|
+
for (const edit of sorted) {
|
|
37
|
+
if (edit.start < cursor) {
|
|
38
|
+
throw new Error(`Overlapping edit at ${edit.start}..${edit.end}; the previous edit ended ` + `at ${cursor}.`);
|
|
39
|
+
}
|
|
40
|
+
out += source.slice(cursor, edit.start) + edit.text;
|
|
41
|
+
cursor = edit.end;
|
|
42
|
+
}
|
|
43
|
+
return out + source.slice(cursor);
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
// src/erased.ts
|
|
47
|
+
var collectTypeOnlyNames = (program) => {
|
|
48
|
+
const names = new Set;
|
|
49
|
+
walk(program, (node) => {
|
|
50
|
+
if (isImportDeclaration(node)) {
|
|
51
|
+
for (const specifier of node.specifiers) {
|
|
52
|
+
if (!isImportSpecifier(specifier))
|
|
53
|
+
continue;
|
|
54
|
+
if (node.importKind === "type" || specifier.importKind === "type") {
|
|
55
|
+
names.add(specifier.local.name);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
if (node.type === "TSInterfaceDeclaration" || node.type === "TSTypeAliasDeclaration") {
|
|
61
|
+
const declared = node.id;
|
|
62
|
+
const name = nameOf(declared);
|
|
63
|
+
if (name !== undefined)
|
|
64
|
+
names.add(name);
|
|
65
|
+
}
|
|
66
|
+
});
|
|
67
|
+
return names;
|
|
68
|
+
};
|
|
69
|
+
var collectTypeParameters = (klass) => {
|
|
70
|
+
const names = new Set;
|
|
71
|
+
if (klass.typeParameters === null)
|
|
72
|
+
return names;
|
|
73
|
+
walk(klass.typeParameters, (node) => {
|
|
74
|
+
if (node.type !== "TSTypeParameter")
|
|
75
|
+
return;
|
|
76
|
+
const name = nameOf(node.name);
|
|
77
|
+
if (name !== undefined)
|
|
78
|
+
names.add(name);
|
|
79
|
+
});
|
|
80
|
+
return names;
|
|
81
|
+
};
|
|
82
|
+
var erasedNames = (typeOnly, klass) => new Set([...typeOnly, ...collectTypeParameters(klass)]);
|
|
83
|
+
|
|
84
|
+
// src/deps.ts
|
|
85
|
+
var DEPS_KEY = "Symbol.for('dunx.deps')";
|
|
86
|
+
var slice = (source, node) => source.slice(node.start, node.end);
|
|
87
|
+
var constructorParams = (klass) => {
|
|
88
|
+
const found = klass.body.body.find((member) => isMethodDefinition(member) && nameOf(member.key) === "constructor");
|
|
89
|
+
return isMethodDefinition(found) ? found.value.params : [];
|
|
90
|
+
};
|
|
91
|
+
var annotationOf = (param) => {
|
|
92
|
+
const inner = isParameterProperty(param) ? param.parameter : param;
|
|
93
|
+
if (!isIdentifier(inner))
|
|
94
|
+
return;
|
|
95
|
+
return inner.typeAnnotation?.typeAnnotation;
|
|
96
|
+
};
|
|
97
|
+
var entryFor = (source, param, erased) => {
|
|
98
|
+
const unresolved = `{ unresolved: ${JSON.stringify(slice(source, param))} }`;
|
|
99
|
+
const annotation = annotationOf(param);
|
|
100
|
+
if (!annotation || !isTypeReference(annotation))
|
|
101
|
+
return unresolved;
|
|
102
|
+
const token = slice(source, annotation.typeName);
|
|
103
|
+
if (erased.has(token))
|
|
104
|
+
return unresolved;
|
|
105
|
+
return token;
|
|
106
|
+
};
|
|
107
|
+
var transform = (source, filename = "input.ts") => {
|
|
108
|
+
const parsed = parseSync(filename, source);
|
|
109
|
+
if (parsed.errors.length > 0) {
|
|
110
|
+
const detail = parsed.errors.slice(0, 3).map((error) => error.message).join("; ");
|
|
111
|
+
throw new Error(`${filename}: could not parse \u2014 ${detail}`);
|
|
112
|
+
}
|
|
113
|
+
const program = parsed.program;
|
|
114
|
+
const typeOnly = collectTypeOnlyNames(program);
|
|
115
|
+
const edits = [];
|
|
116
|
+
const annotated = [];
|
|
117
|
+
walk(program, (node) => {
|
|
118
|
+
if (!isClassDeclaration(node))
|
|
119
|
+
return;
|
|
120
|
+
const name = node.id?.name;
|
|
121
|
+
if (name === undefined)
|
|
122
|
+
return;
|
|
123
|
+
const erased = erasedNames(typeOnly, node);
|
|
124
|
+
const params = constructorParams(node);
|
|
125
|
+
if (params.length > 0) {
|
|
126
|
+
const entries = params.map((param) => entryFor(source, param, erased));
|
|
127
|
+
annotated.push(name);
|
|
128
|
+
edits.push({
|
|
129
|
+
start: node.end,
|
|
130
|
+
end: node.end,
|
|
131
|
+
text: `
|
|
132
|
+
Object.defineProperty(${name}, ${DEPS_KEY}, {
|
|
133
|
+
` + ` value: () => [${entries.join(", ")}],
|
|
134
|
+
});`
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
});
|
|
138
|
+
const code = applyEdits(source, edits);
|
|
139
|
+
return { code, changed: code !== source, annotated };
|
|
140
|
+
};
|
|
141
|
+
// src/plugin.ts
|
|
142
|
+
var depsPlugin = {
|
|
143
|
+
name: "dunx-deps",
|
|
144
|
+
setup(build) {
|
|
145
|
+
build.onLoad({ filter: /\.tsx?$/ }, async ({ path }) => {
|
|
146
|
+
const source = await Bun.file(path).text();
|
|
147
|
+
const loader = path.endsWith(".tsx") ? "tsx" : "ts";
|
|
148
|
+
if (path.includes("/node_modules/"))
|
|
149
|
+
return { contents: source, loader };
|
|
150
|
+
return { contents: transform(source, path).code, loader };
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
export {
|
|
155
|
+
transform,
|
|
156
|
+
depsPlugin,
|
|
157
|
+
applyEdits
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
//# debugId=3995A726D31893AF64756E2164756E21
|
|
161
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/deps.ts", "../src/ast.ts", "../src/edits.ts", "../src/erased.ts", "../src/plugin.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import { parseSync } from 'oxc-parser';\nimport {\n isClassDeclaration,\n isIdentifier,\n isMethodDefinition,\n isParameterProperty,\n isTypeReference,\n nameOf,\n walk,\n type ClassNode,\n type Node,\n} from './ast.js';\nimport { applyEdits, type Edit } from './edits.js';\nimport { collectTypeOnlyNames, erasedNames } from './erased.js';\n\n/**\n * `Symbol.for`, not `Symbol`: two copies of `@dunx/core` in one dependency tree\n * still agree on the key. Same technique as module and route markers.\n */\nconst DEPS_KEY = \"Symbol.for('dunx.deps')\";\n\nexport interface TransformResult {\n readonly code: string;\n readonly changed: boolean;\n /** Classes that received dependency metadata, in source order. */\n readonly annotated: readonly string[];\n}\n\nconst slice = (source: string, node: Node): string =>\n source.slice(node.start, node.end);\n\nconst constructorParams = (klass: ClassNode): readonly Node[] => {\n const found = klass.body.body.find(\n (member) =>\n isMethodDefinition(member) && nameOf(member.key) === 'constructor',\n );\n return isMethodDefinition(found) ? found.value.params : [];\n};\n\n/** The declared type of a parameter, unwrapping `private readonly x: X`. */\nconst annotationOf = (param: Node): Node | undefined => {\n const inner = isParameterProperty(param) ? param.parameter : param;\n if (!isIdentifier(inner)) return undefined;\n return inner.typeAnnotation?.typeAnnotation;\n};\n\n/**\n * One entry per constructor parameter. A parameter whose type names something\n * that exists at runtime becomes that expression; anything else becomes an\n * `unresolved` descriptor so the container can name it precisely at boot instead\n * of constructing a broken object.\n */\nconst entryFor = (\n source: string,\n param: Node,\n erased: ReadonlySet<string>,\n): string => {\n const unresolved = `{ unresolved: ${JSON.stringify(slice(source, param))} }`;\n const annotation = annotationOf(param);\n\n if (!annotation || !isTypeReference(annotation)) return unresolved;\n\n const token = slice(source, annotation.typeName);\n // A qualified name (`ns.Thing`) is a runtime value; a bare erased name is not.\n if (erased.has(token)) return unresolved;\n\n return token;\n};\n\n/**\n * Records each class's constructor dependencies, and each decorated field's\n * declared type, as thunks on the class itself.\n *\n * A thunk, not a literal: the body is evaluated when the record is read rather\n * than when the module is defined, so a dependency declared later in the file —\n * or in a circular import — is not a temporal-dead-zone crash. That is what\n * removes the need for Nest's `forwardRef`, and it is also why a class decorator\n * cannot read the field record while it runs: the statement is appended after the\n * class, which is after decoration.\n */\nexport const transform = (\n source: string,\n filename = 'input.ts',\n): TransformResult => {\n const parsed = parseSync(filename, source);\n\n if (parsed.errors.length > 0) {\n const detail = parsed.errors\n .slice(0, 3)\n .map((error) => error.message)\n .join('; ');\n throw new Error(`${filename}: could not parse — ${detail}`);\n }\n\n const program = parsed.program;\n const typeOnly = collectTypeOnlyNames(program);\n const edits: Edit[] = [];\n const annotated: string[] = [];\n\n walk(program, (node) => {\n if (!isClassDeclaration(node)) return;\n\n const name = node.id?.name;\n if (name === undefined) return;\n\n const erased = erasedNames(typeOnly, node);\n const params = constructorParams(node);\n\n if (params.length > 0) {\n const entries = params.map((param) => entryFor(source, param, erased));\n annotated.push(name);\n edits.push({\n start: node.end,\n end: node.end,\n text:\n `\\nObject.defineProperty(${name}, ${DEPS_KEY}, {\\n` +\n ` value: () => [${entries.join(', ')}],\\n});`,\n });\n }\n });\n\n const code = applyEdits(source, edits);\n return { code, changed: code !== source, annotated };\n};\n",
|
|
6
|
+
"/**\n * Minimal structural views over oxc's ESTree output — only the node shapes the\n * dependency transform reads. Verified against real `oxc-parser` output.\n */\nexport interface Node {\n readonly type: string;\n readonly start: number;\n readonly end: number;\n}\n\nexport interface Identifier extends Node {\n readonly type: 'Identifier';\n readonly name: string;\n readonly typeAnnotation?: TSTypeAnnotation | null;\n}\n\nexport interface ClassBody extends Node {\n readonly type: 'ClassBody';\n readonly body: readonly Node[];\n}\n\n/** `ClassDeclaration` and `ClassExpression` share every field read here. */\nexport interface ClassNode extends Node {\n readonly id: Identifier | null;\n readonly typeParameters: Node | null;\n readonly body: ClassBody;\n}\n\nexport interface FunctionExpression extends Node {\n readonly params: readonly Node[];\n}\n\nexport interface MethodDefinition extends Node {\n readonly type: 'MethodDefinition';\n readonly key: Node;\n readonly value: FunctionExpression;\n}\n\nexport interface TSParameterProperty extends Node {\n readonly type: 'TSParameterProperty';\n readonly parameter: Node;\n}\n\nexport interface TSTypeAnnotation extends Node {\n readonly type: 'TSTypeAnnotation';\n readonly typeAnnotation: Node;\n}\n\nexport interface TSTypeReference extends Node {\n readonly type: 'TSTypeReference';\n readonly typeName: Node;\n}\n\nexport interface ImportDeclaration extends Node {\n readonly type: 'ImportDeclaration';\n readonly specifiers: readonly Node[];\n readonly importKind: 'value' | 'type';\n}\n\nexport interface ImportSpecifier extends Node {\n readonly type: 'ImportSpecifier';\n readonly local: Identifier;\n readonly importKind: 'value' | 'type';\n}\n\nconst guard =\n <T extends Node>(type: T['type']) =>\n (node: Node | null | undefined): node is T =>\n node?.type === type;\n\nexport const isIdentifier = guard<Identifier>('Identifier');\nexport const isMethodDefinition = guard<MethodDefinition>('MethodDefinition');\nexport const isTypeReference = guard<TSTypeReference>('TSTypeReference');\nexport const isImportDeclaration =\n guard<ImportDeclaration>('ImportDeclaration');\nexport const isImportSpecifier = guard<ImportSpecifier>('ImportSpecifier');\nexport const isParameterProperty = guard<TSParameterProperty>(\n 'TSParameterProperty',\n);\n\n/**\n * Declarations only. A `ClassExpression`'s own name is bound inside the class\n * body, not outside it, so a statement appended after `const X = class Foo {}`\n * could not reference `Foo` — it would be a ReferenceError at load.\n */\nexport const isClassDeclaration = (node: Node): node is ClassNode =>\n node.type === 'ClassDeclaration';\n\n/**\n * Depth-first over every object in the tree. oxc's ESTree output is a plain\n * object graph with no parent links, so recursing every own value is safe and\n * needs no visitor-key table.\n */\nexport const walk = (root: unknown, visit: (node: Node) => void): void => {\n if (Array.isArray(root)) {\n for (const child of root) walk(child, visit);\n return;\n }\n if (root === null || typeof root !== 'object') return;\n\n const candidate = root as Partial<Node>;\n if (\n typeof candidate.type === 'string' &&\n typeof candidate.start === 'number' &&\n typeof candidate.end === 'number'\n ) {\n visit(root as Node);\n }\n\n for (const child of Object.values(root)) walk(child, visit);\n};\n\nexport const nameOf = (node: Node | null | undefined): string | undefined =>\n isIdentifier(node) ? node.name : undefined;\n",
|
|
7
|
+
"export interface Edit {\n readonly start: number;\n readonly end: number;\n readonly text: string;\n}\n\n/**\n * Splices edits into the original text rather than reprinting the AST, so\n * everything untouched keeps its exact bytes — comments, formatting, and the\n * line numbers stack traces point at.\n */\nexport const applyEdits = (source: string, edits: readonly Edit[]): string => {\n const sorted = [...edits].sort(\n (left, right) => left.start - right.start || left.end - right.end,\n );\n\n let out = '';\n let cursor = 0;\n\n for (const edit of sorted) {\n if (edit.start < cursor) {\n throw new Error(\n `Overlapping edit at ${edit.start}..${edit.end}; the previous edit ended ` +\n `at ${cursor}.`,\n );\n }\n out += source.slice(cursor, edit.start) + edit.text;\n cursor = edit.end;\n }\n\n return out + source.slice(cursor);\n};\n",
|
|
8
|
+
"import {\n isImportDeclaration,\n isImportSpecifier,\n nameOf,\n walk,\n type ClassNode,\n type Node,\n} from './ast.js';\n\n/**\n * Names that exist only in the type system, so emitting them in a value position\n * would be a `ReferenceError` at runtime. Collected per file: type-only imports,\n * inline `type` specifiers, local interfaces and type aliases.\n */\nexport const collectTypeOnlyNames = (program: Node): ReadonlySet<string> => {\n const names = new Set<string>();\n\n walk(program, (node) => {\n if (isImportDeclaration(node)) {\n for (const specifier of node.specifiers) {\n if (!isImportSpecifier(specifier)) continue;\n if (node.importKind === 'type' || specifier.importKind === 'type') {\n names.add(specifier.local.name);\n }\n }\n return;\n }\n\n if (\n node.type === 'TSInterfaceDeclaration' ||\n node.type === 'TSTypeAliasDeclaration'\n ) {\n const declared = (node as { id?: Node }).id;\n const name = nameOf(declared);\n if (name !== undefined) names.add(name);\n }\n });\n\n return names;\n};\n\n/** A class's own type parameters are erased, so `T` is never a usable token. */\nexport const collectTypeParameters = (\n klass: ClassNode,\n): ReadonlySet<string> => {\n const names = new Set<string>();\n if (klass.typeParameters === null) return names;\n\n walk(klass.typeParameters, (node) => {\n if (node.type !== 'TSTypeParameter') return;\n const name = nameOf((node as { name?: Node }).name);\n if (name !== undefined) names.add(name);\n });\n\n return names;\n};\n\n/** Every name in this file that a value position cannot use. */\nexport const erasedNames = (\n typeOnly: ReadonlySet<string>,\n klass: ClassNode,\n): ReadonlySet<string> =>\n new Set([...typeOnly, ...collectTypeParameters(klass)]);\n",
|
|
9
|
+
"import type { BunPlugin } from 'bun';\nimport { transform } from './deps.js';\n\n/**\n * Rewrites TypeScript as it is loaded so the container can read constructor\n * dependencies. Usable in three places, all the same object:\n *\n * - `bunfig.toml` -> `preload = [\"@dunx/transform/preload\"]` for `bun run`\n * - `Bun.build({ plugins: [depsPlugin] })` for a production build\n * - `Bun.plugin(depsPlugin)` from a test preload\n *\n * Dependencies are skipped: a published package was already transformed by its\n * own build, and re-parsing `node_modules` on every load is pure cost.\n */\nexport const depsPlugin: BunPlugin = {\n name: 'dunx-deps',\n setup(build) {\n // A runtime plugin's onLoad must always return a result — there is no\n // \"decline and fall through\", so untransformed files are handed back as-is.\n build.onLoad({ filter: /\\.tsx?$/ }, async ({ path }) => {\n const source = await Bun.file(path).text();\n const loader = path.endsWith('.tsx') ? 'tsx' : 'ts';\n\n if (path.includes('/node_modules/')) return { contents: source, loader };\n\n return { contents: transform(source, path).code, loader };\n });\n },\n};\n"
|
|
10
|
+
],
|
|
11
|
+
"mappings": ";;AAAA;;;ACiEA,IAAM,QACJ,CAAiB,SACjB,CAAC,SACC,MAAM,SAAS;AAEZ,IAAM,eAAe,MAAkB,YAAY;AACnD,IAAM,qBAAqB,MAAwB,kBAAkB;AACrE,IAAM,kBAAkB,MAAuB,iBAAiB;AAChE,IAAM,sBACX,MAAyB,mBAAmB;AACvC,IAAM,oBAAoB,MAAuB,iBAAiB;AAClE,IAAM,sBAAsB,MACjC,qBACF;AAOO,IAAM,qBAAqB,CAAC,SACjC,KAAK,SAAS;AAOT,IAAM,OAAO,CAAC,MAAe,UAAsC;AAAA,EACxE,IAAI,MAAM,QAAQ,IAAI,GAAG;AAAA,IACvB,WAAW,SAAS;AAAA,MAAM,KAAK,OAAO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,mBAAmB,QAAQ,KAAK,IAAI;AAAA;AAAA,MACxC,CAAC;AAAA,IACH;AAAA,GACD;AAAA,EAED,MAAM,OAAO,WAAW,QAAQ,KAAK;AAAA,EACrC,OAAO,EAAE,MAAM,SAAS,SAAS,QAAQ,UAAU;AAAA;;AI5G9C,IAAM,aAAwB;AAAA,EACnC,MAAM;AAAA,EACN,KAAK,CAAC,OAAO;AAAA,IAGX,MAAM,OAAO,EAAE,QAAQ,UAAU,GAAG,SAAS,WAAW;AAAA,MACtD,MAAM,SAAS,MAAM,IAAI,KAAK,IAAI,EAAE,KAAK;AAAA,MACzC,MAAM,SAAS,KAAK,SAAS,MAAM,IAAI,QAAQ;AAAA,MAE/C,IAAI,KAAK,SAAS,gBAAgB;AAAA,QAAG,OAAO,EAAE,UAAU,QAAQ,OAAO;AAAA,MAEvE,OAAO,EAAE,UAAU,UAAU,QAAQ,IAAI,EAAE,MAAM,OAAO;AAAA,KACzD;AAAA;AAEL;",
|
|
12
|
+
"debugId": "3995A726D31893AF64756E2164756E21",
|
|
13
|
+
"names": []
|
|
14
|
+
}
|
package/dist/plugin.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { BunPlugin } from 'bun';
|
|
2
|
+
/**
|
|
3
|
+
* Rewrites TypeScript as it is loaded so the container can read constructor
|
|
4
|
+
* dependencies. Usable in three places, all the same object:
|
|
5
|
+
*
|
|
6
|
+
* - `bunfig.toml` -> `preload = ["@dunx/transform/preload"]` for `bun run`
|
|
7
|
+
* - `Bun.build({ plugins: [depsPlugin] })` for a production build
|
|
8
|
+
* - `Bun.plugin(depsPlugin)` from a test preload
|
|
9
|
+
*
|
|
10
|
+
* Dependencies are skipped: a published package was already transformed by its
|
|
11
|
+
* own build, and re-parsing `node_modules` on every load is pure cost.
|
|
12
|
+
*/
|
|
13
|
+
export declare const depsPlugin: BunPlugin;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/preload.js
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// src/preload.ts
|
|
3
|
+
var {plugin } = globalThis.Bun;
|
|
4
|
+
|
|
5
|
+
// src/deps.ts
|
|
6
|
+
import { parseSync } from "oxc-parser";
|
|
7
|
+
|
|
8
|
+
// src/ast.ts
|
|
9
|
+
var guard = (type) => (node) => node?.type === type;
|
|
10
|
+
var isIdentifier = guard("Identifier");
|
|
11
|
+
var isMethodDefinition = guard("MethodDefinition");
|
|
12
|
+
var isTypeReference = guard("TSTypeReference");
|
|
13
|
+
var isImportDeclaration = guard("ImportDeclaration");
|
|
14
|
+
var isImportSpecifier = guard("ImportSpecifier");
|
|
15
|
+
var isParameterProperty = guard("TSParameterProperty");
|
|
16
|
+
var isClassDeclaration = (node) => node.type === "ClassDeclaration";
|
|
17
|
+
var walk = (root, visit) => {
|
|
18
|
+
if (Array.isArray(root)) {
|
|
19
|
+
for (const child of root)
|
|
20
|
+
walk(child, visit);
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
if (root === null || typeof root !== "object")
|
|
24
|
+
return;
|
|
25
|
+
const candidate = root;
|
|
26
|
+
if (typeof candidate.type === "string" && typeof candidate.start === "number" && typeof candidate.end === "number") {
|
|
27
|
+
visit(root);
|
|
28
|
+
}
|
|
29
|
+
for (const child of Object.values(root))
|
|
30
|
+
walk(child, visit);
|
|
31
|
+
};
|
|
32
|
+
var nameOf = (node) => isIdentifier(node) ? node.name : undefined;
|
|
33
|
+
|
|
34
|
+
// src/edits.ts
|
|
35
|
+
var applyEdits = (source, edits) => {
|
|
36
|
+
const sorted = [...edits].sort((left, right) => left.start - right.start || left.end - right.end);
|
|
37
|
+
let out = "";
|
|
38
|
+
let cursor = 0;
|
|
39
|
+
for (const edit of sorted) {
|
|
40
|
+
if (edit.start < cursor) {
|
|
41
|
+
throw new Error(`Overlapping edit at ${edit.start}..${edit.end}; the previous edit ended ` + `at ${cursor}.`);
|
|
42
|
+
}
|
|
43
|
+
out += source.slice(cursor, edit.start) + edit.text;
|
|
44
|
+
cursor = edit.end;
|
|
45
|
+
}
|
|
46
|
+
return out + source.slice(cursor);
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
// src/erased.ts
|
|
50
|
+
var collectTypeOnlyNames = (program) => {
|
|
51
|
+
const names = new Set;
|
|
52
|
+
walk(program, (node) => {
|
|
53
|
+
if (isImportDeclaration(node)) {
|
|
54
|
+
for (const specifier of node.specifiers) {
|
|
55
|
+
if (!isImportSpecifier(specifier))
|
|
56
|
+
continue;
|
|
57
|
+
if (node.importKind === "type" || specifier.importKind === "type") {
|
|
58
|
+
names.add(specifier.local.name);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
if (node.type === "TSInterfaceDeclaration" || node.type === "TSTypeAliasDeclaration") {
|
|
64
|
+
const declared = node.id;
|
|
65
|
+
const name = nameOf(declared);
|
|
66
|
+
if (name !== undefined)
|
|
67
|
+
names.add(name);
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
return names;
|
|
71
|
+
};
|
|
72
|
+
var collectTypeParameters = (klass) => {
|
|
73
|
+
const names = new Set;
|
|
74
|
+
if (klass.typeParameters === null)
|
|
75
|
+
return names;
|
|
76
|
+
walk(klass.typeParameters, (node) => {
|
|
77
|
+
if (node.type !== "TSTypeParameter")
|
|
78
|
+
return;
|
|
79
|
+
const name = nameOf(node.name);
|
|
80
|
+
if (name !== undefined)
|
|
81
|
+
names.add(name);
|
|
82
|
+
});
|
|
83
|
+
return names;
|
|
84
|
+
};
|
|
85
|
+
var erasedNames = (typeOnly, klass) => new Set([...typeOnly, ...collectTypeParameters(klass)]);
|
|
86
|
+
|
|
87
|
+
// src/deps.ts
|
|
88
|
+
var DEPS_KEY = "Symbol.for('dunx.deps')";
|
|
89
|
+
var slice = (source, node) => source.slice(node.start, node.end);
|
|
90
|
+
var constructorParams = (klass) => {
|
|
91
|
+
const found = klass.body.body.find((member) => isMethodDefinition(member) && nameOf(member.key) === "constructor");
|
|
92
|
+
return isMethodDefinition(found) ? found.value.params : [];
|
|
93
|
+
};
|
|
94
|
+
var annotationOf = (param) => {
|
|
95
|
+
const inner = isParameterProperty(param) ? param.parameter : param;
|
|
96
|
+
if (!isIdentifier(inner))
|
|
97
|
+
return;
|
|
98
|
+
return inner.typeAnnotation?.typeAnnotation;
|
|
99
|
+
};
|
|
100
|
+
var entryFor = (source, param, erased) => {
|
|
101
|
+
const unresolved = `{ unresolved: ${JSON.stringify(slice(source, param))} }`;
|
|
102
|
+
const annotation = annotationOf(param);
|
|
103
|
+
if (!annotation || !isTypeReference(annotation))
|
|
104
|
+
return unresolved;
|
|
105
|
+
const token = slice(source, annotation.typeName);
|
|
106
|
+
if (erased.has(token))
|
|
107
|
+
return unresolved;
|
|
108
|
+
return token;
|
|
109
|
+
};
|
|
110
|
+
var transform = (source, filename = "input.ts") => {
|
|
111
|
+
const parsed = parseSync(filename, source);
|
|
112
|
+
if (parsed.errors.length > 0) {
|
|
113
|
+
const detail = parsed.errors.slice(0, 3).map((error) => error.message).join("; ");
|
|
114
|
+
throw new Error(`${filename}: could not parse \u2014 ${detail}`);
|
|
115
|
+
}
|
|
116
|
+
const program = parsed.program;
|
|
117
|
+
const typeOnly = collectTypeOnlyNames(program);
|
|
118
|
+
const edits = [];
|
|
119
|
+
const annotated = [];
|
|
120
|
+
walk(program, (node) => {
|
|
121
|
+
if (!isClassDeclaration(node))
|
|
122
|
+
return;
|
|
123
|
+
const name = node.id?.name;
|
|
124
|
+
if (name === undefined)
|
|
125
|
+
return;
|
|
126
|
+
const erased = erasedNames(typeOnly, node);
|
|
127
|
+
const params = constructorParams(node);
|
|
128
|
+
if (params.length > 0) {
|
|
129
|
+
const entries = params.map((param) => entryFor(source, param, erased));
|
|
130
|
+
annotated.push(name);
|
|
131
|
+
edits.push({
|
|
132
|
+
start: node.end,
|
|
133
|
+
end: node.end,
|
|
134
|
+
text: `
|
|
135
|
+
Object.defineProperty(${name}, ${DEPS_KEY}, {
|
|
136
|
+
` + ` value: () => [${entries.join(", ")}],
|
|
137
|
+
});`
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
});
|
|
141
|
+
const code = applyEdits(source, edits);
|
|
142
|
+
return { code, changed: code !== source, annotated };
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
// src/plugin.ts
|
|
146
|
+
var depsPlugin = {
|
|
147
|
+
name: "dunx-deps",
|
|
148
|
+
setup(build) {
|
|
149
|
+
build.onLoad({ filter: /\.tsx?$/ }, async ({ path }) => {
|
|
150
|
+
const source = await Bun.file(path).text();
|
|
151
|
+
const loader = path.endsWith(".tsx") ? "tsx" : "ts";
|
|
152
|
+
if (path.includes("/node_modules/"))
|
|
153
|
+
return { contents: source, loader };
|
|
154
|
+
return { contents: transform(source, path).code, loader };
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
// src/preload.ts
|
|
160
|
+
await plugin(depsPlugin);
|
|
161
|
+
|
|
162
|
+
//# debugId=BAAA0FE7F215564464756E2164756E21
|
|
163
|
+
//# sourceMappingURL=preload.js.map
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/preload.ts", "../src/deps.ts", "../src/ast.ts", "../src/edits.ts", "../src/erased.ts", "../src/plugin.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import { plugin } from 'bun';\nimport { depsPlugin } from './plugin.js';\n\n// Side-effect entrypoint for `bunfig.toml`:\n// preload = [\"@dunx/transform/preload\"]\n//\n// Awaited, not fire-and-forget: registration has to finish before the entrypoint\n// is loaded, or the first modules through would miss the transform.\nawait plugin(depsPlugin);\n",
|
|
6
|
+
"import { parseSync } from 'oxc-parser';\nimport {\n isClassDeclaration,\n isIdentifier,\n isMethodDefinition,\n isParameterProperty,\n isTypeReference,\n nameOf,\n walk,\n type ClassNode,\n type Node,\n} from './ast.js';\nimport { applyEdits, type Edit } from './edits.js';\nimport { collectTypeOnlyNames, erasedNames } from './erased.js';\n\n/**\n * `Symbol.for`, not `Symbol`: two copies of `@dunx/core` in one dependency tree\n * still agree on the key. Same technique as module and route markers.\n */\nconst DEPS_KEY = \"Symbol.for('dunx.deps')\";\n\nexport interface TransformResult {\n readonly code: string;\n readonly changed: boolean;\n /** Classes that received dependency metadata, in source order. */\n readonly annotated: readonly string[];\n}\n\nconst slice = (source: string, node: Node): string =>\n source.slice(node.start, node.end);\n\nconst constructorParams = (klass: ClassNode): readonly Node[] => {\n const found = klass.body.body.find(\n (member) =>\n isMethodDefinition(member) && nameOf(member.key) === 'constructor',\n );\n return isMethodDefinition(found) ? found.value.params : [];\n};\n\n/** The declared type of a parameter, unwrapping `private readonly x: X`. */\nconst annotationOf = (param: Node): Node | undefined => {\n const inner = isParameterProperty(param) ? param.parameter : param;\n if (!isIdentifier(inner)) return undefined;\n return inner.typeAnnotation?.typeAnnotation;\n};\n\n/**\n * One entry per constructor parameter. A parameter whose type names something\n * that exists at runtime becomes that expression; anything else becomes an\n * `unresolved` descriptor so the container can name it precisely at boot instead\n * of constructing a broken object.\n */\nconst entryFor = (\n source: string,\n param: Node,\n erased: ReadonlySet<string>,\n): string => {\n const unresolved = `{ unresolved: ${JSON.stringify(slice(source, param))} }`;\n const annotation = annotationOf(param);\n\n if (!annotation || !isTypeReference(annotation)) return unresolved;\n\n const token = slice(source, annotation.typeName);\n // A qualified name (`ns.Thing`) is a runtime value; a bare erased name is not.\n if (erased.has(token)) return unresolved;\n\n return token;\n};\n\n/**\n * Records each class's constructor dependencies, and each decorated field's\n * declared type, as thunks on the class itself.\n *\n * A thunk, not a literal: the body is evaluated when the record is read rather\n * than when the module is defined, so a dependency declared later in the file —\n * or in a circular import — is not a temporal-dead-zone crash. That is what\n * removes the need for Nest's `forwardRef`, and it is also why a class decorator\n * cannot read the field record while it runs: the statement is appended after the\n * class, which is after decoration.\n */\nexport const transform = (\n source: string,\n filename = 'input.ts',\n): TransformResult => {\n const parsed = parseSync(filename, source);\n\n if (parsed.errors.length > 0) {\n const detail = parsed.errors\n .slice(0, 3)\n .map((error) => error.message)\n .join('; ');\n throw new Error(`${filename}: could not parse — ${detail}`);\n }\n\n const program = parsed.program;\n const typeOnly = collectTypeOnlyNames(program);\n const edits: Edit[] = [];\n const annotated: string[] = [];\n\n walk(program, (node) => {\n if (!isClassDeclaration(node)) return;\n\n const name = node.id?.name;\n if (name === undefined) return;\n\n const erased = erasedNames(typeOnly, node);\n const params = constructorParams(node);\n\n if (params.length > 0) {\n const entries = params.map((param) => entryFor(source, param, erased));\n annotated.push(name);\n edits.push({\n start: node.end,\n end: node.end,\n text:\n `\\nObject.defineProperty(${name}, ${DEPS_KEY}, {\\n` +\n ` value: () => [${entries.join(', ')}],\\n});`,\n });\n }\n });\n\n const code = applyEdits(source, edits);\n return { code, changed: code !== source, annotated };\n};\n",
|
|
7
|
+
"/**\n * Minimal structural views over oxc's ESTree output — only the node shapes the\n * dependency transform reads. Verified against real `oxc-parser` output.\n */\nexport interface Node {\n readonly type: string;\n readonly start: number;\n readonly end: number;\n}\n\nexport interface Identifier extends Node {\n readonly type: 'Identifier';\n readonly name: string;\n readonly typeAnnotation?: TSTypeAnnotation | null;\n}\n\nexport interface ClassBody extends Node {\n readonly type: 'ClassBody';\n readonly body: readonly Node[];\n}\n\n/** `ClassDeclaration` and `ClassExpression` share every field read here. */\nexport interface ClassNode extends Node {\n readonly id: Identifier | null;\n readonly typeParameters: Node | null;\n readonly body: ClassBody;\n}\n\nexport interface FunctionExpression extends Node {\n readonly params: readonly Node[];\n}\n\nexport interface MethodDefinition extends Node {\n readonly type: 'MethodDefinition';\n readonly key: Node;\n readonly value: FunctionExpression;\n}\n\nexport interface TSParameterProperty extends Node {\n readonly type: 'TSParameterProperty';\n readonly parameter: Node;\n}\n\nexport interface TSTypeAnnotation extends Node {\n readonly type: 'TSTypeAnnotation';\n readonly typeAnnotation: Node;\n}\n\nexport interface TSTypeReference extends Node {\n readonly type: 'TSTypeReference';\n readonly typeName: Node;\n}\n\nexport interface ImportDeclaration extends Node {\n readonly type: 'ImportDeclaration';\n readonly specifiers: readonly Node[];\n readonly importKind: 'value' | 'type';\n}\n\nexport interface ImportSpecifier extends Node {\n readonly type: 'ImportSpecifier';\n readonly local: Identifier;\n readonly importKind: 'value' | 'type';\n}\n\nconst guard =\n <T extends Node>(type: T['type']) =>\n (node: Node | null | undefined): node is T =>\n node?.type === type;\n\nexport const isIdentifier = guard<Identifier>('Identifier');\nexport const isMethodDefinition = guard<MethodDefinition>('MethodDefinition');\nexport const isTypeReference = guard<TSTypeReference>('TSTypeReference');\nexport const isImportDeclaration =\n guard<ImportDeclaration>('ImportDeclaration');\nexport const isImportSpecifier = guard<ImportSpecifier>('ImportSpecifier');\nexport const isParameterProperty = guard<TSParameterProperty>(\n 'TSParameterProperty',\n);\n\n/**\n * Declarations only. A `ClassExpression`'s own name is bound inside the class\n * body, not outside it, so a statement appended after `const X = class Foo {}`\n * could not reference `Foo` — it would be a ReferenceError at load.\n */\nexport const isClassDeclaration = (node: Node): node is ClassNode =>\n node.type === 'ClassDeclaration';\n\n/**\n * Depth-first over every object in the tree. oxc's ESTree output is a plain\n * object graph with no parent links, so recursing every own value is safe and\n * needs no visitor-key table.\n */\nexport const walk = (root: unknown, visit: (node: Node) => void): void => {\n if (Array.isArray(root)) {\n for (const child of root) walk(child, visit);\n return;\n }\n if (root === null || typeof root !== 'object') return;\n\n const candidate = root as Partial<Node>;\n if (\n typeof candidate.type === 'string' &&\n typeof candidate.start === 'number' &&\n typeof candidate.end === 'number'\n ) {\n visit(root as Node);\n }\n\n for (const child of Object.values(root)) walk(child, visit);\n};\n\nexport const nameOf = (node: Node | null | undefined): string | undefined =>\n isIdentifier(node) ? node.name : undefined;\n",
|
|
8
|
+
"export interface Edit {\n readonly start: number;\n readonly end: number;\n readonly text: string;\n}\n\n/**\n * Splices edits into the original text rather than reprinting the AST, so\n * everything untouched keeps its exact bytes — comments, formatting, and the\n * line numbers stack traces point at.\n */\nexport const applyEdits = (source: string, edits: readonly Edit[]): string => {\n const sorted = [...edits].sort(\n (left, right) => left.start - right.start || left.end - right.end,\n );\n\n let out = '';\n let cursor = 0;\n\n for (const edit of sorted) {\n if (edit.start < cursor) {\n throw new Error(\n `Overlapping edit at ${edit.start}..${edit.end}; the previous edit ended ` +\n `at ${cursor}.`,\n );\n }\n out += source.slice(cursor, edit.start) + edit.text;\n cursor = edit.end;\n }\n\n return out + source.slice(cursor);\n};\n",
|
|
9
|
+
"import {\n isImportDeclaration,\n isImportSpecifier,\n nameOf,\n walk,\n type ClassNode,\n type Node,\n} from './ast.js';\n\n/**\n * Names that exist only in the type system, so emitting them in a value position\n * would be a `ReferenceError` at runtime. Collected per file: type-only imports,\n * inline `type` specifiers, local interfaces and type aliases.\n */\nexport const collectTypeOnlyNames = (program: Node): ReadonlySet<string> => {\n const names = new Set<string>();\n\n walk(program, (node) => {\n if (isImportDeclaration(node)) {\n for (const specifier of node.specifiers) {\n if (!isImportSpecifier(specifier)) continue;\n if (node.importKind === 'type' || specifier.importKind === 'type') {\n names.add(specifier.local.name);\n }\n }\n return;\n }\n\n if (\n node.type === 'TSInterfaceDeclaration' ||\n node.type === 'TSTypeAliasDeclaration'\n ) {\n const declared = (node as { id?: Node }).id;\n const name = nameOf(declared);\n if (name !== undefined) names.add(name);\n }\n });\n\n return names;\n};\n\n/** A class's own type parameters are erased, so `T` is never a usable token. */\nexport const collectTypeParameters = (\n klass: ClassNode,\n): ReadonlySet<string> => {\n const names = new Set<string>();\n if (klass.typeParameters === null) return names;\n\n walk(klass.typeParameters, (node) => {\n if (node.type !== 'TSTypeParameter') return;\n const name = nameOf((node as { name?: Node }).name);\n if (name !== undefined) names.add(name);\n });\n\n return names;\n};\n\n/** Every name in this file that a value position cannot use. */\nexport const erasedNames = (\n typeOnly: ReadonlySet<string>,\n klass: ClassNode,\n): ReadonlySet<string> =>\n new Set([...typeOnly, ...collectTypeParameters(klass)]);\n",
|
|
10
|
+
"import type { BunPlugin } from 'bun';\nimport { transform } from './deps.js';\n\n/**\n * Rewrites TypeScript as it is loaded so the container can read constructor\n * dependencies. Usable in three places, all the same object:\n *\n * - `bunfig.toml` -> `preload = [\"@dunx/transform/preload\"]` for `bun run`\n * - `Bun.build({ plugins: [depsPlugin] })` for a production build\n * - `Bun.plugin(depsPlugin)` from a test preload\n *\n * Dependencies are skipped: a published package was already transformed by its\n * own build, and re-parsing `node_modules` on every load is pure cost.\n */\nexport const depsPlugin: BunPlugin = {\n name: 'dunx-deps',\n setup(build) {\n // A runtime plugin's onLoad must always return a result — there is no\n // \"decline and fall through\", so untransformed files are handed back as-is.\n build.onLoad({ filter: /\\.tsx?$/ }, async ({ path }) => {\n const source = await Bun.file(path).text();\n const loader = path.endsWith('.tsx') ? 'tsx' : 'ts';\n\n if (path.includes('/node_modules/')) return { contents: source, loader };\n\n return { contents: transform(source, path).code, loader };\n });\n },\n};\n"
|
|
11
|
+
],
|
|
12
|
+
"mappings": ";;AAAA;;;ACAA;;;ACiEA,IAAM,QACJ,CAAiB,SACjB,CAAC,SACC,MAAM,SAAS;AAEZ,IAAM,eAAe,MAAkB,YAAY;AACnD,IAAM,qBAAqB,MAAwB,kBAAkB;AACrE,IAAM,kBAAkB,MAAuB,iBAAiB;AAChE,IAAM,sBACX,MAAyB,mBAAmB;AACvC,IAAM,oBAAoB,MAAuB,iBAAiB;AAClE,IAAM,sBAAsB,MACjC,qBACF;AAOO,IAAM,qBAAqB,CAAC,SACjC,KAAK,SAAS;AAOT,IAAM,OAAO,CAAC,MAAe,UAAsC;AAAA,EACxE,IAAI,MAAM,QAAQ,IAAI,GAAG;AAAA,IACvB,WAAW,SAAS;AAAA,MAAM,KAAK,OAAO,KAAK;AAAA,IAC3C;AAAA,EACF;AAAA,EACA,IAAI,SAAS,QAAQ,OAAO,SAAS;AAAA,IAAU;AAAA,EAE/C,MAAM,YAAY;AAAA,EAClB,IACE,OAAO,UAAU,S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MAAM,SAAS,SAAS,QAAQ,UAAU;AAAA;;;AI5G9C,IAAM,aAAwB;AAAA,EACnC,MAAM;AAAA,EACN,KAAK,CAAC,OAAO;AAAA,IAGX,MAAM,OAAO,EAAE,QAAQ,UAAU,GAAG,SAAS,WAAW;AAAA,MACtD,MAAM,SAAS,MAAM,IAAI,KAAK,IAAI,EAAE,KAAK;AAAA,MACzC,MAAM,SAAS,KAAK,SAAS,MAAM,IAAI,QAAQ;AAAA,MAE/C,IAAI,KAAK,SAAS,gBAAgB;AAAA,QAAG,OAAO,EAAE,UAAU,QAAQ,OAAO;AAAA,MAEvE,OAAO,EAAE,UAAU,UAAU,QAAQ,IAAI,EAAE,MAAM,OAAO;AAAA,KACzD;AAAA;AAEL;;;ALpBA,MAAM,OAAO,UAAU;",
|
|
13
|
+
"debugId": "BAAA0FE7F215564464756E2164756E21",
|
|
14
|
+
"names": []
|
|
15
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@dunx/transform",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Load-time transform that records constructor dependencies for the dunx container",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"bun",
|
|
7
|
+
"bun-plugin",
|
|
8
|
+
"dependency-injection",
|
|
9
|
+
"dunx",
|
|
10
|
+
"transform"
|
|
11
|
+
],
|
|
12
|
+
"homepage": "https://github.com/petarzarkov/dunx/tree/main/packages/transform#readme",
|
|
13
|
+
"license": "MIT",
|
|
14
|
+
"author": {
|
|
15
|
+
"name": "Petar Zarkov",
|
|
16
|
+
"email": "pzarko1@gmail.com",
|
|
17
|
+
"url": "https://github.com/petarzarkov"
|
|
18
|
+
},
|
|
19
|
+
"repository": {
|
|
20
|
+
"type": "git",
|
|
21
|
+
"url": "git+https://github.com/petarzarkov/dunx.git",
|
|
22
|
+
"directory": "packages/transform"
|
|
23
|
+
},
|
|
24
|
+
"files": [
|
|
25
|
+
"LICENSE",
|
|
26
|
+
"README.md",
|
|
27
|
+
"dist"
|
|
28
|
+
],
|
|
29
|
+
"type": "module",
|
|
30
|
+
"main": "./dist/index.js",
|
|
31
|
+
"types": "./dist/index.d.ts",
|
|
32
|
+
"exports": {
|
|
33
|
+
".": {
|
|
34
|
+
"types": "./dist/index.d.ts",
|
|
35
|
+
"import": "./dist/index.js"
|
|
36
|
+
},
|
|
37
|
+
"./preload": {
|
|
38
|
+
"types": "./dist/preload.d.ts",
|
|
39
|
+
"import": "./dist/preload.js"
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
"publishConfig": {
|
|
43
|
+
"access": "public"
|
|
44
|
+
},
|
|
45
|
+
"scripts": {
|
|
46
|
+
"build": "bun ../../scripts/build-package.ts",
|
|
47
|
+
"test": "bun test --bail",
|
|
48
|
+
"test:cov": "bun test --coverage",
|
|
49
|
+
"typecheck": "tsc --noEmit"
|
|
50
|
+
},
|
|
51
|
+
"dependencies": {
|
|
52
|
+
"oxc-parser": "0.142.0"
|
|
53
|
+
},
|
|
54
|
+
"peerDependencies": {
|
|
55
|
+
"@types/bun": ">=1.3.0"
|
|
56
|
+
},
|
|
57
|
+
"peerDependenciesMeta": {
|
|
58
|
+
"@types/bun": {
|
|
59
|
+
"optional": true
|
|
60
|
+
}
|
|
61
|
+
},
|
|
62
|
+
"engines": {
|
|
63
|
+
"bun": ">=1.3.0"
|
|
64
|
+
}
|
|
65
|
+
}
|