unreflect 0.0.1

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)
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,82 @@
1
+ # unreflect
2
+
3
+ <!-- automd:badges color=yellow -->
4
+
5
+ [![npm version](https://img.shields.io/npm/v/unreflect?color=yellow)](https://npmjs.com/package/unreflect)
6
+ [![npm downloads](https://img.shields.io/npm/dm/unreflect?color=yellow)](https://npm.chart.dev/unreflect)
7
+
8
+ <!-- /automd -->
9
+
10
+ Access and modify private class fields and methods in JavaScript using the V8 inspector API.
11
+
12
+ ## Installation
13
+
14
+ ```sh
15
+ npx nypm install unreflect
16
+ ```
17
+
18
+ ## Usage
19
+
20
+ ```js
21
+ import { ReflectionClass } from "unreflect";
22
+
23
+ class User {
24
+ #name = "John";
25
+ public email = "john@example.com";
26
+
27
+ getName() {
28
+ return this.#name;
29
+ }
30
+ }
31
+
32
+ const user = new User();
33
+ const ref = new ReflectionClass(user);
34
+
35
+ // Get class name
36
+ ref.getClassName(); // "User"
37
+
38
+ // Get/set property values (public and private)
39
+ await ref.getPropertyValue("name"); // "John"
40
+ await ref.getPropertyValue("email"); // "john@example.com"
41
+
42
+ ref.setProperty("name", "Jane");
43
+ user.getName(); // "Jane"
44
+
45
+ // Get property metadata
46
+ await ref.getProperty("name");
47
+ // { name: "name", visibility: "private", value: "Jane" }
48
+
49
+ // List all properties
50
+ await ref.getProperties();
51
+ // [
52
+ // { name: "email", visibility: "public", value: "john@example.com" },
53
+ // { name: "name", visibility: "private" }
54
+ // ]
55
+
56
+ // List all methods (including private)
57
+ await ref.getMethods();
58
+ // [
59
+ // { name: "getName", visibility: "public", isStatic: false }
60
+ // ]
61
+
62
+ // Check existence
63
+ await ref.hasProperty("name"); // true
64
+ await ref.hasMethod("getName"); // true
65
+ ```
66
+
67
+ ## API
68
+
69
+ | Method | Description |
70
+ | -------------------------- | --------------------------------------------------- |
71
+ | `getClassName()` | Returns the class name |
72
+ | `setProperty(name, value)` | Sets a property value (public or private) |
73
+ | `getProperty(name)` | Returns property metadata with visibility and value |
74
+ | `getPropertyValue(name)` | Returns just the property value |
75
+ | `getProperties()` | Returns all properties with visibility |
76
+ | `getMethods()` | Returns all methods with visibility and static flag |
77
+ | `hasProperty(name)` | Checks if a property exists |
78
+ | `hasMethod(name)` | Checks if a method exists |
79
+
80
+ ## License
81
+
82
+ Published under the [MIT](https://github.com/KABBOUCHI/unreflect/blob/main/LICENSE) license.
@@ -0,0 +1,27 @@
1
+ //#region src/index.d.ts
2
+ type PropertyVisibility = "public" | "private";
3
+ interface ReflectionProperty {
4
+ name: string;
5
+ visibility: PropertyVisibility;
6
+ value?: any;
7
+ }
8
+ interface ReflectionMethod {
9
+ name: string;
10
+ visibility: PropertyVisibility;
11
+ isStatic: boolean;
12
+ }
13
+ declare class ReflectionClass {
14
+ private obj;
15
+ private values;
16
+ constructor(obj: any);
17
+ setProperty(name: string, value: any): void;
18
+ getProperty(name: string): Promise<ReflectionProperty | undefined>;
19
+ getPropertyValue(name: string): Promise<any>;
20
+ getClassName(): string;
21
+ getProperties(): Promise<ReflectionProperty[]>;
22
+ getMethods(): Promise<ReflectionMethod[]>;
23
+ hasProperty(name: string): Promise<boolean>;
24
+ hasMethod(name: string): Promise<boolean>;
25
+ }
26
+ //#endregion
27
+ export { PropertyVisibility, ReflectionClass, ReflectionMethod, ReflectionProperty };
package/dist/index.mjs ADDED
@@ -0,0 +1,189 @@
1
+ import vm from "node:vm";
2
+ import inspector from "node:inspector/promises";
3
+
4
+ //#region src/index.ts
5
+ var ReflectionClass = class {
6
+ obj;
7
+ values = /* @__PURE__ */ new Map();
8
+ constructor(obj) {
9
+ this.obj = obj;
10
+ }
11
+ setProperty(name, value) {
12
+ const obj = this.obj;
13
+ if (Object.prototype.hasOwnProperty.call(obj, name)) {
14
+ obj[name] = value;
15
+ return;
16
+ }
17
+ const proto = Object.getPrototypeOf(obj);
18
+ const classSource = proto.constructor.toString();
19
+ if (!classSource.includes(`#${name}`)) {
20
+ obj[name] = value;
21
+ return;
22
+ }
23
+ const modifiedSource = classSource.replace(/#(\w+)\s*=\s*[^;]+;/g, "#$1;").replace(/^(class\s+\w+)\s*\{/, `$1 { static __reflectionSet__(obj, val) { obj.#${name} = val; } static __reflectionGet__(obj) { return obj.#${name}; }`);
24
+ const ModifiedClass = vm.runInThisContext(`(${modifiedSource})`);
25
+ Object.setPrototypeOf(obj, ModifiedClass.prototype);
26
+ const originalProps = Object.getOwnPropertyDescriptors(obj);
27
+ const freshInstance = new ModifiedClass();
28
+ for (const key of Object.getOwnPropertyNames(originalProps)) Object.defineProperty(freshInstance, key, originalProps[key]);
29
+ ModifiedClass.__reflectionSet__(freshInstance, value);
30
+ this.values.set(name, {
31
+ freshInstance,
32
+ ModifiedClass
33
+ });
34
+ Object.setPrototypeOf(obj, proto);
35
+ const methodNames = Object.getOwnPropertyNames(proto).filter((n) => n !== "constructor" && typeof proto[n] === "function");
36
+ for (const methodName of methodNames) if (proto[methodName].toString().includes(`#${name}`)) {
37
+ const boundMethod = ModifiedClass.prototype[methodName].bind(freshInstance);
38
+ Object.defineProperty(obj, methodName, {
39
+ value: boundMethod,
40
+ writable: true,
41
+ configurable: true
42
+ });
43
+ }
44
+ }
45
+ async getProperty(name) {
46
+ const obj = this.obj;
47
+ if (Object.prototype.hasOwnProperty.call(obj, name)) return {
48
+ name,
49
+ visibility: "public",
50
+ value: obj[name]
51
+ };
52
+ const id = `__ref_${Date.now()}_${Math.random().toString(36).slice(2)}__`;
53
+ globalThis[id] = obj;
54
+ const session = new inspector.Session();
55
+ session.connect();
56
+ try {
57
+ await session.post("Runtime.enable");
58
+ const { result } = await session.post("Runtime.evaluate", { expression: `globalThis.${id}` });
59
+ const privateProp = (await session.post("Runtime.getProperties", {
60
+ objectId: result.objectId,
61
+ ownProperties: true
62
+ })).privateProperties?.find((p) => p.name === `#${name}`);
63
+ if (!privateProp) return;
64
+ let value;
65
+ if (privateProp.value.type === "object" && privateProp.value.objectId) {
66
+ const extractId = `__extract_${Date.now()}_${Math.random().toString(36).slice(2)}__`;
67
+ await session.post("Runtime.callFunctionOn", {
68
+ objectId: privateProp.value.objectId,
69
+ functionDeclaration: `function() { globalThis.${extractId} = this; }`
70
+ });
71
+ value = globalThis[extractId];
72
+ delete globalThis[extractId];
73
+ } else value = privateProp.value.value;
74
+ return {
75
+ name,
76
+ visibility: "private",
77
+ value
78
+ };
79
+ } finally {
80
+ delete globalThis[id];
81
+ session.disconnect();
82
+ }
83
+ }
84
+ async getPropertyValue(name) {
85
+ const cached = this.values.get(name);
86
+ if (cached) return cached.ModifiedClass.__reflectionGet__(cached.freshInstance);
87
+ return (await this.getProperty(name))?.value;
88
+ }
89
+ getClassName() {
90
+ return Object.getPrototypeOf(this.obj).constructor.name;
91
+ }
92
+ async getProperties() {
93
+ const obj = this.obj;
94
+ const properties = [];
95
+ const publicProps = Object.getOwnPropertyNames(obj);
96
+ for (const name of publicProps) {
97
+ const descriptor = Object.getOwnPropertyDescriptor(obj, name);
98
+ if (descriptor && typeof descriptor.value !== "function") properties.push({
99
+ name,
100
+ visibility: "public",
101
+ value: descriptor.value
102
+ });
103
+ }
104
+ const id = `__ref_${Date.now()}_${Math.random().toString(36).slice(2)}__`;
105
+ globalThis[id] = obj;
106
+ const session = new inspector.Session();
107
+ session.connect();
108
+ try {
109
+ await session.post("Runtime.enable");
110
+ const { result } = await session.post("Runtime.evaluate", { expression: `globalThis.${id}` });
111
+ const props = await session.post("Runtime.getProperties", {
112
+ objectId: result.objectId,
113
+ ownProperties: true
114
+ });
115
+ if (props.privateProperties) for (const prop of props.privateProperties) {
116
+ const name = prop.name.replace(/^#/, "");
117
+ properties.push({
118
+ name,
119
+ visibility: "private"
120
+ });
121
+ }
122
+ } finally {
123
+ delete globalThis[id];
124
+ session.disconnect();
125
+ }
126
+ return properties;
127
+ }
128
+ async getMethods() {
129
+ const obj = this.obj;
130
+ const proto = Object.getPrototypeOf(obj);
131
+ const constructor = proto.constructor;
132
+ const methods = [];
133
+ const protoMethods = Object.getOwnPropertyNames(proto).filter((n) => n !== "constructor" && typeof proto[n] === "function");
134
+ for (const name of protoMethods) methods.push({
135
+ name,
136
+ visibility: "public",
137
+ isStatic: false
138
+ });
139
+ const staticMethods = Object.getOwnPropertyNames(constructor).filter((n) => typeof constructor[n] === "function" && ![
140
+ "length",
141
+ "name",
142
+ "prototype"
143
+ ].includes(n));
144
+ for (const name of staticMethods) methods.push({
145
+ name,
146
+ visibility: "public",
147
+ isStatic: true
148
+ });
149
+ const id = `__ref_${Date.now()}_${Math.random().toString(36).slice(2)}__`;
150
+ globalThis[id] = obj;
151
+ const session = new inspector.Session();
152
+ session.connect();
153
+ try {
154
+ await session.post("Runtime.enable");
155
+ const { result } = await session.post("Runtime.evaluate", { expression: `globalThis.${id}` });
156
+ const privateMethods = (await session.post("Runtime.getProperties", {
157
+ objectId: result.objectId,
158
+ ownProperties: true
159
+ })).internalProperties?.find((p) => p.name === "[[PrivateMethods]]");
160
+ if (privateMethods?.value?.objectId) {
161
+ const methodsProps = await session.post("Runtime.getProperties", {
162
+ objectId: privateMethods.value.objectId,
163
+ ownProperties: true
164
+ });
165
+ for (const prop of methodsProps.result || []) {
166
+ const match = (prop.value?.description || "").match(/^#(\w+)\s*\(/);
167
+ if (match) methods.push({
168
+ name: match[1],
169
+ visibility: "private",
170
+ isStatic: false
171
+ });
172
+ }
173
+ }
174
+ } finally {
175
+ delete globalThis[id];
176
+ session.disconnect();
177
+ }
178
+ return methods;
179
+ }
180
+ async hasProperty(name) {
181
+ return (await this.getProperties()).some((p) => p.name === name);
182
+ }
183
+ async hasMethod(name) {
184
+ return (await this.getMethods()).some((m) => m.name === name);
185
+ }
186
+ };
187
+
188
+ //#endregion
189
+ export { ReflectionClass };
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "unreflect",
3
+ "version": "0.0.1",
4
+ "description": "Access and modify private class fields and methods in JavaScript",
5
+ "repository": "KABBOUCHI/unreflect",
6
+ "license": "MIT",
7
+ "sideEffects": false,
8
+ "type": "module",
9
+ "exports": {
10
+ ".": "./dist/index.mjs"
11
+ },
12
+ "types": "./dist/index.d.mts",
13
+ "files": [
14
+ "dist"
15
+ ],
16
+ "devDependencies": {
17
+ "@types/node": "^25.0.3",
18
+ "@vitest/coverage-v8": "^4.0.16",
19
+ "automd": "^0.4.2",
20
+ "changelogen": "^0.6.2",
21
+ "eslint": "^9.39.2",
22
+ "eslint-config-unjs": "^0.6.2",
23
+ "obuild": "^0.4.10",
24
+ "prettier": "^3.7.4",
25
+ "typescript": "^5.9.3",
26
+ "vitest": "^4.0.16"
27
+ },
28
+ "scripts": {
29
+ "build": "obuild",
30
+ "dev": "vitest dev",
31
+ "lint": "eslint . && prettier -c .",
32
+ "lint:fix": "automd && eslint . --fix && prettier -w .",
33
+ "release": "pnpm test && pnpm build && changelogen --release && npm publish && git push --follow-tags",
34
+ "test": "pnpm lint:fix && pnpm test:types && vitest run --coverage",
35
+ "test:types": "tsc --noEmit --skipLibCheck"
36
+ }
37
+ }