@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/README.md ADDED
@@ -0,0 +1,813 @@
1
+ # `@locker/cli` — `lws` command-line tool
2
+
3
+ > **Evaluate JavaScript or render Lightning Web Components inside a real Lightning Web Security sandbox, in a real browser, from your terminal.** No hosted console. No JSDOM mock. No "works on my machine" between dev and prod.
4
+
5
+ ## Why `lws`
6
+
7
+ For years, the way to see how your code behaved under Lightning Web Security was to open the web-based LWS Console — a hosted website maintained on shared infrastructure, gated behind auth, slow to iterate against, and impossible to script. `lws` replaces it with something better in every dimension:
8
+
9
+ - **Production-faithful, not approximated.** Other tools mock the browser (JSDOM, happy-dom) or mock the sandbox (custom test harnesses). `lws` does neither. It boots a real Chromium / Firefox / WebKit / Chrome via Playwright, loads the **same `@locker/sandbox` runtime that ships in production Salesforce orgs**, and runs your code through the real near-membrane proxies and real distortions. What you see is what your users get.
10
+ - **Local, fast, scriptable.** A round trip is ~1 second from `lws eval "..."` to "transformed source on stdout, console output on stderr, exit code 0." Pipe it. Loop it. Wire it into your editor. CI it. The web console couldn't do any of those.
11
+ - **Three workflows, one tool.** Quick eval of a snippet (`lws eval`), full LWC component render with the production compiler (`lws component`), or an interactive REPL with persistent state (`lws repl`) — all share the same shared options, the same trust boundary, and the same sandbox runtime. Learn one, use three.
12
+ - **The compile pipeline is the real one too.** `lws component` runs `@lwc/rollup-plugin` with `enableLightningWebSecurityTransforms: true` — the same flag, same plugin, same transforms used to ship your component to production. You're not testing against a "close enough" build; you're testing the actual binary your users will run.
13
+ - **`--headed` mode opens a real browser window.** Need DevTools? Need to inspect the DOM after a distortion fired? Need to set a breakpoint inside the membrane? Pass `--headed` and the browser stays open after evaluation, with all your usual tooling available. No more printf-debugging through `console.log`.
14
+ - **`--browser=chrome` uses your installed Google Chrome.** When the question is "does my code work in the binary my users have," there's no substitute for the actual binary. Playwright's chromium-with-channel feature lets you point at the installed Chrome (or Edge) in seconds.
15
+ - **The REPL is genuinely useful.** Not a textarea-on-a-page imitation: real `node:readline`, real multi-line input auto-detection (open a brace, hit Enter, keep typing), real `util.inspect` pretty-printing, `.help` / `.break` / `.clear` / `.exit` dot-commands, persistent sandbox state across lines. Built like a REPL should be, all the way down.
16
+ - **Zero deployment required.** No hosted infrastructure to maintain, no auth to navigate, no rate limits, no "is the console up today?" Slack threads. The tool ships with your code, runs on your laptop, and is yours to break.
17
+
18
+ ## When to use it
19
+
20
+ - **Reproduce a sandbox-related bug** — paste the failing snippet into `lws eval`, see exactly what the transform pipeline does to it, see exactly what the runtime does on top.
21
+ - **Investigate a distortion** — write a one-liner that exercises the API, run it under `lws eval --headed`, set a breakpoint inside the distortion, watch it fire.
22
+ - **Validate a fix locally before pushing** — `lws component ./my-fix` renders against the production compile + runtime in seconds. Fast inner loop = better fixes.
23
+ - **Learn the LWS surface** — `lws repl`, type things, see what happens. Every distortion is one line of input away.
24
+ - **Wire it into CI** — exits non-zero on transform errors, browser launch failures, or sandbox-side throws. Stable enough to gate PRs on.
25
+ - **Demo a security property** — show that `document.cookie = 'evil=true'` throws `LockerSecurityError`, with a real browser screenshot in `--headed` mode if you need it. The console couldn't compete with that either.
26
+
27
+ ## What you get
28
+
29
+ Three subcommands, each with a clearly-shaped contract:
30
+
31
+ - **`lws eval`** — evaluate a JS string or file inside the sandbox; prints the transformed source on stdout and forwards browser console output to stderr.
32
+ - **`lws component`** — compile an LWC component directory (using `@lwc/rollup-plugin` with `enableLightningWebSecurityTransforms: true`) and render it inside the sandbox; prints the compiled bundle on stdout and forwards lifecycle/render output to stderr.
33
+ - **`lws repl`** — open an interactive REPL backed by a single long-lived browser + sandbox; multi-line input is auto-detected, expression results are pretty-printed.
34
+ - **`--before` / `--after`** are shared across all three subcommands. Inject system-mode `<script>` tags before (and after) sandboxed user code. Repeatable, argv-order, accepts either a file path or an inline JS string. Use them to seed the DOM, register fixtures, or assert post-execution state.
35
+ - **`--endowments`** is shared across all three subcommands. Inject a JSON, JS, or inline-object value as the 4th argument of `evaluateInSandbox`, exposing those properties to sandboxed code as bare identifiers AND on `globalThis`. **Functions are invocable from inside the sandbox.** In `repl` the bindings persist across every line typed at the prompt.
36
+ - **`--timeout <ms>`** aborts an `lws eval` run after the deadline and exits non-zero. Composes with `--endowments`: endowments inject before the timeout race starts.
37
+
38
+ ---
39
+
40
+ ## Install
41
+
42
+ ### As a user (most people)
43
+
44
+ Install from npm. `@locker/cli` ships with a `lws` bin so the command is on your PATH after install (or invokable via `npx`).
45
+
46
+ ```sh
47
+ # Globally — `lws` is available everywhere
48
+ npm install -g @locker/cli
49
+ # or:
50
+ yarn global add @locker/cli
51
+
52
+ # Or per-project — invoke via npx / yarn dlx without installing
53
+ npx @locker/cli eval "console.log('hello')"
54
+
55
+ # Or as a project devDependency — invoke via your local node_modules/.bin
56
+ npm install --save-dev @locker/cli
57
+ yarn add --dev @locker/cli
58
+ ```
59
+
60
+ After install, install at least one Playwright browser binary. The npm package can't ship them — they're hundreds of megabytes per browser and licensed separately.
61
+
62
+ ```sh
63
+ # Default: just chromium
64
+ npx playwright install chromium
65
+
66
+ # Or all three engines (chromium, firefox, webkit)
67
+ npx playwright install
68
+ ```
69
+
70
+ If you want to use `--browser=chrome`, you also need the actual Google Chrome installed on your machine (Playwright launches your installed Chrome rather than downloading one).
71
+
72
+ Verify the install:
73
+
74
+ ```sh
75
+ lws --version
76
+ lws eval "console.log('hello-world')"
77
+ ```
78
+
79
+ ### As a contributor (working in the LWS monorepo)
80
+
81
+ ```sh
82
+ yarn install # from the repo root, installs all workspaces
83
+ yarn build # from packages/@locker/cli, builds the dist/ bundles
84
+ npx playwright install chromium # one-time per machine
85
+ ```
86
+
87
+ Then invoke via `node bin/lws.mjs <command>` from the package directory, or via the workspace-resolved `lws <command>`.
88
+
89
+ ---
90
+
91
+ ## System requirements
92
+
93
+ - **Node.js `^22.22.3`** (uses ESM, top-level `await`, and `node:readline` async iteration).
94
+ - **A supported OS for Playwright**: macOS 12+, recent Linux distros, Windows 10+.
95
+ - **Disk space**: ~150 MB per Playwright browser binary you install.
96
+
97
+ ---
98
+
99
+ ## Subcommand: `lws eval`
100
+
101
+ Evaluate JavaScript inside the LWS sandbox.
102
+
103
+ ```
104
+ lws eval <code-or-file> [options]
105
+ ```
106
+
107
+ `<code-or-file>` accepts:
108
+ - An inline JavaScript string (e.g. `"console.log('hello')"`)
109
+ - A path to a `.js` file
110
+ - `-` to read from stdin
111
+
112
+ **Output**:
113
+ - **stdout** — the transformed source, after `@locker/rollup-plugin` has applied LWS compile-time transforms (unforgeable property rewrites, async-to-generator, etc.). This is exactly what runs inside the sandbox.
114
+ - **stderr** — `[browser:log]`/`[browser:error]`/`[browser:pageerror]` lines, one per console event from the page.
115
+
116
+ **Exit codes**: semantic, per the error-classification contract below: `0` normal completion, `10` confirmed security verdict (LockerSecurityError), `20` unsignaled throw, `1` harness/infra failure (transform error, browser launch failure, timeout). See [Error classification and completion](#error-classification-and-completion).
117
+
118
+ ### Examples
119
+
120
+ ```sh
121
+ # Inline source
122
+ lws eval "console.log('hello-cli')"
123
+
124
+ # Source from a file
125
+ lws eval ./my-script.js
126
+
127
+ # Source from stdin
128
+ echo "console.log('from-stdin')" | lws eval -
129
+
130
+ # Try a forbidden mutation; observe the LockerSecurityError on stderr
131
+ lws eval "document.cookie = 'evil=true'"
132
+
133
+ # Open a visible browser window so you can poke around in DevTools
134
+ lws eval ./my-script.js --headed
135
+
136
+ # Run in Firefox instead of headless Chromium
137
+ lws eval ./my-script.js --browser=firefox
138
+
139
+ # Use your installed Google Chrome (uses Playwright's chromium launcher with channel=chrome)
140
+ lws eval ./my-script.js --browser=chrome --headed
141
+
142
+ # Pin a specific sandbox key (default: "cli")
143
+ lws eval ./my-script.js --key=my-component
144
+
145
+ # Seed the system-mode DOM before the sandbox runs (inline)
146
+ lws eval --before "document.body.dataset.user = 'alice'" \
147
+ "console.log(document.body.dataset.user)"
148
+
149
+ # Same with a file
150
+ lws eval --before ./fixtures/seed-dom.js ./my-script.js
151
+
152
+ # Multiple before-scripts inject in argv order
153
+ lws eval --before ./fixtures/a.js --before ./fixtures/b.js ./my-script.js
154
+
155
+ # After-script as a system-mode assertion: throws on failure, exits non-zero
156
+ lws eval \
157
+ --before "document.body.dataset.value = 'before'" \
158
+ --after "if (document.body.dataset.value !== 'after') throw new Error('did not mutate')" \
159
+ "document.body.dataset.value = 'after'"
160
+
161
+ # Inject endowments via inline JSON; visible inside the sandbox as bare
162
+ # identifiers AND on globalThis.
163
+ lws eval --endowments '{"GREETING": "hello", "USER_ID": 42}' \
164
+ 'console.log(GREETING + " user " + USER_ID)'
165
+
166
+ # Inject endowments from a .json file
167
+ lws eval --endowments ./fixtures/endow.json ./my-script.js
168
+
169
+ # .mjs / .cjs files work too (default export becomes the endowments
170
+ # object). Function values are invocable from inside the sandbox:
171
+ # a Node-side `add: (a, b) => a + b` shows up as a real callable.
172
+ lws eval --endowments ./fixtures/endow.mjs ./my-script.js
173
+
174
+ # Timeout: kill long-running evaluations and exit non-zero
175
+ lws eval --timeout 5000 ./my-script.js
176
+
177
+ # Endowments + timeout compose: setup, then bounded evaluation
178
+ lws eval --endowments '{"BASE_URL": "https://api.example.com"}' --timeout 3000 \
179
+ ./my-fetch-script.js
180
+ ```
181
+
182
+ ---
183
+
184
+ ## Subcommand: `lws component`
185
+
186
+ Compile and render an LWC component inside the LWS sandbox.
187
+
188
+ ```
189
+ lws component <directory> [options]
190
+ ```
191
+
192
+ `<directory>` is the path to an LWC component directory. It must contain `<name>.js` and `<name>.html` matching the directory name (e.g. `helloWorld/helloWorld.js` + `helloWorld/helloWorld.html`).
193
+
194
+ The compiler runs with `enableLightningWebSecurityTransforms: true` — the same flag used in production Salesforce orgs. Sibling-namespace imports (e.g. `c-wrapped-box` from `helloWorld.html`) resolve via the directory's grandparent as the LWC modules root.
195
+
196
+ **Output**:
197
+ - **stdout** — the compiled IIFE bundle for the component (the per-invocation script that the harness page loads).
198
+ - **stderr** — browser console output, including LWC lifecycle callbacks (`connectedCallback`, `renderedCallback`, etc.) if your component logs from them.
199
+
200
+ **Component-specific flags**:
201
+ - `--name <tag-name>` — override the derived custom-element tag name. By default the tag is camelCase → kebab-case (`helloWorld` → `hello-world`).
202
+ - `--namespace <ns>` — override the LWC namespace. Default is `c`.
203
+ - `--lwc-modules <dir>`: additional LWC namespace-root directory the compiler should resolve imports from. Repeatable; argv-order is preserved (first match wins). Layered before the implicit grandparent default, so an explicit `--lwc-modules` path takes precedence when both have the same `<ns>/<name>`. Use this to point the compiler at vendored or first-party component sources (`lightning/`, `ui/`, project-local namespaces, etc.) that live outside the component's own directory tree.
204
+
205
+ ### Examples
206
+
207
+ ```sh
208
+ # Render the bundled hello-world fixture (from packages/@locker/cli)
209
+ lws component ./test/fixtures/c/helloWorld
210
+
211
+ # Open the rendered component in a visible browser window
212
+ lws component ./test/fixtures/c/helloWorld --headed
213
+
214
+ # Use installed Chrome with DevTools available
215
+ lws component ./test/fixtures/c/helloWorld --browser=chrome --headed
216
+
217
+ # Override the custom-element tag name
218
+ lws component ./my-component --name=my-custom-tag
219
+
220
+ # Use a non-default LWC namespace
221
+ lws component ./my-component --namespace=lightning
222
+
223
+ # Seed system-mode DOM before the component renders (inline before-script)
224
+ lws component ./test/fixtures/c/helloWorld \
225
+ --before "document.body.dataset.theme = 'dark'"
226
+
227
+ # Assert against the rendered DOM after stabilization (after-script)
228
+ lws component ./test/fixtures/c/helloWorld \
229
+ --after "if (!document.querySelector('hello-world')) throw new Error('component did not mount')"
230
+
231
+ # Inject endowments visible to the component (bare identifiers + globalThis)
232
+ lws component ./my-component --endowments '{"BASE_URL": "https://api.example.com"}'
233
+
234
+ # Endowments from a .js file. Function values are invocable inside the
235
+ # component (e.g. from connectedCallback or renderedCallback).
236
+ # fixtures/endow.mjs:
237
+ # export default { GREETING: 'alice', makeGreeting: (n) => 'hello ' + n };
238
+ lws component ./my-component --endowments ./fixtures/endow.mjs
239
+
240
+ # Resolve imports from a vendored namespace tree outside the component's
241
+ # own directory. The directory is the namespace ROOT (the parent of the
242
+ # `<ns>/` subdirs), not a single namespace dir.
243
+ # ./vendor/components/
244
+ # lightning/button/button.js
245
+ # ui/spinner/spinner.js
246
+ # Either namespace import resolves through one --lwc-modules root:
247
+ lws component ./my-component --lwc-modules ./vendor/components
248
+
249
+ # Render a component that imports from BOTH lightning/ and ui/ when
250
+ # the two namespaces live in disjoint trees. Repeat the flag; argv-order
251
+ # is preserved (first match wins).
252
+ lws component ./my-component \
253
+ --lwc-modules ./vendor/lightning-base \
254
+ --lwc-modules ./vendor/ui-base
255
+ ```
256
+
257
+ ---
258
+
259
+ ## Subcommand: `lws repl`
260
+
261
+ Open an interactive REPL backed by a persistent LWS sandbox.
262
+
263
+ ```
264
+ lws repl [options]
265
+ ```
266
+
267
+ The REPL launches a browser, loads the sandbox harness once, then accepts JavaScript input line-by-line. State persists across lines because the sandbox runtime keys its realm on `--key`; reusing the same key (the default `cli`) hits the same realm on every evaluation.
268
+
269
+ **Multi-line input** is auto-detected: open a bracket / paren / brace / string / template literal and hit Enter. The prompt switches from `lws> ` to `... ` while buffering, and the buffer flushes when the input becomes syntactically complete. Trailing `\` at end-of-line forces continuation even when the line is complete on its own.
270
+
271
+ **Dot-commands**:
272
+
273
+ | Command | Effect |
274
+ |---|---|
275
+ | `.help` | Print the command list and behavior notes |
276
+ | `.break` | Cancel a multi-line input in progress, return to the main prompt |
277
+ | `.clear` | Alias for `.break` |
278
+ | `.exit` | Exit the REPL (also: Ctrl+D / EOF) |
279
+
280
+ **Output**:
281
+ - **stdout** — the prompt (`lws> ` or `... `) and the `util.inspect`-formatted result of each evaluated expression.
282
+ - **stderr** — `[browser:log]`/`[browser:error]`/`[browser:pageerror]` lines from sandboxed code's console output.
283
+
284
+ ### Examples
285
+
286
+ ```sh
287
+ # Start a REPL session
288
+ lws repl
289
+
290
+ # Use Firefox
291
+ lws repl --browser=firefox
292
+
293
+ # Open a visible browser alongside the prompt (useful for inspecting DOM
294
+ # mutations made from the REPL via DevTools while the session is live)
295
+ lws repl --headed --browser=chrome
296
+
297
+ # Pin a sandbox key — repeated invocations against the same key share the
298
+ # realm across REPL sessions (until the browser closes).
299
+ lws repl --key=playground
300
+
301
+ # Seed a cookie at session start; print it back at session end.
302
+ lws repl --before "document.cookie = 'blue=true'" --after "console.log(document.cookie)"
303
+
304
+ # Multi-before-script argv order; after-script runs at .exit / EOF / Ctrl+D
305
+ lws repl \
306
+ --before ./fixtures/seed-dom.js \
307
+ --before "document.body.dataset.session = 'demo'" \
308
+ --after "console.log('final:', document.body.dataset.session)"
309
+
310
+ # Inject endowments. The bindings are visible on every REPL line as
311
+ # plain globals; they persist for the lifetime of the session.
312
+ lws repl --endowments '{"GREETING": "hello", "USER_ID": 42}'
313
+ # lws> GREETING
314
+ # 'hello'
315
+ # lws> USER_ID + 1
316
+ # 43
317
+
318
+ # Endowments from a .js file. Function values are callable from any
319
+ # REPL line.
320
+ # fixtures/endow.mjs:
321
+ # export default { add: (a, b) => a + b, greet: (n) => 'hi ' + n };
322
+ lws repl --endowments ./fixtures/endow.mjs
323
+ # lws> add(3, 4)
324
+ # 7
325
+ # lws> greet('alice')
326
+ # 'hi alice'
327
+ ```
328
+
329
+ ### Sample session
330
+
331
+ ```
332
+ $ lws repl
333
+ lws repl ready (chromium, key="cli"). Type .help for commands, .exit or Ctrl+D to quit.
334
+ lws> 1 + 2
335
+ 3
336
+ lws> let arr = [1, 2, 3]
337
+ [ 1, 2, 3 ]
338
+ lws> arr.push(4)
339
+ 4
340
+ lws> arr
341
+ [ 1, 2, 3, 4 ]
342
+ lws> let double = function(n) {
343
+ ... return n * 2
344
+ ... }
345
+ lws> double(21)
346
+ 42
347
+ lws> .exit
348
+ $
349
+ ```
350
+
351
+ ---
352
+
353
+ ## Shared options
354
+
355
+ These flags apply to all three subcommands.
356
+
357
+ | Flag | Type | Default | Effect |
358
+ |---|---|---|---|
359
+ | `--browser <name>` | `chromium` \| `firefox` \| `webkit` \| `chrome` | `chromium` | Which browser to launch. `chrome` uses Playwright's chromium launcher with the installed Google Chrome channel — useful when you want to test against the actual Chrome binary your users have. |
360
+ | `--headed` | boolean | `false` | Open a visible browser window. The default is headless. In headed mode, `eval` and `component` keep the browser open until you press Ctrl+C, so you can poke around in DevTools. |
361
+ | `--key <id>` | string | `cli` | Sandbox key identifier. Reusing the same key hits the same persistent realm in the sandbox runtime — that's how `repl` accumulates state across lines. |
362
+ | `--port <n>` | number | `0` | Local HTTP server port. `0` means "auto-select a free port." Useful only if you have a tool that needs to know the URL ahead of time. |
363
+ | `--before <file-or-inline>` | string (repeatable) | none | Inject a system-mode `<script>` BEFORE sandboxed user code runs. Each occurrence takes one value, which is either a path to a `.js`/`.mjs`/`.cjs` file or an inline JavaScript string (same heuristic as `eval`'s positional). Multiple `--before` flags inject in argv order, each as its own `<script>` (so `var x` in one file does not collide with `var x` in another). A throw in any before-script exits non-zero before the sandbox runs. In `repl`, before-script injection happens once per session, before the prompt appears; the seeded state persists across every REPL line. |
364
+ | `--after <file-or-inline>` | string (repeatable) | none | Inject a system-mode `<script>` AFTER sandboxed user code runs. Same shape as `--before` (file or inline, repeatable, argv-order). Use it for assertion-style checks: a throw in any after-script flips the exit code to non-zero, signalling a failed run. In `repl`, after-scripts run at session termination (`.exit`, EOF, Ctrl+D) BEFORE the browser closes, so DOM state accumulated across REPL lines is still observable. |
365
+ | `--endowments <value>` | string | none | Inject an object into the sandbox as the 4th argument of `evaluateInSandbox(key, source, context, endowments)`. Inside the sandbox, the object's properties are visible as bare identifiers AND on `globalThis`. The value is one of: a path to a `.json` file (read + parsed), a path to a `.js`/`.mjs`/`.cjs` file (dynamic-imported, default export becomes the object), or an inline JSON string. **Function values are invocable from inside the sandbox**: a Node-side `(a, b) => a + b` shows up as a real callable. In `repl`, the bindings persist for the lifetime of the session and are visible on every line. Symbols, Maps, Sets, Dates, and other non-plain-object values throw at registration time. |
366
+ | `--json` | boolean | `false` | Emit a single JSON envelope on stdout at exit instead of plain text. The envelope shape is `{ ok: true, result, timing }` on success and `{ ok: false, error: { message, name }, timing }` on failure. `info()`/`debug()` output is silenced (consumers expect exactly one line). Exit code still reflects success. The envelope is buffered and flushed once at teardown so a sandbox throw after compile collapses into a single `ok: false` line: JSON consumers never see a half-state. **Not allowed with `repl`** (an interactive prompt has no terminal envelope point). |
367
+ | `--quiet` | boolean | `false` | Suppress `info()`, `debug()`, and `result()` output. Errors still print to stderr. Not allowed with `--verbose`. |
368
+ | `--verbose` | boolean | `false` | Print `debug()`-level messages to stderr (server URL, input origin, span markers). Not allowed with `--quiet`. |
369
+
370
+ ### Eval-only options
371
+
372
+ These flags apply to `lws eval` only.
373
+
374
+ | Flag | Type | Default | Effect |
375
+ |---|---|---|---|
376
+ | `--timeout <ms>` | number | none (no timeout) | Abort the sandbox evaluation after `<ms>` milliseconds. The runner force-closes the browser via the standard teardown path (same one SIGINT uses) and exits non-zero with `evaluation timed out after <ms>ms` on stderr. Catches infinite loops, hung awaits, and slow distortion paths. Does NOT catch browser-launch hangs (which happen before the race) or before-script hangs (before-scripts inject before the timeout starts). The flag is accepted at parse time on `component` and `repl` too but is not yet wired there. |
377
+
378
+ ### Built-in flags
379
+
380
+ | Flag | Effect |
381
+ |---|---|
382
+ | `--help` | Print yargs usage |
383
+ | `--version` | Print package version |
384
+
385
+ ### Version check
386
+
387
+ Every invocation kicks off a non-blocking check against the npm registry to see whether a newer `@locker/cli` is published. If one is, a single line lands on stderr at exit:
388
+
389
+ ```
390
+ Update available for @locker/cli: 0.28.1 -> 0.29.0. Run `npm i -g @locker/cli` to upgrade.
391
+ ```
392
+
393
+ The notice goes to stderr only, never stdout, so `--json` envelopes stay single-line and shell pipelines that consume stdout are unaffected.
394
+
395
+ The check is cached for 24h at `~/.cache/lws-cli/version-check.json`. Within the window, no network call is made. The fetch itself has a 1.5s timeout, so an unreachable registry never adds visible latency.
396
+
397
+ The check is suppressed in three cases:
398
+ - `--quiet` is passed (the flag also suppresses other diagnostics).
399
+ - The package's `package.json` declares `"private": true` (the pre-publish state).
400
+ - The package is running from a path outside any `node_modules` directory (contributor dev loops in the monorepo source tree).
401
+
402
+ ---
403
+
404
+ ## Before-script / after-script recipes
405
+
406
+ Before-scripts and after-scripts are the recommended way to compose **system-mode** state around your sandboxed run. They're injected as plain `<script>` tags into the harness page, so they run with full system-mode trust (full DOM access, no membrane in front of them, no `@locker/rollup-plugin` transform applied).
407
+
408
+ ### When to use which
409
+
410
+ - **`--before`** sets up the system-mode environment your sandbox code reads from. Seed DOM nodes, register fetch mocks, drop fixtures into `document.body.dataset`, attach event listeners on the system-mode side.
411
+ - **`--after`** asserts against the result of your sandbox code. Check that a DOM mutation landed (or didn't), that a side-effect fired exactly once, that no unexpected nodes leaked. A throw fails the run with a non-zero exit code.
412
+
413
+ ### How sandbox code "sees" before-script state (read this first)
414
+
415
+ The LWS sandbox runs each `evaluateInSandbox(key, ...)` call in a **separate proxied realm**. The sandbox's `window` is its own global namespace, distinct from the host page's window. **Direct global reads from inside the sandbox do NOT see the system-mode `window`.** That is:
416
+
417
+ ```js
418
+ // Before-script (system-mode):
419
+ globalThis.MARKER = 'visible-from-sandbox?';
420
+
421
+ // Sandboxed code (sees an entirely different `window`):
422
+ console.log(globalThis.MARKER); // → undefined
423
+ ```
424
+
425
+ The membrane bridges sandbox code to the system-mode DOM, so DOM mutations made by a before-script *are* visible to the sandbox. Use the DOM as your channel, not globals:
426
+
427
+ ```js
428
+ // Before-script (system-mode):
429
+ document.body.dataset.marker = 'visible-from-sandbox';
430
+
431
+ // Sandboxed code (reads the DOM through the membrane):
432
+ console.log(document.body.dataset.marker); // → 'visible-from-sandbox'
433
+ ```
434
+
435
+ ### Recipe: distortion smoke test (eval)
436
+
437
+ Demonstrate that a forbidden cookie write is blocked, with a before-script that seeds the "before" state and an after-script that asserts the "after":
438
+
439
+ ```sh
440
+ lws eval \
441
+ --before "document.cookie = 'before=ok'" \
442
+ --after "if (!document.cookie.includes('before=ok')) throw new Error('cookie was clobbered')" \
443
+ "try { document.cookie = 'attack=true'; } catch (e) {}"
444
+ ```
445
+
446
+ ### Recipe: REPL session warm-up + final-state dump
447
+
448
+ Pre-populate the DOM at session start and dump the final cookie state at session end:
449
+
450
+ ```sh
451
+ lws repl --before "document.cookie = 'blue=true'" --after "console.log(document.cookie)"
452
+ ```
453
+
454
+ Inside the REPL, every line you type sees the before-script-seeded state through the membrane. The after-script fires at `.exit` (or EOF), printing the final cookie state via the browser-console pump (which appears as `[browser:log] blue=true` on stderr).
455
+
456
+ ### Recipe: argv-order composition
457
+
458
+ Multiple `--before`/`--after` flags inject in argv order, each as its own `<script>` element:
459
+
460
+ ```sh
461
+ lws eval \
462
+ --before "document.body.dataset.order = 'A'" \
463
+ --before "document.body.dataset.order += 'B'" \
464
+ --before "document.body.dataset.order += 'C'" \
465
+ "console.log('order:', document.body.dataset.order)"
466
+ # stderr: order: ABC
467
+ ```
468
+
469
+ Because each value is a separate `<script>`, top-level `var`/`let` declarations in one before-script don't collide with the next:
470
+
471
+ ```sh
472
+ lws eval \
473
+ --before "var leaked = 'one'; document.body.dataset.one = leaked" \
474
+ --before "var leaked = 'two'; document.body.dataset.two = leaked" \
475
+ "console.log(document.body.dataset.one, document.body.dataset.two)"
476
+ # stderr: one two
477
+ ```
478
+
479
+ ### Recipe: file-based fixtures
480
+
481
+ For non-trivial fixtures, point at a `.js` file. The path heuristic matches `eval`'s positional: anything ending in `.js`/`.mjs`/`.cjs` (or containing a `/`) is treated as a path.
482
+
483
+ ```sh
484
+ # fixtures/seed.js:
485
+ # document.body.innerHTML = '<input id="email"><input id="pw">';
486
+ # window.fetchMockData = { user: { id: 1 } };
487
+
488
+ lws eval --before ./fixtures/seed.js ./my-script.js
489
+ ```
490
+
491
+ ### Recipe: process-substitution for one-off inline files
492
+
493
+ For when you want the structure of a file but the ergonomics of inline source, your shell already has the answer:
494
+
495
+ ```sh
496
+ lws eval --before <(cat <<'JS'
497
+ document.body.dataset.user = 'alice';
498
+ document.body.dataset.role = 'admin';
499
+ JS
500
+ ) "console.log('user:', document.body.dataset.user)"
501
+ ```
502
+
503
+ Bash and zsh expand `<(...)` to a temporary file path, which `lws` reads as a normal before-script file.
504
+
505
+ ---
506
+
507
+ ## Endowments and timeout recipes
508
+
509
+ `--endowments` works with all three subcommands: `eval`, `component`, and `repl`. It injects directly into the sandbox's evaluation scope, so the object's properties are visible as bare identifiers and on `globalThis` inside sandboxed code. **Function values are invocable** from inside the sandbox. In `repl`, the bindings persist for the lifetime of the session and are visible on every line.
510
+
511
+ `--timeout` is `eval`-only today (component and repl accept the flag but don't yet observe it). It bounds the run: useful when scripting `lws` into CI or wrapping a tool that might hang.
512
+
513
+ ### When endowments vs. before-scripts
514
+
515
+ - **`--endowments`** is the right channel when sandboxed code wants to read a value as a plain global. Examples: a base URL, a feature-flag map, a user ID, a fixture function the script will call, an object the script will iterate over. Properties land on `globalThis` AND as bare identifiers, so `console.log(USER_ID)` works. Functions transport intact: `add(3, 4)` returns `7`.
516
+ - **`--before`** is the right channel when you want to seed the **system-mode** DOM, register a fetch mock, or attach event listeners on the host page. Sandbox code reads through the membrane via DOM APIs.
517
+
518
+ A single invocation can combine both: before-script seeds DOM, endowments seeds globals, sandbox code reads from both channels through their respective paths.
519
+
520
+ ### Recipe: parameterize a sandbox script via inline JSON
521
+
522
+ ```sh
523
+ lws eval --endowments '{"BASE_URL": "https://api.example.com", "API_KEY": "demo-key"}' \
524
+ 'console.log(BASE_URL + "/users?key=" + API_KEY)'
525
+ # stderr: https://api.example.com/users?key=demo-key
526
+ ```
527
+
528
+ ### Recipe: load endowments from a JSON file
529
+
530
+ For non-trivial fixture shapes, factor the JSON into a file:
531
+
532
+ ```sh
533
+ # fixtures/endow.json:
534
+ # { "BASE_URL": "...", "ROUTES": [...], "FEATURES": {...} }
535
+
536
+ lws eval --endowments ./fixtures/endow.json ./my-script.js
537
+ ```
538
+
539
+ ### Recipe: computed endowments via a `.js` file
540
+
541
+ When the values need to be computed at load time (timestamps, env-derived values, or functions), use a `.js`/`.mjs`/`.cjs` file whose default export is the endowments object:
542
+
543
+ ```js
544
+ // fixtures/endow.mjs
545
+ export default {
546
+ NOW: Date.now(),
547
+ ENV: process.env.NODE_ENV ?? 'development',
548
+ HASH: 'abc123',
549
+ formatGreeting: (name) => `hello, ${name}`,
550
+ };
551
+ ```
552
+
553
+ ```sh
554
+ lws eval --endowments ./fixtures/endow.mjs ./my-script.js
555
+ ```
556
+
557
+ ### Recipe: function endowments
558
+
559
+ Function values transport intact and are callable from any sandboxed context (`eval` source, component lifecycle hooks, REPL lines):
560
+
561
+ ```js
562
+ // fixtures/api-helpers.mjs
563
+ export default {
564
+ USER_ID: 42,
565
+ buildUrl: (path) => `https://api.example.com/v1${path}`,
566
+ parseJson: (text) => JSON.parse(text),
567
+ };
568
+ ```
569
+
570
+ ```sh
571
+ # eval: invoke the helper inline
572
+ lws eval --endowments ./fixtures/api-helpers.mjs \
573
+ 'console.log(buildUrl("/users/" + USER_ID))'
574
+ # stderr: https://api.example.com/v1/users/42
575
+
576
+ # component: connectedCallback can call the helper
577
+ lws component --endowments ./fixtures/api-helpers.mjs ./my-component
578
+
579
+ # repl: the helper is on every line
580
+ lws repl --endowments ./fixtures/api-helpers.mjs
581
+ # lws> buildUrl('/me')
582
+ # 'https://api.example.com/v1/me'
583
+ ```
584
+
585
+ **Closures don't survive.** A function endowment's source text is what reaches the sandbox, not its lexical scope. A closure-capturing helper like `let count = 0; const next = () => ++count;` will start at `count = 0` inside the sandbox each time it's reached because the `count` reference resolves anew. For shared mutable state, put the state on the endowment object itself (e.g. `{ counter: { n: 0 }, next() { return ++this.counter.n; } }`).
586
+
587
+ **Unsupported value types throw at registration.** Symbols, Maps, Sets, Dates, RegExps, and other non-plain-object values throw a clear error before the run starts (better than D8.2's earlier silent-drop behavior).
588
+
589
+ ### Recipe: REPL session with endowments
590
+
591
+ Endowments make `lws repl` a useful interactive harness for poking at sandbox-wrapped APIs:
592
+
593
+ ```sh
594
+ # fixtures/probes.mjs
595
+ # export default {
596
+ # fetchMock: async (url) => { /* ... */ },
597
+ # distortion: (api) => { /* introspect distortion behavior */ },
598
+ # };
599
+
600
+ lws repl --endowments ./fixtures/probes.mjs
601
+ # lws> distortion('Worker')
602
+ # { distorted: true, throws: ['blob:'], allows: ['/'] }
603
+ # lws> await fetchMock('/users/42')
604
+ # { id: 42, name: 'alice' }
605
+ ```
606
+
607
+ The bindings are set once at session start and persist across every line. Combine with `--before` to seed both the sandbox globals (`--endowments`) and the system-mode DOM (`--before`).
608
+
609
+ ### Recipe: bound a hung-evaluation suspect
610
+
611
+ ```sh
612
+ # Aborts after 5 seconds and exits non-zero
613
+ lws eval --timeout 5000 ./my-suspect.js
614
+ ```
615
+
616
+ The teardown path is identical to SIGINT: browser closed, server stopped, no leaked processes. Useful for CI gates: a `--timeout` set just above your worst-case-acceptable runtime catches regressions before they hang the build.
617
+
618
+ ### Recipe: endowments + timeout in CI
619
+
620
+ ```sh
621
+ lws eval \
622
+ --endowments '{"BASE_URL": "https://staging.example.com", "TIMEOUT_BUDGET": 3000}' \
623
+ --timeout 10000 \
624
+ ./scripts/smoke-test.js
625
+ ```
626
+
627
+ Endowments parameterize the test (different `BASE_URL` per environment); the timeout enforces an outer bound that's larger than the script's internal budget but small enough to fail fast when the run actually deadlocks.
628
+
629
+ ---
630
+
631
+ ## Structured output and verbosity
632
+
633
+ Three flags control how `lws` presents its output: `--json` for machine-readable consumers, `--quiet` for "just give me the exit code," and `--verbose` for diagnostic noise. They apply across all three subcommands (with the noted exception that `--json` is not allowed with `repl`).
634
+
635
+ ### `--json` envelope
636
+
637
+ `--json` emits exactly one JSON line on stdout at exit. Consumers can parse it without buffering or stream-splitting.
638
+
639
+ Success:
640
+ ```json
641
+ {
642
+ "ok": true,
643
+ "result": "/* transformed source */",
644
+ "timing": { "compile": 12.3, "server-startup": 7.1, "browser-launch": 240.7, "evaluation": 18.0, "total": 280.5 }
645
+ }
646
+ ```
647
+
648
+ Failure:
649
+ ```json
650
+ {
651
+ "ok": false,
652
+ "error": { "message": "evaluation timed out after 50ms", "name": "Error" },
653
+ "timing": { "compile": 11.8, "server-startup": 6.9, "browser-launch": 235.1, "evaluation": 50.0, "total": 305.4 }
654
+ }
655
+ ```
656
+
657
+ ```bash
658
+ # Pipe a single envelope into jq
659
+ lws eval --json "1 + 1" | jq .
660
+
661
+ # Bash one-liner: did this run succeed?
662
+ lws eval --json ./flaky.js | jq -e '.ok' >/dev/null && echo OK || echo FAIL
663
+
664
+ # Fail-fast watcher: capture timing.total per run
665
+ while inotifywait -e modify ./script.js; do
666
+ lws eval --json --timeout 5000 ./script.js | jq '.timing.total'
667
+ done
668
+
669
+ # Stdin + JSON: useful in shell pipelines that synthesize source on the fly
670
+ echo "console.log(7 * 6)" | lws eval --json -
671
+ ```
672
+
673
+ The single-envelope contract holds even when the run partially succeeds and then fails. If compilation produces a transformed source (which would normally print to stdout) but the sandbox subsequently throws, the envelope reflects the **final** outcome: `ok: false` with the throw's message. JSON consumers never see two lines.
674
+
675
+ `info()` and `debug()` output is silenced in `--json` mode so the single-line contract holds. Sandbox-side `console.log` from inside the user's code is a separate channel and still streams to stderr (it's user-controlled output, not runner diagnostics).
676
+
677
+ ### Error classification and completion
678
+
679
+ This section is a normative contract. Other tools and agents build on top of it, so the definitions below are precise and stable.
680
+
681
+ #### The model: completion records
682
+
683
+ `lws` models the outcome of a run on the JavaScript Completion Record (ECMA-262, sec-completion-record-specification-type). A run is evaluated at a Script top-level boundary, so the spec's five completion types collapse to a clean binary: a run either completes `normal` or it `throw`s. (`return`, `break`, and `continue` cannot escape a Script boundary, so they are not representable outcomes.)
684
+
685
+ Only a `throw` completion carries a security verdict, classified from the thrown value.
686
+
687
+ #### The security-verdict taxonomy
688
+
689
+ | Verdict | Means | Does NOT mean |
690
+ |---|---|---|
691
+ | `confirmed` | A LockerSecurityError was observed. LWS actively blocked an operation. In triage terms: vector CLOSED. | (n/a) |
692
+ | `unsignaled` | An ordinary error (TypeError, ReferenceError, etc.) with no known tie to a distortion. | It does NOT mean "safe". It is the absence of a security verdict, not proof of safety. |
693
+ | `ambiguous` | Reserved. A non-security error raised on a known soft-fail distorted API surface. Detection is a follow-up; the term and its exit code are reserved so the contract is complete. | (n/a) |
694
+
695
+ The crucial epistemic point: "non-LockerSecurityError errors don't specifically mean a security issue" is why the second branch must be named `unsignaled`, not `safe` or `none`. It is the absence of a security verdict, not proof of safety. Naming it honestly is what keeps a machine consumer from over-reading a TypeError as "all clear".
696
+
697
+ #### Detection rule
698
+
699
+ A `confirmed` verdict is detected by the LockerSecurityError message PREFIX (`"Lightning Web Security: "`), never by `instanceof` or by `error.name`. Two reasons: the near-membrane proxy boundary makes `instanceof` unreliable across realms, and LockerSecurityError does not set `this.name` (so `error.name` is `"Error"`, not `"LockerSecurityError"`). The message is read in-page, before the thrown value crosses to the CLI as an opaque proxy, so the prefix is intact. The prefix is the only reliable signal.
700
+
701
+ #### Exit-code contract
702
+
703
+ The exit code is a semantic verdict (the grep/diff family: exit 1 means "no match" or "files differ", a meaningful RESULT, not a failure), so a script can branch on the outcome without parsing JSON.
704
+
705
+ | Outcome | Verdict | Exit | Triage reading |
706
+ |---|---|---|---|
707
+ | normal completion | (n/a) | `0` | often OPEN: the op was NOT blocked |
708
+ | throw | `confirmed` | `10` | CLOSED: LWS blocked it |
709
+ | throw | `unsignaled` | `20` | inconclusive: non-security failure |
710
+ | throw | `ambiguous` | `30` | needs human triage (reserved) |
711
+ | harness/infra failure (launch, server bind, timeout, interrupt, usage): no completion produced | (n/a) | `1` | tooling problem, not a verdict |
712
+
713
+ A confirmed security block is exit `10`, deliberately NOT `0`. "Success" is caller-relative: a block is the desired outcome in a triage run but a failure in a plain eval run, so the category stays descriptive and the caller decides how to read it. Harness failures stay at the generic code `1`, so `1` keeps its meaning and the semantic codes are purely additive.
714
+
715
+ A throw in a `--before` or `--after` script also exits `1`, not `10`/`20`. Those scripts are system-mode assertion code, not sandboxed code: a throw in one is caught at the harness boundary (it never produces a sandbox completion), so it folds into the harness-failure bucket. The semantic verdict codes describe the SANDBOXED run's outcome only. If you need a before/after assertion's pass or fail as a distinct signal, read its own output rather than the process exit code.
716
+
717
+ Spoofability: the verdict keys on the message prefix, so sandboxed code can force a `confirmed` verdict by throwing an error whose own message starts with `"Lightning Web Security: "`. This is a self-inflicted spoof inside a triage harness, not a boundary the CLI defends. Treat exit `10` as "a LockerSecurityError-shaped throw occurred," which is exactly what triage wants.
718
+
719
+ #### The Completion Report (JSON)
720
+
721
+ With `--json`, the envelope carries an additive `completion` field. The legacy `ok`, `result`, and `error` fields keep their meaning, so existing consumers do not break. The compiled `result` is present on both success and throw envelopes (a compile-then-throw run does not lose it).
722
+
723
+ Normal completion:
724
+ ```json
725
+ {
726
+ "ok": true,
727
+ "result": "/* compiled source */",
728
+ "completion": { "type": "normal", "value": { "resultType": "undefined" } },
729
+ "timing": { "total": 280.5 }
730
+ }
731
+ ```
732
+
733
+ Throw completion with a confirmed verdict:
734
+ ```json
735
+ {
736
+ "ok": false,
737
+ "result": "/* compiled source */",
738
+ "error": { "message": "Lightning Web Security: Cannot create Worker with .", "name": "Error" },
739
+ "completion": {
740
+ "type": "throw",
741
+ "value": {
742
+ "securityVerdict": "confirmed",
743
+ "errorName": "Error",
744
+ "message": "Lightning Web Security: Cannot create Worker with ."
745
+ }
746
+ },
747
+ "timing": { "total": 285.4 }
748
+ }
749
+ ```
750
+
751
+ A harness/infra failure (timeout, launch error) produces NO completion, so the `completion` field is absent and the exit code is `1`. This is how a consumer distinguishes "the sandbox threw" from "the tooling broke".
752
+
753
+ ```bash
754
+ # Branch on the verdict without parsing JSON: assert a vector is CLOSED.
755
+ lws eval "new Worker('')"; [ $? -eq 10 ] && echo CLOSED || echo OPEN
756
+
757
+ # Read the structured verdict from the envelope.
758
+ lws eval --json "new Worker('')" | jq -r '.completion.value.securityVerdict'
759
+ ```
760
+
761
+ ### `--quiet` and `--verbose`
762
+
763
+ ```bash
764
+ # Quiet: nothing on stdout, only errors on stderr. Useful for "just tell me
765
+ # if it passes" smoke runs in CI.
766
+ lws eval --quiet ./script.js && echo PASS
767
+
768
+ # Verbose: surface debug() messages (server URL, input origin, span markers).
769
+ # Useful when something is wrong and the default output isn't enough.
770
+ lws eval --verbose ./script.js
771
+ ```
772
+
773
+ `--quiet` and `--verbose` together is a contradiction (suppress info vs. show debug); the combination is not allowed and exits with `--quiet and --verbose are mutually exclusive; pick one`.
774
+
775
+ ### `--json` and `lws repl`
776
+
777
+ `lws repl --json` is not allowed:
778
+
779
+ ```
780
+ $ lws repl --json
781
+ --json is not supported in `lws repl` (interactive prompt has no terminal envelope point)
782
+ ```
783
+
784
+ A REPL by definition produces output as the user types, with no single "end of run" point at which a JSON envelope could land. Per-line envelopes would also break consumers that parse one line per invocation. If you want structured output from a sequence of evaluations, drive `lws eval --json` from a shell loop instead.
785
+
786
+ ---
787
+
788
+ ## How it works (briefly)
789
+
790
+ Each invocation does roughly the same dance:
791
+
792
+ 1. **Start a local HTTP server** (`node:http`, no extra dependency) that serves a static harness page (`eval.html` or `component.html`), the build-time IIFE bundles (`lws-sandbox.js`, `lwc-engine.js`, `purify.js`), and any per-invocation compiled bundles.
793
+ 2. **Launch a browser** via Playwright. The harness page loads DOMPurify, the LWS sandbox runtime, and (for `component`) the LWC engine — all in **system mode**, before any sandboxed user code runs.
794
+ 3. **Inject the user's code**:
795
+ - `eval` — the source is run through `@locker/rollup-plugin`, wrapped in `evaluateInSandbox(key, () => { ... })`, and added as a `<script>` tag.
796
+ - `component` — the directory is compiled via `@lwc/rollup-plugin` with the production LWS flag, then served as a per-invocation bundle and loaded by the harness.
797
+ - `repl` — each line is handed directly to `window.evaluateInSandbox(key, source)` via `page.evaluate`.
798
+ 4. **Capture browser console output** through Playwright's page-console events and forward to stderr.
799
+ 5. **Tear down**: close the browser, stop the server, clean up any temp files. SIGINT/SIGTERM trigger an orderly shutdown.
800
+
801
+ The trust boundary mirrors production: the LWS engine and runtime run in **system mode**; your code runs **inside the sandbox** with the membrane and all distortions active.
802
+
803
+ ---
804
+
805
+ ## Troubleshooting
806
+
807
+ **`Browser was not found`** — run `npx playwright install chromium` (or `firefox`/`webkit`) once per machine. Playwright's npm package doesn't ship binaries.
808
+
809
+ **Hanging on launch with `--browser=chrome`** — `chrome` requires an installed Google Chrome on your system (not a Chromium download). On macOS, `brew install --cask google-chrome` or download from google.com/chrome.
810
+
811
+ **`window.evaluateInSandbox not exposed by harness`** — the package's `dist/` is missing or stale. Run `yarn build` from `packages/@locker/cli` to rebuild the IIFE bundles.
812
+
813
+ **REPL prompt looks doubled (`lws> lws> 5`) when piping input** — that's expected. In non-TTY mode the prompt and the result share stdout without redraw; the visual artifact has no effect on functionality.