@locker/cli 0.28.3 → 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 +195 -0
- package/bin/lws.mjs +185 -30
- package/dist/index.cjs.js +1 -1
- package/dist/index.mjs.js +1 -1
- package/dist/lws-sandbox.js +149 -46
- package/dist/purify.js +2 -2
- package/package.json +7 -5
- package/src/compile-lwc.mjs +37 -0
- package/src/config-resolver.mjs +269 -0
- package/src/constants.mjs +18 -0
- package/src/gates.mjs +132 -0
- package/src/output.mjs +19 -0
- package/src/playwright-check.mjs +65 -0
- package/src/repl.mjs +15 -0
- package/src/runner.mjs +68 -0
- package/src/sandbox-entry.ts +25 -0
- package/src/wire-mock.mjs +733 -0
|
@@ -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 };
|