@jesscss/plugin-js 2.0.0-alpha.1 → 2.0.0-alpha.10

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/lib/index.js CHANGED
@@ -1,442 +1,778 @@
1
- import { AbstractPlugin } from '@jesscss/core';
2
- import * as fs from 'node:fs';
3
- import * as net from 'node:net';
4
- import * as path from 'node:path';
5
- import { fileURLToPath, pathToFileURL } from 'node:url';
6
- import { spawn, spawnSync } from 'node:child_process';
1
+ import { AbstractPlugin } from "@jesscss/core";
2
+ import * as fs from "node:fs";
3
+ import * as net from "node:net";
4
+ import * as path from "node:path";
5
+ import { fileURLToPath, pathToFileURL } from "node:url";
6
+ import { spawn, spawnSync } from "node:child_process";
7
+ import { HEX, makeColorRgb, makeDimension, makeKeyword, makeList, makeQuoted, sniffLiteral } from "@jesscss/core/value";
8
+ //#region src/bridge.ts
9
+ const isRecord = (value) => typeof value === "object" && value !== null;
10
+ const isBridgeValue = (value) => isRecord(value) && value.__jessBridge === true && typeof value.kind === "string";
11
+ const isValueObj = (value) => isRecord(value) && typeof value.type === "string" && typeof value.bytes === "string";
12
+ const isDetached = (value) => isRecord(value) && value.type === "DetachedRuleset" && Array.isArray(value.rules);
13
+ function encodeBridgeChildValue(value) {
14
+ const encoded = encodeBridgeValue(value);
15
+ if (isBridgeValue(encoded)) return encoded;
16
+ return {
17
+ __jessBridge: true,
18
+ kind: "scalar",
19
+ value: String(encoded)
20
+ };
21
+ }
22
+ function encodeFacadeValue(value) {
23
+ switch (value.type) {
24
+ case "Dimension": return typeof value.value === "number" ? {
25
+ __jessBridge: true,
26
+ kind: "dimension",
27
+ value: value.value,
28
+ unit: typeof value.unit === "string" ? value.unit : void 0
29
+ } : void 0;
30
+ case "Color": return Array.isArray(value.rgb) && value.rgb.length === 3 ? {
31
+ __jessBridge: true,
32
+ kind: "color",
33
+ rgb: [
34
+ value.rgb[0],
35
+ value.rgb[1],
36
+ value.rgb[2]
37
+ ],
38
+ alpha: typeof value.alpha === "number" ? value.alpha : void 0
39
+ } : void 0;
40
+ case "Quoted": return typeof value.value === "string" ? {
41
+ __jessBridge: true,
42
+ kind: "quoted",
43
+ value: value.value,
44
+ quote: value.quote === "'" ? "'" : "\"",
45
+ escaped: value.escaped === true
46
+ } : void 0;
47
+ case "Anonymous":
48
+ case "Keyword": return typeof value.value === "string" ? {
49
+ __jessBridge: true,
50
+ kind: "anonymous",
51
+ value: value.value
52
+ } : void 0;
53
+ case "Expression": return Array.isArray(value.value) ? {
54
+ __jessBridge: true,
55
+ kind: "expression",
56
+ items: value.value.map(encodeBridgeChildValue)
57
+ } : void 0;
58
+ case "Value": return Array.isArray(value.value) ? {
59
+ __jessBridge: true,
60
+ kind: "list",
61
+ items: value.value.map(encodeBridgeChildValue),
62
+ separator: value.separator === "/" || value.separator === ";" ? value.separator : ","
63
+ } : void 0;
64
+ case "Mixin": {
65
+ const ruleset = value.ruleset;
66
+ if (!isRecord(ruleset) || !Array.isArray(ruleset.rules)) return;
67
+ const rules = [];
68
+ for (const rule of ruleset.rules) {
69
+ if (!isRecord(rule)) continue;
70
+ if (rule.type === "Declaration" && typeof rule.name === "string") rules.push({
71
+ name: rule.name,
72
+ value: encodeBridgeChildValue(rule.value)
73
+ });
74
+ }
75
+ return {
76
+ __jessBridge: true,
77
+ kind: "mixin",
78
+ rules
79
+ };
80
+ }
81
+ default: return;
82
+ }
83
+ }
84
+ function encodeBridgeValue(value) {
85
+ if (Array.isArray(value)) return {
86
+ __jessBridge: true,
87
+ kind: "expression",
88
+ items: value.map(encodeBridgeChildValue)
89
+ };
90
+ if (isValueObj(value)) switch (value.type) {
91
+ case "Dimension": return {
92
+ __jessBridge: true,
93
+ kind: "dimension",
94
+ value: value.number,
95
+ unit: value.unit
96
+ };
97
+ case "Color": return {
98
+ __jessBridge: true,
99
+ kind: "color",
100
+ rgb: [
101
+ value.rgb[0],
102
+ value.rgb[1],
103
+ value.rgb[2]
104
+ ],
105
+ alpha: value.alpha
106
+ };
107
+ case "Quoted": return {
108
+ __jessBridge: true,
109
+ kind: "quoted",
110
+ value: value.value,
111
+ quote: value.quote === "'" ? "'" : "\"",
112
+ escaped: value.escaped
113
+ };
114
+ case "List": return value.sep === "," || value.sep === "/" ? {
115
+ __jessBridge: true,
116
+ kind: "list",
117
+ items: value.value.map(encodeBridgeChildValue),
118
+ separator: value.sep
119
+ } : {
120
+ __jessBridge: true,
121
+ kind: "anonymous",
122
+ value: value.bytes
123
+ };
124
+ case "Block": return {
125
+ __jessBridge: true,
126
+ kind: "anonymous",
127
+ value: value.bytes
128
+ };
129
+ default: return {
130
+ __jessBridge: true,
131
+ kind: "anonymous",
132
+ value: value.bytes
133
+ };
134
+ }
135
+ if (isDetached(value)) return {
136
+ __jessBridge: true,
137
+ kind: "mixin",
138
+ rules: value.rules.map((rule) => ({
139
+ name: rule.name,
140
+ value: encodeBridgeChildValue(rule.value)
141
+ }))
142
+ };
143
+ if (isRecord(value)) return encodeFacadeValue(value) ?? value;
144
+ return value;
145
+ }
146
+ function decodeValue(value) {
147
+ switch (value.kind) {
148
+ case "scalar": return typeof value.value === "number" ? makeDimension(value.value) : sniffLiteral(String(value.value));
149
+ case "dimension": return makeDimension(value.value, value.unit ?? "");
150
+ case "color": return makeColorRgb(value.rgb, value.alpha ?? 1, HEX);
151
+ case "quoted": return makeQuoted(value.value, value.quote ?? "\"", value.escaped === true);
152
+ case "anonymous": return sniffLiteral(value.value);
153
+ case "expression": return value.items.map(decodeValue);
154
+ case "list": return makeList(value.items.map(decodeValue), value.separator === ";" ? "," : value.separator);
155
+ case "mixin": return makeKeyword("");
156
+ }
157
+ }
158
+ function decodeMixin(value) {
159
+ const nil = {
160
+ type: "Nil",
161
+ value: ""
162
+ };
163
+ const mixin = {
164
+ type: "Mixin",
165
+ name: nil,
166
+ args: nil,
167
+ ruleset: { rules: value.rules.map((rule) => ({
168
+ type: "Declaration",
169
+ name: rule.name,
170
+ value: decodeValue(rule.value),
171
+ eval() {
172
+ return this;
173
+ }
174
+ })) },
175
+ eval() {
176
+ return mixin;
177
+ }
178
+ };
179
+ return mixin;
180
+ }
181
+ function decodeBridgeValue(value) {
182
+ if (!isBridgeValue(value)) return value;
183
+ return value.kind === "mixin" ? decodeMixin(value) : decodeValue(value);
184
+ }
185
+ function encodeBridgeArgs(args) {
186
+ return args.map(encodeBridgeValue);
187
+ }
188
+ //#endregion
189
+ //#region src/index.ts
190
+ /**
191
+ * A failure raised BY a `@plugin` script (its own `throw`, or a shim member it
192
+ * cannot use), as distinct from a value the engine simply could not compute.
193
+ * The distinction is what lets the compiler report a plugin fault loudly and
194
+ * attributably instead of preserving the call verbatim.
195
+ */
196
+ var PluginFunctionError = class extends Error {
197
+ functionName;
198
+ pluginStack;
199
+ originalName;
200
+ constructor(functionName, reason, pluginStack, originalName = "Error") {
201
+ super(`Less @plugin function "${functionName}" threw: ${reason}`);
202
+ this.name = "PluginFunctionError";
203
+ this.functionName = functionName;
204
+ this.pluginStack = pluginStack;
205
+ this.originalName = originalName;
206
+ }
207
+ };
208
+ /**
209
+ * Child-process stdio streams are typed as bare `Writable`/`Readable`, which do
210
+ * not declare `unref`, but the underlying pipe sockets expose it at runtime.
211
+ * The optional structural member lets any stream be passed without an unsafe
212
+ * cast; the runtime `?.` guard covers streams that genuinely lack the method.
213
+ */
214
+ const unrefStream = (stream) => {
215
+ if (typeof stream === "object" && stream !== null && "unref" in stream && typeof stream.unref === "function") stream.unref();
216
+ };
7
217
  const SCRIPT_EXTENSIONS = new Set([
8
- '.js',
9
- '.mjs',
10
- '.cjs',
11
- '.ts',
12
- '.mts',
13
- '.cts'
218
+ ".js",
219
+ ".mjs",
220
+ ".cjs",
221
+ ".ts",
222
+ ".mts",
223
+ ".cts"
14
224
  ]);
15
225
  const RUNTIME_MISSING_MESSAGE = [
16
- 'Deno runtime is required for @jesscss/plugin-js, but no usable Deno binary was found.',
17
- 'If using pnpm, approve build scripts for "deno" (pnpm approve-builds).',
18
- 'If using npm with ignored scripts, reinstall with lifecycle scripts enabled.',
19
- 'Or install native Deno and ensure "deno" is on PATH.'
20
- ].join('\n');
21
- const BOOT_TIMEOUT_MS = 8000;
22
- const REQUEST_TIMEOUT_MS = 10_000;
226
+ "Deno runtime is required for @jesscss/plugin-js, but no usable Deno binary was found.",
227
+ "If using pnpm, approve build scripts for \"deno\" (pnpm approve-builds).",
228
+ "If using npm with ignored scripts, reinstall with lifecycle scripts enabled.",
229
+ "Or install native Deno and ensure \"deno\" is on PATH."
230
+ ].join("\n");
231
+ const BOOT_TIMEOUT_MS = 8e3;
232
+ const REQUEST_TIMEOUT_MS = 1e4;
233
+ const IDLE_SHUTDOWN_MS = 5e3;
234
+ /**
235
+ * Environment variables that inject a Node.js debugger/inspector bootloader
236
+ * into child processes (VS Code / Cursor "Auto Attach", `node --inspect`, etc.).
237
+ *
238
+ * These must never leak into the sandboxed Deno worker: the injected bootloader
239
+ * tries to read the environment, the Jess Deno sandbox denies `env` permission,
240
+ * and the worker never signals ready — producing a spurious
241
+ * "Timed out waiting for Deno worker startup" failure. Deno does not use any of
242
+ * these vars, so stripping them is safe.
243
+ */
244
+ const DEBUG_ENV_KEY_RE = /^(NODE_OPTIONS|NODE_INSPECT|VSCODE_INSPECTOR_OPTIONS)/i;
245
+ const DEBUG_ENV_VALUE_RE = /js-debug|bootloader/i;
246
+ /**
247
+ * Returns a copy of `env` with Node debugger/inspector-attach variables removed,
248
+ * so a spawned Deno subprocess starts regardless of the parent's debug env.
249
+ * The Deno permission sandbox is untouched; this only stops leaking the debugger
250
+ * into it.
251
+ */
252
+ const sanitizeSpawnEnv = (env = process.env) => {
253
+ const clean = {};
254
+ for (const [key, value] of Object.entries(env)) {
255
+ if (DEBUG_ENV_KEY_RE.test(key)) continue;
256
+ if (typeof value === "string" && DEBUG_ENV_VALUE_RE.test(value)) continue;
257
+ clean[key] = value;
258
+ }
259
+ return clean;
260
+ };
23
261
  const isPathInside = (candidatePath, rootPath) => {
24
- const rel = path.relative(rootPath, candidatePath);
25
- return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
262
+ const rel = path.relative(rootPath, candidatePath);
263
+ return rel === "" || !rel.startsWith("..") && !path.isAbsolute(rel);
26
264
  };
27
265
  const canonicalPath = (p) => {
28
- try {
29
- return fs.realpathSync.native(p);
30
- }
31
- catch {
32
- return p;
33
- }
266
+ try {
267
+ return fs.realpathSync.native(p);
268
+ } catch {
269
+ return p;
270
+ }
34
271
  };
35
272
  const normalizePermissionPath = (value) => {
36
- if (!value) {
37
- return null;
38
- }
39
- if (value.startsWith('file://')) {
40
- try {
41
- return fileURLToPath(value);
42
- }
43
- catch {
44
- return value;
45
- }
46
- }
47
- return value;
273
+ if (!value) return null;
274
+ if (value.startsWith("file://")) try {
275
+ return fileURLToPath(value);
276
+ } catch {
277
+ return value;
278
+ }
279
+ return value;
48
280
  };
49
281
  const isFnsPath = (importPath) => {
50
- const normalized = importPath.replace(/\\/g, '/');
51
- const isFnsPackagePath = /(^|\/)(@jesscss\/fns|packages\/fns)(\/|$)/.test(normalized);
52
- return (normalized === '@jesscss/fns'
53
- || normalized.startsWith('@jesscss/fns/')
54
- || normalized === '#less'
55
- || normalized.startsWith('#less/')
56
- || normalized === '#sass'
57
- || normalized.startsWith('#sass/')
58
- || isFnsPackagePath);
282
+ const normalized = importPath.replace(/\\/g, "/");
283
+ const isFnsPackagePath = /(^|\/)(@jesscss\/fns|packages\/fns)(\/|$)/.test(normalized);
284
+ return normalized === "@jesscss/fns" || normalized.startsWith("@jesscss/fns/") || normalized === "#less" || normalized.startsWith("#less/") || normalized === "#sass" || normalized.startsWith("#sass/") || isFnsPackagePath;
59
285
  };
60
286
  const isJsonValue = (value) => {
61
- try {
62
- JSON.stringify(value);
63
- return true;
64
- }
65
- catch {
66
- return false;
67
- }
287
+ try {
288
+ JSON.stringify(value);
289
+ return true;
290
+ } catch {
291
+ return false;
292
+ }
68
293
  };
69
- export class JsPlugin extends AbstractPlugin {
70
- opts;
71
- name = 'js';
72
- supportedExtensions = Array.from(SCRIPT_EXTENSIONS);
73
- runtimeState = { status: 'idle' };
74
- brokerServer;
75
- brokerSocketPath;
76
- worker;
77
- workerBuffer = '';
78
- nextRequestId = 1;
79
- pending = new Map();
80
- constructor(opts = {}) {
81
- super();
82
- this.opts = opts;
83
- }
84
- prewarm() {
85
- return this.ensureRuntime().catch(() => undefined);
86
- }
87
- ensureRuntimeAvailable() {
88
- const denoCommand = this.opts.denoCommand ?? 'deno';
89
- const result = spawnSync(denoCommand, ['--version'], {
90
- stdio: 'ignore'
91
- });
92
- if (result.status !== 0) {
93
- throw new Error(RUNTIME_MISSING_MESSAGE);
94
- }
95
- }
96
- ensureRuntime() {
97
- if (this.runtimeState.status === 'ready') {
98
- return Promise.resolve();
99
- }
100
- if (this.runtimeState.status === 'initializing') {
101
- return this.runtimeState.promise;
102
- }
103
- if (this.runtimeState.status === 'failed') {
104
- return Promise.reject(this.runtimeState.error);
105
- }
106
- const promise = this.startRuntime().then(() => {
107
- this.runtimeState = { status: 'ready' };
108
- }, (err) => {
109
- this.runtimeState = { status: 'failed', error: err };
110
- throw err;
111
- });
112
- this.runtimeState = { status: 'initializing', promise };
113
- return promise;
114
- }
115
- createBrokerPath() {
116
- if (process.platform === 'win32') {
117
- const rand = `${process.pid}-${Date.now()}-${Math.floor(Math.random() * 10000)}`;
118
- return `\\\\.\\pipe\\jess-deno-broker-${rand}`;
119
- }
120
- // macOS temp dir paths can exceed unix socket limits. Keep this short.
121
- const rand = Math.floor(Math.random() * 10000);
122
- return `/tmp/jd-${process.pid}-${Date.now()}-${rand}.sock`;
123
- }
124
- isReadAllowed(value) {
125
- const normalized = normalizePermissionPath(value);
126
- if (!normalized) {
127
- return false;
128
- }
129
- const requestedPath = canonicalPath(path.resolve(normalized));
130
- const jsReadRoot = this.opts.jsReadRoot ? canonicalPath(path.resolve(this.opts.jsReadRoot)) : undefined;
131
- if (jsReadRoot && isPathInside(requestedPath, jsReadRoot)) {
132
- return true;
133
- }
134
- return requestedPath.includes(`${path.sep}node_modules${path.sep}`);
135
- }
136
- isNetAllowed(value) {
137
- if (!this.opts.allowHttp) {
138
- return false;
139
- }
140
- const allowHosts = this.opts.allowNetHosts ?? [];
141
- if (allowHosts.length === 0) {
142
- return true;
143
- }
144
- if (!value) {
145
- return false;
146
- }
147
- const host = value.split(':')[0] ?? value;
148
- return allowHosts.includes(host);
149
- }
150
- handleBrokerRequest(request) {
151
- const deny = (reason) => ({
152
- id: request.id,
153
- result: 'deny',
154
- reason
155
- });
156
- switch (request.permission) {
157
- case 'read':
158
- return this.isReadAllowed(request.value)
159
- ? { id: request.id, result: 'allow' }
160
- : deny('Read access denied by Jess policy.');
161
- case 'net':
162
- return this.isNetAllowed(request.value)
163
- ? { id: request.id, result: 'allow' }
164
- : deny('Network access denied by Jess policy.');
165
- case 'env':
166
- case 'run':
167
- case 'ffi':
168
- case 'sys':
169
- case 'write':
170
- return deny(`${request.permission} permission denied by Jess policy.`);
171
- default:
172
- return deny(`Permission "${request.permission}" denied by Jess policy.`);
173
- }
174
- }
175
- async startBroker() {
176
- const socketPath = this.createBrokerPath();
177
- if (process.platform !== 'win32' && fs.existsSync(socketPath)) {
178
- fs.unlinkSync(socketPath);
179
- }
180
- const server = net.createServer((socket) => {
181
- let buf = '';
182
- socket.setEncoding('utf8');
183
- socket.on('data', (chunk) => {
184
- buf += chunk;
185
- let idx = buf.indexOf('\n');
186
- while (idx >= 0) {
187
- const line = buf.slice(0, idx).trim();
188
- buf = buf.slice(idx + 1);
189
- idx = buf.indexOf('\n');
190
- if (!line) {
191
- continue;
192
- }
193
- let req;
194
- try {
195
- req = JSON.parse(line);
196
- }
197
- catch {
198
- socket.write(JSON.stringify({
199
- id: -1,
200
- result: 'deny',
201
- reason: 'Malformed permission request.'
202
- }) + '\n');
203
- continue;
204
- }
205
- const response = this.handleBrokerRequest(req);
206
- socket.write(`${JSON.stringify(response)}\n`);
207
- }
208
- });
209
- });
210
- await new Promise((resolve, reject) => {
211
- server.once('error', reject);
212
- server.listen(socketPath, () => resolve());
213
- });
214
- this.brokerServer = server;
215
- this.brokerSocketPath = socketPath;
216
- return socketPath;
217
- }
218
- startWorker(socketPath) {
219
- const denoCommand = this.opts.denoCommand ?? 'deno';
220
- const moduleDir = path.dirname(fileURLToPath(import.meta.url));
221
- const compiledWorkerPath = path.join(moduleDir, 'runtime-worker.js');
222
- const sourceWorkerPath = path.join(moduleDir, 'runtime-worker.ts');
223
- const workerScriptPath = fs.existsSync(compiledWorkerPath)
224
- ? compiledWorkerPath
225
- : sourceWorkerPath;
226
- const child = spawn(denoCommand, ['run', '--no-prompt', workerScriptPath], {
227
- stdio: ['pipe', 'pipe', 'pipe'],
228
- env: {
229
- ...process.env,
230
- DENO_PERMISSION_BROKER_PATH: socketPath
231
- }
232
- });
233
- this.worker = child;
234
- child.stdout.setEncoding('utf8');
235
- child.stderr.setEncoding('utf8');
236
- child.stdout.on('data', chunk => this.onWorkerStdout(chunk));
237
- child.on('exit', () => {
238
- const err = new Error('Deno worker exited unexpectedly.');
239
- this.rejectAllPending(err);
240
- if (this.runtimeState.status !== 'failed') {
241
- this.runtimeState = { status: 'failed', error: err };
242
- }
243
- });
244
- return new Promise((resolve, reject) => {
245
- const timer = setTimeout(() => {
246
- reject(new Error('Timed out waiting for Deno worker startup.'));
247
- }, BOOT_TIMEOUT_MS);
248
- const onData = (chunk) => {
249
- this.workerBuffer += chunk;
250
- let idx = this.workerBuffer.indexOf('\n');
251
- while (idx >= 0) {
252
- const line = this.workerBuffer.slice(0, idx).trim();
253
- this.workerBuffer = this.workerBuffer.slice(idx + 1);
254
- idx = this.workerBuffer.indexOf('\n');
255
- if (!line) {
256
- continue;
257
- }
258
- try {
259
- const parsed = JSON.parse(line);
260
- if (parsed.type === 'ready') {
261
- clearTimeout(timer);
262
- child.stdout.off('data', onData);
263
- resolve();
264
- return;
265
- }
266
- }
267
- catch {
268
- // ignore until ready payload appears
269
- }
270
- }
271
- };
272
- child.stdout.on('data', onData);
273
- child.once('error', (err) => {
274
- clearTimeout(timer);
275
- child.stdout.off('data', onData);
276
- reject(err);
277
- });
278
- });
279
- }
280
- async startRuntime() {
281
- this.ensureRuntimeAvailable();
282
- const socketPath = await this.startBroker();
283
- try {
284
- await this.startWorker(socketPath);
285
- }
286
- catch (err) {
287
- this.shutdown();
288
- throw err instanceof Error ? err : new Error(String(err));
289
- }
290
- }
291
- onWorkerStdout(chunk) {
292
- this.workerBuffer += chunk;
293
- let idx = this.workerBuffer.indexOf('\n');
294
- while (idx >= 0) {
295
- const line = this.workerBuffer.slice(0, idx).trim();
296
- this.workerBuffer = this.workerBuffer.slice(idx + 1);
297
- idx = this.workerBuffer.indexOf('\n');
298
- if (!line) {
299
- continue;
300
- }
301
- let parsed;
302
- try {
303
- parsed = JSON.parse(line);
304
- }
305
- catch {
306
- continue;
307
- }
308
- if (!parsed || typeof parsed.id !== 'number') {
309
- continue;
310
- }
311
- const pending = this.pending.get(parsed.id);
312
- if (!pending) {
313
- continue;
314
- }
315
- this.pending.delete(parsed.id);
316
- clearTimeout(pending.timeout);
317
- pending.resolve(parsed);
318
- }
319
- }
320
- rejectAllPending(err) {
321
- for (const pending of this.pending.values()) {
322
- clearTimeout(pending.timeout);
323
- pending.reject(err);
324
- }
325
- this.pending.clear();
326
- }
327
- async callWorker(request) {
328
- await this.ensureRuntime();
329
- if (!this.worker || !this.worker.stdin.writable) {
330
- throw new Error('Deno worker is not available.');
331
- }
332
- const id = this.nextRequestId++;
333
- const payload = { ...request, id };
334
- return await new Promise((resolve, reject) => {
335
- const timeout = setTimeout(() => {
336
- this.pending.delete(id);
337
- reject(new Error('Timed out waiting for Deno worker response.'));
338
- }, REQUEST_TIMEOUT_MS);
339
- this.pending.set(id, { resolve, reject, timeout });
340
- this.worker.stdin.write(`${JSON.stringify(payload)}\n`);
341
- });
342
- }
343
- shutdown() {
344
- if (this.worker && !this.worker.killed) {
345
- this.worker.kill();
346
- }
347
- this.worker = undefined;
348
- if (this.brokerServer) {
349
- this.brokerServer.close();
350
- this.brokerServer = undefined;
351
- }
352
- if (this.brokerSocketPath && process.platform !== 'win32') {
353
- try {
354
- if (fs.existsSync(this.brokerSocketPath)) {
355
- fs.unlinkSync(this.brokerSocketPath);
356
- }
357
- }
358
- catch {
359
- // ignore
360
- }
361
- }
362
- this.brokerSocketPath = undefined;
363
- }
364
- dispose() {
365
- this.shutdown();
366
- this.runtimeState = { status: 'idle' };
367
- }
368
- assertAllowedPath(absoluteFilePath) {
369
- const resolvedPath = path.resolve(absoluteFilePath);
370
- const jsReadRoot = this.opts.jsReadRoot ? path.resolve(this.opts.jsReadRoot) : undefined;
371
- if (!jsReadRoot) {
372
- return;
373
- }
374
- if (isPathInside(resolvedPath, jsReadRoot)) {
375
- return;
376
- }
377
- // pnpm layouts may resolve package files outside project root.
378
- if (resolvedPath.includes(`${path.sep}node_modules${path.sep}`)) {
379
- return;
380
- }
381
- throw new Error(`Script path "${resolvedPath}" is outside jsReadRoot "${jsReadRoot}"`);
382
- }
383
- async import(absoluteFilePath) {
384
- const ext = path.extname(absoluteFilePath);
385
- if (!SCRIPT_EXTENSIONS.has(ext)) {
386
- throw new Error(`Plugin "${this.name}" cannot import "${absoluteFilePath}"`);
387
- }
388
- if (!isFnsPath(absoluteFilePath)) {
389
- this.assertAllowedPath(absoluteFilePath);
390
- await this.ensureRuntime();
391
- const modulePath = path.resolve(absoluteFilePath);
392
- const loadResult = await this.callWorker({ type: 'load', modulePath });
393
- if (!loadResult.ok) {
394
- throw new Error(loadResult.error);
395
- }
396
- const moduleObject = {};
397
- const exported = loadResult.exports ?? [];
398
- for (const item of exported) {
399
- if (item.kind === 'function') {
400
- moduleObject[item.name] = async (...args) => {
401
- const invokeResult = await this.callWorker({
402
- type: 'invoke',
403
- modulePath,
404
- exportName: item.name,
405
- args
406
- });
407
- if (!invokeResult.ok) {
408
- throw new Error(invokeResult.error);
409
- }
410
- return invokeResult.value;
411
- };
412
- }
413
- else {
414
- moduleObject[item.name] = item.value;
415
- }
416
- }
417
- return moduleObject;
418
- }
419
- const modulePath = pathToFileURL(path.resolve(absoluteFilePath)).href;
420
- const module = await import(modulePath);
421
- const safeModule = {};
422
- for (const [key, value] of Object.entries(module)) {
423
- if (typeof value === 'function' || isJsonValue(value)) {
424
- safeModule[key] = value;
425
- }
426
- }
427
- return safeModule;
428
- }
429
- }
430
294
  /**
431
- * Global flag set when @jesscss/plugin-js is loaded.
432
- * less-compat checks this before running @plugin scripts (scripts must be run when plugin-js/Deno is present).
433
- */
434
- export const JESS_PLUGIN_JS_GLOBAL = '__JESS_PLUGIN_JS_AVAILABLE__';
435
- if (typeof globalThis !== 'undefined') {
436
- globalThis[JESS_PLUGIN_JS_GLOBAL] = true;
437
- }
295
+ * Ceiling on resolve-and-replay rounds for a single call. Each round satisfies
296
+ * exactly one fact, so this also bounds a pathological plugin that asks for an
297
+ * unbounded number of distinct variables.
298
+ */
299
+ const MAX_FACT_ROUNDS = 64;
300
+ var JsPlugin = class JsPlugin extends AbstractPlugin {
301
+ static cleanupRegistered = false;
302
+ static liveInstances = /* @__PURE__ */ new Set();
303
+ name = "js";
304
+ supportedExtensions = Array.from(SCRIPT_EXTENSIONS);
305
+ runtimeState = { status: "idle" };
306
+ shuttingDown = false;
307
+ brokerServer;
308
+ brokerSocketPath;
309
+ worker;
310
+ workerBuffer = "";
311
+ nextRequestId = 1;
312
+ pending = /* @__PURE__ */ new Map();
313
+ idleTimer;
314
+ /**
315
+ * Variable names each legacy plugin function has been observed to read,
316
+ * keyed by module+options+function. Prefetching them turns the steady-state
317
+ * call into a single round trip instead of one round trip per read.
318
+ */
319
+ factMemo = /* @__PURE__ */ new Map();
320
+ constructor(opts = {}) {
321
+ super();
322
+ this.opts = opts;
323
+ JsPlugin.liveInstances.add(this);
324
+ JsPlugin.registerProcessCleanup();
325
+ }
326
+ prewarm() {
327
+ return this.ensureRuntime().catch(() => void 0);
328
+ }
329
+ static registerProcessCleanup() {
330
+ if (JsPlugin.cleanupRegistered) return;
331
+ JsPlugin.cleanupRegistered = true;
332
+ const cleanup = () => {
333
+ for (const instance of JsPlugin.liveInstances) try {
334
+ instance.dispose();
335
+ } catch {}
336
+ };
337
+ process.once("beforeExit", cleanup);
338
+ process.once("exit", cleanup);
339
+ }
340
+ clearIdleTimer() {
341
+ if (this.idleTimer) {
342
+ clearTimeout(this.idleTimer);
343
+ this.idleTimer = void 0;
344
+ }
345
+ }
346
+ scheduleIdleShutdown() {
347
+ this.clearIdleTimer();
348
+ if (this.pending.size > 0 || this.runtimeState.status !== "ready") return;
349
+ this.idleTimer = setTimeout(() => {
350
+ this.shutdown();
351
+ this.runtimeState = { status: "idle" };
352
+ }, IDLE_SHUTDOWN_MS);
353
+ this.idleTimer.unref?.();
354
+ }
355
+ ensureRuntimeAvailable() {
356
+ if (spawnSync(this.opts.denoCommand ?? "deno", ["--version"], {
357
+ stdio: "ignore",
358
+ env: sanitizeSpawnEnv(process.env)
359
+ }).status !== 0) throw new Error(RUNTIME_MISSING_MESSAGE);
360
+ }
361
+ ensureRuntime() {
362
+ if (this.runtimeState.status === "ready") {
363
+ this.clearIdleTimer();
364
+ return Promise.resolve();
365
+ }
366
+ if (this.runtimeState.status === "initializing") return this.runtimeState.promise;
367
+ if (this.runtimeState.status === "failed") return Promise.reject(this.runtimeState.error);
368
+ if (this.runtimeState.status === "disposed") return Promise.reject(/* @__PURE__ */ new Error("Deno worker has been disposed."));
369
+ const promise = this.startRuntime().then(() => {
370
+ this.runtimeState = { status: "ready" };
371
+ this.scheduleIdleShutdown();
372
+ }, (err) => {
373
+ this.runtimeState = {
374
+ status: "failed",
375
+ error: err
376
+ };
377
+ throw err;
378
+ });
379
+ this.runtimeState = {
380
+ status: "initializing",
381
+ promise
382
+ };
383
+ return promise;
384
+ }
385
+ createBrokerPath() {
386
+ if (process.platform === "win32") return `\\\\.\\pipe\\jess-deno-broker-${`${process.pid}-${Date.now()}-${Math.floor(Math.random() * 1e4)}`}`;
387
+ const rand = Math.floor(Math.random() * 1e4);
388
+ return `/tmp/jd-${process.pid}-${Date.now()}-${rand}.sock`;
389
+ }
390
+ isReadAllowed(value) {
391
+ const normalized = normalizePermissionPath(value);
392
+ if (!normalized) return false;
393
+ const requestedPath = canonicalPath(path.resolve(normalized));
394
+ const jsReadRoot = this.opts.jsReadRoot ? canonicalPath(path.resolve(this.opts.jsReadRoot)) : void 0;
395
+ if (jsReadRoot && isPathInside(requestedPath, jsReadRoot)) return true;
396
+ return requestedPath.includes(`${path.sep}node_modules${path.sep}`);
397
+ }
398
+ isNetAllowed(value) {
399
+ if (!this.opts.allowHttp) return false;
400
+ const allowHosts = this.opts.allowNetHosts ?? [];
401
+ if (allowHosts.length === 0) return true;
402
+ if (!value) return false;
403
+ const host = value.split(":")[0] ?? value;
404
+ return allowHosts.includes(host);
405
+ }
406
+ handleBrokerRequest(request) {
407
+ const deny = (reason) => ({
408
+ id: request.id,
409
+ result: "deny",
410
+ reason
411
+ });
412
+ switch (request.permission) {
413
+ case "read": return this.isReadAllowed(request.value) ? {
414
+ id: request.id,
415
+ result: "allow"
416
+ } : deny("Read access denied by Jess policy.");
417
+ case "net": return this.isNetAllowed(request.value) ? {
418
+ id: request.id,
419
+ result: "allow"
420
+ } : deny("Network access denied by Jess policy.");
421
+ case "env":
422
+ case "run":
423
+ case "ffi":
424
+ case "sys":
425
+ case "write": return deny(`${request.permission} permission denied by Jess policy.`);
426
+ default: return deny(`Permission "${request.permission}" denied by Jess policy.`);
427
+ }
428
+ }
429
+ async startBroker() {
430
+ const socketPath = this.createBrokerPath();
431
+ if (process.platform !== "win32" && fs.existsSync(socketPath)) fs.unlinkSync(socketPath);
432
+ const server = net.createServer((socket) => {
433
+ socket.unref();
434
+ let buf = "";
435
+ socket.setEncoding("utf8");
436
+ socket.on("data", (chunk) => {
437
+ buf += chunk;
438
+ let idx = buf.indexOf("\n");
439
+ while (idx >= 0) {
440
+ const line = buf.slice(0, idx).trim();
441
+ buf = buf.slice(idx + 1);
442
+ idx = buf.indexOf("\n");
443
+ if (!line) continue;
444
+ let req;
445
+ try {
446
+ req = JSON.parse(line);
447
+ } catch {
448
+ socket.write(JSON.stringify({
449
+ id: -1,
450
+ result: "deny",
451
+ reason: "Malformed permission request."
452
+ }) + "\n");
453
+ continue;
454
+ }
455
+ const response = this.handleBrokerRequest(req);
456
+ socket.write(`${JSON.stringify(response)}\n`);
457
+ }
458
+ });
459
+ });
460
+ await new Promise((resolve, reject) => {
461
+ server.once("error", reject);
462
+ server.listen(socketPath, () => resolve());
463
+ });
464
+ server.unref();
465
+ this.brokerServer = server;
466
+ this.brokerSocketPath = socketPath;
467
+ return socketPath;
468
+ }
469
+ startWorker(socketPath) {
470
+ const denoCommand = this.opts.denoCommand ?? "deno";
471
+ const moduleDir = path.dirname(fileURLToPath(import.meta.url));
472
+ const compiledWorkerPath = path.join(moduleDir, "runtime-worker.js");
473
+ const sourceWorkerPath = path.join(moduleDir, "runtime-worker.ts");
474
+ const child = spawn(denoCommand, [
475
+ "run",
476
+ "--no-prompt",
477
+ fs.existsSync(compiledWorkerPath) ? compiledWorkerPath : sourceWorkerPath,
478
+ `--runtime-api=${this.opts.runtimeApi ?? "module"}`
479
+ ], {
480
+ stdio: [
481
+ "pipe",
482
+ "pipe",
483
+ "pipe"
484
+ ],
485
+ env: {
486
+ ...sanitizeSpawnEnv(process.env),
487
+ DENO_PERMISSION_BROKER_PATH: socketPath
488
+ }
489
+ });
490
+ this.worker = child;
491
+ child.unref();
492
+ unrefStream(child.stdin);
493
+ unrefStream(child.stdout);
494
+ unrefStream(child.stderr);
495
+ child.stdout.setEncoding("utf8");
496
+ child.stderr.setEncoding("utf8");
497
+ child.stdout.on("data", (chunk) => this.onWorkerStdout(chunk));
498
+ child.on("exit", () => {
499
+ this.worker = void 0;
500
+ if (this.shuttingDown) {
501
+ this.shuttingDown = false;
502
+ return;
503
+ }
504
+ const err = /* @__PURE__ */ new Error("Deno worker exited unexpectedly.");
505
+ this.rejectAllPending(err);
506
+ if (this.runtimeState.status !== "failed") this.runtimeState = {
507
+ status: "failed",
508
+ error: err
509
+ };
510
+ });
511
+ return new Promise((resolve, reject) => {
512
+ let stderrText = "";
513
+ const timer = setTimeout(() => {
514
+ reject(/* @__PURE__ */ new Error(stderrText.trim() ? `Timed out waiting for Deno worker startup.\n${stderrText.trim()}` : "Timed out waiting for Deno worker startup."));
515
+ }, BOOT_TIMEOUT_MS);
516
+ const onStderr = (chunk) => {
517
+ stderrText += chunk;
518
+ };
519
+ const onData = (chunk) => {
520
+ this.workerBuffer += chunk;
521
+ let idx = this.workerBuffer.indexOf("\n");
522
+ while (idx >= 0) {
523
+ const line = this.workerBuffer.slice(0, idx).trim();
524
+ this.workerBuffer = this.workerBuffer.slice(idx + 1);
525
+ idx = this.workerBuffer.indexOf("\n");
526
+ if (!line) continue;
527
+ try {
528
+ if (JSON.parse(line).type === "ready") {
529
+ clearTimeout(timer);
530
+ child.stdout.off("data", onData);
531
+ child.stderr.off("data", onStderr);
532
+ resolve();
533
+ return;
534
+ }
535
+ } catch {}
536
+ }
537
+ };
538
+ child.stdout.on("data", onData);
539
+ child.stderr.on("data", onStderr);
540
+ child.once("error", (err) => {
541
+ clearTimeout(timer);
542
+ child.stdout.off("data", onData);
543
+ child.stderr.off("data", onStderr);
544
+ reject(err);
545
+ });
546
+ });
547
+ }
548
+ async startRuntime() {
549
+ this.ensureRuntimeAvailable();
550
+ const socketPath = await this.startBroker();
551
+ try {
552
+ await this.startWorker(socketPath);
553
+ } catch (err) {
554
+ this.shutdown();
555
+ throw err instanceof Error ? err : new Error(String(err));
556
+ }
557
+ }
558
+ onWorkerStdout(chunk) {
559
+ this.workerBuffer += chunk;
560
+ let idx = this.workerBuffer.indexOf("\n");
561
+ while (idx >= 0) {
562
+ const line = this.workerBuffer.slice(0, idx).trim();
563
+ this.workerBuffer = this.workerBuffer.slice(idx + 1);
564
+ idx = this.workerBuffer.indexOf("\n");
565
+ if (!line) continue;
566
+ let parsed;
567
+ try {
568
+ parsed = JSON.parse(line);
569
+ } catch {
570
+ continue;
571
+ }
572
+ if (!parsed || typeof parsed.id !== "number") continue;
573
+ const pending = this.pending.get(parsed.id);
574
+ if (!pending) continue;
575
+ this.pending.delete(parsed.id);
576
+ clearTimeout(pending.timeout);
577
+ pending.resolve(parsed);
578
+ if (this.pending.size === 0) this.scheduleIdleShutdown();
579
+ }
580
+ }
581
+ rejectAllPending(err) {
582
+ for (const pending of this.pending.values()) {
583
+ clearTimeout(pending.timeout);
584
+ pending.reject(err);
585
+ }
586
+ this.pending.clear();
587
+ }
588
+ async callWorker(request) {
589
+ await this.ensureRuntime();
590
+ this.clearIdleTimer();
591
+ if (!this.worker?.stdin.writable) throw new Error("Deno worker is not available.");
592
+ const id = this.nextRequestId++;
593
+ const payload = {
594
+ ...request,
595
+ id
596
+ };
597
+ return await new Promise((resolve, reject) => {
598
+ const timeout = setTimeout(() => {
599
+ this.pending.delete(id);
600
+ reject(/* @__PURE__ */ new Error("Timed out waiting for Deno worker response."));
601
+ }, REQUEST_TIMEOUT_MS);
602
+ this.pending.set(id, {
603
+ resolve,
604
+ reject,
605
+ timeout
606
+ });
607
+ this.worker.stdin.write(`${JSON.stringify(payload)}\n`);
608
+ });
609
+ }
610
+ shutdown() {
611
+ this.clearIdleTimer();
612
+ if (this.worker && !this.worker.killed) {
613
+ this.shuttingDown = true;
614
+ this.worker.stdin.destroy();
615
+ this.worker.stdout.destroy();
616
+ this.worker.stderr.destroy();
617
+ this.worker.kill();
618
+ }
619
+ this.worker = void 0;
620
+ if (this.brokerServer) {
621
+ this.brokerServer.close();
622
+ this.brokerServer = void 0;
623
+ }
624
+ if (this.brokerSocketPath && process.platform !== "win32") try {
625
+ if (fs.existsSync(this.brokerSocketPath)) fs.unlinkSync(this.brokerSocketPath);
626
+ } catch {}
627
+ this.brokerSocketPath = void 0;
628
+ }
629
+ dispose() {
630
+ this.shutdown();
631
+ JsPlugin.liveInstances.delete(this);
632
+ this.runtimeState = { status: "disposed" };
633
+ }
634
+ assertAllowedPath(absoluteFilePath) {
635
+ const resolvedPath = path.resolve(absoluteFilePath);
636
+ const jsReadRoot = this.opts.jsReadRoot ? path.resolve(this.opts.jsReadRoot) : void 0;
637
+ if (!jsReadRoot) return;
638
+ if (isPathInside(resolvedPath, jsReadRoot)) return;
639
+ if (resolvedPath.includes(`${path.sep}node_modules${path.sep}`)) return;
640
+ throw new Error(`Script path "${resolvedPath}" is outside jsReadRoot "${jsReadRoot}"`);
641
+ }
642
+ async import(absoluteFilePath) {
643
+ const ext = path.extname(absoluteFilePath);
644
+ if (!SCRIPT_EXTENSIONS.has(ext)) throw new Error(`Plugin "${this.name}" cannot import "${absoluteFilePath}"`);
645
+ if (!isFnsPath(absoluteFilePath)) {
646
+ this.assertAllowedPath(absoluteFilePath);
647
+ await this.ensureRuntime();
648
+ const modulePath = path.resolve(absoluteFilePath);
649
+ const loadResult = await this.callWorker({
650
+ type: "load",
651
+ modulePath
652
+ });
653
+ if (!loadResult.ok) throw new Error(loadResult.error);
654
+ const moduleObject = {};
655
+ const exported = loadResult.exports ?? [];
656
+ for (const item of exported) if (item.kind === "function") moduleObject[item.name] = async (...args) => {
657
+ const invokeResult = await this.callWorker({
658
+ type: "invoke",
659
+ modulePath,
660
+ exportName: item.name,
661
+ args: encodeBridgeArgs(args)
662
+ });
663
+ if (!invokeResult.ok) throw new Error(invokeResult.error);
664
+ return decodeBridgeValue(invokeResult.value);
665
+ };
666
+ else moduleObject[item.name] = item.value;
667
+ return moduleObject;
668
+ }
669
+ const module = await import(pathToFileURL(path.resolve(absoluteFilePath)).href);
670
+ const safeModule = {};
671
+ for (const [key, value] of Object.entries(module)) if (typeof value === "function" || isJsonValue(value)) safeModule[key] = value;
672
+ return safeModule;
673
+ }
674
+ /**
675
+ * Loads a legacy Less `@plugin` wrapper file in Deno Less-compat mode.
676
+ *
677
+ * @deprecated Less `@plugin` is deprecated. Prefer `@-from` for
678
+ * ESM-style script imports or `@-use` for Sass-module-style namespace imports.
679
+ */
680
+ async importLessPlugin(absoluteFilePath, options = null) {
681
+ const ext = path.extname(absoluteFilePath);
682
+ if (!SCRIPT_EXTENSIONS.has(ext)) throw new Error(`Plugin "${this.name}" cannot import Less plugin "${absoluteFilePath}"`);
683
+ this.assertAllowedPath(absoluteFilePath);
684
+ await this.ensureRuntime();
685
+ const modulePath = path.resolve(absoluteFilePath);
686
+ const loadResult = await this.callWorker({
687
+ type: "loadLessPlugin",
688
+ modulePath,
689
+ options
690
+ });
691
+ if (!loadResult.ok) throw new PluginFunctionError(path.basename(modulePath), loadResult.error ?? "an unknown sandbox failure", loadResult.stack);
692
+ const functions = {};
693
+ for (const functionName of loadResult.functions ?? []) functions[functionName] = (args, capabilities) => this.invokePluginFunction(modulePath, options, functionName, args, capabilities);
694
+ return { functions };
695
+ }
696
+ /**
697
+ * Runs one legacy `@plugin` function, resolving the scope/built-in facts its
698
+ * body reads. The sandbox reports one unmet fact at a time; the host answers
699
+ * it from the LIVE call-site capabilities and replays. The names a function
700
+ * asked for are remembered per function, so steady-state calls ship the facts
701
+ * up front and complete in a single round trip.
702
+ */
703
+ invokePluginFunction(modulePath, options, functionName, args, capabilities) {
704
+ const memoKey = `${modulePath} ${options ?? ""} ${functionName}`;
705
+ const known = this.factMemo.get(memoKey) ?? /* @__PURE__ */ new Set();
706
+ const facts = {
707
+ vars: {},
708
+ calls: {},
709
+ fileInfo: capabilities.currentFileInfo ?? null
710
+ };
711
+ for (const name of known) facts.vars[name] = this.resolveVariableFact(name, capabilities);
712
+ const request = {
713
+ type: "invokeLessPluginFunction",
714
+ modulePath,
715
+ options,
716
+ functionName,
717
+ args: encodeBridgeArgs([...args]),
718
+ facts
719
+ };
720
+ /**
721
+ * Folds one reply. Returns the decoded value, or `undefined` to signal that
722
+ * `facts` has been extended and the call must be replayed.
723
+ */
724
+ const settle = (result) => {
725
+ for (const record of result.logs ?? []) capabilities.log?.(record);
726
+ if (result.ok) {
727
+ if (result.important) capabilities.markImportant?.();
728
+ return { value: decodeBridgeValue(result.value) };
729
+ }
730
+ if (!result.need) throw new PluginFunctionError(functionName, result.error ?? "an unknown sandbox failure", result.stack, result.errorName);
731
+ if (result.need.kind === "variable") {
732
+ const name = result.need.name;
733
+ facts.vars[name] = this.resolveVariableFact(name, capabilities);
734
+ known.add(name);
735
+ this.factMemo.set(memoKey, known);
736
+ return;
737
+ }
738
+ facts.calls[result.need.key] = this.resolveCallFact(result.need, capabilities);
739
+ };
740
+ const exhausted = () => new PluginFunctionError(functionName, `resolving its scope reads did not settle after ${MAX_FACT_ROUNDS} rounds.`);
741
+ const replay = async () => {
742
+ for (let round = 0; round <= MAX_FACT_ROUNDS; round++) {
743
+ const settled = settle(await this.callWorker(request));
744
+ if (settled) return settled.value;
745
+ }
746
+ throw exhausted();
747
+ };
748
+ return replay();
749
+ }
750
+ resolveVariableFact(name, capabilities) {
751
+ const hit = capabilities.lookupVariable?.(name);
752
+ if (!hit) return null;
753
+ return {
754
+ value: encodeBridgeValue(hit.value),
755
+ important: hit.important === true
756
+ };
757
+ }
758
+ resolveCallFact(need, capabilities) {
759
+ const decoded = need.args.map(decodeBridgeValue);
760
+ const answer = capabilities.callFunction?.(need.name, decoded);
761
+ return answer === void 0 ? null : encodeBridgeValue(answer);
762
+ }
763
+ /** Context-facing executable-plugin capability used by the direct AST path. */
764
+ async importPlugin(absoluteFilePath, options = null) {
765
+ return this.importLessPlugin(absoluteFilePath, options);
766
+ }
767
+ };
768
+ /**
769
+ * Global flag set when @jesscss/plugin-js is loaded.
770
+ * less-compat checks this before running @plugin scripts (scripts must be run when plugin-js/Deno is present).
771
+ */
772
+ const JESS_PLUGIN_JS_GLOBAL = "__JESS_PLUGIN_JS_AVAILABLE__";
773
+ if (typeof globalThis !== "undefined") globalThis[JESS_PLUGIN_JS_GLOBAL] = true;
438
774
  const jsPlugin = ((opts) => {
439
- return new JsPlugin(opts);
775
+ return new JsPlugin(opts);
440
776
  });
441
- export default jsPlugin;
442
- //# sourceMappingURL=index.js.map
777
+ //#endregion
778
+ export { JESS_PLUGIN_JS_GLOBAL, JsPlugin, PluginFunctionError, jsPlugin as default, sanitizeSpawnEnv };