typescript-plugin-mark-fields 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 linsk
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,156 @@
1
+ # typescript-plugin-mark-fields
2
+
3
+ [![npm version](https://img.shields.io/npm/v/typescript-plugin-mark-fields.svg)](https://www.npmjs.com/package/typescript-plugin-mark-fields)
4
+ [![License](https://img.shields.io/npm/l/typescript-plugin-mark-fields.svg)](https://github.com/linsk1998/typescript-plugin-mark-fields/blob/main/LICENSE)
5
+
6
+ TypeScript transformer 插件。编译期自动在每个 class 头部插入 `static {}` 块,将实例字段显式标记到 `prototype` 上,使运行时代码能在实例化之前感知类有哪些字段。
7
+
8
+ ## 快速预览
9
+
10
+ **输入:**
11
+
12
+ ```ts
13
+ const TAG = 'tag';
14
+
15
+ class Animal {
16
+ static count = 0;
17
+ name;
18
+ type = 'dog';
19
+ [TAG];
20
+ legs = 4;
21
+ }
22
+ ```
23
+
24
+ **输出:**
25
+
26
+ ```js
27
+ const TAG = 'tag';
28
+
29
+ class Animal {
30
+ static {
31
+ this.prototype.name = undefined;
32
+ this.prototype.type = undefined;
33
+ this.prototype[TAG] = undefined;
34
+ this.prototype.legs = undefined;
35
+ }
36
+ static count = 0;
37
+ name;
38
+ type = 'dog';
39
+ [TAG];
40
+ legs = 4;
41
+ }
42
+ ```
43
+
44
+ > `static {}` 中的 `this` 指向类自身,无论具名类还是匿名类表达式均有效。
45
+
46
+ ## 处理规则
47
+
48
+ | 字段类型 | 示例 | 处理 |
49
+ |---------|------|:---:|
50
+ | 普通标识符字段 | `name` | ✅ `this.prototype.name = undefined` |
51
+ | 带初始值的字段 | `type = "dog"` | ✅ `this.prototype.type = undefined` |
52
+ | 计算属性名 | `[TAG]` | ✅ `this.prototype[TAG] = undefined` |
53
+ | 字符串字面量 key | `"my-field"` | ✅ `this.prototype["my-field"] = undefined` |
54
+ | 数字字面量 key | `0` | ✅ `this.prototype[0] = undefined` |
55
+ | 类表达式 | `const X = class { ... }` | ✅ 同 class 声明一样生效 |
56
+ | static 字段 | `static count = 0` | ❌ 跳过 |
57
+ | 方法 / getter / setter | `greet() {}` | ❌ 跳过 |
58
+ | 无实例字段的类 | 纯方法 | ❌ 不插入 static block |
59
+
60
+ ## 适用场景
61
+
62
+ - **装饰器方案补充**:未写装饰器的字段也会被标记到 prototype
63
+ - **运行时反射 / ORM / 序列化**:框架在实例化前就能收集字段元数据
64
+ - **AOP 切面注入**:在字段读取/写入时插入拦截逻辑
65
+ - **与 `useDefineForClassFields` 一致的可见语义**:让运行时代码明确知道字段的存在
66
+
67
+ ## 要求
68
+
69
+ - TypeScript >= 4.4(需要 `static {}` 语法支持)
70
+
71
+ ## 安装
72
+
73
+ ```bash
74
+ npm install typescript-plugin-mark-fields
75
+ ```
76
+
77
+ ## 用法
78
+
79
+ ### TypeScript Compiler API
80
+
81
+ ```ts
82
+ import ts from 'typescript';
83
+ import plugin from 'typescript-plugin-mark-fields';
84
+
85
+ const program = ts.createProgram(['src/index.ts'], {
86
+ target: ts.ScriptTarget.ESNext,
87
+ });
88
+
89
+ const transformers: ts.CustomTransformers = {
90
+ before: [plugin(program, {})],
91
+ };
92
+
93
+ program.emit(undefined, undefined, undefined, undefined, transformers);
94
+ ```
95
+
96
+ ### Rollup
97
+
98
+ ```js
99
+ // rollup.config.js
100
+ import typescript from '@rollup/plugin-typescript';
101
+ import plugin from 'typescript-plugin-mark-fields';
102
+
103
+ export default {
104
+ input: 'src/index.ts',
105
+ plugins: [
106
+ typescript({
107
+ transformers: (program) => ({
108
+ before: [plugin(program, {})],
109
+ }),
110
+ }),
111
+ ],
112
+ };
113
+ ```
114
+
115
+ ### Webpack (ts-loader)
116
+
117
+ ```js
118
+ // webpack.config.js
119
+ const plugin = require('typescript-plugin-mark-fields');
120
+
121
+ module.exports = {
122
+ module: {
123
+ rules: [
124
+ {
125
+ test: /\.tsx?$/,
126
+ loader: 'ts-loader',
127
+ options: {
128
+ getCustomTransformers: (program) => ({
129
+ before: [plugin(program, {})],
130
+ }),
131
+ },
132
+ },
133
+ ],
134
+ },
135
+ };
136
+ ```
137
+
138
+ ### ttypescript / ts-patch
139
+
140
+ 在 `tsconfig.json` 中添加:
141
+
142
+ ```json
143
+ {
144
+ "compilerOptions": {
145
+ "plugins": [
146
+ { "transform": "typescript-plugin-mark-fields" }
147
+ ]
148
+ }
149
+ }
150
+ ```
151
+
152
+ 然后用 `ttsc` 代替 `tsc` 编译。
153
+
154
+ ## License
155
+
156
+ MIT
@@ -0,0 +1,7 @@
1
+ import ts = require('typescript');
2
+ declare function transformerFactory(program: ts.Program, options?: {}): ts.TransformerFactory<ts.SourceFile>;
3
+ declare namespace transformerFactory {
4
+ var _a: typeof transformerFactory;
5
+ export { _a as default };
6
+ }
7
+ export = transformerFactory;
package/dist/index.js ADDED
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ const ts = require("typescript");
3
+ /** 检查成员是否有 static 修饰符 */
4
+ function isStatic(member) {
5
+ if (!member.modifiers)
6
+ return false;
7
+ return member.modifiers.some((m) => m.kind === ts.SyntaxKind.StaticKeyword);
8
+ }
9
+ /** 收集非 static 的 class property,返回 key 和 computed 标记 */
10
+ function collectFields(members) {
11
+ const fields = [];
12
+ for (const member of members) {
13
+ if (!ts.isPropertyDeclaration(member))
14
+ continue;
15
+ if (isStatic(member))
16
+ continue;
17
+ if (ts.isComputedPropertyName(member.name)) {
18
+ fields.push({ name: member.name.expression, computed: true });
19
+ }
20
+ else if (ts.isIdentifier(member.name)) {
21
+ fields.push({ name: member.name, computed: false });
22
+ }
23
+ else if (ts.isStringLiteral(member.name)) {
24
+ fields.push({ name: member.name, computed: true });
25
+ }
26
+ else if (ts.isNumericLiteral(member.name)) {
27
+ fields.push({ name: member.name, computed: true });
28
+ }
29
+ }
30
+ return fields;
31
+ }
32
+ /** 根据收集的字段信息生成 static {} 块 */
33
+ function createStaticBlock(fields) {
34
+ const statements = fields.map((f) => {
35
+ // this.prototype
36
+ const prototypeAccess = ts.factory.createPropertyAccessExpression(ts.factory.createThis(), ts.factory.createIdentifier('prototype'));
37
+ // this.prototype[key] 或 this.prototype.key
38
+ const memberAccess = f.computed
39
+ ? ts.factory.createElementAccessExpression(prototypeAccess, f.name)
40
+ : ts.factory.createPropertyAccessExpression(prototypeAccess, f.name);
41
+ // this.prototype[key] = undefined
42
+ const assignment = ts.factory.createAssignment(memberAccess, ts.factory.createIdentifier('undefined'));
43
+ return ts.factory.createExpressionStatement(assignment);
44
+ });
45
+ return ts.factory.createClassStaticBlockDeclaration(ts.factory.createBlock(statements, true));
46
+ }
47
+ function transformerFactory(program, options = {}) {
48
+ return (context) => {
49
+ function visit(node) {
50
+ if (ts.isClassDeclaration(node) || ts.isClassExpression(node)) {
51
+ return transformClass(node);
52
+ }
53
+ return ts.visitEachChild(node, visit, context);
54
+ }
55
+ function transformClass(node) {
56
+ const fields = collectFields(node.members);
57
+ if (fields.length === 0) {
58
+ return node;
59
+ }
60
+ const staticBlock = createStaticBlock(fields);
61
+ // 把 static {} 插到 class body 最前面
62
+ const newMembers = ts.factory.createNodeArray([staticBlock, ...node.members]);
63
+ if (ts.isClassDeclaration(node)) {
64
+ return ts.factory.updateClassDeclaration(node, node.modifiers, node.name, node.typeParameters, node.heritageClauses, newMembers);
65
+ }
66
+ else {
67
+ return ts.factory.updateClassExpression(node, node.modifiers, node.name, node.typeParameters, node.heritageClauses, newMembers);
68
+ }
69
+ }
70
+ return (sourceFile) => {
71
+ return ts.visitNode(sourceFile, visit);
72
+ };
73
+ };
74
+ }
75
+ transformerFactory.default = transformerFactory;
76
+ module.exports = transformerFactory;
package/package.json ADDED
@@ -0,0 +1,58 @@
1
+ {
2
+ "name": "typescript-plugin-mark-fields",
3
+ "version": "1.0.0",
4
+ "description": "Auto-mark class fields on prototype via static block for runtime introspection",
5
+ "keywords": [
6
+ "typescript",
7
+ "transformer",
8
+ "plugin",
9
+ "class",
10
+ "fields",
11
+ "prototype",
12
+ "static-block",
13
+ "decorator",
14
+ "reflect-metadata",
15
+ "runtime",
16
+ "introspection",
17
+ "ttypescript"
18
+ ],
19
+ "author": "linsk",
20
+ "license": "MIT",
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "https://github.com/linsk1998/typescript-plugin-mark-fields.git"
24
+ },
25
+ "bugs": {
26
+ "url": "https://github.com/linsk1998/typescript-plugin-mark-fields/issues"
27
+ },
28
+ "homepage": "https://github.com/linsk1998/typescript-plugin-mark-fields#readme",
29
+ "main": "dist/index.js",
30
+ "types": "dist/index.d.ts",
31
+ "files": [
32
+ "dist"
33
+ ],
34
+ "scripts": {
35
+ "build": "rimraf dist && tsc",
36
+ "gen-fixtures": "rimraf tests/fixtures && ttsc -p ./tests/tsconfig.json --noEmit false",
37
+ "test": "mocha tests/**/*.test.js",
38
+ "prepublishOnly": "npm run build && npm run test"
39
+ },
40
+ "peerDependencies": {
41
+ "typescript": ">=4.4"
42
+ },
43
+ "publishConfig": {
44
+ "access": "public",
45
+ "registry": "https://registry.npmjs.org/"
46
+ },
47
+ "devDependencies": {
48
+ "@rollup/plugin-typescript": "^12.1.4",
49
+ "mocha": "^8.0.1",
50
+ "rimraf": "^6.0.1",
51
+ "rollup": "3.0.0",
52
+ "ts-loader": "^9.5.4",
53
+ "tslib": "^2.8.1",
54
+ "ttypescript": "^1.5.15",
55
+ "typescript": "^4.9.5",
56
+ "webpack": "^5.102.1"
57
+ }
58
+ }