@locker/cli 0.28.3

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/src/repl.mjs ADDED
@@ -0,0 +1,527 @@
1
+ import { createRequire } from 'node:module';
2
+ import readline from 'node:readline';
3
+ import { inspect } from 'node:util';
4
+
5
+ import * as acorn from 'acorn';
6
+
7
+ import { injectScriptTags, loadScriptFiles } from './before-after.mjs';
8
+ import { Browser } from './browser.mjs';
9
+ import { buildEndowmentsReplAssignments, loadEndowments } from './endowments.mjs';
10
+ import { Output } from './output.mjs';
11
+ import { Server } from './server.mjs';
12
+ import { awaitAndEmitUpgradeNotice, startVersionCheckForCLI } from './version-check.mjs';
13
+
14
+ const require = createRequire(import.meta.url);
15
+ const PACKAGE_JSON = require('../package.json');
16
+ const REPL_MODULE_PATH = new URL(import.meta.url).pathname;
17
+
18
+ const EVAL_HARNESS_PATH = '/eval.html';
19
+ const PROMPT = 'lws> ';
20
+ const CONTINUATION_PROMPT = '... ';
21
+
22
+ // Dot-command help text. Two-column layout matches Node REPL's `.help`
23
+ // shape so users with prior REPL muscle memory know what to expect.
24
+ // The footer notes are LWS-specific — state-persistence caveats users
25
+ // will otherwise hit and not understand. Keep this short; it's a
26
+ // reference, not a tutorial.
27
+ export const HELP_TEXT = [
28
+ '.break Cancel a multi-line input in progress, return to the main prompt',
29
+ '.clear Alias for .break',
30
+ '.exit Exit the REPL',
31
+ '.help Print this help message',
32
+ '',
33
+ 'REPL behavior:',
34
+ '- Multi-line input is auto-detected: open a bracket / paren / brace / string,',
35
+ ' hit Enter, keep typing. The prompt switches to `... ` while buffering.',
36
+ '- Trailing `\\` at end-of-line forces continuation even on syntactically',
37
+ ' complete input.',
38
+ '- Ctrl+C cancels a buffered input (TTY only); Ctrl+D / .exit close the REPL.',
39
+ ].join('\n');
40
+ // Magic prefix used to ferry the result of each REPL evaluation back
41
+ // through the existing console pump. The in-page driver (see runReplLine)
42
+ // JSON-encodes the value and `console.log`s it with this prefix; the
43
+ // Browser's consoleInterceptor strips the prefix, decodes, and pretty-
44
+ // prints to stdout. Reusing the existing console channel keeps user
45
+ // `console.log` output and result output in a single ordered stream and
46
+ // avoids a second `page.evaluate()` round-trip per line.
47
+ const RESULT_MARKER = '__LWS_REPL_RESULT__';
48
+ const UNDEFINED_TOKEN = '__lws_undefined__';
49
+
50
+ // JSON-encode a value for the result channel. Non-JSON values (functions,
51
+ // symbols, bigints, undefined) are folded to printable strings so the
52
+ // payload is always parseable on the Node side; the renderer reverses this
53
+ // when formatting via util.inspect.
54
+ function buildResultEncoder() {
55
+ return `function _lwsEncode(v) {
56
+ try {
57
+ return JSON.stringify(v, (_k, val) => {
58
+ if (typeof val === 'function') {
59
+ return String(val);
60
+ }
61
+ if (typeof val === 'undefined') {
62
+ return ${JSON.stringify(UNDEFINED_TOKEN)};
63
+ }
64
+ if (typeof val === 'bigint') {
65
+ return val.toString() + 'n';
66
+ }
67
+ if (typeof val === 'symbol') {
68
+ return val.toString();
69
+ }
70
+ return val;
71
+ });
72
+ } catch (_e) {
73
+ return JSON.stringify(String(v));
74
+ }
75
+ }`;
76
+ }
77
+
78
+ function decodeResultPayload(jsonText) {
79
+ const parsed = JSON.parse(jsonText);
80
+ if (parsed === UNDEFINED_TOKEN) {
81
+ return undefined;
82
+ }
83
+ return parsed;
84
+ }
85
+
86
+ // Classify a buffered REPL input as complete, incomplete (continuation
87
+ // expected), or syntactically broken. Implements Node REPL's heuristic:
88
+ // parse the source with Acorn; if the parse succeeds the input is
89
+ // complete; if the error is at end-of-input (e.g. unclosed bracket,
90
+ // unterminated string/template, trailing operator) the input is
91
+ // incomplete and the REPL should buffer and re-prompt with `... `; if
92
+ // the error is anywhere else, it is a real syntax error to surface.
93
+ //
94
+ // Trailing `\` at end-of-line is also treated as an explicit continuation
95
+ // marker (legacy shell convention). The backslash is stripped during
96
+ // joining so the final source is parser-clean.
97
+ //
98
+ // Returns one of: 'complete' | 'incomplete' | { error }
99
+ export function classifyReplInput(src) {
100
+ if (/\\\s*$/.test(src)) {
101
+ return 'incomplete';
102
+ }
103
+ try {
104
+ acorn.parse(src, { ecmaVersion: 'latest', sourceType: 'script' });
105
+ return 'complete';
106
+ } catch (err) {
107
+ const atEnd =
108
+ (typeof err.pos === 'number' && err.pos === src.length) ||
109
+ /Unterminated|end of input/i.test(err.message);
110
+ if (atEnd) {
111
+ return 'incomplete';
112
+ }
113
+ return { error: err };
114
+ }
115
+ }
116
+
117
+ // Strip trailing-backslash continuation markers and join buffered REPL
118
+ // lines into a single source string. The backslashes are line-final
119
+ // continuation hints (shell-style); they don't belong in the source we
120
+ // hand to the sandbox.
121
+ export function joinReplBuffer(lines) {
122
+ return lines
123
+ .map((line, i) => {
124
+ if (i === lines.length - 1) {
125
+ return line;
126
+ }
127
+ return line.replace(/\\\s*$/, '');
128
+ })
129
+ .join('\n');
130
+ }
131
+
132
+ // State-persistence rewrite for top-level `let`/`const`/`var` declarations.
133
+ //
134
+ // `evaluateInSandbox(key, source)` evaluates each call as a fresh Module.
135
+ // Module-level `let`/`const`/`var` bind to that module's lexical environment
136
+ // — they do not persist after the module finishes, even when the sandbox
137
+ // realm (keyed on `key`) persists across calls. Without a rewrite, the
138
+ // canonical REPL pattern `let x = 1` then `x` would fail with
139
+ // "x is not defined" because the binding from the first call has been
140
+ // discarded by the time the second call evaluates.
141
+ //
142
+ // Node's REPL solves this by rewriting top-level `let` to `var` at the
143
+ // Script level — Script-level `var` declarations land on the global object.
144
+ // We're stuck in Module mode (the only public sandbox API), so the
145
+ // equivalent is to rewrite top-level declarations to assignments on
146
+ // `globalThis`, which the sandbox runtime persists as part of its
147
+ // per-key Window.
148
+ //
149
+ // The rewrite is intentionally conservative: it only fires for a single
150
+ // declarator on a line whose first non-whitespace token is `let`, `const`,
151
+ // or `var`, and only when the value expression contains no top-level
152
+ // comma. Multi-declarator forms (`let a = 1, b = 2`) and destructuring
153
+ // patterns are left alone — they evaluate as Module scope and won't
154
+ // persist, but that's a documented REPL limitation rather than a wrong
155
+ // rewrite. The top-level comma check uses a depth-tracking scan so commas
156
+ // inside arrays / objects / parens / template literals (`let arr = [1, 2,
157
+ // 3]`) don't disqualify the rewrite.
158
+ const TOP_LEVEL_DECL_PATTERN = /^\s*(let|const|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=([\s\S]*)$/;
159
+
160
+ // Returns true if `s` contains a comma at bracket-depth 0. Brackets: `()`,
161
+ // `[]`, `{}`. Template literals (backticks) and string literals are also
162
+ // tracked so a comma inside them doesn't count. This is intentionally a
163
+ // best-effort scanner — it doesn't handle regex literals or comments,
164
+ // which are rare in REPL inputs and produce safe failure modes (we'd
165
+ // either bail when we shouldn't or rewrite when we shouldn't, but the
166
+ // CLI smoke test catches the latter for the common shapes).
167
+ function hasTopLevelComma(s) {
168
+ let depth = 0;
169
+ let inSingle = false;
170
+ let inDouble = false;
171
+ let inTemplate = false;
172
+ for (let i = 0; i < s.length; i += 1) {
173
+ const ch = s[i];
174
+ const prev = i > 0 ? s[i - 1] : '';
175
+ if (inSingle) {
176
+ if (ch === "'" && prev !== '\\') {
177
+ inSingle = false;
178
+ }
179
+ continue;
180
+ }
181
+ if (inDouble) {
182
+ if (ch === '"' && prev !== '\\') {
183
+ inDouble = false;
184
+ }
185
+ continue;
186
+ }
187
+ if (inTemplate) {
188
+ if (ch === '`' && prev !== '\\') {
189
+ inTemplate = false;
190
+ }
191
+ continue;
192
+ }
193
+ if (ch === "'") {
194
+ inSingle = true;
195
+ continue;
196
+ }
197
+ if (ch === '"') {
198
+ inDouble = true;
199
+ continue;
200
+ }
201
+ if (ch === '`') {
202
+ inTemplate = true;
203
+ continue;
204
+ }
205
+ if (ch === '(' || ch === '[' || ch === '{') {
206
+ depth += 1;
207
+ continue;
208
+ }
209
+ if (ch === ')' || ch === ']' || ch === '}') {
210
+ depth -= 1;
211
+ continue;
212
+ }
213
+ if (ch === ',' && depth === 0) {
214
+ return true;
215
+ }
216
+ }
217
+ return false;
218
+ }
219
+
220
+ export function rewriteForReplPersistence(line) {
221
+ const match = line.match(TOP_LEVEL_DECL_PATTERN);
222
+ if (!match) {
223
+ return line;
224
+ }
225
+ const [, , identifier, valueExpr] = match;
226
+ const trimmedValue = valueExpr.replace(/;\s*$/, '');
227
+ if (hasTopLevelComma(trimmedValue)) {
228
+ // Multi-declarator (`let a = 1, b = 2`) or comma expression at
229
+ // top level. Rewriting would either change semantics (b becomes
230
+ // a sloppy-mode global) or throw under strict mode. Pass through.
231
+ return line;
232
+ }
233
+ return `globalThis.${identifier} =${trimmedValue}`;
234
+ }
235
+
236
+ function formatForDisplay(value) {
237
+ return inspect(value, {
238
+ colors: process.stdout.isTTY === true,
239
+ depth: 4,
240
+ breakLength: 80,
241
+ });
242
+ }
243
+
244
+ export async function runRepl(argv) {
245
+ const output = new Output({
246
+ json: false,
247
+ verbosity: argv.quiet ? 'quiet' : argv.verbose ? 'verbose' : 'normal',
248
+ });
249
+ // Version check kicks off when the REPL starts, runs in parallel
250
+ // with the browser launch, and emits its notice (if any) at session
251
+ // teardown. The check is per-session, not per-line: a long-running
252
+ // REPL won't keep checking the registry.
253
+ const versionCheckPromise = startVersionCheckForCLI({
254
+ argv,
255
+ packageJson: PACKAGE_JSON,
256
+ installedPath: REPL_MODULE_PATH,
257
+ });
258
+
259
+ let server = null;
260
+ let browser = null;
261
+ let rl = null;
262
+
263
+ // Console interceptor: peel result-marker lines off and route them to
264
+ // stdout (formatted), let everything else flow to stderr per default.
265
+ const consoleInterceptor = ({ type, text }) => {
266
+ if (type !== 'log' || !text.startsWith(RESULT_MARKER)) {
267
+ return false;
268
+ }
269
+ const payload = text.slice(RESULT_MARKER.length);
270
+ try {
271
+ const value = decodeResultPayload(payload);
272
+ process.stdout.write(`${formatForDisplay(value)}\n`);
273
+ } catch (err) {
274
+ // Malformed result payload — surface as a debug line rather
275
+ // than crashing the REPL.
276
+ output.error(`[repl] failed to decode result: ${err.message}`);
277
+ }
278
+ return true;
279
+ };
280
+
281
+ try {
282
+ output.timing.start('total');
283
+
284
+ output.timing.start('server-startup');
285
+ server = new Server({ port: argv.port });
286
+ await server.start();
287
+ output.timing.end('server-startup');
288
+ output.debug(`server listening at ${server.origin}`);
289
+
290
+ output.timing.start('browser-launch');
291
+ browser = new Browser({
292
+ browser: argv.browser,
293
+ headed: argv.headed === true,
294
+ consoleStream: process.stderr,
295
+ consoleInterceptor,
296
+ });
297
+ await browser.launch();
298
+ output.timing.end('browser-launch');
299
+
300
+ await browser.goto(`${server.origin}${EVAL_HARNESS_PATH}`, { waitUntil: 'load' });
301
+ await browser.evaluate(() => {
302
+ if (typeof window.evaluateInSandbox !== 'function') {
303
+ throw new Error('window.evaluateInSandbox not exposed by harness');
304
+ }
305
+ });
306
+
307
+ // Endowments inject ONCE per session, before --before scripts
308
+ // and before the readline loop. REPL bypasses the rollup compile pipeline:
309
+ // each line goes directly to `window.evaluateInSandbox(key,
310
+ // source)` via page.evaluate, so the karma-pattern wrapper
311
+ // module isn't on the call path. Instead, the runner runs ONE
312
+ // evaluation at session start that lands the endowments on the
313
+ // per-key SandboxRecord's globalThis. Subsequent REPL lines see
314
+ // the bindings as plain globals because the per-key
315
+ // SandboxRecord persists across module evaluations.
316
+ //
317
+ // A throw during injection (eg an endowment file errors during
318
+ // dynamic-import, or `valueToJsLiteral` rejects a Symbol)
319
+ // surfaces as a pageerror and the runner exits non-zero before
320
+ // the user ever sees the `lws> ` prompt.
321
+ const endowments = await loadEndowments(argv.endowments);
322
+ if (endowments !== null) {
323
+ const assignments = buildEndowmentsReplAssignments(endowments);
324
+ if (assignments.length > 0) {
325
+ await browser.withPageErrorTrap(() =>
326
+ browser.evaluate(({ key, source }) => window.evaluateInSandbox(key, source), {
327
+ key: argv.key,
328
+ source: assignments,
329
+ }),
330
+ );
331
+ }
332
+ }
333
+
334
+ // Before-scripts inject ONCE per session, after endowments +
335
+ // harness verification but before the readline loop. Their
336
+ // globals/side-effects persist for the lifetime of the REPL:
337
+ // every subsequent line evaluated through
338
+ // `window.evaluateInSandbox(key, source)` can read them through
339
+ // the membrane. A throw in any before-script exits non-zero
340
+ // BEFORE the user ever sees the `lws> ` prompt.
341
+ const beforeEntries = await loadScriptFiles(argv.before);
342
+ if (beforeEntries.length > 0) {
343
+ await browser.withPageErrorTrap(() => injectScriptTags(browser, beforeEntries));
344
+ }
345
+
346
+ output.info(
347
+ `lws repl ready (${argv.browser}, key="${argv.key}"). Type .help for commands, .exit or Ctrl+D to quit.`,
348
+ );
349
+
350
+ rl = readline.createInterface({
351
+ input: process.stdin,
352
+ output: process.stdout,
353
+ prompt: PROMPT,
354
+ terminal: process.stdin.isTTY === true,
355
+ });
356
+
357
+ // Continuation buffer: Node-REPL-style implicit multi-line input.
358
+ // When `classifyReplInput` says the buffered source is incomplete
359
+ // (unclosed bracket / unterminated string / trailing operator /
360
+ // trailing `\`), we keep accumulating lines and switch to the
361
+ // continuation prompt. When the buffer becomes complete (or the
362
+ // user types `.exit` mid-buffer, or hits Ctrl+C), we flush.
363
+ const buffer = [];
364
+
365
+ // SIGINT on terminals: if a continuation buffer is in flight,
366
+ // Ctrl+C cancels just the buffer and returns to the main prompt
367
+ // (Node REPL behavior). Otherwise it closes the REPL. Without
368
+ // this, readline's default re-prompts.
369
+ rl.on('SIGINT', () => {
370
+ if (buffer.length > 0) {
371
+ buffer.length = 0;
372
+ process.stdout.write('\n');
373
+ rl.setPrompt(PROMPT);
374
+ rl.prompt();
375
+ return;
376
+ }
377
+ rl.close();
378
+ });
379
+
380
+ rl.prompt();
381
+
382
+ // `for await` is the only safe shape here: an `rl.on('line', async …)`
383
+ // listener runs concurrently with the emitter, so when stdin is a
384
+ // pipe (not a TTY) every queued line fires before the first `await`
385
+ // resolves — including `.exit`, which closes the interface before
386
+ // any evaluation completes. The async iterator pauses the line
387
+ // stream until the loop body returns, serializing input strictly.
388
+ for await (const rawLine of rl) {
389
+ const command = rawLine.trim();
390
+
391
+ // `.break` / `.clear` work mid-buffer — that's their entire
392
+ // purpose: an explicit escape hatch from continuation when
393
+ // Ctrl+C isn't available (piped input, scripted REPL).
394
+ // Dropping them here drains the buffer, resets the prompt,
395
+ // and re-prompts without evaluating anything.
396
+ if (command === '.break' || command === '.clear') {
397
+ buffer.length = 0;
398
+ rl.setPrompt(PROMPT);
399
+ rl.prompt();
400
+ continue;
401
+ }
402
+
403
+ // `.exit` and `.help` only fire on a clean prompt. Mid-
404
+ // buffer they're treated as user code, since the user might
405
+ // genuinely want a string `.exit` inside a template literal
406
+ // or array. This matches Node REPL's behavior.
407
+ if (buffer.length === 0 && command === '.exit') {
408
+ break;
409
+ }
410
+ if (buffer.length === 0 && command === '.help') {
411
+ process.stdout.write(`${HELP_TEXT}\n`);
412
+ rl.prompt();
413
+ continue;
414
+ }
415
+
416
+ buffer.push(rawLine);
417
+ const joined = joinReplBuffer(buffer);
418
+ const trimmed = joined.trim();
419
+
420
+ if (trimmed === '') {
421
+ buffer.length = 0;
422
+ rl.setPrompt(PROMPT);
423
+ rl.prompt();
424
+ continue;
425
+ }
426
+
427
+ const classification = classifyReplInput(joined);
428
+ if (classification === 'incomplete') {
429
+ rl.setPrompt(CONTINUATION_PROMPT);
430
+ rl.prompt();
431
+ continue;
432
+ }
433
+ // Either 'complete' or { error }: flush the buffer either way.
434
+ // Real syntax errors surface as evaluation errors below.
435
+ buffer.length = 0;
436
+ rl.setPrompt(PROMPT);
437
+ try {
438
+ const sourceForSandbox = rewriteForReplPersistence(joined);
439
+ await evalReplLine({ browser, line: sourceForSandbox, sandboxKey: argv.key });
440
+ } catch (err) {
441
+ output.error(err.message);
442
+ }
443
+ rl.prompt();
444
+ }
445
+
446
+ // After-scripts run when the REPL terminates (`.exit`, EOF,
447
+ // Ctrl+D), BEFORE the browser is closed so the DOM state seeded
448
+ // by before-scripts and accumulated across REPL lines is still
449
+ // observable. A throw in any after-script flips the exit code
450
+ // to non-zero, signalling a failed assertion-style after-script.
451
+ const afterEntries = await loadScriptFiles(argv.after);
452
+ if (afterEntries.length > 0) {
453
+ await browser.withPageErrorTrap(() => injectScriptTags(browser, afterEntries));
454
+ }
455
+
456
+ output.timing.end('total');
457
+ return 0;
458
+ } catch (err) {
459
+ output.fail(err);
460
+ return 1;
461
+ } finally {
462
+ // Emit the upgrade notice (if any) at session teardown. Goes to
463
+ // stderr so it doesn't tangle with the result-marker output the
464
+ // REPL writes to stdout.
465
+ await awaitAndEmitUpgradeNotice({
466
+ promise: versionCheckPromise,
467
+ packageJson: PACKAGE_JSON,
468
+ output,
469
+ });
470
+ if (rl) {
471
+ rl.close();
472
+ }
473
+ if (browser) {
474
+ await browser.close();
475
+ }
476
+ if (server) {
477
+ await server.stop();
478
+ }
479
+ }
480
+ }
481
+
482
+ // Hand the line to window.evaluateInSandbox(key, source) directly. The
483
+ // sandbox runtime keys its persistent SandboxRecord on `sandboxKey`, so
484
+ // repeated calls with the same key share the realm — that's how
485
+ // `let x = 1` on line N is reachable as `x` on line N+1.
486
+ //
487
+ // We do NOT route REPL input through the rollup transform path. transform()
488
+ // is the one-shot `lws eval` pipeline: it wraps source in
489
+ // `evaluateInSandbox(key, () => { ... })` and emits a complete IIFE for a
490
+ // classic <script> tag. For REPL we want the raw string source path
491
+ // — `evaluateInSandbox(key, source)` accepts a string and the sandbox
492
+ // runtime compiles + evaluates it inside the existing realm, returning the
493
+ // last expression's value. That's exactly Node REPL semantics.
494
+ async function evalReplLine({ browser, line, sandboxKey }) {
495
+ return browser.evaluate(
496
+ ({ key, source, marker, encoderSrc }) => {
497
+ // Build the encoder via the Function constructor on the page
498
+ // side — this avoids both string-concatenation eval on the Node
499
+ // side (security hook) and indirect eval inside the sandbox
500
+ // (eval is distorted). The encoder is a plain function expr.
501
+ // eslint-disable-next-line no-new-func
502
+ const encode = new Function(`return (${encoderSrc})`)();
503
+ let result;
504
+ let threw = false;
505
+ let errMessage = null;
506
+ try {
507
+ result = window.evaluateInSandbox(key, source);
508
+ } catch (err) {
509
+ threw = true;
510
+ errMessage = err && err.message ? err.message : String(err);
511
+ }
512
+ if (threw) {
513
+ // eslint-disable-next-line no-console
514
+ console.error(`[repl error] ${errMessage}`);
515
+ return;
516
+ }
517
+ // eslint-disable-next-line no-console
518
+ console.log(marker + encode(result));
519
+ },
520
+ {
521
+ key: sandboxKey,
522
+ source: line,
523
+ marker: RESULT_MARKER,
524
+ encoderSrc: buildResultEncoder(),
525
+ },
526
+ );
527
+ }