@locker/cli 0.28.4 → 0.28.5

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 CHANGED
@@ -227,6 +227,8 @@ The compiler runs with `enableLightningWebSecurityTransforms: true` — the same
227
227
  - `--name <tag-name>` — override the derived custom-element tag name. By default the tag is camelCase → kebab-case (`helloWorld` → `hello-world`).
228
228
  - `--namespace <ns>` — override the LWC namespace. Default is `c`.
229
229
  - `--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.
230
+ - `--wire-mode <mode>`: auto-mock the component's `@wire` adapters so it renders on a laptop with no scratch-org deploy. Takes an explicit value: `--wire-mode=success` feeds each adapter fabricated data (the data branch); `--wire-mode=error` fires each adapter's error callback instead (the error branch), so you can exercise a component's error UI. There is no bare form; the value must be `success` or `error`. See "Wire auto-mocking" below for how the data is chosen and how it is reported. Omit the flag entirely and adapters are left untouched (the default). Config key: `wireMode`.
231
+ - `--wire-fixtures <adapter>=<path-to-json>`: supply your own mock data for one adapter, overriding whatever `--wire-mode` would have chosen for it. `<adapter>` is either the module specifier (`lightning/uiRecordApi`) or the adapter export name (`getRecord`); `<path-to-json>` is a JSON file whose parsed contents become the adapter's `data`. Repeatable (one adapter per occurrence, last wins on a duplicate). A file that is missing or is not valid JSON fails the run before a browser launches. Only meaningful together with `--wire-mode`. Config key: `wireFixtures`.
230
232
 
231
233
  ### Examples
232
234
 
@@ -282,6 +284,57 @@ lws component ./my-component --lwc-modules ./vendor/components
282
284
  lws component ./my-component \
283
285
  --lwc-modules ./vendor/lightning-base \
284
286
  --lwc-modules ./vendor/ui-base
287
+
288
+ # Auto-mock a component's @wire adapters so it renders locally with no
289
+ # scratch-org deploy. Every adapter gets fabricated data, and a
290
+ # [wire mock] marker prints to stderr per adapter.
291
+ lws component ./my-component --wire-mode=success
292
+
293
+ # Exercise the component's error UI instead: every adapter fires its
294
+ # error callback rather than its data callback.
295
+ lws component ./my-component --wire-mode=error
296
+
297
+ # Supply your own data for one adapter, letting the rest auto-mock.
298
+ # The adapter can be named by module specifier or by export name.
299
+ lws component ./my-component \
300
+ --wire-mode=success \
301
+ --wire-fixtures getRecord=./fixtures/record.json
302
+ ```
303
+
304
+ ### Wire auto-mocking (`--wire-mode` / `--wire-fixtures`)
305
+
306
+ An LWC that uses `@wire` normally needs a live Salesforce org: `lightning/uiRecordApi`, `@salesforce/schema/*`, and `@salesforce/apex/*` all resolve to org-provided modules that do not exist on a laptop. Without them the compile externalizes the import and the render throws at runtime on the missing binding. `--wire-mode` closes that gap by supplying each `@wire` adapter a synthetic implementation so the component renders locally.
307
+
308
+ **Turning it on.** `--wire-mode` takes an explicit value:
309
+
310
+ - `--wire-mode=success` feeds every adapter fabricated data (fires the adapter's data callback).
311
+ - `--wire-mode=error` fires every adapter's error callback instead, with a `FetchResponse`-shaped error object, so a component's error branch and error UI are exercised.
312
+
313
+ There is no bare `--wire-mode`; the value is required and must be `success` or `error`. Omit the flag and adapters are untouched (unchanged from a normal `lws component` run).
314
+
315
+ **Where the fake data comes from.** For each adapter, the data is resolved through a four-step ladder, highest priority first:
316
+
317
+ 1. **Your override.** A `--wire-fixtures <adapter>=<path.json>` for that adapter. The parsed JSON becomes the adapter's `data` verbatim.
318
+ 2. **A curated shape.** For a known platform adapter (`getRecord`, `getRecords`, `getObjectInfo`, `getPicklistValues`, `getRelatedListRecords`), a hand-authored shape that matches the adapter's real payload. Values for the `@salesforce/schema` fields the component declares are filled in from the field name (a `Name` field gets a plausible name string, and so on).
319
+ 3. **An inferred shape.** For any other adapter (including `@salesforce/apex/*` methods), the component's own source is scanned for the `this.<wired>.data.<path>` properties it reads, and an object with exactly those paths present is synthesized. This is enough to get the component past its `if (this.x.data)` guards and render.
320
+ 4. **Empty.** If none of the above apply, the adapter emits `null` data (the component renders in its no-data state).
321
+
322
+ **How it is reported.** Fabricated data must never be mistaken for real data, so every mocked adapter prints one line to stderr:
323
+
324
+ ```
325
+ [wire mock] getRecord -> A/success
326
+ ```
327
+
328
+ The suffix names which rung of the ladder supplied the data (`override`, `A` for curated, `B` for inferred, or `null`) and the mode (`success` or `error`). One line per adapter.
329
+
330
+ **Overriding one adapter.** `--wire-fixtures <adapter>=<path.json>` supplies your own data for a single adapter while the rest auto-mock. Name the adapter by module specifier (`lightning/uiRecordApi`) or by export name (`getRecord`). The flag is repeatable (one adapter per occurrence, last wins if you name the same adapter twice). A path that is missing or is not valid JSON fails the run before a browser launches, so a typo is caught immediately rather than surfacing as a confusing render error.
331
+
332
+ ```sh
333
+ # fixtures/record.json:
334
+ # { "fields": { "Name": { "value": "Acme Corp" } } }
335
+ lws component ./recordCard \
336
+ --wire-mode=success \
337
+ --wire-fixtures getRecord=./fixtures/record.json
285
338
  ```
286
339
 
287
340
  ---
@@ -505,7 +558,7 @@ export default {
505
558
  };
506
559
  ```
507
560
 
508
- Keys are camelCase because a few flags are kebab-case on the command line: `--lwc-modules` is `lwcModules`, `--gates-on` is `gatesOn`, and `--gates-off` is `gatesOff` in the file. Everything else is the flag name verbatim (`browser`, `headed`, `key`, `port`, `before`, `after`, `endowments`, `timeout`, `json`, `quiet`, `verbose`, `watch`, `name`, `namespace`). The array-valued keys (`before`, `after`, `lwcModules`, `gatesOn`, `gatesOff`) take an array of strings; `gatesOn`/`gatesOff` also accept a single comma-separated string for convenience. An unknown key (a typo like `broswer`) fails the run with a message naming the offending key and the file it came from, so a misspelling never silently does nothing.
561
+ Keys are camelCase because a few flags are kebab-case on the command line: `--lwc-modules` is `lwcModules`, `--gates-on` is `gatesOn`, `--gates-off` is `gatesOff`, and `--wire-mode` is `wireMode` in the file. Everything else is the flag name verbatim (`browser`, `headed`, `key`, `port`, `before`, `after`, `endowments`, `timeout`, `json`, `quiet`, `verbose`, `watch`, `name`, `namespace`, `wireFixtures`). The array-valued keys (`before`, `after`, `lwcModules`, `gatesOn`, `gatesOff`, `wireFixtures`) take an array of strings; `gatesOn`/`gatesOff` also accept a single comma-separated string for convenience. `wireMode` is a single string (`'success'` or `'error'`); `wireFixtures` is an array of `<adapter>=<path.json>` strings. An unknown key (a typo like `broswer`) fails the run with a message naming the offending key and the file it came from, so a misspelling never silently does nothing.
509
562
 
510
563
  ### How a config value is resolved (the cascade)
511
564
 
package/bin/lws.mjs CHANGED
@@ -4,7 +4,7 @@ import { hideBin } from 'yargs/helpers';
4
4
  import yargs from 'yargs/yargs';
5
5
 
6
6
  import { BUILTIN_DEFAULTS, resolveConfig } from '../src/config-resolver.mjs';
7
- import { SUPPORTED_BROWSERS } from '../src/constants.mjs';
7
+ import { SUPPORTED_BROWSERS, WIRE_MOCK_MODES } from '../src/constants.mjs';
8
8
  import { assertPlaywrightInstalled } from '../src/playwright-check.mjs';
9
9
 
10
10
  // The command modules (runner.mjs, repl.mjs) statically import
@@ -273,6 +273,40 @@ await yargs(hideBin(process.argv))
273
273
  nargs: 1,
274
274
  default: config.lwcModules ?? BUILTIN_DEFAULTS.lwcModules,
275
275
  })
276
+ // Wire auto-mocking (D16). Takes an explicit value:
277
+ // --wire-mode=success renders each @wire adapter with fake
278
+ // data; --wire-mode=error fires its error branch instead.
279
+ // There is no bare form: yargs cannot express a
280
+ // bare-or-`=value` optional-value flag that is also safe next
281
+ // to the required <directory> positional (a bare flag
282
+ // greedily consumes the positional as its value). A plain
283
+ // string+choices option sidesteps that: the value only
284
+ // attaches via `=`, so the positional is never eaten, and
285
+ // yargs validates the value natively, so argv.wireMode is
286
+ // already `undefined | 'success' | 'error'` with no coercion.
287
+ // WIRE_MOCK_MODES comes from constants.mjs (Playwright-free)
288
+ // so this validates without loading wire-mock.mjs + babel.
289
+ .option('wire-mode', {
290
+ describe:
291
+ 'Auto-mock @wire adapters so the component renders locally: =success fills fake data, =error fires the error branch. Prints a [wire mock] marker per adapter.',
292
+ choices: WIRE_MOCK_MODES,
293
+ type: 'string',
294
+ default: config.wireMode ?? BUILTIN_DEFAULTS.wireMode,
295
+ })
296
+ // Per-adapter explicit fixture data, overriding the auto shape.
297
+ // Repeatable `<adapter>=<path-to-json>`, argv-order (last
298
+ // wins on a duplicate adapter). The adapter is a module
299
+ // specifier (lightning/uiRecordApi) or an export name
300
+ // (getRecord). Same array/nargs:1 shape as --lwc-modules;
301
+ // the config key is camelCase (wireFixtures).
302
+ .option('wire-fixtures', {
303
+ describe:
304
+ 'Explicit fixture data for one @wire adapter: <adapter>=<path-to-json> (repeatable). Overrides the auto-mock shape for that adapter.',
305
+ type: 'string',
306
+ array: true,
307
+ nargs: 1,
308
+ default: config.wireFixtures ?? BUILTIN_DEFAULTS.wireFixtures,
309
+ })
276
310
  .option('watch', {
277
311
  describe: 'Re-compile and reload when files in the directory change',
278
312
  type: 'boolean',
package/dist/index.cjs.js CHANGED
@@ -2,4 +2,4 @@
2
2
  * Copyright (C) 2026 salesforce.com, inc.
3
3
  */
4
4
  'use strict';
5
- /*! version: 0.28.4 */
5
+ /*! version: 0.28.5 */
package/dist/index.mjs.js CHANGED
@@ -2,4 +2,4 @@
2
2
  * Copyright (C) 2026 salesforce.com, inc.
3
3
  */
4
4
 
5
- /*! version: 0.28.4 */
5
+ /*! version: 0.28.5 */
@@ -1369,7 +1369,7 @@
1369
1369
  // reads identically to what isGaterEnabledFeature stores (register and
1370
1370
  // deregister also accept the short form via fullName above). Frozen so a
1371
1371
  // consumer cannot mutate the shared array.
1372
- Object.freeze([`${FEATURE_NAME_PREFIX$LWS}changesSince.256`, `${FEATURE_NAME_PREFIX$LWS}changesSince.258`, `${FEATURE_NAME_PREFIX$LWS}changesSince.260`, `${FEATURE_NAME_PREFIX$LWS}changesSince.262`, `${FEATURE_NAME_PREFIX$LWS}changesSince.264`, `${FEATURE_NAME_PREFIX$LWS}htmlAnchorElementHrefValidation`, `${FEATURE_NAME_PREFIX$LWS}enableSandboxedSameOriginIframe`, `${FEATURE_NAME_PREFIX$LWS}xmlEntityAttackPrologScan`]);
1372
+ Object.freeze([`${FEATURE_NAME_PREFIX$LWS}changesSince.260`, `${FEATURE_NAME_PREFIX$LWS}changesSince.262`, `${FEATURE_NAME_PREFIX$LWS}changesSince.264`, `${FEATURE_NAME_PREFIX$LWS}htmlAnchorElementHrefValidation`, `${FEATURE_NAME_PREFIX$LWS}enableSandboxedSameOriginIframe`, `${FEATURE_NAME_PREFIX$LWS}xmlEntityAttackPrologScan`]);
1373
1373
  function registerGaterEnabledFeatures$LWS(lockerGaterEnabledFeatures$LWS) {
1374
1374
  if (ArrayIsArray$LWS$1(lockerGaterEnabledFeatures$LWS)) {
1375
1375
  lockerGaterEnabledFeatures$LWS.forEach(feature$LWS => gaterEnabledFeatures$LWS.add(fullName$LWS(feature$LWS)));
@@ -1539,7 +1539,7 @@
1539
1539
  const PromiseResolve$LWS = PromiseCtor$LWS.resolve.bind(PromiseCtor$LWS);
1540
1540
  const PromiseReject$LWS = PromiseCtor$LWS.reject.bind(PromiseCtor$LWS);
1541
1541
  toSafeSet$LWS(new SetCtor$LWS$1());
1542
- /*! version: 0.28.4 */
1542
+ /*! version: 0.28.5 */
1543
1543
 
1544
1544
  /*!
1545
1545
  * Copyright (C) 2019 salesforce.com, inc.
@@ -2284,11 +2284,8 @@
2284
2284
  return false;
2285
2285
  }
2286
2286
  function hasTag$LWS(input$LWS, tag$LWS) {
2287
- let checkableInput$LWS = input$LWS;
2288
- if (isGaterEnabledFeature$LWS('changesSince.256')) {
2289
- // Input is already lowercased and invisible chars stripped by caller
2290
- checkableInput$LWS = ReflectApply$LWS$1(StringProtoReplace$LWS, input$LWS, [/\s+/g, ' ']);
2291
- }
2287
+ // Input is already lowercased and invisible chars stripped by caller
2288
+ const checkableInput$LWS = ReflectApply$LWS$1(StringProtoReplace$LWS, input$LWS, [/\s+/g, ' ']);
2292
2289
  // Match <tag or :tag (namespaced) followed by whitespace, >, /
2293
2290
  // Also match when directly followed by src or srcdoc (null byte was stripped)
2294
2291
  const tagPattern$LWS = new RegExpCtor$LWS$1(`[<:]${tag$LWS}(?:[\\s>/]|(?=src))`);
@@ -2622,7 +2619,7 @@
2622
2619
  const XhrProtoResponseTextGetter$LWS = ObjectLookupOwnGetter$LWS$1(XhrProto$LWS, 'responseText');
2623
2620
  const XhrProtoStatusGetter$LWS = ObjectLookupOwnGetter$LWS$1(XhrProto$LWS, 'status');
2624
2621
  ObjectLookupOwnSetter$LWS(XhrProto$LWS, 'withCredentials');
2625
- /*! version: 0.28.4 */
2622
+ /*! version: 0.28.5 */
2626
2623
 
2627
2624
  /*!
2628
2625
  * Copyright (C) 2019 salesforce.com, inc.
@@ -2790,7 +2787,7 @@
2790
2787
  }
2791
2788
  return sanitized$LWS;
2792
2789
  }
2793
- /*! version: 0.28.4 */
2790
+ /*! version: 0.28.5 */
2794
2791
 
2795
2792
  /*!
2796
2793
  * Copyright (C) 2023 salesforce.com, inc.
@@ -2866,7 +2863,7 @@
2866
2863
  // swallow
2867
2864
  }
2868
2865
  const trusted = createPolicy('trusted', policyOptions);
2869
- /*! version: 0.28.4 */
2866
+ /*! version: 0.28.5 */
2870
2867
 
2871
2868
  /*!
2872
2869
  * Copyright (C) 2019 salesforce.com, inc.
@@ -3175,7 +3172,7 @@
3175
3172
  }
3176
3173
  return getSanitizerForConfig$LWS(sandboxKey$LWS, 'STRING_BLOB_HTML');
3177
3174
  }
3178
- /*! version: 0.28.4 */
3175
+ /*! version: 0.28.5 */
3179
3176
 
3180
3177
  /*!
3181
3178
  * Copyright (C) 2023 salesforce.com, inc.
@@ -3384,7 +3381,7 @@
3384
3381
  ReflectApply$LWS$1(ElementProtoSetAttributeNS$LWS, targetElement$LWS, [attributeNamespaceURI$LWS, attributeName$LWS, src$LWS]);
3385
3382
  };
3386
3383
  }
3387
- /*! version: 0.28.4 */
3384
+ /*! version: 0.28.5 */
3388
3385
 
3389
3386
  /*!
3390
3387
  * Copyright (C) 2019 salesforce.com, inc.
@@ -5488,14 +5485,8 @@
5488
5485
  }
5489
5486
  const childWindow$LWS = ReflectApply$LWS$1(originalDocumentOpen$LWS, this, normalizedArgs$LWS);
5490
5487
  // istanbul ignore next: behavior will not be tested in collection coverage
5491
- if (!isGaterEnabledFeature$LWS('changesSince.262')) {
5492
- if (isGaterEnabledFeature$LWS('changesSince.256')) {
5493
- if (isSameOriginURL$LWS(resourceUrl$LWS)) {
5494
- markForUnsafePropertyBlocking$LWS(childWindow$LWS);
5495
- }
5496
- } else {
5497
- markForUnsafePropertyBlocking$LWS(childWindow$LWS);
5498
- }
5488
+ if (!isGaterEnabledFeature$LWS('changesSince.262') && isSameOriginURL$LWS(resourceUrl$LWS)) {
5489
+ markForUnsafePropertyBlocking$LWS(childWindow$LWS);
5499
5490
  }
5500
5491
  if (childWindow$LWS) {
5501
5492
  initWindowOpenChildWindow$LWS(childWindow$LWS, resourceUrl$LWS);
@@ -7884,14 +7875,12 @@
7884
7875
  if (urlString$LWS && !isValidURLScheme$LWS(urlString$LWS)) {
7885
7876
  throw new LockerSecurityError$LWS('HTMLIFrameElement.src supports http://, https:// schemes, relative urls and about:blank.');
7886
7877
  }
7887
- if (isGaterEnabledFeature$LWS('changesSince.258')) {
7888
- const parsedURL$LWS = parseURL$LWS(urlString$LWS);
7889
- if (!isAllowedEndpointURL$LWS(parsedURL$LWS)) {
7890
- const {
7891
- normalizedURL: normalizedURL$LWS
7892
- } = parsedURL$LWS;
7893
- throw new LockerSecurityError$LWS(`Cannot request disallowed endpoint: ${toSafeTemplateStringValue$LWS(normalizedURL$LWS)}`);
7894
- }
7878
+ const parsedURL$LWS = parseURL$LWS(urlString$LWS);
7879
+ if (!isAllowedEndpointURL$LWS(parsedURL$LWS)) {
7880
+ const {
7881
+ normalizedURL: normalizedURL$LWS
7882
+ } = parsedURL$LWS;
7883
+ throw new LockerSecurityError$LWS(`Cannot request disallowed endpoint: ${toSafeTemplateStringValue$LWS(normalizedURL$LWS)}`);
7895
7884
  }
7896
7885
  // Same-origin URLs go through an async pre-flight that fetches
7897
7886
  // the resource and runs its body through the rootValidator
@@ -8822,7 +8811,7 @@
8822
8811
  const descriptor$LWS = ReflectGetOwnPropertyDescriptor$LWS(HTMLScriptElement$LWS.prototype, 'textContent');
8823
8812
  // This may not be implemented in all browsers.
8824
8813
  // https://www.w3.org/TR/trusted-types/#enforcement-in-scripts
8825
- if (!isGaterEnabledFeature$LWS('changesSince.256') || !descriptor$LWS) {
8814
+ if (!descriptor$LWS) {
8826
8815
  return noop$LWS$1;
8827
8816
  }
8828
8817
  // istanbul ignore next: currently not implemented in Chrome (used for coverage collection)
@@ -8853,7 +8842,7 @@
8853
8842
  const descriptor$LWS = ReflectGetOwnPropertyDescriptor$LWS(HTMLScriptElement$LWS.prototype, 'textContent');
8854
8843
  // This may not be implemented in all browsers.
8855
8844
  // https://www.w3.org/TR/trusted-types/#enforcement-in-scripts
8856
- if (!isGaterEnabledFeature$LWS('changesSince.256') || !descriptor$LWS) {
8845
+ if (!descriptor$LWS) {
8857
8846
  return noop$LWS$1;
8858
8847
  }
8859
8848
  // istanbul ignore next: currently not implemented in Chrome (used for coverage collection)
@@ -11890,9 +11879,6 @@
11890
11879
  return noop$LWS$1;
11891
11880
  }
11892
11881
  const distortionEntry$LWS = [originalFetchLater$LWS, function fetchLater$LWS(...args$LWS) {
11893
- if (!isGaterEnabledFeature$LWS('changesSince.258')) {
11894
- return ReflectApply$LWS$1(originalFetchLater$LWS, this, args$LWS);
11895
- }
11896
11882
  // Let the native method handle missing parameters error or null/undefined URL case.
11897
11883
  let {
11898
11884
  0: url$LWS
@@ -12279,14 +12265,8 @@
12279
12265
  }
12280
12266
  const childWindow$LWS = ReflectApply$LWS$1(originalWindowOpen$LWS, this, normalizedArgs$LWS);
12281
12267
  // istanbul ignore next: behavior will not be tested in collection coverage
12282
- if (!isGaterEnabledFeature$LWS('changesSince.262')) {
12283
- if (isGaterEnabledFeature$LWS('changesSince.256')) {
12284
- if (isSameOriginURL$LWS(resourceUrl$LWS)) {
12285
- markForUnsafePropertyBlocking$LWS(childWindow$LWS);
12286
- }
12287
- } else {
12288
- markForUnsafePropertyBlocking$LWS(childWindow$LWS);
12289
- }
12268
+ if (!isGaterEnabledFeature$LWS('changesSince.262') && isSameOriginURL$LWS(resourceUrl$LWS)) {
12269
+ markForUnsafePropertyBlocking$LWS(childWindow$LWS);
12290
12270
  }
12291
12271
  // W-14218118
12292
12272
  // If the target is '_self', '_parent', or '_top', only makes one request
@@ -12370,7 +12350,7 @@
12370
12350
  // Defer transforming source text asynchronously.
12371
12351
  sandboxEvaluator$LWS(transformSourceText$LWS(sourceText$LWS), UNCOMPILED_CONTEXT$LWS);
12372
12352
  };
12373
- } else if (isGaterEnabledFeature$LWS('changesSince.256')) {
12353
+ } else {
12374
12354
  throwIfUnsafeCallbackReference$LWS(callback$LWS);
12375
12355
  }
12376
12356
  }
@@ -12407,7 +12387,7 @@
12407
12387
  // Defer transforming source text asynchronously.
12408
12388
  sandboxEvaluator$LWS(transformSourceText$LWS(sourceText$LWS), UNCOMPILED_CONTEXT$LWS);
12409
12389
  };
12410
- } else if (isGaterEnabledFeature$LWS('changesSince.256')) {
12390
+ } else {
12411
12391
  throwIfUnsafeCallbackReference$LWS(callback$LWS);
12412
12392
  }
12413
12393
  }
@@ -12789,7 +12769,7 @@
12789
12769
  const UIEventProtoBlockedProperties$LWS = ['rangeParent'];
12790
12770
  const WindowBlockedProperties$LWS = ['find', 'requestFileSystem', 'webkitRequestFileSystem'];
12791
12771
  const XSLTProcessorProtoBlockedProperties$LWS = ['transformToDocument', 'transformToFragment'];
12792
- /*! version: 0.28.4 */
12772
+ /*! version: 0.28.5 */
12793
12773
 
12794
12774
  /*!
12795
12775
  * Copyright (C) 2021 salesforce.com, inc.
@@ -12798,7 +12778,7 @@
12798
12778
  function getPdpSchema$LWS() {
12799
12779
  return pdpSchema$LWS;
12800
12780
  }
12801
- /*! version: 0.28.4 */
12781
+ /*! version: 0.28.5 */
12802
12782
 
12803
12783
  /*!
12804
12784
  * Copyright (C) 2019 salesforce.com, inc.
@@ -18190,7 +18170,7 @@
18190
18170
  // tools from mistaking the regexp or the replacement string for an
18191
18171
  // actual source mapping URL.
18192
18172
  /\/\/# sandbox(?=MappingURL=.*?\s*$)/, '//# source']);
18193
- sourceText$LWS = `\n//# LWS Version = "0.28.4"\n${sourceText$LWS}`;
18173
+ sourceText$LWS = `\n//# LWS Version = "0.28.5"\n${sourceText$LWS}`;
18194
18174
  return sourceType$LWS === 1 /* SourceType.Module */ && indexOfPragma$LWS(sourceText$LWS, 'use strict') === -1 ?
18195
18175
  // Append "'use strict'" to the extracted function body so it is
18196
18176
  // evaluated in strict mode.
@@ -18870,7 +18850,7 @@
18870
18850
  }
18871
18851
  toSafeMap$LWS$1(new MapCtor$LWS$1());
18872
18852
  toSafeSet$LWS(new SetCtor$LWS$1(['lightning/platformResourceLoader', 'lightning:platformResourceLoader', 'lightningmobileruntime/platformResourceLoader', 'lightningmobileruntime:platformResourceLoader']));
18873
- /*! version: 0.28.4 */
18853
+ /*! version: 0.28.5 */
18874
18854
 
18875
18855
  // Expose evaluateInSandbox on the window global so the browser harness page
18876
18856
  // (eval.html / component.html) can invoke it against source delivered by the
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@locker/cli",
3
- "version": "0.28.4",
3
+ "version": "0.28.5",
4
4
  "license": "SEE LICENSE IN LICENSE.txt",
5
5
  "author": "Salesforce UI Security Team",
6
6
  "description": "Lightning Web Security CLI",
@@ -26,9 +26,10 @@
26
26
  "test:integration": "jest --config jest.config.integration.cjs"
27
27
  },
28
28
  "dependencies": {
29
- "@locker/rollup-plugin": "0.28.4",
30
- "@locker/sandbox": "0.28.4",
31
- "@locker/shared": "0.28.4",
29
+ "@babel/parser": "7.28.0",
30
+ "@locker/rollup-plugin": "0.28.5",
31
+ "@locker/sandbox": "0.28.5",
32
+ "@locker/shared": "0.28.5",
32
33
  "@lwc/engine-dom": "8.21.1",
33
34
  "@lwc/rollup-plugin": "8.21.1",
34
35
  "@rollup/plugin-commonjs": "21.1.0",
@@ -42,5 +43,5 @@
42
43
  "rollup-plugin-ts": "3.4.5",
43
44
  "yargs": "17.7.2"
44
45
  },
45
- "gitHead": "5a4e252a066299e969fa95068928dd569f3cf9aa"
46
+ "gitHead": "16f7eebf99a3b13eeb1831518cbb1de79a7aff15"
46
47
  }
@@ -5,6 +5,8 @@ import path from 'node:path';
5
5
 
6
6
  import { rollup } from 'rollup';
7
7
 
8
+ import { createWireMockPlugin } from './wire-mock.mjs';
9
+
8
10
  const require = createRequire(import.meta.url);
9
11
  const lockerRollupPlugin = require('@locker/rollup-plugin');
10
12
  const lwcRollupPlugin = require('@lwc/rollup-plugin');
@@ -54,6 +56,15 @@ export async function compileComponent({
54
56
  namespace = DEFAULT_NAMESPACE,
55
57
  sandboxKey = 'cli',
56
58
  lwcModules = [],
59
+ // Wire auto-mocking (D16). `wireMode` is undefined (off), 'success', or
60
+ // 'error'; `wireMockOverrides` is the Map from loadWireMockOverrides
61
+ // (adapter -> explicit shape); `onWireMock` receives each
62
+ // `[wire mock] ...` marker line so the runner can print it to stderr.
63
+ // When wireMode is undefined the plugin is not added and compilation
64
+ // is byte-for-byte what it was before D16.
65
+ wireMode,
66
+ wireMockOverrides = new Map(),
67
+ onWireMock = () => {},
57
68
  }) {
58
69
  const { dirName, jsFile } = await validateComponentDir(directory);
59
70
  const derivedTag = name ?? deriveTagName(dirName);
@@ -96,9 +107,35 @@ export async function compileComponent({
96
107
  }));
97
108
  const moduleRecords = [...explicitModules, { dir: modulesRoot }];
98
109
 
110
+ // Wire auto-mocking (D16). When enabled, a virtual-module plugin
111
+ // supplies synthetic source for the wire specifiers the component
112
+ // imports (lightning/uiRecordApi, @salesforce/schema/*,
113
+ // @salesforce/apex/*) so the component renders locally with fake data
114
+ // instead of dying at runtime on an unresolved platform module. The
115
+ // plugin needs the component's OWN source for Tier A schema-field
116
+ // collection and Tier B usage inference, so read the entry component
117
+ // file here. It MUST sit before nodeResolve in the plugins array (see
118
+ // below) so it claims the wire specifiers before node-resolve can
119
+ // externalize them.
120
+ const wireMockPlugins = [];
121
+ if (wireMode !== undefined) {
122
+ const componentSource = await fs.readFile(jsFile, 'utf8');
123
+ wireMockPlugins.push(
124
+ createWireMockPlugin({
125
+ mode: wireMode,
126
+ overrides: wireMockOverrides,
127
+ componentSource,
128
+ report: onWireMock,
129
+ }),
130
+ );
131
+ }
132
+
99
133
  const bundle = await rollup({
100
134
  input: entryFile,
101
135
  plugins: [
136
+ // Wire-mock virtual modules first: its resolveId must claim the
137
+ // wire specifiers before nodeResolve can mark them external.
138
+ ...wireMockPlugins,
102
139
  nodeResolve({ preferBuiltins: true }),
103
140
  // Plugin order matters: LWC compiler MUST run before the LWS
104
141
  // compiler. Reversing the order breaks LWC component-file
@@ -45,8 +45,8 @@ const CONFIG_KEY = 'config';
45
45
  // (the flag is simply absent unless set), e.g. `timeout`, `name`.
46
46
  //
47
47
  // INVARIANT: array-typed options default to `[]`, never `undefined`.
48
- // `before`, `after`, `lwcModules`, `gatesOn`, and `gatesOff` are
49
- // `array: true` yargs options. Feeding `default: undefined` to an
48
+ // `before`, `after`, `lwcModules`, `gatesOn`, `gatesOff`, and `wireFixtures`
49
+ // are `array: true` yargs options. Feeding `default: undefined` to an
50
50
  // `array: true` option does NOT leave it absent: yargs wraps the scalar
51
51
  // default in an array and yields `[null]`, which then flows into the
52
52
  // consumer (loadScriptFiles -> resolveInput(null), or parseGateList) and
@@ -86,6 +86,8 @@ export const BUILTIN_DEFAULTS = Object.freeze({
86
86
  timeout: undefined,
87
87
  verbose: false,
88
88
  watch: false,
89
+ wireFixtures: [],
90
+ wireMode: undefined,
89
91
  });
90
92
 
91
93
  // The typo guard: a config key outside this set (e.g. `broswer`) is
package/src/constants.mjs CHANGED
@@ -13,3 +13,21 @@ export const SUPPORTED_BROWSERS = ['chromium', 'firefox', 'webkit', 'chrome'];
13
13
  export const BROWSER_CHANNEL_MAP = {
14
14
  chrome: { launcher: 'chromium', channel: 'chrome' },
15
15
  };
16
+
17
+ // Wire auto-mocking modes (D16), shared between bin/lws.mjs (the
18
+ // --wire-mode `choices` list) and wire-mock.mjs (adapter emission).
19
+ // `success` fires each mocked adapter's data branch; `error` fires its
20
+ // error branch so a component's error UI can be exercised. These live here
21
+ // (a Playwright-free module bin already imports) so the flag validates via
22
+ // yargs `choices` without pulling wire-mock.mjs and its @babel/parser
23
+ // dependency into the eager bin load.
24
+ //
25
+ // The flag takes an explicit value (--wire-mode=success | --wire-mode=error),
26
+ // with no bare form: yargs cannot express a bare-or-`=value` optional-value
27
+ // flag that is also safe next to the required <directory> positional (a
28
+ // bare flag greedily consumes the positional). A plain string+choices
29
+ // option sidesteps that entirely and validates the value natively, so no
30
+ // custom coercion is needed. Verified against yargs 17.7.2.
31
+ export const WIRE_MOCK_MODE_SUCCESS = 'success';
32
+ export const WIRE_MOCK_MODE_ERROR = 'error';
33
+ export const WIRE_MOCK_MODES = [WIRE_MOCK_MODE_SUCCESS, WIRE_MOCK_MODE_ERROR];
package/src/runner.mjs CHANGED
@@ -21,6 +21,7 @@ import { Server } from './server.mjs';
21
21
  import { transform } from './transform.mjs';
22
22
  import { awaitAndEmitUpgradeNotice, startVersionCheckForCLI } from './version-check.mjs';
23
23
  import { assertWatchableEvalOrigin, rerunBanner, watchPaths } from './watcher.mjs';
24
+ import { loadWireMockOverrides } from './wire-mock.mjs';
24
25
 
25
26
  const require = createRequire(import.meta.url);
26
27
  // `private: true` in package.json is the pre-publish signal that skips
@@ -360,6 +361,7 @@ export async function runComponent(argv) {
360
361
  const directory = path.resolve(process.cwd(), argv.directory);
361
362
 
362
363
  output.timing.start('compile');
364
+ const wireMockOverrides = await loadWireMockOverrides(argv['wire-fixtures']);
363
365
  const compiled = await compileComponent({
364
366
  directory,
365
367
  name: argv.name,
@@ -368,6 +370,17 @@ export async function runComponent(argv) {
368
370
  // yargs gives us the array on argv['lwc-modules'] when --lwc-modules
369
371
  // is passed at least once; default to [] when absent.
370
372
  lwcModules: argv['lwc-modules'] ?? [],
373
+ // Wire auto-mocking (D16). argv.wireMode is undefined (off),
374
+ // 'success', or 'error'. Each mocked adapter emits a
375
+ // `[wire mock] ...` marker to stderr so the run is unmistakably
376
+ // flagged as using fabricated data.
377
+ wireMode: argv.wireMode,
378
+ wireMockOverrides,
379
+ // info(), not debug(): a wire mock means the render used
380
+ // fabricated data and is NOT a true production render, so the
381
+ // marker must be visible by default (suppressed only under
382
+ // --quiet / --json, which opt out of all info by contract).
383
+ onWireMock: (line) => output.info(line),
371
384
  });
372
385
  output.timing.end('compile');
373
386
  tmpDir = compiled.tmpDir;
@@ -729,6 +742,12 @@ async function runComponentWatch(argv) {
729
742
  });
730
743
  }
731
744
 
745
+ // Wire-mock overrides (D16) are loaded once, like endowments: the
746
+ // override JSON files are not the watch target (the component
747
+ // directory is), so a one-time load matches the watch scope. Each
748
+ // re-compile reuses the same override Map.
749
+ const wireMockOverrides = await loadWireMockOverrides(argv['wire-fixtures']);
750
+
732
751
  const runOnce = async () => {
733
752
  const compiled = await compileComponent({
734
753
  directory,
@@ -736,6 +755,9 @@ async function runComponentWatch(argv) {
736
755
  namespace: argv.namespace,
737
756
  sandboxKey: argv.key,
738
757
  lwcModules: argv['lwc-modules'] ?? [],
758
+ wireMode: argv.wireMode,
759
+ wireMockOverrides,
760
+ onWireMock: (line) => output.info(line),
739
761
  });
740
762
  output.result(compiled.code);
741
763
  output.debug(`compiled component → ${compiled.bundleFile} (tag: ${compiled.tag})`);
@@ -0,0 +1,733 @@
1
+ import { promises as fs } from 'node:fs';
2
+ import { createRequire } from 'node:module';
3
+ import path from 'node:path';
4
+
5
+ import { WIRE_MOCK_MODE_ERROR, WIRE_MOCK_MODE_SUCCESS } from './constants.mjs';
6
+
7
+ // Auto-mocking of LWC @wire adapters for `lws component`. A customer LWC
8
+ // that imports a platform adapter (getRecord from 'lightning/uiRecordApi')
9
+ // or an Apex adapter (@salesforce/apex/MyClass.myMethod) cannot render
10
+ // outside a Salesforce org: those module specifiers resolve to nothing on
11
+ // a laptop. Today rollup externalizes them and the render dies at runtime
12
+ // with "uiRecordApi is not defined". This module supplies synthetic source
13
+ // for those specifiers so the component renders locally with plausible
14
+ // fake data.
15
+ //
16
+ // The mechanism is a rollup plugin (see createWireMockPlugin) whose
17
+ // resolveId/load hooks intercept the wire specifiers BEFORE
18
+ // @rollup/plugin-node-resolve can externalize them, emitting a small
19
+ // module that exports each adapter as a class implementing the modern LWC
20
+ // WireAdapter contract:
21
+ //
22
+ // class Adapter {
23
+ // constructor(dataCallback) { this.dataCallback = dataCallback; }
24
+ // connect() { this.dataCallback({ data, error }); }
25
+ // update(config) {}
26
+ // disconnect() {}
27
+ // }
28
+ //
29
+ // The LWC compiler lowers `@wire(getRecord, {...}) record;` to a wire
30
+ // descriptor whose `adapter` is the imported `getRecord` binding, and the
31
+ // engine instantiates that binding as a WireAdapter and reads what it
32
+ // pushes to `dataCallback`. So exporting the adapter name as such a class
33
+ // is all it takes to satisfy the wire.
34
+ //
35
+ // The shape a given adapter emits is chosen by a fixed resolution ladder,
36
+ // evaluated per adapter (see resolveAdapterMock):
37
+ //
38
+ // 1. An explicit --wire-fixtures override for that adapter, if supplied.
39
+ // 2. Tier A: a hardcoded shape for a known platform adapter (top-5),
40
+ // with values drawn from the @salesforce/schema/Object.Field imports
41
+ // the component declares.
42
+ // 3. Tier B: a shape inferred by scanning the component source for how
43
+ // it consumes `this.<wired>.data.*`, synthesizing the minimum object
44
+ // that satisfies those reads.
45
+ // 4. null: no shape could be determined; the component renders its
46
+ // empty/loading state.
47
+
48
+ const require = createRequire(import.meta.url);
49
+ const babelParser = require('@babel/parser');
50
+
51
+ // The babel parser plugin set for reading component source. decorators-legacy
52
+ // is required for @wire, which stock acorn/espree reject. typescript is
53
+ // included unconditionally: an LWC may be AUTHORED in TypeScript (compiled to
54
+ // JS before deployment, but scanned here in its authored form), and the
55
+ // typescript plugin is a pure superset for our purposes. It parses plain JS
56
+ // with decorators AND TS source (type annotations, optional properties,
57
+ // access modifiers) under one plugin list, so there is no need to branch on
58
+ // file extension. Verified: a plain-JS @wire class and a TS class with
59
+ // `record?: T` and `get n(): string` both parse under this exact list.
60
+ const BABEL_PLUGINS = ['decorators-legacy', 'classProperties', 'typescript'];
61
+
62
+ // Rollup virtual-module id prefix. The leading NUL marks the id as
63
+ // synthetic so no other plugin (nor rollup's own fs resolution) treats it
64
+ // as a real path. Every id this plugin owns starts with this prefix.
65
+ const VIRTUAL_PREFIX = '\0lws-wire-mock:';
66
+
67
+ // The bare-specifier namespace for Salesforce schema field references
68
+ // (`@salesforce/schema/Account.Name`). A schema import is a value import
69
+ // whose default export is the field's API path string; the component
70
+ // passes those strings to an adapter's `fields` config. We resolve them to
71
+ // the path string itself so both the fields config and our field-name ->
72
+ // fake-value lookup see the same token.
73
+ const SCHEMA_PREFIX = '@salesforce/schema/';
74
+
75
+ // The bare-specifier namespace for imperative/Apex wire adapters
76
+ // (`@salesforce/apex/ContactController.getContacts`). These have no
77
+ // published shape (they are customer Apex), so they never hit Tier A; they
78
+ // fall to Tier B inference or null.
79
+ //
80
+ // Note on the lightning/* namespace at large: only the modules listed in
81
+ // PLATFORM_ADAPTER_MODULES are auto-mocked. Other lightning/* specifiers
82
+ // (base components like lightning/button) are a separate concern
83
+ // (first-party resolution) and are left untouched, so there is no broad
84
+ // `lightning/` prefix match here: isWireMockSpecifier gates on exact
85
+ // PLATFORM_ADAPTER_MODULES membership.
86
+ const APEX_PREFIX = '@salesforce/apex/';
87
+
88
+ // Stderr marker prefix. Every line the CLI prints about wire mocking
89
+ // starts with this so a customer scanning output can see, unmistakably,
90
+ // that a run used fabricated data and is not a true production render.
91
+ export const WIRE_MOCK_MARKER = '[wire mock]';
92
+
93
+ // Tier A. The curated table of known platform adapters, keyed by the
94
+ // lightning/* module that exports them, then by the adapter's export name.
95
+ // Each entry is a factory `(fields) => shape` that builds the adapter's
96
+ // success-branch `data` value. `fields` is the array of schema field API
97
+ // names the component declared (e.g. ['Account.Name', 'Account.AnnualRevenue']),
98
+ // so getRecord can populate exactly the fields the component asked for.
99
+ //
100
+ // Shapes are pinned to the current production UI API contract. They are
101
+ // demo-quality, not test-quality: the goal is a component that renders
102
+ // something plausible locally, not a faithful reproduction of every field
103
+ // the real API would return. See the design section in PLAN.md.
104
+ const PLATFORM_ADAPTER_MODULES = {
105
+ 'lightning/uiRecordApi': {
106
+ getRecord: (fields) => buildRecordShape(fields),
107
+ getRecords: (fields) => ({
108
+ results: [{ result: buildRecordShape(fields), statusCode: 200 }],
109
+ }),
110
+ },
111
+ 'lightning/uiObjectInfoApi': {
112
+ getObjectInfo: () => buildObjectInfoShape(),
113
+ getPicklistValues: () => buildPicklistValuesShape(),
114
+ },
115
+ 'lightning/uiRelatedListApi': {
116
+ getRelatedListRecords: (fields) => ({
117
+ count: 1,
118
+ currentPageToken: '0',
119
+ listReference: { type: 'relatedList' },
120
+ records: [buildRecordShape(fields)],
121
+ }),
122
+ },
123
+ };
124
+
125
+ // The flat set of adapter export names that Tier A knows, derived from the
126
+ // module table so the two cannot drift. Used to decide whether an
127
+ // adapter name is "known" (Tier A) or "unknown" (Tier B).
128
+ const KNOWN_ADAPTER_NAMES = new Set(
129
+ Object.values(PLATFORM_ADAPTER_MODULES).flatMap((mod) => Object.keys(mod)),
130
+ );
131
+
132
+ // Tier A. Field-name -> fake-value lookup. Keyed by the LAST dotted
133
+ // segment of a schema field path (`Account.Name` -> `Name`), so the same
134
+ // field name populates plausibly regardless of object. Unmatched fields
135
+ // fall back to inferFakeValueFromFieldName, which keys off common suffixes,
136
+ // then to a generic string.
137
+ const FIELD_NAME_FAKE_VALUES = {
138
+ Name: 'Acme Corp',
139
+ FirstName: 'Ada',
140
+ LastName: 'Lovelace',
141
+ Email: 'ada@example.com',
142
+ Phone: '(415) 555-0100',
143
+ AnnualRevenue: 1000000,
144
+ NumberOfEmployees: 500,
145
+ Industry: 'Technology',
146
+ Website: 'https://example.com',
147
+ CloseDate: '2026-01-01',
148
+ Amount: 50000,
149
+ StageName: 'Prospecting',
150
+ Title: 'CTO',
151
+ Description: 'Sample record generated by lws --wire-mode.',
152
+ };
153
+
154
+ // Suffix-based fallbacks for field names not in FIELD_NAME_FAKE_VALUES.
155
+ // Ordered longest-suffix-first at match time. Demo-quality guesses.
156
+ const FIELD_SUFFIX_FAKE_VALUES = [
157
+ ['Date', '2026-01-01'],
158
+ ['Email', 'sample@example.com'],
159
+ ['Phone', '(415) 555-0100'],
160
+ ['Revenue', 1000000],
161
+ ['Amount', 50000],
162
+ ['Count', 42],
163
+ ['Number', 42],
164
+ ['Id', '001000000000000AAA'],
165
+ ['Url', 'https://example.com'],
166
+ ['Name', 'Sample Name'],
167
+ ];
168
+
169
+ // The last dotted segment of a schema field path: `Account.Name` -> `Name`,
170
+ // `Opportunity.Account.Name` -> `Name`. Schema paths are always at least
171
+ // Object.Field; this returns Field.
172
+ function fieldNameOf(fieldPath) {
173
+ const parts = String(fieldPath).split('.');
174
+ return parts[parts.length - 1];
175
+ }
176
+
177
+ // Pick a plausible fake value for a schema field name. Exact table match
178
+ // first, then a suffix heuristic, then a generic string that names the
179
+ // field so the rendered output is at least self-describing.
180
+ export function inferFakeValueFromFieldName(fieldName) {
181
+ if (Object.hasOwn(FIELD_NAME_FAKE_VALUES, fieldName)) {
182
+ return FIELD_NAME_FAKE_VALUES[fieldName];
183
+ }
184
+ for (const [suffix, value] of FIELD_SUFFIX_FAKE_VALUES) {
185
+ if (fieldName.length >= suffix.length && fieldName.endsWith(suffix)) {
186
+ return value;
187
+ }
188
+ }
189
+ return `Sample ${fieldName}`;
190
+ }
191
+
192
+ // Build a getRecord-shaped record from the declared schema field paths.
193
+ // The UI API record shape is { apiName, id, fields: { <Field>: { value,
194
+ // displayValue } } }. When no fields were declared we still emit a Name so
195
+ // the component has something to show.
196
+ function buildRecordShape(fields) {
197
+ const fieldNames = (fields && fields.length > 0 ? fields : ['Name']).map(fieldNameOf);
198
+ const fieldEntries = {};
199
+ for (const fieldName of fieldNames) {
200
+ const value = inferFakeValueFromFieldName(fieldName);
201
+ fieldEntries[fieldName] = {
202
+ value,
203
+ displayValue: typeof value === 'string' ? value : String(value),
204
+ };
205
+ }
206
+ return {
207
+ apiName: 'Account',
208
+ id: '001000000000000AAA',
209
+ fields: fieldEntries,
210
+ };
211
+ }
212
+
213
+ function buildObjectInfoShape() {
214
+ return {
215
+ apiName: 'Account',
216
+ label: 'Account',
217
+ labelPlural: 'Accounts',
218
+ keyPrefix: '001',
219
+ custom: false,
220
+ fields: {
221
+ Name: { apiName: 'Name', label: 'Account Name', dataType: 'String', required: true },
222
+ },
223
+ };
224
+ }
225
+
226
+ function buildPicklistValuesShape() {
227
+ return {
228
+ controllerValues: {},
229
+ defaultValue: null,
230
+ url: '/services/data/vXX.0/ui-api/object-info/Account/picklist-values/012/Type',
231
+ values: [
232
+ { attributes: null, label: 'Prospect', validFor: [], value: 'Prospect' },
233
+ { attributes: null, label: 'Customer', validFor: [], value: 'Customer' },
234
+ ],
235
+ };
236
+ }
237
+
238
+ // The FetchResponse-shaped error the UI API adapters emit on failure. The
239
+ // --wire-mode=error mode fires this instead of the success data so a
240
+ // customer can exercise their component's error branch. Kept faithful to
241
+ // the real getRecord error contract (status/statusText/body) so error UI
242
+ // that reads `error.body.message` or `error.status` behaves as it would in
243
+ // production.
244
+ export function buildMockError() {
245
+ return {
246
+ status: 404,
247
+ statusText: 'Not Found',
248
+ body: {
249
+ message: '[wire mock] simulated error branch (--wire-mode=error)',
250
+ errorCode: 'NOT_FOUND',
251
+ },
252
+ ok: false,
253
+ };
254
+ }
255
+
256
+ // Parse --wire-fixtures override values into a Map of adapterSpecifier ->
257
+ // resolved shape. Each raw value is `<adapter>=<path-to-json>`, where
258
+ // <adapter> is a module specifier (`lightning/uiRecordApi`) or an adapter
259
+ // export name (`getRecord`), and the JSON file holds the exact `data`
260
+ // shape to emit. Repeatable: yargs hands us an array. Later entries win on
261
+ // a duplicate adapter key. Paths resolve against cwd so a customer can
262
+ // pass a relative path from their shell, mirroring --endowments.
263
+ export async function loadWireMockOverrides(rawValues, cwd = process.cwd()) {
264
+ // Validate and split every `<adapter>=<path>` synchronously first, so a
265
+ // malformed value fails before any disk I/O. The parsed entries keep
266
+ // argv order, which the Map.set loop below relies on for last-wins.
267
+ const entries = (rawValues ?? []).map((raw) => {
268
+ const eq = raw.indexOf('=');
269
+ if (eq === -1) {
270
+ throw new Error(`--wire-fixtures expects "<adapter>=<path-to-json>", got "${raw}"`);
271
+ }
272
+ const adapter = raw.slice(0, eq).trim();
273
+ const filePath = raw.slice(eq + 1).trim();
274
+ if (adapter === '' || filePath === '') {
275
+ throw new Error(
276
+ `--wire-fixtures expects a non-empty adapter and path in "<adapter>=<path>", got "${raw}"`,
277
+ );
278
+ }
279
+ return { adapter, absolute: path.resolve(cwd, filePath) };
280
+ });
281
+ // Reads are independent I/O, so run them in parallel (mirrors
282
+ // loadScriptFiles). Plain readFile + JSON.parse (not dynamic import) is
283
+ // simplest and matches how the rest of the CLI loads data files; it
284
+ // also keeps the override strictly data (a JSON import assertion would
285
+ // tie us to a Node version and admit non-JSON modules). `source`
286
+ // records the absolute path for diagnostics.
287
+ const loaded = await Promise.all(
288
+ entries.map(async ({ adapter, absolute }) => {
289
+ let parsed;
290
+ try {
291
+ const text = await fs.readFile(absolute, 'utf8');
292
+ parsed = JSON.parse(text);
293
+ } catch (err) {
294
+ throw new Error(
295
+ `--wire-fixtures could not read JSON for "${adapter}" from ${absolute}: ${err.message}`,
296
+ );
297
+ }
298
+ return { adapter, data: parsed, source: absolute };
299
+ }),
300
+ );
301
+ // Set in argv order so a duplicated adapter key resolves last-wins.
302
+ const overrides = new Map();
303
+ for (const { adapter, data, source } of loaded) {
304
+ overrides.set(adapter, { data, source });
305
+ }
306
+ return overrides;
307
+ }
308
+
309
+ // Tier B. Parse the component source and, for each @wire property, record
310
+ // how the component reads `this.<property>.data.*`, so we can synthesize a
311
+ // data shape that satisfies those reads. Returns a Map of adapterName ->
312
+ // { property, shape } where shape is a nested plain object mirroring the
313
+ // accessed paths (leaves become a generic scalar), or null when the
314
+ // property's data is used opaquely (passed around but not destructured),
315
+ // in which case Tier B yields null and the component gets its empty state.
316
+ //
317
+ // @babel/parser is used, not acorn: raw LWC source contains `@wire`
318
+ // decorators, which stock acorn (and espree) reject. Babel parses them
319
+ // natively with the decorators-legacy plugin. @babel/parser is a direct
320
+ // dependency for this reason.
321
+ export function inferShapesFromSource(source) {
322
+ const inferred = new Map();
323
+
324
+ let ast;
325
+ try {
326
+ ast = babelParser.parse(source, {
327
+ sourceType: 'module',
328
+ plugins: BABEL_PLUGINS,
329
+ });
330
+ } catch {
331
+ // A source we cannot parse yields no inference; every adapter in
332
+ // this component falls to null. Tier B is best-effort by design.
333
+ return inferred;
334
+ }
335
+
336
+ // Map of wired class-property name -> adapter name, harvested from the
337
+ // @wire decorators. `@wire(getRecord, {...}) record;` -> record:getRecord.
338
+ const propertyToAdapter = new Map();
339
+ const classBodies = [];
340
+ for (const node of ast.program.body) {
341
+ const decl =
342
+ node.type === 'ExportDefaultDeclaration' || node.type === 'ExportNamedDeclaration'
343
+ ? node.declaration
344
+ : node;
345
+ if (decl && decl.type === 'ClassDeclaration' && decl.body) {
346
+ classBodies.push(decl.body.body);
347
+ }
348
+ }
349
+ for (const members of classBodies) {
350
+ for (const member of members) {
351
+ if (!member.decorators) {
352
+ continue;
353
+ }
354
+ for (const decorator of member.decorators) {
355
+ const call = decorator.expression;
356
+ if (
357
+ call &&
358
+ call.type === 'CallExpression' &&
359
+ call.callee &&
360
+ call.callee.name === 'wire' &&
361
+ call.arguments.length > 0 &&
362
+ call.arguments[0].type === 'Identifier' &&
363
+ member.key &&
364
+ member.key.name
365
+ ) {
366
+ propertyToAdapter.set(member.key.name, call.arguments[0].name);
367
+ }
368
+ }
369
+ }
370
+ }
371
+
372
+ if (propertyToAdapter.size === 0) {
373
+ return inferred;
374
+ }
375
+
376
+ // Walk every member expression, collecting access paths rooted at
377
+ // `this.<wiredProperty>.data`. For `this.contacts.data.map(...)` we do
378
+ // not learn the element shape, but `this.record.data.fields.Name.value`
379
+ // tells us data.fields.Name.value must exist. We collect the dotted
380
+ // paths under `.data` and merge them into a nested object per adapter.
381
+ const pathsByProperty = new Map();
382
+ for (const property of propertyToAdapter.keys()) {
383
+ pathsByProperty.set(property, []);
384
+ }
385
+
386
+ collectDataAccessPaths(ast, propertyToAdapter, pathsByProperty);
387
+
388
+ for (const [property, adapter] of propertyToAdapter) {
389
+ const paths = pathsByProperty.get(property);
390
+ const shape = paths.length > 0 ? buildShapeFromPaths(paths) : null;
391
+ inferred.set(adapter, { property, shape });
392
+ }
393
+ return inferred;
394
+ }
395
+
396
+ // Recursively find `this.<prop>.data.<a>.<b>...` chains. For each wired
397
+ // property, push the array of segments AFTER `.data` (e.g. ['fields',
398
+ // 'Name', 'value']) into pathsByProperty. A bare `this.<prop>.data` with
399
+ // no further access yields the empty path, which buildShapeFromPaths turns
400
+ // into a truthy-but-empty object so the component's `if (data)` guard
401
+ // passes.
402
+ function collectDataAccessPaths(ast, propertyToAdapter, pathsByProperty) {
403
+ const visit = (node) => {
404
+ if (node === null || typeof node !== 'object') {
405
+ return;
406
+ }
407
+ if (Array.isArray(node)) {
408
+ for (const child of node) {
409
+ visit(child);
410
+ }
411
+ return;
412
+ }
413
+ if (isMemberExpression(node)) {
414
+ const chain = flattenMemberChain(node);
415
+ // chain is [rootObject, ...propertyNames]. We want chains that
416
+ // start `this . <wiredProp> . data`.
417
+ if (
418
+ chain &&
419
+ chain.length >= 3 &&
420
+ chain[0] === 'this' &&
421
+ propertyToAdapter.has(chain[1]) &&
422
+ chain[2] === 'data'
423
+ ) {
424
+ const afterData = chain.slice(3);
425
+ pathsByProperty.get(chain[1]).push(afterData);
426
+ }
427
+ }
428
+ for (const key of Object.keys(node)) {
429
+ if (key === 'loc' || key === 'start' || key === 'end' || key === 'range') {
430
+ continue;
431
+ }
432
+ visit(node[key]);
433
+ }
434
+ };
435
+ visit(ast);
436
+ }
437
+
438
+ // Whether a node is a member-access node. Optional chaining
439
+ // (`this.record?.data`) parses as OptionalMemberExpression, plain access as
440
+ // MemberExpression; both must be treated identically here, since a
441
+ // component that reads `this.record?.data?.fields` needs the same inferred
442
+ // shape as one that reads `this.record.data.fields`. Optional chaining is
443
+ // idiomatic in @wire data reads (the data is undefined until the adapter
444
+ // emits), so missing it would drop the most common access form.
445
+ function isMemberExpression(node) {
446
+ return node.type === 'MemberExpression' || node.type === 'OptionalMemberExpression';
447
+ }
448
+
449
+ // Flatten a member-access chain into a list of string segments, or null if
450
+ // any link is computed/dynamic (so we only reason about static dotted
451
+ // access). `this.record.data.fields.Name.value` ->
452
+ // ['this','record','data','fields','Name','value']. An optional chain
453
+ // (`?.`) is flattened the same as a plain member access.
454
+ function flattenMemberChain(node) {
455
+ const segments = [];
456
+ let current = node;
457
+ for (;;) {
458
+ if (isMemberExpression(current)) {
459
+ if (current.computed || !current.property || current.property.type !== 'Identifier') {
460
+ return null;
461
+ }
462
+ segments.unshift(current.property.name);
463
+ current = current.object;
464
+ } else if (current.type === 'ThisExpression') {
465
+ segments.unshift('this');
466
+ return segments;
467
+ } else if (current.type === 'Identifier') {
468
+ segments.unshift(current.name);
469
+ return segments;
470
+ } else {
471
+ return null;
472
+ }
473
+ }
474
+ }
475
+
476
+ // Merge a set of post-`.data` access paths into one nested plain object.
477
+ // Each leaf becomes a generic scalar. An empty path (bare `.data` access)
478
+ // makes the shape a non-null object so truthiness guards pass. A path
479
+ // whose next segment is a numeric-ish array method access cannot be
480
+ // distinguished here, so array-shaped data (`.data.map`) collapses to an
481
+ // object; Tier B is a best-effort minimum, documented as such.
482
+ function buildShapeFromPaths(paths) {
483
+ const root = {};
484
+ for (const segments of paths) {
485
+ if (segments.length === 0) {
486
+ continue;
487
+ }
488
+ let cursor = root;
489
+ for (let i = 0; i < segments.length; i += 1) {
490
+ const segment = segments[i];
491
+ const isLeaf = i === segments.length - 1;
492
+ if (isLeaf) {
493
+ if (!Object.hasOwn(cursor, segment)) {
494
+ cursor[segment] = inferFakeValueFromFieldName(segment);
495
+ }
496
+ } else {
497
+ if (!isPlainObject(cursor[segment])) {
498
+ cursor[segment] = {};
499
+ }
500
+ cursor = cursor[segment];
501
+ }
502
+ }
503
+ }
504
+ return root;
505
+ }
506
+
507
+ function isPlainObject(value) {
508
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
509
+ }
510
+
511
+ // The resolution ladder for a single adapter. Returns the `data` value to
512
+ // emit (success mode), or undefined when nothing could be resolved (the
513
+ // caller then emits null data). `mode === error` short-circuits the ladder
514
+ // for a mocked error and is handled by the caller; this function is only
515
+ // consulted for the success branch.
516
+ //
517
+ // 1. explicit override
518
+ // 2. Tier A known platform adapter
519
+ // 3. Tier B inferred shape
520
+ // 4. undefined (-> null data)
521
+ export function resolveAdapterData({
522
+ moduleSpecifier,
523
+ adapterName,
524
+ declaredFields,
525
+ overrides,
526
+ inferredShapes,
527
+ }) {
528
+ // 1. Explicit override, keyed by module specifier first, then by the
529
+ // adapter export name, so a customer can target either granularity.
530
+ if (overrides) {
531
+ if (overrides.has(moduleSpecifier)) {
532
+ return { data: overrides.get(moduleSpecifier).data, tier: 'override' };
533
+ }
534
+ if (overrides.has(adapterName)) {
535
+ return { data: overrides.get(adapterName).data, tier: 'override' };
536
+ }
537
+ }
538
+
539
+ // 2. Tier A: known platform adapter.
540
+ const moduleTable = PLATFORM_ADAPTER_MODULES[moduleSpecifier];
541
+ if (moduleTable && Object.hasOwn(moduleTable, adapterName)) {
542
+ return { data: moduleTable[adapterName](declaredFields), tier: 'A' };
543
+ }
544
+
545
+ // 3. Tier B: inferred shape from source.
546
+ if (inferredShapes && inferredShapes.has(adapterName)) {
547
+ const { shape } = inferredShapes.get(adapterName);
548
+ if (shape !== null) {
549
+ return { data: shape, tier: 'B' };
550
+ }
551
+ }
552
+
553
+ // 4. Nothing resolved.
554
+ return { data: undefined, tier: 'null' };
555
+ }
556
+
557
+ // Emit the synthetic module source for a lightning/* platform module. The
558
+ // module exports each of its known adapters as a WireAdapter class that
559
+ // pushes the resolved data (or the mock error) to its dataCallback on
560
+ // connect. `adapters` is an array of { adapterName, data } for every
561
+ // adapter this module exports.
562
+ function emitPlatformModuleSource(adapters, mode) {
563
+ const decls = adapters.map(({ adapterName, data }) =>
564
+ emitAdapterClass(adapterName, data, mode),
565
+ );
566
+ return decls.join('\n\n');
567
+ }
568
+
569
+ // Emit one exported WireAdapter class. In success mode it calls back with
570
+ // `{ data, error: undefined }`; in error mode with `{ data: undefined,
571
+ // error: <FetchResponse-shaped> }`. The class implements the full modern
572
+ // adapter contract (connect/update/disconnect) so the engine drives it
573
+ // without warnings.
574
+ function emitAdapterClass(exportName, data, mode) {
575
+ const payload =
576
+ mode === WIRE_MOCK_MODE_ERROR
577
+ ? `{ data: undefined, error: ${JSON.stringify(buildMockError())} }`
578
+ : `{ data: ${JSON.stringify(data ?? null)}, error: undefined }`;
579
+ return [
580
+ `export class ${exportName}Adapter {`,
581
+ ` constructor(dataCallback) {`,
582
+ ` this.dataCallback = dataCallback;`,
583
+ ` }`,
584
+ ` connect() {`,
585
+ ` this.dataCallback(${payload});`,
586
+ ` }`,
587
+ ` update() {}`,
588
+ ` disconnect() {}`,
589
+ `}`,
590
+ `export const ${exportName} = ${exportName}Adapter;`,
591
+ ].join('\n');
592
+ }
593
+
594
+ // Emit the synthetic module source for a @salesforce/schema/* import. The
595
+ // default export is the field's API path string, which is exactly what the
596
+ // real platform emits and what the adapters' `fields` config expects.
597
+ function emitSchemaModuleSource(fieldPath) {
598
+ return `export default ${JSON.stringify(fieldPath)};`;
599
+ }
600
+
601
+ // Emit the synthetic module source for an @salesforce/apex/* import (or any
602
+ // unknown single-adapter specifier resolved via Tier B / override). The
603
+ // default export is the adapter class; Apex adapters are imported as
604
+ // default imports (`import getContacts from '@salesforce/apex/...'`).
605
+ function emitApexModuleSource(adapterName, data, mode) {
606
+ const cls = emitAdapterClass(adapterName, data, mode);
607
+ return `${cls}\nexport default ${adapterName}Adapter;`;
608
+ }
609
+
610
+ // Collect the @salesforce/schema/* field paths a component declares, by
611
+ // scanning its import statements. Returned as an array of dotted paths
612
+ // (['Account.Name', ...]) so Tier A's getRecord can populate them. Uses
613
+ // babel for consistency with Tier B (schema imports sit alongside the
614
+ // @wire decorators that need babel anyway).
615
+ export function collectDeclaredSchemaFields(source) {
616
+ const fields = [];
617
+ let ast;
618
+ try {
619
+ ast = babelParser.parse(source, {
620
+ sourceType: 'module',
621
+ plugins: BABEL_PLUGINS,
622
+ });
623
+ } catch {
624
+ return fields;
625
+ }
626
+ for (const node of ast.program.body) {
627
+ if (
628
+ node.type === 'ImportDeclaration' &&
629
+ typeof node.source.value === 'string' &&
630
+ node.source.value.startsWith(SCHEMA_PREFIX)
631
+ ) {
632
+ fields.push(node.source.value.slice(SCHEMA_PREFIX.length));
633
+ }
634
+ }
635
+ return fields;
636
+ }
637
+
638
+ // Whether a module specifier is one this plugin owns (and should mock).
639
+ // Platform adapters are limited to the modules in PLATFORM_ADAPTER_MODULES
640
+ // PLUS the schema/apex namespaces. Other lightning/* specifiers (base
641
+ // components) are deliberately NOT claimed here.
642
+ export function isWireMockSpecifier(specifier) {
643
+ if (specifier.startsWith(SCHEMA_PREFIX) || specifier.startsWith(APEX_PREFIX)) {
644
+ return true;
645
+ }
646
+ return Object.hasOwn(PLATFORM_ADAPTER_MODULES, specifier);
647
+ }
648
+
649
+ // Build the rollup plugin. Placed BEFORE @rollup/plugin-node-resolve in
650
+ // compile-lwc.mjs so it claims the wire specifiers before node-resolve can
651
+ // externalize them. `report(line)` is invoked once per mocked adapter with
652
+ // a human-readable `[wire mock] <adapter> -> <tier>/<mode>` line so the
653
+ // runner can print the markers to stderr.
654
+ //
655
+ // options.mode — 'success' | 'error'
656
+ // options.overrides — Map from loadWireMockOverrides
657
+ // options.componentSource — the raw component .js source (for Tier A
658
+ // schema-field collection and Tier B inference)
659
+ // options.report — (line: string) => void
660
+ export function createWireMockPlugin({
661
+ mode = WIRE_MOCK_MODE_SUCCESS,
662
+ overrides = new Map(),
663
+ componentSource = '',
664
+ report = () => {},
665
+ } = {}) {
666
+ const declaredFields = collectDeclaredSchemaFields(componentSource);
667
+ const inferredShapes = inferShapesFromSource(componentSource);
668
+ const reported = new Set();
669
+
670
+ const reportOnce = (adapterName, tier) => {
671
+ if (reported.has(adapterName)) {
672
+ return;
673
+ }
674
+ reported.add(adapterName);
675
+ report(`${WIRE_MOCK_MARKER} ${adapterName} -> ${tier}/${mode}`);
676
+ };
677
+
678
+ return {
679
+ name: 'lws-wire-mock',
680
+ resolveId(source) {
681
+ if (isWireMockSpecifier(source)) {
682
+ return VIRTUAL_PREFIX + source;
683
+ }
684
+ return null;
685
+ },
686
+ load(id) {
687
+ if (!id.startsWith(VIRTUAL_PREFIX)) {
688
+ return null;
689
+ }
690
+ const specifier = id.slice(VIRTUAL_PREFIX.length);
691
+
692
+ if (specifier.startsWith(SCHEMA_PREFIX)) {
693
+ return emitSchemaModuleSource(specifier.slice(SCHEMA_PREFIX.length));
694
+ }
695
+
696
+ if (specifier.startsWith(APEX_PREFIX)) {
697
+ // Apex adapter name is the method segment:
698
+ // @salesforce/apex/ContactController.getContacts -> getContacts.
699
+ const tail = specifier.slice(APEX_PREFIX.length);
700
+ const adapterName = tail.slice(tail.lastIndexOf('.') + 1);
701
+ const { data, tier } = resolveAdapterData({
702
+ moduleSpecifier: specifier,
703
+ adapterName,
704
+ declaredFields,
705
+ overrides,
706
+ inferredShapes,
707
+ });
708
+ reportOnce(adapterName, tier);
709
+ return emitApexModuleSource(adapterName, data, mode);
710
+ }
711
+
712
+ // A known platform module: emit every adapter it exports.
713
+ const moduleTable = PLATFORM_ADAPTER_MODULES[specifier] ?? {};
714
+ const adapters = Object.keys(moduleTable).map((adapterName) => {
715
+ const { data, tier } = resolveAdapterData({
716
+ moduleSpecifier: specifier,
717
+ adapterName,
718
+ declaredFields,
719
+ overrides,
720
+ inferredShapes,
721
+ });
722
+ reportOnce(adapterName, tier);
723
+ return { adapterName, data };
724
+ });
725
+ return emitPlatformModuleSource(adapters, mode);
726
+ },
727
+ };
728
+ }
729
+
730
+ // Exported for tests and the design doc: the set of known adapter names and
731
+ // the module table, so a test can assert the top-5 are present and a doc
732
+ // can enumerate them without duplicating the list.
733
+ export { KNOWN_ADAPTER_NAMES, PLATFORM_ADAPTER_MODULES };