@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
package/vite.config.js ADDED
@@ -0,0 +1,399 @@
1
+ import { defineConfig } from 'vite';
2
+ import { readFile, realpath, stat } from 'node:fs/promises';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { isAbsolute, relative, resolve, sep } from 'node:path';
5
+ import react from '@vitejs/plugin-react';
6
+ import { MOCK_API_PATH, MOCK_WEB_API_PATH, MOCK_LISTS_API_PATH, MOCK_HAR_API_PATH, capturedApiRequestKey, indexCapturedApiRequests, matchCapturedApiRequest, isSupportedListItemsPath, isSupportedWebMetadataPath, isSupportedSharePointListsPath, replayListItems, replayWebMetadata, replaySharePointLists, validateReplayCapture } from './scripts/mock-contract.mjs';
7
+
8
+ const fixturePath = fileURLToPath(new URL('./fixtures/library-items.synthetic.json', import.meta.url));
9
+ const workbenchRoot = resolve(fileURLToPath(new URL('.', import.meta.url)));
10
+ const captureRoot = resolve(process.env.SPFX_WORKBENCH_DATA_ROOT ?? process.cwd());
11
+ const capturePath = resolve(captureRoot, '.spfx-workbench/captures/library-items.json');
12
+ const tenantHarPath = resolve(captureRoot, '.spfx-workbench/captures/tenant.har');
13
+ const liveTenantHarPath = resolve(captureRoot, '.spfx-workbench/captures/tenant-live.json');
14
+ let tenantHarCache;
15
+ const componentModule = 'virtual:spfx-workbench-consumer';
16
+ const resolvedComponentModule = `\0${componentModule}`;
17
+ const consumerComponentPath = process.env.SPFX_WORKBENCH_COMPONENT;
18
+ const spfxRuntimeShim = resolve(workbenchRoot, 'src/spfx-preview-shims.mjs');
19
+ const spfxRuntimeAliases = [
20
+ '@microsoft/sp-component-base',
21
+ '@microsoft/sp-core-library',
22
+ '@microsoft/sp-lodash-subset',
23
+ '@microsoft/sp-property-pane',
24
+ '@microsoft/sp-webpart-base',
25
+ ].map((moduleName) => ({ find: new RegExp(`^${moduleName.replaceAll('/', '\\/')}$`), replacement: spfxRuntimeShim }));
26
+
27
+ function consumerComponent() {
28
+ return {
29
+ name: 'spfx-workbench-consumer-component',
30
+ enforce: 'pre',
31
+ resolveId(id) {
32
+ if (id === componentModule) return resolvedComponentModule;
33
+ },
34
+ load(id) {
35
+ if (id !== resolvedComponentModule) return;
36
+ if (!consumerComponentPath) return 'export default null;';
37
+ const target = consumerComponentPath;
38
+ const props = process.env.SPFX_WORKBENCH_PROPS ?? '{}';
39
+ return `import React from 'react';\nimport Component from ${JSON.stringify(target)};\nimport LifecycleWebPart from ${JSON.stringify(resolve(workbenchRoot, 'src/lifecycle-webpart.jsx'))};\nimport { createSimulatorContext } from ${JSON.stringify(resolve(workbenchRoot, 'src/simulator-context.mjs'))};\nconst suppliedProps = ${props};\nconst isLifecycleWebPart = Component?.prototype && typeof Component.prototype.render === 'function' && !Component.prototype.isReactComponent;\nexport default function SimulatorEntry() { const [context] = React.useState(() => createSimulatorContext()); return isLifecycleWebPart ? React.createElement(LifecycleWebPart, { Component, properties: suppliedProps.properties }) : React.createElement(Component, { ...suppliedProps, context }); }`;
40
+ },
41
+ };
42
+ }
43
+
44
+ function consumerLocalizedResources() {
45
+ const consumerRoot = resolve(process.env.SPFX_WORKBENCH_DATA_ROOT ?? process.cwd());
46
+ const virtualPrefix = '\0spfx-workbench-localized:';
47
+ const resolvedResources = new Map();
48
+ let resourceMappings;
49
+
50
+ async function loadResourceMappings() {
51
+ if (!resourceMappings) {
52
+ resourceMappings = readFile(resolve(consumerRoot, 'config/config.json'), 'utf8')
53
+ .then((contents) => JSON.parse(contents).localizedResources ?? {})
54
+ .catch((error) => {
55
+ if (error.code === 'ENOENT') return {};
56
+ throw new Error(`Could not read consumer config/config.json: ${error.message}`);
57
+ });
58
+ }
59
+ return resourceMappings;
60
+ }
61
+
62
+ return {
63
+ name: 'spfx-workbench-localized-resources',
64
+ enforce: 'pre',
65
+ async resolveId(id) {
66
+ const mappings = await loadResourceMappings();
67
+ const configuredPath = mappings[id];
68
+ if (typeof configuredPath !== 'string') return null;
69
+
70
+ const builtPath = resolve(consumerRoot, configuredPath.replaceAll('{locale}', 'en-us'));
71
+ const candidates = [builtPath];
72
+ const libRoot = resolve(consumerRoot, 'lib');
73
+ const libRelativePath = relative(libRoot, builtPath);
74
+ if (libRelativePath && libRelativePath !== '..' && !libRelativePath.startsWith(`..${sep}`) && !isAbsolute(libRelativePath)) {
75
+ candidates.push(resolve(consumerRoot, 'src', libRelativePath));
76
+ }
77
+
78
+ for (const candidate of candidates) {
79
+ let canonicalPath;
80
+ try { canonicalPath = await realpath(candidate); }
81
+ catch (error) { if (error.code === 'ENOENT') continue; throw error; }
82
+ const relativePath = relative(consumerRoot, canonicalPath);
83
+ if (relativePath === '..' || relativePath.startsWith(`..${sep}`) || isAbsolute(relativePath)) {
84
+ throw new Error(`SPFx localized resource "${id}" resolves outside the consumer project.`);
85
+ }
86
+ if (!(await stat(canonicalPath)).isFile()) continue;
87
+ const virtualId = `${virtualPrefix}${id}`;
88
+ resolvedResources.set(virtualId, canonicalPath);
89
+ return virtualId;
90
+ }
91
+
92
+ throw new Error(`Could not find the en-us SPFx localized resource "${id}" mapped in config/config.json.`);
93
+ },
94
+ async load(id) {
95
+ const resourcePath = resolvedResources.get(id);
96
+ if (!resourcePath) return null;
97
+ this.addWatchFile(resourcePath);
98
+ const source = await readFile(resourcePath, 'utf8');
99
+ const match = source.match(/^\s*define\s*\(\s*\[\s*\]\s*,\s*function\s*\(\s*\)\s*\{\s*return\s+(\{[\s\S]*\})\s*;?\s*\}\s*\)\s*;?\s*$/);
100
+ if (!match) throw new Error(`SPFx localized resource "${id}" is not a generated AMD resource object.`);
101
+ let values;
102
+ try { values = JSON.parse(match[1]); }
103
+ catch { throw new Error(`SPFx localized resource "${id}" does not contain a JSON-compatible resource object.`); }
104
+ if (!values || Array.isArray(values) || typeof values !== 'object') {
105
+ throw new Error(`SPFx localized resource "${id}" must contain an object.`);
106
+ }
107
+ const namedExports = Object.keys(values)
108
+ .filter((key) => /^[A-Za-z_$][\w$]*$/.test(key))
109
+ .map((key) => `export const ${key} = resources[${JSON.stringify(key)}];`)
110
+ .join('\n');
111
+ return `const resources = ${JSON.stringify(values)};\nexport default resources;\n${namedExports}`;
112
+ },
113
+ };
114
+ }
115
+
116
+ async function loadTenantHar() {
117
+ let sourcePath = liveTenantHarPath;
118
+ let info;
119
+ try { info = await stat(sourcePath); }
120
+ catch (error) {
121
+ if (error.code !== 'ENOENT') throw error;
122
+ sourcePath = tenantHarPath;
123
+ try { info = await stat(sourcePath); }
124
+ catch (fallbackError) {
125
+ if (fallbackError.code === 'ENOENT') {
126
+ tenantHarCache = { version: 'missing', index: new Map(), occurrences: new Map(), sourcePath: null, captureId: null };
127
+ return tenantHarCache;
128
+ }
129
+ throw fallbackError;
130
+ }
131
+ }
132
+ const version = `${sourcePath}:${info.size}:${info.mtimeMs}:${info.ctimeMs}`;
133
+ if (tenantHarCache?.version === version) return tenantHarCache;
134
+ const capture = JSON.parse(await readFile(sourcePath, 'utf8'));
135
+ const entries = capture?.log?.entries;
136
+ if (!Array.isArray(entries)) throw new Error('The local tenant HAR has no entries array.');
137
+ const captureId = capture.spfxWorkbenchCaptureId ?? null;
138
+ const occurrences = tenantHarCache?.sourcePath === sourcePath && tenantHarCache.captureId === captureId
139
+ ? tenantHarCache.occurrences : new Map();
140
+ tenantHarCache = { version, index: indexCapturedApiRequests(entries), occurrences, sourcePath, captureId };
141
+ return tenantHarCache;
142
+ }
143
+
144
+ async function readJsonRequest(req, maxBytes = 1_000_000) {
145
+ const chunks = [];
146
+ let size = 0;
147
+ for await (const chunk of req) {
148
+ size += chunk.length;
149
+ if (size > maxBytes) throw new Error('too-large');
150
+ chunks.push(chunk);
151
+ }
152
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'));
153
+ }
154
+
155
+ function capturedBody(entry) {
156
+ const content = entry.response?.content ?? {};
157
+ if (typeof content.text !== 'string') return Buffer.alloc(0);
158
+ return content.encoding === 'base64' ? Buffer.from(content.text, 'base64') : Buffer.from(content.text, 'utf8');
159
+ }
160
+
161
+ function replyWithCapturedEntry(res, entry, version) {
162
+ const status = Number(entry.response?.status);
163
+ if (!Number.isInteger(status) || status < 100 || status > 599) {
164
+ res.statusCode = 502;
165
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
166
+ res.end('{"error":"Captured response has an invalid HTTP status."}');
167
+ return;
168
+ }
169
+ res.statusCode = status;
170
+ res.setHeader('Cache-Control', 'no-store');
171
+ res.setHeader('X-SPFx-Workbench-Data', 'captured-tenant-har');
172
+ res.setHeader('X-SPFx-Workbench-HAR-Matched', 'true');
173
+ res.setHeader('X-SPFx-Workbench-HAR-Version', version);
174
+ const blockedHeaders = new Set([
175
+ 'set-cookie', 'set-cookie2', 'content-encoding', 'content-length', 'transfer-encoding',
176
+ 'connection', 'keep-alive', 'upgrade', 'trailer', 'te', 'location',
177
+ ]);
178
+ for (const { name, value } of entry.response?.headers ?? []) {
179
+ const headerName = String(name).toLowerCase();
180
+ if (!blockedHeaders.has(headerName)) {
181
+ try { res.setHeader(name, value); } catch {}
182
+ }
183
+ }
184
+ if (!res.hasHeader('Content-Type') && entry.response?.content?.mimeType) {
185
+ res.setHeader('Content-Type', entry.response.content.mimeType);
186
+ }
187
+ res.end(capturedBody(entry));
188
+ }
189
+
190
+ async function replyWithCapturedHar(req, res) {
191
+ if (req.method !== 'POST') {
192
+ res.statusCode = 405;
193
+ res.setHeader('Allow', 'POST');
194
+ res.end();
195
+ return;
196
+ }
197
+ let input;
198
+ let requestUrl;
199
+ let requestMethod;
200
+ let requestBody;
201
+ try {
202
+ input = await readJsonRequest(req);
203
+ if (typeof input?.url !== 'string' || !/^[0-9a-f-]{36}$/i.test(input.sessionId ?? '')) {
204
+ throw new Error('invalid-request');
205
+ }
206
+ requestMethod = String(input.method ?? 'GET').toUpperCase();
207
+ requestBody = typeof input.requestBody === 'string' ? input.requestBody : '';
208
+ if (!['GET', 'POST'].includes(requestMethod) || (requestMethod === 'POST' && typeof input.requestBody !== 'string')) {
209
+ throw new Error('invalid-request');
210
+ }
211
+ requestUrl = new URL(input.url);
212
+ if (!['http:', 'https:'].includes(requestUrl.protocol) || requestUrl.username || requestUrl.password || requestUrl.hash
213
+ || !capturedApiRequestKey(requestMethod, requestUrl.href, requestBody)) throw new Error('invalid-request');
214
+ } catch (error) {
215
+ const tooLarge = error.message === 'too-large';
216
+ res.statusCode = tooLarge ? 413 : 400;
217
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
218
+ res.end(JSON.stringify({ error: tooLarge ? 'Replay request exceeded 1 MB.' : 'Replay request must contain a valid SharePoint REST GET or captured POST URL.' }));
219
+ return;
220
+ }
221
+
222
+ let cache;
223
+ try { cache = await loadTenantHar(); }
224
+ catch {
225
+ res.statusCode = 500;
226
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
227
+ res.end('{"error":"The local tenant HAR is invalid; capture it again."}');
228
+ return;
229
+ }
230
+ const key = capturedApiRequestKey(requestMethod, requestUrl.href, requestBody);
231
+ const occurrenceKey = `${input.sessionId}\n${key}`;
232
+ const occurrence = cache.occurrences.get(occurrenceKey) ?? 0;
233
+ const entry = matchCapturedApiRequest(cache.index, requestMethod, requestUrl.href, occurrence, requestBody);
234
+ if (entry) {
235
+ const count = cache.index.get(key)?.length ?? 1;
236
+ if (!cache.occurrences.has(occurrenceKey) && cache.occurrences.size >= 10_000) {
237
+ cache.occurrences.delete(cache.occurrences.keys().next().value);
238
+ }
239
+ cache.occurrences.set(occurrenceKey, Math.min(occurrence + 1, count - 1));
240
+ replyWithCapturedEntry(res, entry, cache.version);
241
+ return;
242
+ }
243
+
244
+ const relativePath = requestUrl.pathname.slice(requestUrl.pathname.indexOf('/_api/'));
245
+ const fallbackPath = requestMethod !== 'GET' ? null : isSupportedListItemsPath(relativePath) ? MOCK_API_PATH
246
+ : isSupportedWebMetadataPath(relativePath) ? MOCK_WEB_API_PATH
247
+ : isSupportedSharePointListsPath(relativePath) ? MOCK_LISTS_API_PATH : null;
248
+ res.setHeader('X-SPFx-Workbench-HAR-Version', cache.version);
249
+ if (fallbackPath) {
250
+ const fallbackUrl = new URL(fallbackPath, 'http://localhost');
251
+ fallbackUrl.search = requestUrl.search;
252
+ const fallbackRequest = { method: 'GET', url: `${fallbackUrl.pathname}${fallbackUrl.search}` };
253
+ await replyWithMock(fallbackRequest, res, () => {});
254
+ return;
255
+ }
256
+ res.statusCode = 404;
257
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
258
+ res.end(JSON.stringify({ error: `No matching ${requestMethod} was found in the local SharePoint HAR or supported synthetic routes.`, path: relativePath }));
259
+ }
260
+
261
+ async function replyWithMock(req, res, next) {
262
+ let url;
263
+ try { url = new URL(req.url, 'http://localhost'); }
264
+ catch { return next(); }
265
+ if (url.pathname === MOCK_HAR_API_PATH) return replyWithCapturedHar(req, res);
266
+ if (url.pathname !== MOCK_API_PATH && url.pathname !== MOCK_WEB_API_PATH && url.pathname !== MOCK_LISTS_API_PATH) return next();
267
+ if (req.method !== 'GET') {
268
+ res.statusCode = 405;
269
+ res.setHeader('Allow', 'GET');
270
+ res.end();
271
+ return;
272
+ }
273
+
274
+ if (url.pathname === MOCK_WEB_API_PATH) {
275
+ try {
276
+ const body = JSON.stringify(replayWebMetadata(url.searchParams));
277
+ res.statusCode = 200;
278
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
279
+ res.setHeader('Cache-Control', 'no-store');
280
+ res.setHeader('X-SPFx-Workbench-Data', 'committed-synthetic-fixture');
281
+ res.end(body);
282
+ } catch (error) {
283
+ res.statusCode = 400;
284
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
285
+ res.setHeader('Cache-Control', 'no-store');
286
+ res.end(JSON.stringify({ error: error.message }));
287
+ }
288
+ return;
289
+ }
290
+
291
+ if (url.pathname === MOCK_LISTS_API_PATH) {
292
+ try {
293
+ const body = JSON.stringify(replaySharePointLists(url.searchParams));
294
+ res.statusCode = 200;
295
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
296
+ res.setHeader('Cache-Control', 'no-store');
297
+ res.setHeader('X-SPFx-Workbench-Data', 'committed-synthetic-fixture');
298
+ res.end(body);
299
+ } catch (error) {
300
+ res.statusCode = 400;
301
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
302
+ res.setHeader('Cache-Control', 'no-store');
303
+ res.end(JSON.stringify({ error: error.message }));
304
+ }
305
+ return;
306
+ }
307
+
308
+ try {
309
+ let raw;
310
+ let source = 'committed-synthetic-fixture';
311
+ let fromLocalCapture = false;
312
+ try {
313
+ raw = await readFile(capturePath, 'utf8');
314
+ fromLocalCapture = true;
315
+ } catch (error) {
316
+ if (error.code !== 'ENOENT') throw error;
317
+ raw = await readFile(fixturePath, 'utf8');
318
+ }
319
+ const capture = validateReplayCapture(JSON.parse(raw));
320
+ if (fromLocalCapture) source = 'ignored-local-capture';
321
+ let body;
322
+ try { body = JSON.stringify(replayListItems(capture, url.searchParams)); }
323
+ catch (error) {
324
+ res.statusCode = 400;
325
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
326
+ res.setHeader('Cache-Control', 'no-store');
327
+ res.end(JSON.stringify({ error: error.message }));
328
+ return;
329
+ }
330
+ res.statusCode = capture.response.status;
331
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
332
+ res.setHeader('Cache-Control', 'no-store');
333
+ res.setHeader('X-SPFx-Workbench-Data', source);
334
+ res.end(body);
335
+ } catch {
336
+ res.statusCode = 500;
337
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
338
+ res.setHeader('Cache-Control', 'no-store');
339
+ res.end('{"error":"Local mock capture is invalid."}');
340
+ }
341
+ }
342
+
343
+ function mockApi() {
344
+ return {
345
+ name: 'spfx-workbench-mock-api',
346
+ configureServer(server) { server.middlewares.use(replyWithMock); },
347
+ configurePreviewServer(server) { server.middlewares.use(replyWithMock); },
348
+ };
349
+ }
350
+
351
+ function canonicalFileAccessGuard() {
352
+ return {
353
+ name: 'spfx-workbench-canonical-file-access',
354
+ configureServer(server) {
355
+ const allowedRoots = Promise.all(server.config.server.fs.allow.map((root) =>
356
+ realpath(root).catch(() => null),
357
+ )).then((roots) => roots.filter(Boolean));
358
+
359
+ server.middlewares.use((req, res, next) => {
360
+ let pathname;
361
+ try { pathname = new URL(req.url, 'http://localhost').pathname; }
362
+ catch { return next(); }
363
+ if (!pathname.startsWith('/@fs/')) return next();
364
+
365
+ void (async () => {
366
+ try {
367
+ let target = decodeURIComponent(pathname.slice('/@fs/'.length));
368
+ if (!isAbsolute(target) && !/^[A-Z]:[\\/]/i.test(target)) target = resolve(sep, target);
369
+ const canonicalTarget = await realpath(target);
370
+ const roots = await allowedRoots;
371
+ const allowed = roots.some((root) => {
372
+ const relativeTarget = relative(root, canonicalTarget);
373
+ return relativeTarget === '' || (
374
+ relativeTarget !== '..' && !relativeTarget.startsWith(`..${sep}`) && !isAbsolute(relativeTarget)
375
+ );
376
+ });
377
+ if (!allowed) {
378
+ res.statusCode = 403;
379
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
380
+ res.end('{"error":"Local file is outside approved workbench roots."}');
381
+ return;
382
+ }
383
+ next();
384
+ } catch {
385
+ res.statusCode = 404;
386
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
387
+ res.end('{"error":"Local file is unavailable."}');
388
+ }
389
+ })();
390
+ });
391
+ },
392
+ };
393
+ }
394
+
395
+ export default defineConfig({
396
+ resolve: { alias: spfxRuntimeAliases, dedupe: ['react', 'react-dom'] },
397
+ optimizeDeps: { include: ['react', 'react-dom', 'react-dom/client'], noDiscovery: true },
398
+ plugins: [canonicalFileAccessGuard(), consumerLocalizedResources(), react(), consumerComponent(), mockApi()],
399
+ });