@lopatnov/javascripttostring 1.7.3 → 2.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/README.md CHANGED
@@ -1,170 +1,259 @@
1
- # JavaScriptToString [![Twitter](https://img.shields.io/twitter/url?url=https%3A%2F%2Fwww.npmjs.com%2Fpackage%2F%40lopatnov%2Fjavascripttostring)](https://twitter.com/intent/tweet?text=Wow:&url=https%3A%2F%2Fwww.npmjs.com%2Fpackage%2F%40lopatnov%2Fjavascripttostring)
1
+ # @lopatnov/javascripttostring
2
2
 
3
3
  [![npm](https://img.shields.io/npm/dt/@lopatnov/javascripttostring)](https://www.npmjs.com/package/@lopatnov/javascripttostring)
4
4
  [![NPM version](https://badge.fury.io/js/%40lopatnov%2Fjavascripttostring.svg)](https://www.npmjs.com/package/@lopatnov/javascripttostring)
5
5
  [![License](https://img.shields.io/github/license/lopatnov/jsToString)](https://github.com/lopatnov/jsToString/blob/master/LICENSE)
6
- [![GitHub issues](https://img.shields.io/github/issues/lopatnov/jsToString)](https://github.com/lopatnov/jsToString/issues)
7
- [![GitHub forks](https://img.shields.io/github/forks/lopatnov/jsToString)](https://github.com/lopatnov/jsToString/network)
6
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.8-blue)](https://www.typescriptlang.org/)
8
7
  [![GitHub stars](https://img.shields.io/github/stars/lopatnov/jsToString)](https://github.com/lopatnov/jsToString/stargazers)
9
- ![GitHub top language](https://img.shields.io/github/languages/top/lopatnov/jsToString)
10
8
 
11
- [![Patreon](https://img.shields.io/badge/Donate-Patreon-informational)](https://www.patreon.com/lopatnov)
12
- [![sobe.ru](https://img.shields.io/static/v1?label=sobe.ru&message=%D0%91%D0%BB%D0%B0%D0%B3%D0%BE%D0%B4%D0%B0%D1%80%D0%BD%D0%BE%D1%81%D1%82%D1%8C&color=yellow&logo=data:image/x-icon;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAMAAADXqc3KAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAArlBMVEUAAAD//////////////////////////////////////////////////////////////////PP/3l7/9c//0yb/zAD/6ZP/zQf/++7/3FD/88X/0h7//v7/5oX/zATUqQDktgD/5HjQpgAFBACQcwD/zw/fsgCOcQD6yADZrQD2xAD8yQDnuADxwADcsADbrwDpugD3xQD5xwDjtQDywQD+ywD9ygDvvwD7yAD/1jRaObVGAAAAEHRSTlMAA3zg707pEJP8MMUBYN5fiwXJMQAAAAFiS0dEAf8CLd4AAAAHdElNRQflBgMAAxO4O2jCAAAAuElEQVQoz42S1w7CMAxFS8ueYZgNLZuyRynw/z9GdtxIkbgPceQT6Tq2vZwfEKx8wRPyiaViSYDABqQsAMq0OzxUqhbo9kBcavUM6A9AAtJAYDgC0ID7i+t4AghwfxanszlAGBnA/Flc0MfL1doA5s/ChoLtbg8QI392gpIBzf/AwYAWAsdTrIE05/nz5Xq7S6DKpenHM0pe+o/qg5Am74/0ybTkm+q6wG4iltV2LTko52idy+Banx9RYiS6Vrsc3AAAACV0RVh0ZGF0ZTpjcmVhdGUAMjAyMS0wNi0wM1QwMDowMzoxOCswMDowMLvSSCkAAAAldEVYdGRhdGU6bW9kaWZ5ADIwMjEtMDYtMDNUMDA6MDM6MTgrMDA6MDDKj/CVAAAAAElFTkSuQmCC)](https://sobe.ru/na/tech_knigi)
13
- [![LinkedIn](https://img.shields.io/badge/LinkedIn-lopatnov-informational?style=social&logo=linkedin)](https://www.linkedin.com/in/lopatnov/)
9
+ A TypeScript library that converts any JavaScript runtime value into its string source code representation. Supports objects, arrays, functions, circular references, cross-references, and more.
14
10
 
15
- [![Build Status](https://travis-ci.org/lopatnov/jsToString.png?branch=master)](https://travis-ci.org/lopatnov/jsToString)
11
+ ## Installation
16
12
 
17
- JavaScript value to string runtime converter. It converts a runtime value into string a value.
18
-
19
- ## Install
20
-
21
- [![https://nodei.co/npm/@lopatnov/javascripttostring.png?downloads=true&downloadRank=true&stars=true](https://nodei.co/npm/@lopatnov/javascripttostring.png?downloads=true&downloadRank=true&stars=true)](https://www.npmjs.com/package/@lopatnov/javascripttostring)
22
-
23
- ```shell
13
+ ```bash
24
14
  npm install @lopatnov/javascripttostring
25
15
  ```
26
16
 
27
- [Browser](//lopatnov.github.io/jsToString/dist/javascripttostring.umd.js)
17
+ ### Browser (CDN)
28
18
 
29
19
  ```html
30
- <script src="//lopatnov.github.io/jsToString/dist/javascripttostring.umd.js"></script>
20
+ <script src="https://unpkg.com/@lopatnov/javascripttostring"></script>
31
21
  ```
32
22
 
33
- ## Import package to the project
23
+ ## Usage
34
24
 
35
- ### TypeScript
25
+ ### ES Modules
36
26
 
37
27
  ```typescript
38
- import javaScriptToString from '@lopatnov/javascripttostring';
28
+ import javaScriptToString from "@lopatnov/javascripttostring";
39
29
  ```
40
30
 
41
- ### JavaScript
31
+ ### CommonJS
42
32
 
43
33
  ```javascript
44
- var javaScriptToString = require("@lopatnov/javascripttostring");
34
+ const javaScriptToString = require("@lopatnov/javascripttostring");
45
35
  ```
46
36
 
47
- ## Convert JavaScript values into string values
37
+ ### Browser (UMD)
48
38
 
49
- ```typescript
50
- javaScriptToString(value: any, options?: IJ2SOptions) => string
39
+ ```javascript
40
+ const javaScriptToString = window.javaScriptToString;
51
41
  ```
52
42
 
53
- where
43
+ ## API
54
44
 
55
- ```typescript
56
- interface IJ2SOptions {
57
- includeFunctionProperties?: boolean; // default true
58
- includeFunctionPrototype?: boolean; // default true
59
- includeBuffers?: boolean; // default true
60
- nestedObjectsAmount?: number; // default Number.POSITIVE_INFINITY
61
- nestedArraysAmount?: number; // default Number.POSITIVE_INFINITY
62
- nestedFunctionsAmount?: number; // default Number.POSITIVE_INFINITY
63
- }
64
- ```
45
+ ### javaScriptToString(value, options?): string
46
+
47
+ Converts a JavaScript value to its string source code representation.
48
+
49
+ | Parameter | Type | Description |
50
+ |-----------|------|-------------|
51
+ | `value` | `any` | The value to convert |
52
+ | `options` | `IJ2SOptions` | Optional configuration |
53
+
54
+ **Returns:** `string` - Source code representation that can be evaluated back to the original value
55
+
56
+ ### Options
57
+
58
+ | Option | Type | Default | Description |
59
+ |--------|------|---------|-------------|
60
+ | `includeFunctionProperties` | `boolean` | `true` | Include function's own properties |
61
+ | `includeFunctionPrototype` | `boolean` | `true` | Include function's prototype properties |
62
+ | `includeBuffers` | `boolean` | `true` | Include ArrayBuffer and TypedArray contents |
63
+ | `nestedObjectsAmount` | `number` | `Infinity` | Max depth for nested objects |
64
+ | `nestedArraysAmount` | `number` | `Infinity` | Max depth for nested arrays |
65
+ | `nestedFunctionsAmount` | `number` | `Infinity` | Max depth for nested functions |
66
+ | `throwOnNonSerializable` | `boolean` | `false` | Throw an error for non-serializable values (Promise, Generator, WeakRef, WeakMap, WeakSet, FinalizationRegistry) |
65
67
 
66
68
  ## Examples
67
69
 
70
+ ### Primitives
71
+
68
72
  ```typescript
69
- let myStringOfString = javaScriptToString('Hello world');
70
- console.log(myStringOfString);
71
- /* expected myStringOfString value: "\"Hello world\"" */
73
+ javaScriptToString("Hello world"); // '"Hello world"'
74
+ javaScriptToString(42); // '42'
75
+ javaScriptToString(true); // 'true'
76
+ javaScriptToString(undefined); // 'undefined'
77
+ javaScriptToString(null); // 'null'
72
78
  ```
73
79
 
80
+ ### Arrays
81
+
74
82
  ```typescript
75
- let myStringOfArray = javaScriptToString(["Hello", "World", ".", "How", "do", "you", "do", "?"]);
76
- console.log(myStringOfArray);
77
- /* expected myStringOfArray value: "[\"Hello\",\"World\",\".\",\"How\",\"do\",\"you\",\"do\",\"?\"]" */
83
+ javaScriptToString(["Hello", "World"]);
84
+ // '["Hello", "World"]'
78
85
  ```
79
86
 
87
+ ### Objects
88
+
80
89
  ```typescript
81
- let myObjectString = javaScriptToString({
82
- friend1: "Shurik",
83
- friend2: "Alex",
84
- friends: {
85
- friend3: 123456,
86
- friend4: {},
87
- friend5: ["Hola", "amigo"],
88
- friend6: () => {
89
- console.log("How you doing?");
90
- }
91
- }
90
+ javaScriptToString({
91
+ name: "Alex",
92
+ friends: ["Shurik", "Hola"],
93
+ greet: () => {
94
+ console.log("How you doing?");
95
+ }
92
96
  });
93
-
94
- console.log(myObjectString);
95
- /* expected myObjectString value:
96
- "{friend1: \"Shurik\",friend2: \"Alex\",friends: {friend3: 123456,friend4: {},friend5: [\"Hola\",\"amigo\"],friend6: () => {
97
- console.log(\"How you doing?\");
98
- }}}"
99
- */
97
+ // '{name: "Alex", friends: ["Shurik", "Hola"], greet: () => { console.log("How you doing?"); }}'
100
98
  ```
101
99
 
102
- ```typescript
103
- let myFunctionString = javaScriptToString(function(a,b) {
104
- console.log("Just a function");
105
- })
106
-
107
- console.log(myFunctionString);
108
- /* expected myFunctionString:
109
- "function(a,b) {
110
- console.log(\"Just a function\");
111
- }"
112
- */
113
- ```
100
+ ### Functions with Properties
114
101
 
115
102
  ```typescript
116
103
  function Simple(title) {
117
104
  this.title = title || "world";
118
105
  }
119
-
120
106
  Simple.count = 0;
121
-
122
- Simple.prototype.show = function(){
107
+ Simple.prototype.show = function () {
123
108
  Simple.count++;
124
- console.log('title = ', this.title);
125
- console.log('count = ', Simple.count);
126
- }
127
- console.log(javaScriptToString(Simple));
109
+ console.log("title =", this.title);
110
+ };
128
111
 
129
- /* Expected:
112
+ javaScriptToString(Simple);
113
+ // '(function(){ var Simple = function Simple(title) { ... }; Simple.count = 0; Simple.prototype.show = function(){ ... }; return Simple; }())'
114
+ ```
130
115
 
131
- "(function(){
132
- var Simple = function Simple(title) {
133
- this.title = title || \"world\";
134
- };
135
- Simple.count = 0;
116
+ ### Circular References
136
117
 
137
- Simple.prototype.show = function(){
138
- Simple.count++;
139
- console.log('title = ', this.title);
140
- console.log('count = ', Simple.count);
141
- };
118
+ Objects that reference themselves are fully supported:
142
119
 
143
- return Simple;
144
- }())"
120
+ ```typescript
121
+ var x = [1, 2, 3];
122
+ x[0] = x;
145
123
 
146
- */
124
+ javaScriptToString(x);
125
+ // '(function(){ var ___ref1 = [null, 2, 3]; ___ref1[0] = ___ref1; return ___ref1; }())'
147
126
  ```
148
127
 
149
- ```javascript
150
- var x = [1,2,3];
151
- x[0] = x;
152
- console.log(javaScriptToString(x));
128
+ ### Cross-References
153
129
 
154
- /*
155
- "(function(){ var ___j2s_0 = [null, 2, 3]; ___j2s_0['0'] = ___j2s_0; return ___j2s_0; }())"
156
- */
130
+ Objects shared between different branches are preserved as references:
131
+
132
+ ```typescript
133
+ var shared = { value: 42 };
134
+ var obj = { a: shared, b: shared };
135
+
136
+ javaScriptToString(obj);
137
+ // Generates code where obj.a === obj.b (same reference):
138
+ // (function(){ var ___ref1 = {
139
+ // a: { value: 42 },
140
+ // b: null
141
+ // }; ___ref1.b = ___ref1.a; return ___ref1; }())
142
+ ```
143
+
144
+ ### Using with Web Workers
145
+
146
+ Combine with [@lopatnov/worker-from-string](https://www.npmjs.com/package/@lopatnov/worker-from-string) to serialize functions and data for execution in a Web Worker:
147
+
148
+ ```typescript
149
+ import javaScriptToString from "@lopatnov/javascripttostring";
150
+ import workerFromString from "@lopatnov/worker-from-string";
151
+
152
+ // Function with attached lookup data
153
+ function classify(value) {
154
+ const range = classify.ranges.find(r => value >= r.min && value < r.max);
155
+ return range ? range.label : "unknown";
156
+ }
157
+ classify.ranges = [
158
+ { min: 0, max: 30, label: "cold" },
159
+ { min: 30, max: 60, label: "warm" },
160
+ { min: 60, max: 100, label: "hot" },
161
+ ];
162
+
163
+ // Serialize and send to a worker
164
+ // javaScriptToString preserves the function AND its properties:
165
+ const code = javaScriptToString(classify);
166
+
167
+ const worker = workerFromString(`
168
+ const classify = ${code};
169
+ self.onmessage = (e) => postMessage(classify(e.data));
170
+ `);
171
+
172
+ worker.onmessage = (e) => console.log(e.data);
173
+ worker.postMessage(45); // "warm"
174
+ ```
175
+
176
+ ### Restoring Values
177
+
178
+ The generated string can be evaluated back to a working JavaScript value:
179
+
180
+ ```typescript
181
+ var original = { name: "test" };
182
+ original.self = original;
183
+
184
+ var code = javaScriptToString(original);
185
+ var restored = Function("return " + code)();
186
+
187
+ console.log(restored.self === restored); // true
188
+ console.log(restored.name); // "test"
157
189
  ```
158
190
 
191
+ ## Supported Types
192
+
193
+ | Type | Example | Notes |
194
+ |------|---------|-------|
195
+ | Primitives | `string`, `number`, `boolean`, `undefined`, `null` | Including `-0` and `NaN` |
196
+ | BigInt | `BigInt(123)` | |
197
+ | Symbol | `Symbol("desc")`, `Symbol.for("key")` | Registry symbols preserved |
198
+ | RegExp | `/pattern/gi` | `lastIndex` preserved when non-zero |
199
+ | Date | `new Date("...")` | Invalid dates → `new Date(NaN)` |
200
+ | Error | `new Error()`, `new TypeError()` | TypeError, RangeError, ReferenceError, SyntaxError, URIError, EvalError |
201
+ | Array | `[1, 2, 3]` | Sparse arrays preserved |
202
+ | Object | `{ key: "value" }` | Including `Object.create(null)` |
203
+ | Function | `function() {}`, `() => {}`, `async function() {}` | Properties and prototype included |
204
+ | Generator Function | `function*() {}`, `async function*() {}` | |
205
+ | Map | `new Map([["key", "value"]])` | |
206
+ | Set | `new Set([1, 2, 3])` | |
207
+ | TypedArray | `Int8Array`, `Float64Array`, etc. | |
208
+ | ArrayBuffer | `new ArrayBuffer(8)`, `SharedArrayBuffer` | |
209
+ | DataView | `new DataView(buffer)` | |
210
+
211
+ ### Non-serializable Types
212
+
213
+ The following types cannot be serialized and return `"undefined"` by default. Use `throwOnNonSerializable: true` to throw an error instead:
214
+
215
+ `Promise`, `Generator`, `WeakRef`, `WeakMap`, `WeakSet`, `FinalizationRegistry`
216
+
159
217
  ## Demo
160
218
 
161
- See, how it's working: [https://runkit.com/lopatnov/javascripttostring-demo](https://runkit.com/lopatnov/javascripttostring-demo)
219
+ Try the library interactively:
220
+
221
+ | | Link |
222
+ |---|---|
223
+ | Interactive Demo | [demo/index.html](./demo/index.html) |
224
+ | RunKit Playground | [runkit.com](https://npm.runkit.com/%40lopatnov%2Fjavascripttostring) |
225
+
226
+ ## Documentation
227
+
228
+ | | Link |
229
+ |---|---|
230
+ | API Reference | [docs/index.html](./docs/index.html) |
231
+ | Changelog | [CHANGELOG.md](./CHANGELOG.md) |
232
+
233
+ ## Related Packages
234
+
235
+ | Package | Description |
236
+ |---|---|
237
+ | [@lopatnov/worker-from-string](https://www.npmjs.com/package/@lopatnov/worker-from-string) | Create Web Workers from strings — pairs well with `javaScriptToString` |
238
+ | [@lopatnov/get-internal-type](https://www.npmjs.com/package/@lopatnov/get-internal-type) | Runtime type detection used internally by this library |
239
+
240
+ ## Contributing
241
+
242
+ Contributions are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.
243
+
244
+ ## License
245
+
246
+ [Apache-2.0](LICENSE)
247
+
248
+ Copyright 2019-2026 Oleksandr Lopatnov
162
249
 
163
- Test it with a runkit: [https://npm.runkit.com/%40lopatnov%2Fjavascripttostring](https://npm.runkit.com/%40lopatnov%2Fjavascripttostring)
250
+ ---
164
251
 
165
- ## Rights and Agreements
252
+ ### Author
166
253
 
167
- License [Apache-2.0](https://github.com/lopatnov/jsToString/blob/master/LICENSE)
254
+ **Oleksandr Lopatnov**
168
255
 
169
- Copyright 2019–2021 Oleksandr Lopatnov
256
+ [![LinkedIn](https://img.shields.io/badge/LinkedIn-Connect-blue?style=flat&logo=linkedin)](https://www.linkedin.com/in/lopatnov/)
257
+ [![GitHub](https://img.shields.io/badge/GitHub-Follow-black?style=flat&logo=github)](https://github.com/lopatnov)
170
258
 
259
+ If you find this project useful, please consider giving it a star on GitHub!