@spfx-fast/spfx-workbench 0.0.0-stage → 0.1.0

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.
Files changed (41) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +240 -2
  3. package/bin/spfx-workbench-auth.mjs +143 -0
  4. package/bin/spfx-workbench-capture.mjs +5 -0
  5. package/bin/spfx-workbench-debug.mjs +155 -0
  6. package/bin/spfx-workbench-doctor.mjs +2 -0
  7. package/bin/spfx-workbench-heft-target.mjs +2 -0
  8. package/bin/spfx-workbench-replay.mjs +2 -0
  9. package/bin/spfx-workbench.mjs +97 -0
  10. package/docs/mock-data-and-capture.md +52 -0
  11. package/docs/sharepoint-behavior-snapshot-2026-11-15-1455Z.md +67 -0
  12. package/fixtures/library-items.synthetic.json +23 -0
  13. package/index.html +13 -0
  14. package/package.json +58 -4
  15. package/scripts/benchmark-capture-import.mjs +50 -0
  16. package/scripts/benchmark-consumer-hmr.mjs +251 -0
  17. package/scripts/benchmark-mock-api.mjs +114 -0
  18. package/scripts/check-tarball-install.mjs +413 -0
  19. package/scripts/diagnose-consumer.mjs +228 -0
  20. package/scripts/diff-captures.mjs +452 -0
  21. package/scripts/import-synthetic-capture.mjs +60 -0
  22. package/scripts/minimal-playwright-state.mjs +15 -0
  23. package/scripts/mock-contract.mjs +375 -0
  24. package/scripts/replay-sharepoint-capture.mjs +123 -0
  25. package/scripts/resolve-chromium.mjs +22 -0
  26. package/scripts/resolve-serve-target.mjs +70 -0
  27. package/scripts/spfx-node-runtime.mjs +19 -0
  28. package/scripts/watch-sharepoint-capture.mjs +395 -0
  29. package/scripts/write-local-capture.mjs +121 -0
  30. package/src/auth-state.mjs +44 -0
  31. package/src/contracts/sharepoint-rest.d.ts +38 -0
  32. package/src/contracts/simulator-context.d.ts +38 -0
  33. package/src/data-source-label.mjs +10 -0
  34. package/src/format-modified.mjs +8 -0
  35. package/src/lifecycle-webpart.jsx +43 -0
  36. package/src/main.jsx +14 -0
  37. package/src/simulator-context.mjs +94 -0
  38. package/src/spfx-preview-shims.mjs +21 -0
  39. package/src/workbench.css +187 -0
  40. package/src/workbench.jsx +222 -0
  41. package/vite.config.js +399 -0
@@ -0,0 +1,395 @@
1
+ import { access, lstat, mkdir, readFile, realpath, rm, stat } from 'node:fs/promises';
2
+ import { createHash, randomUUID } from 'node:crypto';
3
+ import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
4
+ import { chromium } from 'playwright-core';
5
+ import { archiveLocalHar, requireRepositoryIgnore, writeLocalCapture } from './write-local-capture.mjs';
6
+ import { resolveChromiumExecutable } from './resolve-chromium.mjs';
7
+ import { minimalPlaywrightState } from './minimal-playwright-state.mjs';
8
+ import { resolveTenantAuthStatePath } from '../src/auth-state.mjs';
9
+
10
+ const args = process.argv.slice(2);
11
+ const valueAfter = (flag) => {
12
+ const index = args.indexOf(flag);
13
+ return index < 0 ? undefined : args[index + 1];
14
+ };
15
+ const pageUrl = valueAfter('--page');
16
+ const durationValue = valueAfter('--duration');
17
+ const durationSeconds = durationValue === undefined ? undefined : Number(durationValue);
18
+ const storageStateValue = valueAfter('--storage-state');
19
+ const tenant = valueAfter('--tenant');
20
+ let storageStatePath = storageStateValue && resolve(storageStateValue);
21
+ const cdpEndpoint = valueAfter('--cdp-endpoint');
22
+ const consumerRoot = resolve(process.cwd());
23
+ const harPath = resolve(consumerRoot, '.spfx-workbench/captures/tenant.har');
24
+ const liveHarName = 'tenant-live';
25
+ const liveHarPath = resolve(consumerRoot, '.spfx-workbench/captures/tenant-live.json');
26
+ const manifestPath = resolve(consumerRoot, '.spfx-workbench/captures/tenant-manifest.json');
27
+ const initiatorTracePath = resolve(consumerRoot, '.spfx-workbench/captures/tenant-initiators.json');
28
+ const usage = 'Usage: spfx-workbench-capture --watch --page <SharePoint-page> (--tenant <tenant> | --storage-state <state.json> | --cdp-endpoint <local-Chromium-CDP>) [--refresh-auth] [--headed] [--edit] [--once] [--duration <seconds>] [--measure]';
29
+ const safeError = (error) => String(error?.message ?? error).replace(/(?:https?|wss?):\/\/[^\s"'<>]+/g, (value) => {
30
+ try {
31
+ const url = new URL(value);
32
+ return ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname) ? url.origin : `${url.origin}${url.pathname}`;
33
+ }
34
+ catch { return '[URL]'; }
35
+ });
36
+ async function enterEditMode(page) {
37
+ const editControl = page.getByRole('button', { name: /^edit page?$/i }).or(
38
+ page.getByRole('menuitem', { name: /^edit page$/i }),
39
+ );
40
+ try {
41
+ await editControl.first().waitFor({ state: 'visible', timeout: 5000 });
42
+ await editControl.first().click();
43
+ await page.waitForTimeout(1500);
44
+ return true;
45
+ } catch { return false; }
46
+ }
47
+
48
+ if (args.includes('--help') || args.includes('-h')) {
49
+ process.stdout.write(`${usage}\n`);
50
+ } else if (!pageUrl || (!storageStatePath && !tenant && !cdpEndpoint)) {
51
+ process.stderr.write(`${usage}\n`);
52
+ process.exitCode = 2;
53
+ } else {
54
+ let browser;
55
+ let authBrowser;
56
+ let context;
57
+ let cdpSession;
58
+ let browserVersion;
59
+ let captureViewport;
60
+ const captureStartedAt = new Date().toISOString();
61
+ let discardCapture = false;
62
+ let stopping = false;
63
+ let resolveStop;
64
+ const stopSignal = new Promise((resolvePromise) => { resolveStop = resolvePromise; });
65
+ try {
66
+ const target = new URL(pageUrl);
67
+ if (!['http:', 'https:'].includes(target.protocol) || target.username || target.password) {
68
+ throw new Error('Capture page must be an HTTP(S) URL without embedded credentials.');
69
+ }
70
+ if (tenant && storageStatePath) throw new Error('Choose either --tenant or --storage-state.');
71
+ if (tenant && cdpEndpoint) throw new Error('Choose either --tenant or --cdp-endpoint.');
72
+ if (tenant) storageStatePath = resolveTenantAuthStatePath(tenant);
73
+ if (storageStatePath && cdpEndpoint) throw new Error('Choose either --storage-state or --cdp-endpoint.');
74
+ if (!storageStatePath && !cdpEndpoint) throw new Error('Provide --tenant, --storage-state, or a local --cdp-endpoint.');
75
+ if (args.includes('--refresh-auth') && !cdpEndpoint) throw new Error('--refresh-auth requires --cdp-endpoint.');
76
+ if (durationSeconds !== undefined && (!Number.isInteger(durationSeconds) || durationSeconds < 1 || durationSeconds > 3600)) {
77
+ throw new Error('--duration must be a whole number of seconds from 1 to 3600.');
78
+ }
79
+ if (cdpEndpoint) {
80
+ let endpoint;
81
+ try { endpoint = new URL(cdpEndpoint); } catch { throw new Error('--cdp-endpoint must be a local Chromium debugging endpoint.'); }
82
+ const loopback = ['localhost', '127.0.0.1', '::1', '[::1]'].includes(endpoint.hostname);
83
+ if (!loopback || !['http:', 'https:', 'ws:', 'wss:'].includes(endpoint.protocol) || endpoint.username || endpoint.password || endpoint.hash) {
84
+ throw new Error('--cdp-endpoint must use a loopback HTTP or WebSocket URL without credentials.');
85
+ }
86
+ }
87
+ requireRepositoryIgnore(consumerRoot, harPath);
88
+ await mkdir(dirname(harPath), { recursive: true });
89
+ try {
90
+ const previousInfo = await lstat(harPath);
91
+ if (!previousInfo.isFile() || previousInfo.isSymbolicLink()) throw new Error('Existing capture must be a regular file.');
92
+ const rootPath = await realpath(consumerRoot);
93
+ const previousPath = await realpath(harPath);
94
+ const relativePath = relative(rootPath, previousPath);
95
+ if (!relativePath || relativePath === '..' || relativePath.startsWith(`..${sep}`) || isAbsolute(relativePath)) {
96
+ throw new Error('Existing capture must stay inside the consuming project.');
97
+ }
98
+ const previousBytes = await readFile(previousPath);
99
+ const previousHar = JSON.parse(previousBytes.toString('utf8'));
100
+ if (!Array.isArray(previousHar.log?.entries)) throw new Error('Existing capture is not a valid HAR.');
101
+ const previousStamp = previousInfo.mtime.toISOString().replace(/[-:.]/g, '');
102
+ const previousHash = createHash('sha256').update(previousBytes).digest('hex');
103
+ await archiveLocalHar(previousBytes, { root: consumerRoot, name: `tenant-archive-${previousStamp}-${previousHash.slice(0, 12)}` });
104
+ } catch (error) {
105
+ if (error.code !== 'ENOENT') throw error;
106
+ }
107
+
108
+ let authStateCaptured = false;
109
+ if (cdpEndpoint) {
110
+ authBrowser = await chromium.connectOverCDP(cdpEndpoint);
111
+ const authContext = authBrowser.contexts()[0];
112
+ if (!authContext) throw new Error('The connected browser has no authenticated context.');
113
+ const sameOriginPages = authContext.pages().filter((candidate) => {
114
+ try { return new URL(candidate.url()).origin === target.origin; } catch { return false; }
115
+ });
116
+ let authPage = sameOriginPages[0];
117
+ let closeAuthPage = false;
118
+ if (!authPage) {
119
+ authPage = await authContext.newPage();
120
+ closeAuthPage = true;
121
+ await authPage.goto(target.href, { waitUntil: 'domcontentloaded', timeout: 45_000 });
122
+ } else if (args.includes('--refresh-auth')) {
123
+ await authPage.reload({ waitUntil: 'domcontentloaded', timeout: 45_000 });
124
+ }
125
+ try {
126
+ const state = await minimalPlaywrightState(authContext, authPage, target.href);
127
+ storageStatePath = resolve(consumerRoot, '.spfx-workbench/captures/sharepoint-state.json');
128
+ await writeLocalCapture(state, { root: consumerRoot, name: 'sharepoint-state' });
129
+ authStateCaptured = true;
130
+ } finally {
131
+ if (closeAuthPage) await authPage.close();
132
+ }
133
+ await authBrowser.close();
134
+ authBrowser = undefined;
135
+ } else {
136
+ await access(storageStatePath);
137
+ }
138
+ browser = await chromium.launch({ headless: !args.includes('--headed'), executablePath: await resolveChromiumExecutable() });
139
+ browserVersion = browser.version();
140
+ context = await browser.newContext({
141
+ storageState: storageStatePath,
142
+ recordHar: { path: harPath, content: 'embed', mode: 'full' },
143
+ });
144
+ const liveEntries = [];
145
+ const liveCaptureId = randomUUID();
146
+ const pendingResponses = new Set();
147
+ const requestMetadata = new WeakMap();
148
+ let requestSequence = 0;
149
+ const initiatorEntries = [];
150
+ let liveWriteTimer;
151
+ let liveWrite = Promise.resolve();
152
+ let liveWriteError;
153
+ const liveCapture = () => ({ spfxWorkbenchCaptureId: liveCaptureId, log: { version: '1.2', creator: { name: 'spfx-workbench', version: '0.1.0' }, entries: liveEntries.toSorted((a, b) => a.sequence - b.sequence).map(({ entry }) => entry) } });
154
+ const writeLiveSnapshot = () => {
155
+ const snapshot = liveCapture();
156
+ liveWrite = liveWrite.then(() => writeLocalCapture(snapshot, { root: consumerRoot, name: liveHarName }))
157
+ .catch((error) => { liveWriteError = error; });
158
+ return liveWrite;
159
+ };
160
+ const scheduleLiveSnapshot = () => {
161
+ clearTimeout(liveWriteTimer);
162
+ liveWriteTimer = setTimeout(() => { void writeLiveSnapshot(); }, 200);
163
+ };
164
+ context.on('request', (request) => requestMetadata.set(request, { sequence: requestSequence++, startedDateTime: new Date().toISOString() }));
165
+ context.on('response', (response) => {
166
+ const task = (async () => {
167
+ const request = response.request();
168
+ if (!['fetch', 'xhr'].includes(request.resourceType())) return;
169
+ const body = await response.body();
170
+ const requestHeaders = await request.allHeaders();
171
+ const responseHeaders = await response.allHeaders();
172
+ const url = new URL(request.url());
173
+ const contentType = responseHeaders['content-type'] ?? '';
174
+ const responseText = body.toString('base64');
175
+ const requestBody = request.postDataBuffer();
176
+ const metadata = requestMetadata.get(request) ?? { sequence: requestSequence++, startedDateTime: new Date().toISOString() };
177
+ liveEntries.push({ sequence: metadata.sequence, entry: {
178
+ _resourceType: request.resourceType(),
179
+ startedDateTime: metadata.startedDateTime,
180
+ time: -1,
181
+ request: {
182
+ method: request.method(), url: request.url(), httpVersion: 'HTTP/1.1',
183
+ headers: Object.entries(requestHeaders).map(([name, value]) => ({ name, value })),
184
+ queryString: [...url.searchParams].map(([name, value]) => ({ name, value })),
185
+ cookies: [], headersSize: -1, bodySize: requestBody?.byteLength ?? 0,
186
+ ...(requestBody ? { postData: { mimeType: requestHeaders['content-type'] ?? '', text: requestBody.toString('base64'), encoding: 'base64' } } : {}),
187
+ },
188
+ response: {
189
+ status: response.status(), statusText: response.statusText(), httpVersion: 'HTTP/1.1',
190
+ headers: Object.entries(responseHeaders).map(([name, value]) => ({ name, value })),
191
+ cookies: [], content: { size: body.byteLength, mimeType: contentType.split(';', 1)[0], text: responseText, encoding: 'base64' },
192
+ redirectURL: responseHeaders.location ?? '', headersSize: -1, bodySize: body.byteLength,
193
+ },
194
+ cache: {}, timings: { send: -1, wait: -1, receive: -1 },
195
+ } });
196
+ scheduleLiveSnapshot();
197
+ })().catch((error) => { liveWriteError = error; });
198
+ pendingResponses.add(task);
199
+ void task.finally(() => pendingResponses.delete(task));
200
+ });
201
+ await writeLiveSnapshot();
202
+ const page = await context.newPage();
203
+ captureViewport = page.viewportSize();
204
+ cdpSession = await context.newCDPSession(page);
205
+ await cdpSession.send('Debugger.enable');
206
+ await cdpSession.send('Network.enable');
207
+ cdpSession.on('Network.requestWillBeSent', ({ requestId, request, initiator, type, timestamp, wallTime }) => {
208
+ if (!['Fetch', 'XHR'].includes(type)) return;
209
+ const frames = [];
210
+ let stack = initiator?.stack;
211
+ while (stack && frames.length < 64) {
212
+ for (const frame of stack.callFrames ?? []) {
213
+ if (frames.length >= 64) break;
214
+ frames.push({
215
+ functionName: frame.functionName,
216
+ url: frame.url,
217
+ lineNumber: frame.lineNumber,
218
+ columnNumber: frame.columnNumber,
219
+ });
220
+ }
221
+ stack = stack.parent;
222
+ }
223
+ initiatorEntries.push({
224
+ sequence: initiatorEntries.length + 1,
225
+ requestId,
226
+ method: request.method,
227
+ url: request.url,
228
+ resourceType: type.toLowerCase(),
229
+ timestamp,
230
+ wallTime: new Date(wallTime * 1000).toISOString(),
231
+ initiator: {
232
+ type: initiator?.type ?? 'unknown',
233
+ url: initiator?.url,
234
+ lineNumber: initiator?.lineNumber,
235
+ columnNumber: initiator?.columnNumber,
236
+ frames,
237
+ },
238
+ });
239
+ });
240
+ await page.goto(target.href, { waitUntil: 'domcontentloaded', timeout: 45_000 });
241
+ const finalUrl = new URL(page.url());
242
+ if (finalUrl.origin !== target.origin) {
243
+ discardCapture = true;
244
+ throw new Error('The saved browser state did not reach the requested SharePoint site.');
245
+ }
246
+
247
+ let editModeEntered = false;
248
+ if (args.includes('--edit')) editModeEntered = await enterEditMode(page);
249
+
250
+ const measurements = [];
251
+ if (args.includes('--measure')) {
252
+ for (const width of [320, 390, 639, 640, 768, 1023, 1024, 1366, 1920]) {
253
+ const measurementContext = await browser.newContext({ storageState: storageStatePath, viewport: { width, height: 900 } });
254
+ try {
255
+ const measurementPage = await measurementContext.newPage();
256
+ await measurementPage.goto(target.href, { waitUntil: 'domcontentloaded', timeout: 45_000 });
257
+ if (new URL(measurementPage.url()).origin !== target.origin) {
258
+ discardCapture = true;
259
+ throw new Error('The saved browser state did not reach the requested SharePoint site.');
260
+ }
261
+ await measurementPage.waitForTimeout(1500);
262
+ const measurementEditModeEntered = args.includes('--edit') ? await enterEditMode(measurementPage) : false;
263
+ const measurement = await measurementPage.evaluate(() => {
264
+ const sections = [...document.querySelectorAll('[class*="CanvasSection"]')]
265
+ .filter((element) => element.classList.contains('CanvasSection'));
266
+ const controls = [...document.querySelectorAll('[class*="ControlZone"]')]
267
+ .filter((element) => !element.parentElement?.closest('[class*="ControlZone"]'));
268
+ const nodes = [
269
+ ...sections.map((element, sectionIndex) => ({ element, kind: 'section', sectionIndex })),
270
+ ...controls.map((element) => ({
271
+ element,
272
+ kind: 'webpart-control',
273
+ sectionIndex: sections.findIndex((section) => section.contains(element)),
274
+ })),
275
+ ];
276
+ const boxes = nodes.flatMap(({ element, kind, sectionIndex }) => {
277
+ const rect = element.getBoundingClientRect();
278
+ if (rect.width < 20 || rect.height < 20) return [];
279
+ const style = getComputedStyle(element);
280
+ const section = kind === 'section' ? element : sections[sectionIndex];
281
+ const sectionX = section?.getBoundingClientRect().x ?? rect.x;
282
+ return [{
283
+ kind,
284
+ sectionIndex,
285
+ structure: [...element.classList].filter((name) => /^(CanvasSection|ControlZone)/.test(name)),
286
+ x: Math.round(rect.x), y: Math.round(rect.y), width: Math.round(rect.width), height: Math.round(rect.height),
287
+ relativeX: Math.round(rect.x - sectionX),
288
+ padding: [style.paddingTop, style.paddingRight, style.paddingBottom, style.paddingLeft],
289
+ margin: [style.marginTop, style.marginRight, style.marginBottom, style.marginLeft],
290
+ gap: style.gap, columns: style.gridTemplateColumns, background: style.backgroundColor,
291
+ }];
292
+ });
293
+ return { viewport: innerWidth, documentWidth: document.documentElement.scrollWidth, boxes };
294
+ });
295
+ measurements.push({ ...measurement, editModeEntered: measurementEditModeEntered });
296
+ } finally {
297
+ await measurementContext.close();
298
+ }
299
+ }
300
+ await writeLocalCapture({
301
+ schema: 'spfx-workbench-page-measurements/v1',
302
+ page: `${target.origin}${target.pathname}`,
303
+ measuredAt: new Date().toISOString(),
304
+ measurements,
305
+ }, { root: consumerRoot, name: 'tenant-measurements' });
306
+ }
307
+
308
+ const measurementSummary = measurements.map(({ viewport, documentWidth, boxes, editModeEntered: measuredInEditMode }) => ({ viewport, documentWidth, boxCount: boxes.length, editModeEntered: measuredInEditMode }));
309
+
310
+ process.stdout.write(JSON.stringify({
311
+ result: 'recording',
312
+ capture: '.spfx-workbench/captures/tenant.har',
313
+ liveCapture: '.spfx-workbench/captures/tenant-live.json',
314
+ scope: 'full browser-context HAR with request/response headers and bodies',
315
+ editModeEntered,
316
+ measurementSummary,
317
+ ...(authStateCaptured ? { authStateCaptured: true, authState: '.spfx-workbench/captures/sharepoint-state.json' } : {}),
318
+ }) + '\n');
319
+
320
+ if (durationSeconds !== undefined || args.includes('--once')) await page.waitForTimeout((durationSeconds ?? 4) * 1000);
321
+ else {
322
+ process.once('SIGINT', () => { stopping = true; resolveStop(); });
323
+ process.once('SIGTERM', () => { stopping = true; resolveStop(); });
324
+ await stopSignal;
325
+ }
326
+ await Promise.allSettled([...pendingResponses]);
327
+ clearTimeout(liveWriteTimer);
328
+ await writeLiveSnapshot();
329
+ if (liveWriteError) throw new Error(`Could not update the live HAR snapshot: ${liveWriteError.message}`);
330
+ await context.close();
331
+ context = undefined;
332
+ await browser.close();
333
+ browser = undefined;
334
+ await rm(resolve(consumerRoot, '.spfx-workbench/captures/tenant-live.json'), { force: true });
335
+
336
+ const capturedAt = new Date().toISOString();
337
+ const harBytes = await readFile(harPath);
338
+ const har = JSON.parse(harBytes.toString('utf8'));
339
+ const fileInfo = await stat(harPath);
340
+ const harSha256 = createHash('sha256').update(harBytes).digest('hex');
341
+ const archiveStamp = capturedAt.replace(/[-:.]/g, '');
342
+ const archiveName = `tenant-archive-${archiveStamp}-${harSha256.slice(0, 12)}`;
343
+ await archiveLocalHar(harBytes, { root: consumerRoot, name: archiveName });
344
+ const apiCalls = har.log.entries.filter((entry) => ['fetch', 'xhr'].includes(entry._resourceType)).length;
345
+ const playwrightVersion = JSON.parse(await readFile(new URL('../node_modules/playwright-core/package.json', import.meta.url), 'utf8')).version;
346
+ if (initiatorEntries.length) {
347
+ await writeLocalCapture({
348
+ schema: 'spfx-workbench-initiators/v1',
349
+ captureId: liveCaptureId,
350
+ entries: initiatorEntries,
351
+ }, { root: consumerRoot, name: 'tenant-initiators' });
352
+ }
353
+ await writeLocalCapture({
354
+ schema: 'spfx-workbench-capture-manifest/v1',
355
+ captureId: liveCaptureId,
356
+ startedAt: captureStartedAt,
357
+ capturedAt,
358
+ durationMs: Math.max(0, Date.parse(capturedAt) - Date.parse(captureStartedAt)),
359
+ pageOrigin: target.origin,
360
+ pagePath: target.pathname,
361
+ editModeEntered,
362
+ viewport: captureViewport,
363
+ runtime: { node: process.version, platform: process.platform, architecture: process.arch, playwright: playwrightVersion, browser: browserVersion },
364
+ requestCount: har.log.entries.length,
365
+ apiCallCount: apiCalls,
366
+ initiatorCount: initiatorEntries.length,
367
+ bytes: fileInfo.size,
368
+ sha256: harSha256,
369
+ }, { root: consumerRoot, name: 'tenant-manifest' });
370
+ process.stdout.write(JSON.stringify({
371
+ result: stopping ? 'stopped' : 'captured',
372
+ capture: '.spfx-workbench/captures/tenant.har',
373
+ manifest: '.spfx-workbench/captures/tenant-manifest.json',
374
+ initiatorTrace: initiatorEntries.length ? '.spfx-workbench/captures/tenant-initiators.json' : null,
375
+ requestCount: har.log.entries.length,
376
+ apiCallCount: apiCalls,
377
+ initiatorCount: initiatorEntries.length,
378
+ bytes: fileInfo.size,
379
+ authStateLoaded: true,
380
+ editModeEntered,
381
+ measurementSummary,
382
+ ...(measurementSummary.length ? { measurementFile: '.spfx-workbench/captures/tenant-measurements.json' } : {}),
383
+ }) + '\n');
384
+ } catch (error) {
385
+ process.stderr.write(`Capture failed: ${safeError(error)}\n`);
386
+ process.exitCode = 1;
387
+ } finally {
388
+ await context?.close().catch(() => {});
389
+ await browser?.close().catch(() => {});
390
+ await authBrowser?.close().catch(() => {});
391
+ await cdpSession?.detach().catch(() => {});
392
+ await rm(liveHarPath, { force: true }).catch(() => {});
393
+ if (discardCapture) await Promise.all([rm(harPath, { force: true }), rm(manifestPath, { force: true }), rm(initiatorTracePath, { force: true })]).catch(() => {});
394
+ }
395
+ }
@@ -0,0 +1,121 @@
1
+ import { lstat, mkdir, open, realpath, rename, rm } from 'node:fs/promises';
2
+ import { execFileSync } from 'node:child_process';
3
+ import { isAbsolute, relative, resolve, sep } from 'node:path';
4
+ import { randomUUID } from 'node:crypto';
5
+
6
+ function isInside(root, target) {
7
+ const path = relative(root, target);
8
+ return path !== '' && path !== '..' && !path.startsWith(`..${sep}`) && !isAbsolute(path);
9
+ }
10
+
11
+ async function validateDirectory(path, root) {
12
+ const info = await lstat(path);
13
+ if (!info.isDirectory() || info.isSymbolicLink() || !isInside(root, await realpath(path))) {
14
+ throw new Error('Capture destination must be a real directory inside the consuming project.');
15
+ }
16
+ }
17
+
18
+ async function validateExistingDirectory(path, root) {
19
+ try { await validateDirectory(path, root); }
20
+ catch (error) { if (error.code !== 'ENOENT') throw error; }
21
+ }
22
+
23
+ async function ensureDirectory(path, root) {
24
+ try { await mkdir(path); }
25
+ catch (error) { if (error.code !== 'EEXIST') throw error; }
26
+ await validateDirectory(path, root);
27
+ }
28
+
29
+ async function replaceCaptureFile(temporaryPath, outputPath) {
30
+ for (let attempt = 0; ; attempt += 1) {
31
+ try {
32
+ await rename(temporaryPath, outputPath);
33
+ return;
34
+ } catch (error) {
35
+ if (process.platform !== 'win32' || !['EACCES', 'EBUSY', 'EPERM'].includes(error.code) || attempt >= 4) throw error;
36
+ await new Promise((resolveDelay) => setTimeout(resolveDelay, 25 * (attempt + 1)));
37
+ }
38
+ }
39
+ }
40
+
41
+ export function requireRepositoryIgnore(root, path) {
42
+ let evidence;
43
+ const repositoryPath = relative(root, path).split(sep).join('/');
44
+ try {
45
+ evidence = execFileSync('git', ['check-ignore', '--verbose', '-z', '--stdin'], {
46
+ cwd: root,
47
+ input: `${repositoryPath}\0`,
48
+ encoding: 'utf8',
49
+ stdio: ['pipe', 'pipe', 'ignore'],
50
+ }).split('\0');
51
+ } catch {
52
+ throw new Error('Add .spfx-workbench/captures/ to a repository .gitignore file before saving a capture.');
53
+ }
54
+ if (!(evidence[0] === '.gitignore' || evidence[0]?.endsWith('/.gitignore'))) {
55
+ throw new Error('Add .spfx-workbench/captures/ to a repository .gitignore file before saving a capture.');
56
+ }
57
+ }
58
+
59
+ /** Write a local JSON artifact after repository ignore and path checks pass. */
60
+ export async function writeLocalCapture(capture, { root, name = 'library-items' } = {}) {
61
+ if (!/^[a-z0-9][a-z0-9._-]{0,50}$/i.test(name)) throw new Error('Capture name must be a safe file name.');
62
+ const consumerRoot = await realpath(root ?? process.cwd());
63
+ const workbenchDir = resolve(consumerRoot, '.spfx-workbench');
64
+ const outputDir = resolve(workbenchDir, 'captures');
65
+ const outputPath = resolve(outputDir, `${name}.json`);
66
+ const temporaryPath = resolve(outputDir, `.capture-${randomUUID()}.tmp`);
67
+
68
+ await validateExistingDirectory(workbenchDir, consumerRoot);
69
+ await validateExistingDirectory(outputDir, consumerRoot);
70
+ for (const path of [outputPath, temporaryPath]) requireRepositoryIgnore(consumerRoot, path);
71
+ await ensureDirectory(workbenchDir, consumerRoot);
72
+ await ensureDirectory(outputDir, consumerRoot);
73
+ try {
74
+ if ((await lstat(outputPath)).isSymbolicLink()) throw new Error('Capture output cannot be a symbolic link.');
75
+ } catch (error) { if (error.code !== 'ENOENT') throw error; }
76
+
77
+ const handle = await open(temporaryPath, 'wx');
78
+ try {
79
+ await handle.writeFile(`${JSON.stringify(capture, null, 2)}\n`);
80
+ await handle.sync();
81
+ await handle.close();
82
+ await replaceCaptureFile(temporaryPath, outputPath);
83
+ } finally {
84
+ await handle.close().catch(() => {});
85
+ await rm(temporaryPath, { force: true }).catch(() => {});
86
+ }
87
+ return outputPath;
88
+ }
89
+
90
+ /** Store a completed HAR beside the consumer's other ignored capture files. */
91
+ export async function archiveLocalHar(bytes, { root, name } = {}) {
92
+ if (!/^[a-z0-9][a-z0-9._-]{0,100}$/i.test(name ?? '') || !Buffer.isBuffer(bytes)) {
93
+ throw new Error('HAR archive requires a safe file name and byte buffer.');
94
+ }
95
+ const consumerRoot = await realpath(root ?? process.cwd());
96
+ const workbenchDir = resolve(consumerRoot, '.spfx-workbench');
97
+ const outputDir = resolve(workbenchDir, 'captures');
98
+ const outputPath = resolve(outputDir, `${name}.har`);
99
+ const temporaryPath = resolve(outputDir, `.capture-${randomUUID()}.tmp`);
100
+
101
+ await validateExistingDirectory(workbenchDir, consumerRoot);
102
+ await validateExistingDirectory(outputDir, consumerRoot);
103
+ for (const path of [outputPath, temporaryPath]) requireRepositoryIgnore(consumerRoot, path);
104
+ await ensureDirectory(workbenchDir, consumerRoot);
105
+ await ensureDirectory(outputDir, consumerRoot);
106
+ try {
107
+ if ((await lstat(outputPath)).isSymbolicLink()) throw new Error('Capture output cannot be a symbolic link.');
108
+ } catch (error) { if (error.code !== 'ENOENT') throw error; }
109
+
110
+ const handle = await open(temporaryPath, 'wx');
111
+ try {
112
+ await handle.writeFile(bytes);
113
+ await handle.sync();
114
+ await handle.close();
115
+ await replaceCaptureFile(temporaryPath, outputPath);
116
+ } finally {
117
+ await handle.close().catch(() => {});
118
+ await rm(temporaryPath, { force: true }).catch(() => {});
119
+ }
120
+ return outputPath;
121
+ }
@@ -0,0 +1,44 @@
1
+ import { access } from 'node:fs/promises';
2
+ import { homedir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { chromium } from 'playwright-core';
5
+ import { resolveChromiumExecutable } from '../scripts/resolve-chromium.mjs';
6
+
7
+ export const AUTH_TENANTS = Object.freeze({
8
+ cfwizdemo: Object.freeze(['https://cfwizdemo.sharepoint.com']),
9
+ cfcloud: Object.freeze(['https://cfcloud.sharepoint.com', 'https://contentformula.visualstudio.com']),
10
+ workswithagents: Object.freeze(['https://workswithagents.sharepoint.com']),
11
+ });
12
+
13
+ export function resolveTenantAuthStatePath(tenant, homeDirectory = homedir()) {
14
+ if (!Object.hasOwn(AUTH_TENANTS, tenant)) {
15
+ throw new Error(`Unknown tenant "${tenant}". Supported tenants: ${Object.keys(AUTH_TENANTS).join(', ')}.`);
16
+ }
17
+ return join(homeDirectory, '.playwright-auth', `${tenant}.json`);
18
+ }
19
+
20
+ export async function createTenantContext(browser, tenant, options = {}) {
21
+ const storageState = resolveTenantAuthStatePath(tenant);
22
+ try { await access(storageState); }
23
+ catch { throw new Error(`No saved sign-in for ${tenant}. Run: spfx-workbench-auth login ${tenant}`); }
24
+ return browser.newContext({ ...options, storageState });
25
+ }
26
+
27
+ export async function launchTenantBrowser(tenant, { headless = true, launchOptions = {}, contextOptions = {} } = {}) {
28
+ const executablePath = await resolveChromiumExecutable();
29
+ const browser = await chromium.launch({ ...launchOptions, executablePath, headless });
30
+ try {
31
+ const context = await createTenantContext(browser, tenant, contextOptions);
32
+ return {
33
+ browser,
34
+ context,
35
+ close: async () => {
36
+ await context.close();
37
+ await browser.close();
38
+ },
39
+ };
40
+ } catch (error) {
41
+ await browser.close().catch(() => {});
42
+ throw error;
43
+ }
44
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Local mirror of the user-defined list-item response shape shown in the
3
+ * Microsoft SPFx REST example. These are response models, not SPFx SDK types.
4
+ */
5
+ export interface SPFxRestListItem {
6
+ /** SharePoint REST Edm.Int32; the simulator accepts 0 through 2,147,483,647. */
7
+ Id: number;
8
+ Title?: string;
9
+ FileLeafRef: string;
10
+ Modified: string;
11
+ }
12
+
13
+ export interface SPFxRestCollection<T> {
14
+ value: T[];
15
+ }
16
+
17
+ /** Synthetic subset of the SharePoint web response documented by SPFx. */
18
+ export interface SPFxWebMetadata {
19
+ Title: string;
20
+ }
21
+
22
+ /** Synthetic projection used in Microsoft's SPFx list-picker example. */
23
+ export interface SPFxRestListMetadata {
24
+ Id: string;
25
+ Title: string;
26
+ ItemCount: number;
27
+ }
28
+
29
+ export interface WorkbenchCapture<T> {
30
+ format: 'spfx-workbench-capture/v1';
31
+ source: 'synthetic';
32
+ request: {
33
+ method: 'GET';
34
+ route: 'sp-rest-library-items';
35
+ query: { $select: string; $top: string };
36
+ };
37
+ response: { status: 200; body: SPFxRestCollection<T> };
38
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Deterministic simulator subset, derived from the SPFx 1.24.1 WebPartContext,
3
+ * inherited component context, PageContext, and web/site/user declarations.
4
+ * These are not tenant context or a complete implementation of those interfaces.
5
+ */
6
+ export interface SimulatorContext {
7
+ readonly domElement: HTMLElement | null;
8
+ readonly manifest: unknown;
9
+ readonly displayMode: 2;
10
+ readonly isServedFromLocalhost: true;
11
+ /** The local canvas simulates a SharePoint page; no Teams SDK is available. */
12
+ readonly sdks: { readonly microsoftTeams?: undefined };
13
+ readonly pageContext: {
14
+ readonly web: { readonly title: string; readonly absoluteUrl: string; readonly serverRelativeUrl: string };
15
+ readonly site: { readonly absoluteUrl: string; readonly serverRelativeUrl: string };
16
+ readonly user: { readonly displayName: string; readonly loginName: string };
17
+ };
18
+ readonly instanceId: string;
19
+ /** Read-only replay subset modeled on @microsoft/sp-http-base 1.24.1. GETs and captured read-only POST routes replay locally; configuration flags and POST headers do not change responses. */
20
+ readonly spHttpClient: {
21
+ get(url: string, configuration: SimulatorSPHttpClientConfiguration, options?: never): Promise<SimulatorSPHttpClientResponse>;
22
+ post(url: string, configuration: SimulatorSPHttpClientConfiguration, options: { readonly body: string; readonly headers?: HeadersInit }): Promise<SimulatorSPHttpClientResponse>;
23
+ };
24
+ }
25
+
26
+ export type SimulatorSPHttpClientResponse = Pick<Response, 'ok' | 'status' | 'statusText' | 'headers' | 'json' | 'text'>;
27
+
28
+ /** Structural view of the 1.24.1 SPHttpClient configuration flags; the simulator accepts but ignores these transport settings. */
29
+ export interface SimulatorSPHttpClientConfiguration {
30
+ readonly jsonRequest?: boolean;
31
+ readonly jsonResponse?: boolean;
32
+ readonly defaultSameOriginCredentials?: boolean;
33
+ readonly defaultODataVersion?: { toString(): string };
34
+ readonly requestDigest?: boolean;
35
+ readonly usePopupForCookieRefresh?: boolean;
36
+ }
37
+
38
+ export declare function createSimulatorContext(options?: { readonly domElement?: HTMLElement | null; readonly manifest?: unknown; readonly displayMode?: 2 }): SimulatorContext;
@@ -0,0 +1,10 @@
1
+ const labels = Object.freeze({
2
+ loading: 'Loading local data',
3
+ unavailable: 'Mock unavailable',
4
+ 'ignored-local-capture': 'Ignored local synthetic capture',
5
+ 'committed-synthetic-fixture': 'Committed synthetic fixture',
6
+ });
7
+
8
+ export function dataSourceLabel(source) {
9
+ return Object.hasOwn(labels, source) ? labels[source] : 'Local mock';
10
+ }
@@ -0,0 +1,8 @@
1
+ const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
2
+ const twoDigits = (value) => String(value).padStart(2, '0');
3
+
4
+ export function formatModified(value) {
5
+ const date = new Date(value);
6
+ if (!Number.isFinite(date.getTime())) return 'Invalid date';
7
+ return `${twoDigits(date.getUTCDate())} ${months[date.getUTCMonth()]} ${date.getUTCFullYear()}, ${twoDigits(date.getUTCHours())}:${twoDigits(date.getUTCMinutes())} UTC`;
8
+ }