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

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