@n3bula/sandbox 0.0.1-alpha.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,20 @@
1
+ The MIT License (MIT)
2
+ Copyright ©️ 2026 Moriart47<wang_jn_xian@163.com>
3
+
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ of this software and associated documentation files (the "Software"), to deal
6
+ in the Software without restriction, including without limitation the rights
7
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ copies of the Software, and to permit persons to whom the Software is
9
+ furnished to do so, subject to the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be included in all
12
+ copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,51 @@
1
+ # `@n3bula/sandbox`
2
+
3
+ ### Simple Sandbox for Node.js module quick test
4
+ Just use for debug
5
+ Debug the current process without restart process
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ npm install @n3bula/sandbox
11
+ # or
12
+ yarn add @n3bula/sandbox
13
+ # or
14
+ pnpm add @n3bula/sandbox
15
+ ```
16
+
17
+ ## Example
18
+
19
+ ```ts
20
+ // server.ts
21
+ import net from 'net';
22
+ import { fileURLToPath } from 'node:url';
23
+ import { dirname, resolve } from 'node:path';
24
+ import { createSandbox } from '@n3bula/sandbox';
25
+ const PORT = 4000;
26
+ const server = net.createServer();
27
+ server.listen(PORT, () => console.log(`TCP server listening on ${PORT}`));
28
+ server.on('error', err => console.error('server error', err));
29
+ const destroy = () => {
30
+ server.close();
31
+ process.exit();
32
+ };
33
+ process.on('SIGINT', destroy);
34
+ process.on('SIGTERM', destroy);
35
+
36
+ createSandbox('sandbox', resolve(fileURLToPath(dirname(import.meta.url)), './client.ts'), { server });
37
+ ```
38
+
39
+ ```ts
40
+ // client.ts
41
+ console.log(1); // change to console.log(server);
42
+ // will print current server instance without restart server
43
+ ```
44
+
45
+ ## Author
46
+
47
+ - [Moriarty47](https://github.com/Moriarty47)
48
+
49
+ ## License
50
+
51
+ [The MIT License(MIT)](https://github.com/Moriarty47/n3bula/blob/main/LICENSE)
@@ -0,0 +1,4 @@
1
+ //#region src/sandbox.d.ts
2
+ declare function createSandbox(name: string, watchFilePath: string, globals?: {}): void;
3
+ //#endregion
4
+ export { createSandbox };
package/dist/index.mjs ADDED
@@ -0,0 +1,128 @@
1
+ import vm from "node:vm";
2
+ import EventEmitter from "node:events";
3
+ import { readFile, stat, watch } from "node:fs";
4
+ import { echo } from "@n3bula/echo/node";
5
+ //#region src/logger.ts
6
+ const createLogger = (tag) => {
7
+ const logger = ((...msg) => {
8
+ tag ? echo.fg.cyan(tag, ...msg) : echo.fg.cyan(...msg);
9
+ });
10
+ logger.info = (...msg) => {
11
+ tag ? echo.fg("#66b5ff")(tag, ...msg) : echo.fg("#66b5ff")(...msg);
12
+ };
13
+ logger.warn = (...msg) => {
14
+ tag ? echo.fg("#ff9966")(tag, ...msg) : echo.fg("#ff9966")(...msg);
15
+ };
16
+ logger.error = (...msg) => {
17
+ tag ? echo.fg.orangeRed(tag, ...msg) : echo.fg.orangeRed(...msg);
18
+ };
19
+ return logger;
20
+ };
21
+ const logger = createLogger("@n3bula/sandbox");
22
+ //#endregion
23
+ //#region src/file-watcher.ts
24
+ const DEBOUNCE_MS = 200;
25
+ const READ_RETRY_MS = 100;
26
+ const MAX_READ_RETRIES = 5;
27
+ var FileWatcher = class extends EventEmitter {
28
+ timer = null;
29
+ lastStat = null;
30
+ readRetries = 0;
31
+ watcher;
32
+ constructor(filePath) {
33
+ super();
34
+ this.filePath = filePath;
35
+ this.scheduleRead = this.scheduleRead.bind(this);
36
+ this.startWatch();
37
+ }
38
+ safeReadAndNotify() {
39
+ readFile(this.filePath, "utf8", (err, data) => {
40
+ if (err) {
41
+ if (err.code === "ENOENT" && this.readRetries < MAX_READ_RETRIES) {
42
+ this.readRetries++;
43
+ setTimeout(this.safeReadAndNotify, READ_RETRY_MS);
44
+ return;
45
+ }
46
+ logger.error("Read error:", err.code, err.message);
47
+ return;
48
+ }
49
+ this.readRetries = 0;
50
+ stat(this.filePath, (err2, fileStat) => {
51
+ if (!err2) {
52
+ if (this.lastStat && fileStat.mtimeMs === this.lastStat.mtimeMs && fileStat.size === this.lastStat.size) return;
53
+ this.lastStat = fileStat;
54
+ }
55
+ this.emit("change", data.split(/\r?\n/).filter((l) => !/^\s*\/\//.test(l)).map((l) => l.trim()).join(" "));
56
+ });
57
+ });
58
+ }
59
+ scheduleRead() {
60
+ if (this.timer) clearTimeout(this.timer);
61
+ this.timer = setTimeout(() => {
62
+ this.timer = null;
63
+ this.safeReadAndNotify();
64
+ }, DEBOUNCE_MS);
65
+ }
66
+ startWatch() {
67
+ try {
68
+ const watcher = watch(this.filePath, {
69
+ encoding: "utf8",
70
+ persistent: true
71
+ }, this.scheduleRead);
72
+ watcher.on("error", (err) => {
73
+ logger.error("fs.watch error", err);
74
+ if (watcher) try {
75
+ watcher.close();
76
+ } catch {}
77
+ });
78
+ stat(this.filePath, (err, fileStat) => {
79
+ if (!err) this.lastStat = fileStat;
80
+ });
81
+ logger("Watching", this.filePath);
82
+ this.watcher = watcher;
83
+ } catch (error) {
84
+ logger.error("fs.watch error", error.message);
85
+ }
86
+ }
87
+ destroy() {
88
+ if (this.watcher && typeof this.watcher.close === "function") try {
89
+ this.watcher.close();
90
+ } catch {}
91
+ }
92
+ };
93
+ //#endregion
94
+ //#region src/sandbox.ts
95
+ function createContext(sandboxGlobals = {}) {
96
+ return vm.createContext({
97
+ console,
98
+ setTimeout,
99
+ setInterval,
100
+ clearTimeout,
101
+ clearInterval,
102
+ fetch: typeof fetch !== "undefined" ? fetch : void 0,
103
+ ...sandboxGlobals
104
+ });
105
+ }
106
+ function createSandbox(name, watchFilePath, globals = {}) {
107
+ const sandboxContext = createContext({
108
+ ...globals,
109
+ __sandbox_name: name
110
+ });
111
+ function runCode(code) {
112
+ return new vm.Script(`(async () => { ${code} })()`).runInContext(sandboxContext, { timeout: 2e3 }).then((res) => res).catch((err) => {
113
+ logger.error(err.name, err.message);
114
+ });
115
+ }
116
+ const watcher = new FileWatcher(watchFilePath);
117
+ watcher.on("change", (code) => {
118
+ runCode(code);
119
+ });
120
+ const destroy = () => {
121
+ watcher.destroy();
122
+ process.exit();
123
+ };
124
+ process.on("SIGINT", destroy);
125
+ process.on("SIGTERM", destroy);
126
+ }
127
+ //#endregion
128
+ export { createSandbox };
@@ -0,0 +1 @@
1
+ console.log(server);
@@ -0,0 +1,20 @@
1
+ import net from 'net';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { dirname, resolve } from 'node:path';
4
+
5
+ import { createSandbox } from '../src';
6
+
7
+ const PORT = 4000;
8
+ const server = net.createServer();
9
+ server.listen(PORT, () => console.log(`TCP server listening on ${PORT}`));
10
+ const destroy = () => {
11
+ server.close();
12
+ process.exit();
13
+ };
14
+ process.on('SIGINT', destroy);
15
+ process.on('SIGTERM', destroy);
16
+
17
+ const file = resolve(fileURLToPath(dirname(import.meta.url)), './client.ts');
18
+ createSandbox('sandbox', file, {
19
+ server,
20
+ });
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@n3bula/sandbox",
3
+ "version": "0.0.1-alpha.1",
4
+ "description": "Simple Sandbox for Node.js module quick test",
5
+ "type": "module",
6
+ "main": "dist/index.mjs",
7
+ "typings": "dist/index.d.mts",
8
+ "keywords": [
9
+ "sandbox",
10
+ "node"
11
+ ],
12
+ "contributors": [
13
+ {
14
+ "name": "Moriarty47",
15
+ "email": "wang_jn_xian@163.com"
16
+ }
17
+ ],
18
+ "homepage": "https://github.com/Moriarty47/n3bula/tree/main/packages/sandbox#readme",
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "https://github.com/Moriarty47/n3bula.git",
22
+ "directory": "packages/sandbox"
23
+ },
24
+ "author": {
25
+ "name": "Moriarty47",
26
+ "email": "wang_jn_xian@163.com"
27
+ },
28
+ "license": "MIT",
29
+ "publishConfig": {
30
+ "access": "public",
31
+ "registry": "https://registry.npmjs.org/"
32
+ },
33
+ "devDependencies": {
34
+ "@types/node": "^25.5.0",
35
+ "tsdown": "^0.21.5"
36
+ },
37
+ "dependencies": {
38
+ "@n3bula/echo": "^0.1.0-alpha.4"
39
+ },
40
+ "scripts": {
41
+ "dev": "tsx --experimental-vm-modules example/server.ts",
42
+ "build": "tsdown"
43
+ }
44
+ }
@@ -0,0 +1,90 @@
1
+ import EventEmitter from 'node:events';
2
+ import { FSWatcher, readFile, stat, Stats, watch } from 'node:fs';
3
+
4
+ import { logger } from './logger';
5
+
6
+ const DEBOUNCE_MS = 200;
7
+ const READ_RETRY_MS = 100;
8
+ const MAX_READ_RETRIES = 5;
9
+
10
+ export class FileWatcher extends EventEmitter {
11
+ timer: NodeJS.Timeout | null = null;
12
+ lastStat: Stats | null = null;
13
+ readRetries = 0;
14
+ watcher!: FSWatcher;
15
+ constructor(public filePath: string) {
16
+ super();
17
+ this.scheduleRead = this.scheduleRead.bind(this);
18
+ this.startWatch();
19
+ }
20
+
21
+ safeReadAndNotify() {
22
+ readFile(this.filePath, 'utf8', (err, data) => {
23
+ if (err) {
24
+ if (err.code === 'ENOENT' && this.readRetries < MAX_READ_RETRIES) {
25
+ this.readRetries++;
26
+ setTimeout(this.safeReadAndNotify, READ_RETRY_MS);
27
+ return;
28
+ }
29
+ logger.error('Read error:', err.code, err.message);
30
+ return;
31
+ }
32
+ this.readRetries = 0;
33
+ stat(this.filePath, (err2, fileStat) => {
34
+ if (!err2) {
35
+ if (this.lastStat && fileStat.mtimeMs === this.lastStat.mtimeMs && fileStat.size === this.lastStat.size)
36
+ return;
37
+ this.lastStat = fileStat;
38
+ }
39
+ this.emit(
40
+ 'change',
41
+ data
42
+ .split(/\r?\n/)
43
+ .filter(l => !/^\s*\/\//.test(l))
44
+ .map(l => l.trim())
45
+ .join(' '),
46
+ );
47
+ });
48
+ });
49
+ }
50
+
51
+ scheduleRead() {
52
+ if (this.timer) clearTimeout(this.timer);
53
+ this.timer = setTimeout(() => {
54
+ this.timer = null;
55
+ this.safeReadAndNotify();
56
+ }, DEBOUNCE_MS);
57
+ }
58
+
59
+ startWatch() {
60
+ try {
61
+ const watcher = watch(this.filePath, { encoding: 'utf8', persistent: true }, this.scheduleRead);
62
+
63
+ watcher.on('error', err => {
64
+ logger.error('fs.watch error', err);
65
+ if (watcher) {
66
+ try {
67
+ watcher.close();
68
+ } catch {}
69
+ }
70
+ });
71
+
72
+ stat(this.filePath, (err, fileStat) => {
73
+ if (!err) this.lastStat = fileStat;
74
+ });
75
+
76
+ logger('Watching', this.filePath);
77
+ this.watcher = watcher;
78
+ } catch (error: any) {
79
+ logger.error('fs.watch error', error.message);
80
+ }
81
+ }
82
+
83
+ destroy() {
84
+ if (this.watcher && typeof this.watcher.close === 'function') {
85
+ try {
86
+ this.watcher.close();
87
+ } catch {}
88
+ }
89
+ }
90
+ }
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export { createSandbox } from './sandbox';
package/src/logger.ts ADDED
@@ -0,0 +1,28 @@
1
+ import { echo } from '@n3bula/echo/node';
2
+
3
+ export const createLogger = (tag?: string) => {
4
+ const logger = ((...msg: any[]) => {
5
+ tag ? echo.fg.cyan(tag, ...msg) : echo.fg.cyan(...msg);
6
+ }) as {
7
+ (...msg: any[]): void;
8
+ info(...msg: any[]): void;
9
+ warn(...msg: any[]): void;
10
+ error(...msg: any[]): void;
11
+ };
12
+
13
+ logger.info = (...msg: any[]) => {
14
+ tag ? echo.fg('#66b5ff')(tag, ...msg) : echo.fg('#66b5ff')(...msg);
15
+ };
16
+
17
+ logger.warn = (...msg: any[]) => {
18
+ tag ? echo.fg('#ff9966')(tag, ...msg) : echo.fg('#ff9966')(...msg);
19
+ };
20
+
21
+ logger.error = (...msg: any[]) => {
22
+ tag ? echo.fg.orangeRed(tag, ...msg) : echo.fg.orangeRed(...msg);
23
+ };
24
+
25
+ return logger;
26
+ };
27
+
28
+ export const logger = createLogger('@n3bula/sandbox');
package/src/sandbox.ts ADDED
@@ -0,0 +1,46 @@
1
+ import vm from 'node:vm';
2
+
3
+ import { FileWatcher } from './file-watcher';
4
+ import { logger } from './logger';
5
+
6
+ function createContext(sandboxGlobals = {}) {
7
+ const context = vm.createContext({
8
+ console,
9
+ setTimeout,
10
+ setInterval,
11
+ clearTimeout,
12
+ clearInterval,
13
+ fetch: typeof fetch !== 'undefined' ? fetch : undefined,
14
+ ...sandboxGlobals,
15
+ });
16
+ return context;
17
+ }
18
+
19
+ export function createSandbox(name: string, watchFilePath: string, globals = {}) {
20
+ const sandboxContext = createContext({
21
+ ...globals,
22
+ __sandbox_name: name,
23
+ });
24
+
25
+ function runCode(code: string) {
26
+ const script = new vm.Script(`(async () => { ${code} })()`);
27
+ const result: Promise<any> = script.runInContext(sandboxContext, { timeout: 2000 });
28
+ return result
29
+ .then(res => res)
30
+ .catch(err => {
31
+ logger.error(err.name, err.message);
32
+ });
33
+ }
34
+
35
+ const watcher = new FileWatcher(watchFilePath);
36
+ watcher.on('change', code => {
37
+ runCode(code);
38
+ });
39
+
40
+ const destroy = () => {
41
+ watcher.destroy();
42
+ process.exit();
43
+ };
44
+ process.on('SIGINT', destroy);
45
+ process.on('SIGTERM', destroy);
46
+ }
@@ -0,0 +1,172 @@
1
+ import vm from 'node:vm';
2
+ import Module from 'node:module';
3
+ import { fileURLToPath, pathToFileURL } from 'node:url';
4
+ import { dirname, resolve } from 'node:path';
5
+ import { existsSync } from 'node:fs';
6
+ import { readFile } from 'node:fs/promises';
7
+ import { PROTOCOL_FILE, PROTOCOL_NODE, resolvedProtocols } from './utils';
8
+
9
+ function createContext(sandboxGlobals = {}) {
10
+ const context = vm.createContext({
11
+ console,
12
+ setTimeout,
13
+ setInterval,
14
+ clearTimeout,
15
+ clearInterval,
16
+ fetch: typeof fetch !== 'undefined' ? fetch : undefined,
17
+ ...sandboxGlobals,
18
+ });
19
+ return context;
20
+ }
21
+
22
+ export function createSandbox(name: string, globals = {}) {
23
+ const memoryModules = new Map<string, { code: string; mtime: number }>();
24
+
25
+ const moduleInstances = new Map<string, vm.Module>();
26
+
27
+ const sandboxContext = createContext({
28
+ ...globals,
29
+ __sandbox_name: name,
30
+ __node_import_fallback: (id: string) => {
31
+ try {
32
+ return Module.createRequire(import.meta.url)(id);
33
+ } catch (error) {
34
+ // try without node: prefix
35
+ return Module.createRequire(import.meta.url)(id);
36
+ }
37
+ },
38
+ });
39
+
40
+ async function resolveSpecifier(specifier: string, referrer?: string) {
41
+ const isFileProtocol = !!(referrer && referrer.startsWith(PROTOCOL_FILE));
42
+ try {
43
+ const url = new URL(specifier, isFileProtocol ? referrer : undefined);
44
+ if (resolvedProtocols.includes(url.protocol)) {
45
+ return url.toString();
46
+ }
47
+ } catch (error) {
48
+ // not a URL, other resolve solution
49
+ }
50
+
51
+ if (memoryModules.has(specifier)) return specifier;
52
+
53
+ try {
54
+ const require = Module.createRequire(isFileProtocol ? referrer : pathToFileURL(`${process.cwd()}/`).toString());
55
+ const resolved = require.resolve(specifier);
56
+ return pathToFileURL(resolved).toString();
57
+ } catch (error) {
58
+ // fallback: try resolving as relative to referrer filesystem path
59
+ if (isFileProtocol) {
60
+ const refPath = fileURLToPath(referrer);
61
+ const candidate = resolve(dirname(refPath), specifier);
62
+ if (existsSync(candidate)) {
63
+ const final = pathToFileURL(candidate).toString();
64
+ return final;
65
+ }
66
+ }
67
+ // last resort: return specifier as-is, link may fail
68
+ return specifier;
69
+ }
70
+ }
71
+
72
+ async function loadSource(resolved: string) {
73
+ const memoryModule = memoryModules.get(resolved);
74
+ if (memoryModule) return { source: memoryModule.code, url: resolved };
75
+
76
+ if (resolved.startsWith(PROTOCOL_FILE)) {
77
+ const filePath = fileURLToPath(resolved);
78
+ const code = await readFile(filePath, 'utf8');
79
+ return { source: code, url: resolved };
80
+ }
81
+
82
+ if (resolved.startsWith(PROTOCOL_NODE)) {
83
+ const pkg = resolved.slice(PROTOCOL_NODE.length);
84
+ const code = `export default globalThis.__node_import_fallback('${pkg}');\nexport const __esModule = true;`;
85
+ return { source: code, url: resolved };
86
+ }
87
+
88
+ try {
89
+ const code = await readFile(resolved, 'utf8');
90
+ return { source: code, url: resolved };
91
+ } catch {
92
+ // fallback: create a wrapper that imports via dynamic import
93
+ const code = `export default await import(${JSON.stringify(resolved)});\n`;
94
+ return { source: code, url: resolved };
95
+ }
96
+ }
97
+
98
+ async function linker(specifier: string, referencingModule: vm.Module) {
99
+ const refUrl = (('identifier' in referencingModule && referencingModule.identifier) as string) || undefined;
100
+ const resolved = await resolveSpecifier(specifier, refUrl);
101
+ const { source, url } = await loadSource(resolved);
102
+
103
+ const moduleInstance = moduleInstances.get(url);
104
+ if (moduleInstance) return moduleInstance;
105
+
106
+ const module = new vm.SourceTextModule(source, {
107
+ context: sandboxContext,
108
+ identifier: url,
109
+ initializeImportMeta: (meta, module) => (meta.url = module.identifier),
110
+ });
111
+
112
+ moduleInstances.set(url, module);
113
+
114
+ // link dependencies recursively inside vm's linker; vm.Module.link willcall our linker for each import
115
+ await module.link(linker);
116
+ return module;
117
+ }
118
+
119
+ function registerModule(specifier: string, code: string) {
120
+ memoryModules.set(specifier, { code, mtime: Date.now() });
121
+ // invalidate instance cache
122
+ moduleInstances.delete(specifier);
123
+ }
124
+
125
+ function unnregisterModule(specifier: string) {
126
+ memoryModules.delete(specifier);
127
+ moduleInstances.delete(specifier);
128
+ }
129
+
130
+ async function runModule(
131
+ code: string,
132
+ specifier: string = `mem://${Date.now()}-${Math.random().toString(36).slice(2)}`,
133
+ globals = {},
134
+ ) {
135
+ Object.assign(sandboxContext, globals);
136
+ registerModule(specifier, code);
137
+
138
+ const resolved = await resolveSpecifier(specifier);
139
+ const { source, url } = await loadSource(resolved);
140
+
141
+ const module = new vm.SourceTextModule(source, {
142
+ context: sandboxContext,
143
+ identifier: url,
144
+ initializeImportMeta: (meta, m) => (meta.url = m.identifier),
145
+ });
146
+
147
+ moduleInstances.set(url, module);
148
+
149
+ await module.link(linker);
150
+
151
+ const result = await module.evaluate();
152
+ return {
153
+ module,
154
+ namespace: module.namespace,
155
+ status: module.status,
156
+ evaluationResult: result,
157
+ };
158
+ }
159
+
160
+ function hotReload(specifier: string, newCode: string) {
161
+ unnregisterModule(specifier);
162
+ registerModule(specifier, newCode);
163
+ return runModule(newCode, specifier);
164
+ }
165
+
166
+ return {
167
+ registerModule,
168
+ unnregisterModule,
169
+ runModule,
170
+ hotReload,
171
+ };
172
+ }
@@ -0,0 +1,90 @@
1
+ import net, { Socket } from 'node:net';
2
+ import { tmpdir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { IS_WIN } from './utils';
5
+ import { chmodSync, existsSync, unlinkSync } from 'node:fs';
6
+ import { logger } from './logger';
7
+
8
+ function getSocketPath(name: string = 'n3bula-sandbox') {
9
+ if (IS_WIN) {
10
+ const pipeName = name.replace(/[\\/:\*\?"<>\|]/g, '_');
11
+ return `\\\\.\\pipe\\${pipeName}`;
12
+ }
13
+ return join(tmpdir(), `${name}.sock`);
14
+ }
15
+
16
+ function cleanupSocketFile(socketPath: string) {
17
+ if (IS_WIN) return;
18
+ try {
19
+ if (existsSync(socketPath)) unlinkSync(socketPath);
20
+ } catch {}
21
+ }
22
+
23
+ export async function createSocketServer(name: string, connectionListener: (socket: Socket) => void) {
24
+ const socketPath = getSocketPath(name);
25
+ cleanupSocketFile(socketPath);
26
+
27
+ const server = net.createServer(socket => {
28
+ socket.on('end', () => socket.end());
29
+ socket.on('close', () => logger('server closed'));
30
+ socket.on('error', err => logger.error('server', err));
31
+ connectionListener(socket);
32
+ });
33
+
34
+ server.listen(socketPath, () => {
35
+ logger('Listening on', socketPath);
36
+ if (IS_WIN) return;
37
+ try {
38
+ chmodSync(socketPath, 0o600);
39
+ } catch {}
40
+ });
41
+
42
+ const cleanup = () => {
43
+ server.close();
44
+ cleanupSocketFile(socketPath);
45
+ };
46
+ const destroy = () => {
47
+ cleanup();
48
+ process.exit();
49
+ };
50
+ process.on('exit', cleanup);
51
+ process.on('SIGINT', destroy);
52
+ process.on('SIGTERM', destroy);
53
+
54
+ return { server, path: socketPath };
55
+ }
56
+
57
+ function connectSocket(name: string, onConnect?: (socket: Socket) => void) {
58
+ const socketPath = getSocketPath(name);
59
+ return new Promise<string>((resolve, reject) => {
60
+ const client = net.createConnection(socketPath, () => onConnect?.(client));
61
+ client.setEncoding('utf8');
62
+
63
+ client.on('close', () => logger('client closed'));
64
+ client.on('error', err => logger.error('client', err));
65
+
66
+ let resp = '';
67
+ client.on('data', d => (resp += d));
68
+
69
+ client.on('end', () => {
70
+ try {
71
+ resolve(JSON.parse(resp));
72
+ } catch (e) {
73
+ reject(e);
74
+ }
75
+ client.end();
76
+ });
77
+ });
78
+ }
79
+
80
+ export function clientSend(name: string, code: string) {
81
+ return connectSocket(name, socket => {
82
+ socket.write(
83
+ `${code
84
+ .split(/\r?\n/)
85
+ .filter(l => !/^\s*\/\//.test(l))
86
+ .map(l => l.trim())
87
+ .join(' ')}\n`,
88
+ );
89
+ });
90
+ }
@@ -0,0 +1,4 @@
1
+ export const PROTOCOL_FILE = 'file:';
2
+ export const PROTOCOL_NODE = 'node:';
3
+ export const resolvedProtocols = [PROTOCOL_NODE, PROTOCOL_FILE, 'data:', 'http:', 'https:'];
4
+ export const IS_WIN = process.platform === 'win32';
package/tsconfig.json ADDED
@@ -0,0 +1,21 @@
1
+ {
2
+ "compilerOptions": {
3
+ "rootDir": ".",
4
+ "target": "ES2022",
5
+ "lib": ["ES2022"],
6
+ "module": "es2022",
7
+ "types": ["node"],
8
+ "skipLibCheck": true,
9
+ "moduleResolution": "bundler",
10
+ "noEmit": true,
11
+ "esModuleInterop": true,
12
+ /* Linting */
13
+ "strict": true,
14
+ "noUnusedLocals": true,
15
+ "noUnusedParameters": true,
16
+ "erasableSyntaxOnly": false,
17
+ "noFallthroughCasesInSwitch": true,
18
+ "noUncheckedSideEffectImports": true
19
+ },
20
+ "include": ["tsdown.config.ts", "src", "example"]
21
+ }
@@ -0,0 +1,5 @@
1
+ import { defineConfig } from 'tsdown';
2
+
3
+ export default defineConfig({
4
+ entry: ['./src/index.ts'],
5
+ });