@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.
- package/LICENSE +21 -0
- package/README.md +240 -2
- package/bin/spfx-workbench-auth.mjs +143 -0
- package/bin/spfx-workbench-capture.mjs +5 -0
- package/bin/spfx-workbench-debug.mjs +155 -0
- package/bin/spfx-workbench-doctor.mjs +2 -0
- package/bin/spfx-workbench-heft-target.mjs +2 -0
- package/bin/spfx-workbench-replay.mjs +2 -0
- package/bin/spfx-workbench.mjs +97 -0
- package/docs/mock-data-and-capture.md +52 -0
- package/docs/sharepoint-behavior-snapshot-2026-11-15-1455Z.md +67 -0
- package/fixtures/library-items.synthetic.json +23 -0
- package/index.html +13 -0
- package/package.json +58 -4
- package/scripts/benchmark-capture-import.mjs +50 -0
- package/scripts/benchmark-consumer-hmr.mjs +251 -0
- package/scripts/benchmark-mock-api.mjs +114 -0
- package/scripts/check-tarball-install.mjs +413 -0
- package/scripts/diagnose-consumer.mjs +228 -0
- package/scripts/diff-captures.mjs +452 -0
- package/scripts/import-synthetic-capture.mjs +60 -0
- package/scripts/minimal-playwright-state.mjs +15 -0
- package/scripts/mock-contract.mjs +375 -0
- package/scripts/replay-sharepoint-capture.mjs +123 -0
- package/scripts/resolve-chromium.mjs +22 -0
- package/scripts/resolve-serve-target.mjs +70 -0
- package/scripts/spfx-node-runtime.mjs +19 -0
- package/scripts/watch-sharepoint-capture.mjs +395 -0
- package/scripts/write-local-capture.mjs +121 -0
- package/src/auth-state.mjs +44 -0
- package/src/contracts/sharepoint-rest.d.ts +38 -0
- package/src/contracts/simulator-context.d.ts +38 -0
- package/src/data-source-label.mjs +10 -0
- package/src/format-modified.mjs +8 -0
- package/src/lifecycle-webpart.jsx +43 -0
- package/src/main.jsx +14 -0
- package/src/simulator-context.mjs +94 -0
- package/src/spfx-preview-shims.mjs +21 -0
- package/src/workbench.css +187 -0
- package/src/workbench.jsx +222 -0
- package/vite.config.js +399 -0
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
import { mkdtemp, readFile, realpath, rename, rm, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { spawn } from 'node:child_process';
|
|
3
|
+
import { dirname, resolve } from 'node:path';
|
|
4
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
5
|
+
import { createServer } from 'node:net';
|
|
6
|
+
|
|
7
|
+
const args = process.argv.slice(2);
|
|
8
|
+
const valueAfter = (flag, fallback) => {
|
|
9
|
+
const index = args.indexOf(flag);
|
|
10
|
+
return index < 0 ? fallback : args[index + 1];
|
|
11
|
+
};
|
|
12
|
+
const samples = Number(valueAfter('--samples', '1'));
|
|
13
|
+
const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
|
14
|
+
const cli = resolve(packageRoot, 'bin/spfx-workbench.mjs');
|
|
15
|
+
const temp = await mkdtemp(resolve(packageRoot, '.spfx-hmr-benchmark-'));
|
|
16
|
+
const componentPath = resolve(temp, 'HmrProbe.jsx');
|
|
17
|
+
let server;
|
|
18
|
+
let socket;
|
|
19
|
+
let serverOutput = '';
|
|
20
|
+
|
|
21
|
+
async function freeLoopbackPort() {
|
|
22
|
+
const probe = createServer();
|
|
23
|
+
await new Promise((resolveListen, reject) => {
|
|
24
|
+
probe.once('error', reject);
|
|
25
|
+
probe.listen(0, '127.0.0.1', resolveListen);
|
|
26
|
+
});
|
|
27
|
+
const port = probe.address().port;
|
|
28
|
+
await new Promise((resolveClose) => probe.close(resolveClose));
|
|
29
|
+
return port;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function viteFsUrl(base, filePath) {
|
|
33
|
+
const normalized = filePath.replaceAll('\\', '/');
|
|
34
|
+
const absolutePath = normalized.startsWith('/') ? normalized.slice(1) : normalized;
|
|
35
|
+
return new URL(`/@fs/${absolutePath}`, base).href;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
if (!Number.isInteger(samples) || samples < 1 || samples > 100) {
|
|
39
|
+
process.stderr.write('--samples must be an integer from 1 to 100.\n');
|
|
40
|
+
process.exitCode = 2;
|
|
41
|
+
} else if (typeof WebSocket !== 'function') {
|
|
42
|
+
process.stderr.write('This benchmark requires a Node.js runtime with the built-in WebSocket client.\n');
|
|
43
|
+
process.exitCode = 2;
|
|
44
|
+
} else {
|
|
45
|
+
try {
|
|
46
|
+
await writeFile(resolve(temp, 'package.json'), JSON.stringify({ name: 'spfx-hmr-benchmark-consumer', private: true }));
|
|
47
|
+
await writeFile(componentPath, 'export default function HmrProbe(){ return <div>Revision 0</div>; }\n');
|
|
48
|
+
const port = await freeLoopbackPort();
|
|
49
|
+
server = spawn(process.execPath, [cli, '--component', 'HmrProbe.jsx', '--port', String(port)], { cwd: temp, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
50
|
+
for (const stream of [server.stdout, server.stderr]) {
|
|
51
|
+
stream.setEncoding('utf8');
|
|
52
|
+
stream.on('data', (chunk) => { serverOutput += chunk; });
|
|
53
|
+
}
|
|
54
|
+
const base = `http://127.0.0.1:${port}`;
|
|
55
|
+
const deadline = Date.now() + 10_000;
|
|
56
|
+
let ready = false;
|
|
57
|
+
while (Date.now() < deadline && server.exitCode === null) {
|
|
58
|
+
try {
|
|
59
|
+
const response = await fetch(`${base}/`);
|
|
60
|
+
if (response.ok) { ready = true; break; }
|
|
61
|
+
} catch {}
|
|
62
|
+
await new Promise((resolveDelay) => setTimeout(resolveDelay, 50));
|
|
63
|
+
}
|
|
64
|
+
if (!ready) throw new Error('Consumer CLI did not start for the HMR benchmark.');
|
|
65
|
+
|
|
66
|
+
const client = await (await fetch(`${base}/@vite/client`)).text();
|
|
67
|
+
const token = client.match(/const wsToken = "([^"]+)"/)?.[1];
|
|
68
|
+
if (!token) throw new Error('Could not find the local Vite HMR connection token.');
|
|
69
|
+
const socketUrl = new URL(base);
|
|
70
|
+
socketUrl.protocol = 'ws:';
|
|
71
|
+
socketUrl.pathname = '/';
|
|
72
|
+
socketUrl.search = '';
|
|
73
|
+
socketUrl.searchParams.set('token', token);
|
|
74
|
+
socket = new WebSocket(socketUrl, 'vite-hmr');
|
|
75
|
+
await new Promise((resolveOpen, rejectOpen) => {
|
|
76
|
+
socket.addEventListener('open', resolveOpen, { once: true });
|
|
77
|
+
socket.addEventListener('error', () => rejectOpen(new Error('Could not connect to the local Vite HMR WebSocket.')), { once: true });
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
const entry = await fetch(`${base}/src/main.jsx`);
|
|
81
|
+
const entrySource = await entry.text();
|
|
82
|
+
const wrapperPath = entrySource.match(/from "([^"]*virtual:spfx-workbench-consumer[^"]*)"/)?.[1];
|
|
83
|
+
if (!entry.ok || !wrapperPath) {
|
|
84
|
+
throw new Error('Vite did not load the Workbench entry module before measuring consumer updates.');
|
|
85
|
+
}
|
|
86
|
+
const wrapper = await fetch(new URL(wrapperPath, base));
|
|
87
|
+
if (!wrapper.ok || !(await wrapper.text()).includes('HmrProbe.jsx')) {
|
|
88
|
+
throw new Error('Vite did not load the consumer wrapper before measuring consumer updates.');
|
|
89
|
+
}
|
|
90
|
+
const componentUrl = viteFsUrl(base, await realpath(componentPath));
|
|
91
|
+
const loaded = await fetch(componentUrl);
|
|
92
|
+
if (!loaded.ok) throw new Error('Vite did not load the consumer component before measuring updates.');
|
|
93
|
+
const updatePath = 'HmrProbe.jsx';
|
|
94
|
+
let pending;
|
|
95
|
+
let measuring = false;
|
|
96
|
+
let waitingFor = 'initialization';
|
|
97
|
+
const recentMessages = [];
|
|
98
|
+
const measuredFullReloadEvents = [];
|
|
99
|
+
const onMessage = ({ data }) => {
|
|
100
|
+
let payload;
|
|
101
|
+
try { payload = JSON.parse(data); } catch { return; }
|
|
102
|
+
recentMessages.push({
|
|
103
|
+
type: payload.type,
|
|
104
|
+
waitingFor,
|
|
105
|
+
hasPendingWaiter: Boolean(pending),
|
|
106
|
+
path: payload.path,
|
|
107
|
+
triggeredBy: payload.triggeredBy,
|
|
108
|
+
updates: payload.updates?.map(({ path, acceptedPath }) => ({ path, acceptedPath })),
|
|
109
|
+
});
|
|
110
|
+
if (recentMessages.length > 8) recentMessages.shift();
|
|
111
|
+
if (payload.type === 'full-reload') {
|
|
112
|
+
if (measuring) measuredFullReloadEvents.push({ path: payload.path, triggeredBy: payload.triggeredBy });
|
|
113
|
+
pending?.resolve({ type: 'full-reload' });
|
|
114
|
+
} else if (payload.type === 'update' && payload.updates?.some((update) => `${update.path} ${update.acceptedPath}`.includes(updatePath))) {
|
|
115
|
+
const update = payload.updates.find((item) => `${item.path} ${item.acceptedPath}`.includes(updatePath));
|
|
116
|
+
pending?.resolve({ type: 'update', path: update.path });
|
|
117
|
+
}
|
|
118
|
+
};
|
|
119
|
+
socket.addEventListener('message', onMessage);
|
|
120
|
+
|
|
121
|
+
const waitForUpdate = (phase) => new Promise((resolveEvent, rejectEvent) => {
|
|
122
|
+
waitingFor = phase;
|
|
123
|
+
const timer = setTimeout(() => {
|
|
124
|
+
pending = undefined;
|
|
125
|
+
rejectEvent(new Error(`Timed out waiting for the Vite module-update event during ${phase}. Recent HMR messages: ${JSON.stringify(recentMessages)}`));
|
|
126
|
+
}, 30_000);
|
|
127
|
+
pending = { resolve: (event) => { clearTimeout(timer); pending = undefined; waitingFor = 'between-updates'; resolveEvent(event); } };
|
|
128
|
+
});
|
|
129
|
+
const replaceComponent = async (source) => {
|
|
130
|
+
const temporaryPath = `${componentPath}.tmp`;
|
|
131
|
+
await writeFile(temporaryPath, source);
|
|
132
|
+
await rename(temporaryPath, componentPath);
|
|
133
|
+
};
|
|
134
|
+
const writeRevision = async (revision) => replaceComponent(
|
|
135
|
+
`export default function HmrProbe(){ return <div>Revision ${revision}</div>; }\n`);
|
|
136
|
+
|
|
137
|
+
const updateTimings = [];
|
|
138
|
+
const verifiedIterationTimings = [];
|
|
139
|
+
let verificationFailures = 0;
|
|
140
|
+
let measuredFullReloads = 0;
|
|
141
|
+
let componentModulePath;
|
|
142
|
+
measuring = true;
|
|
143
|
+
for (let index = 0; index < samples; index += 1) {
|
|
144
|
+
const eventPromise = waitForUpdate(`sample-${index + 1}`);
|
|
145
|
+
const start = performance.now();
|
|
146
|
+
await writeRevision(index);
|
|
147
|
+
const event = await eventPromise;
|
|
148
|
+
if (event.type === 'full-reload') measuredFullReloads += 1;
|
|
149
|
+
else {
|
|
150
|
+
componentModulePath = event.path;
|
|
151
|
+
updateTimings.push(performance.now() - start);
|
|
152
|
+
const response = await fetch(componentUrl);
|
|
153
|
+
const transformedModule = await response.text();
|
|
154
|
+
if (!response.ok || !transformedModule.includes(`Revision ${index}`)) {
|
|
155
|
+
verificationFailures += 1;
|
|
156
|
+
} else {
|
|
157
|
+
verifiedIterationTimings.push(performance.now() - start);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
measuring = false;
|
|
162
|
+
if (!componentModulePath) throw new Error('Vite did not emit a component module update for the measured edit.');
|
|
163
|
+
const previousWindow = Object.getOwnPropertyDescriptor(globalThis, 'window');
|
|
164
|
+
Object.defineProperty(globalThis, 'window', { configurable: true, value: {} });
|
|
165
|
+
let incompatibilityReason;
|
|
166
|
+
try {
|
|
167
|
+
const runtimeUrl = pathToFileURL(resolve(packageRoot, 'node_modules/@vitejs/plugin-react/dist/refresh-runtime.js'));
|
|
168
|
+
const runtime = await import(runtimeUrl.href);
|
|
169
|
+
function HmrProbe() {}
|
|
170
|
+
incompatibilityReason = runtime.validateRefreshBoundaryAndEnqueueUpdate(
|
|
171
|
+
'HmrProbe.jsx',
|
|
172
|
+
{ default: HmrProbe, cacheKey: 1 },
|
|
173
|
+
{ default: HmrProbe, cacheKey: 2 },
|
|
174
|
+
);
|
|
175
|
+
incompatibilityReason = incompatibilityReason?.replace(
|
|
176
|
+
'__README_URL__',
|
|
177
|
+
'https://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-react',
|
|
178
|
+
);
|
|
179
|
+
} finally {
|
|
180
|
+
if (previousWindow) Object.defineProperty(globalThis, 'window', previousWindow);
|
|
181
|
+
else delete globalThis.window;
|
|
182
|
+
}
|
|
183
|
+
if (!/Could not Fast Refresh \("cacheKey" export is incompatible\)/.test(incompatibilityReason ?? '')) {
|
|
184
|
+
throw new Error('Pinned React Refresh runtime did not explain the incompatible export.');
|
|
185
|
+
}
|
|
186
|
+
const transformedResponse = await fetch(componentUrl);
|
|
187
|
+
const transformedModule = await transformedResponse.text();
|
|
188
|
+
if (!transformedResponse.ok || !transformedModule.includes('validateRefreshBoundaryAndEnqueueUpdate')) {
|
|
189
|
+
throw new Error('Vite did not transform the consumer component through its React Refresh boundary validator.');
|
|
190
|
+
}
|
|
191
|
+
const refreshRuntimeResponse = await fetch(`${base}/@react-refresh`);
|
|
192
|
+
const refreshRuntime = await refreshRuntimeResponse.text();
|
|
193
|
+
if (!refreshRuntimeResponse.ok || !refreshRuntime.includes('validateRefreshBoundaryAndEnqueueUpdate') || refreshRuntime.includes('__README_URL__')) {
|
|
194
|
+
throw new Error('Vite did not serve the pinned React Refresh runtime with its diagnostic link resolved.');
|
|
195
|
+
}
|
|
196
|
+
socket.send(JSON.stringify({
|
|
197
|
+
type: 'custom', event: 'vite:invalidate',
|
|
198
|
+
data: { path: componentModulePath, message: incompatibilityReason, firstInvalidatedBy: componentModulePath },
|
|
199
|
+
}));
|
|
200
|
+
const hasInvalidationDiagnostic = () => {
|
|
201
|
+
const output = serverOutput.replace(/\u001b\[[0-?]*[ -/]*[@-~]/g, '');
|
|
202
|
+
return output.includes('hmr invalidate')
|
|
203
|
+
&& output.includes('HmrProbe.jsx')
|
|
204
|
+
&& output.includes('Could not Fast Refresh')
|
|
205
|
+
&& output.includes('cacheKey" export is incompatible');
|
|
206
|
+
};
|
|
207
|
+
const invalidationDeadline = Date.now() + 10_000;
|
|
208
|
+
while (Date.now() < invalidationDeadline && !hasInvalidationDiagnostic()) {
|
|
209
|
+
await new Promise((resolveDelay) => setTimeout(resolveDelay, 25));
|
|
210
|
+
}
|
|
211
|
+
if (!hasInvalidationDiagnostic()) {
|
|
212
|
+
throw new Error('Vite did not surface the incompatible-export reason through its HMR invalidation handler.');
|
|
213
|
+
}
|
|
214
|
+
const statistics = (values) => {
|
|
215
|
+
values.sort((a, b) => a - b);
|
|
216
|
+
const percentile = (p) => values.length ? values[Math.max(0, Math.ceil(p * values.length) - 1)] : null;
|
|
217
|
+
return values.length ? {
|
|
218
|
+
min: +values[0].toFixed(2), median: +percentile(0.5).toFixed(2), p95: +percentile(0.95).toFixed(2), max: +values.at(-1).toFixed(2),
|
|
219
|
+
} : null;
|
|
220
|
+
};
|
|
221
|
+
process.stdout.write(`${JSON.stringify({
|
|
222
|
+
kind: 'synthetic consumer iteration; Vite update, transformed-source verification, and injected incompatibility diagnostic',
|
|
223
|
+
samples, matchingUpdates: updateTimings.length, verifiedIterations: verifiedIterationTimings.length,
|
|
224
|
+
verificationFailures, fullReloadMessages: measuredFullReloads, fullReloadEvents: measuredFullReloadEvents,
|
|
225
|
+
environment: { node: process.version, platform: process.platform, architecture: process.arch },
|
|
226
|
+
viteVersion: JSON.parse(await readFile(resolve(packageRoot, 'node_modules/vite/package.json'), 'utf8')).version,
|
|
227
|
+
updateEventLatencyMs: statistics(updateTimings),
|
|
228
|
+
verifiedSourceLatencyMs: statistics(verifiedIterationTimings),
|
|
229
|
+
incompatibleExport: {
|
|
230
|
+
reason: incompatibilityReason,
|
|
231
|
+
transformedBoundaryValidator: true,
|
|
232
|
+
viteInvalidationLog: true,
|
|
233
|
+
scope: 'synthetic Vite client invalidation message; does not observe browser fallback, React apply, state retention, or navigation',
|
|
234
|
+
},
|
|
235
|
+
scope: 'write to matching Vite WebSocket update and successful transformed-module revision check; does not measure browser React apply, state retention, navigation, or live SharePoint iteration',
|
|
236
|
+
}, null, 2)}\n`);
|
|
237
|
+
if (measuredFullReloads || updateTimings.length !== samples || verifiedIterationTimings.length !== samples || verificationFailures) process.exitCode = 1;
|
|
238
|
+
} catch (error) {
|
|
239
|
+
process.stderr.write(`Consumer HMR benchmark failed: ${error.message}\n`);
|
|
240
|
+
process.exitCode = 1;
|
|
241
|
+
} finally {
|
|
242
|
+
socket?.close();
|
|
243
|
+
if (server && server.exitCode === null) {
|
|
244
|
+
const exited = new Promise((resolveExit) => server.once('exit', resolveExit));
|
|
245
|
+
server.kill('SIGTERM');
|
|
246
|
+
await Promise.race([exited, new Promise((resolveDelay) => setTimeout(resolveDelay, 3000))]);
|
|
247
|
+
if (server.exitCode === null) server.kill('SIGKILL');
|
|
248
|
+
}
|
|
249
|
+
await rm(temp, { recursive: true, force: true });
|
|
250
|
+
}
|
|
251
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { dirname, resolve } from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
|
|
6
|
+
const args = process.argv.slice(2);
|
|
7
|
+
const valueAfter = (flag, fallback) => {
|
|
8
|
+
const index = args.indexOf(flag);
|
|
9
|
+
return index < 0 ? fallback : args[index + 1];
|
|
10
|
+
};
|
|
11
|
+
const samples = Number(valueAfter('--samples', '50'));
|
|
12
|
+
const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
|
13
|
+
const route = valueAfter('--route', 'list-items');
|
|
14
|
+
const routePaths = {
|
|
15
|
+
'list-items': '/__spfx_workbench/api/library-items',
|
|
16
|
+
'web-title': '/__spfx_workbench/api/web',
|
|
17
|
+
lists: '/__spfx_workbench/api/lists',
|
|
18
|
+
'captured-har': '/__spfx_workbench/api/captured',
|
|
19
|
+
};
|
|
20
|
+
const routePath = routePaths[route] ?? routePaths['list-items'];
|
|
21
|
+
const url = new URL(valueAfter('--url', `http://127.0.0.1:4173${routePath}`));
|
|
22
|
+
if (url.protocol !== 'http:' || !['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname) || url.username || url.password || url.hash) {
|
|
23
|
+
process.stderr.write('--url must be an HTTP loopback URL without credentials or a fragment.\n');
|
|
24
|
+
process.exitCode = 2;
|
|
25
|
+
}
|
|
26
|
+
const select = valueAfter('--select');
|
|
27
|
+
const top = valueAfter('--top');
|
|
28
|
+
let capturedRequestUrl;
|
|
29
|
+
if (route === 'captured-har') {
|
|
30
|
+
try { capturedRequestUrl = new URL(valueAfter('--request-url', '')); } catch {}
|
|
31
|
+
if (!capturedRequestUrl || !['http:', 'https:'].includes(capturedRequestUrl.protocol)
|
|
32
|
+
|| capturedRequestUrl.username || capturedRequestUrl.password || capturedRequestUrl.hash
|
|
33
|
+
|| !capturedRequestUrl.pathname.includes('/_api/')) {
|
|
34
|
+
process.stderr.write('--request-url must be an HTTP(S) SharePoint REST URL; its query is not printed.\n');
|
|
35
|
+
process.exitCode = 2;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
if (url.pathname !== routePath) {
|
|
39
|
+
process.stderr.write(`--url path must match the selected ${route} route.\n`);
|
|
40
|
+
process.exitCode = 2;
|
|
41
|
+
}
|
|
42
|
+
if (!['list-items', 'web-title', 'lists', 'captured-har'].includes(route)) {
|
|
43
|
+
process.stderr.write('--route must be list-items, web-title, lists, or captured-har.\n');
|
|
44
|
+
process.exitCode = 2;
|
|
45
|
+
}
|
|
46
|
+
if (route === 'web-title') url.searchParams.set('$select', 'Title');
|
|
47
|
+
if (route === 'lists') {
|
|
48
|
+
url.searchParams.set('$select', 'Id,Title,ItemCount');
|
|
49
|
+
url.searchParams.set('$filter', 'Hidden eq false');
|
|
50
|
+
url.searchParams.set('$orderby', 'Title');
|
|
51
|
+
}
|
|
52
|
+
if (select) url.searchParams.set('$select', select);
|
|
53
|
+
if (top) url.searchParams.set('$top', top);
|
|
54
|
+
|
|
55
|
+
if (process.exitCode === 2) {
|
|
56
|
+
// Invalid route arguments were reported above.
|
|
57
|
+
} else if (!Number.isInteger(samples) || samples < 1 || samples > 1000) {
|
|
58
|
+
process.stderr.write('--samples must be an integer from 1 to 1000.\n');
|
|
59
|
+
process.exitCode = 2;
|
|
60
|
+
} else {
|
|
61
|
+
try {
|
|
62
|
+
const timings = [];
|
|
63
|
+
let source = '';
|
|
64
|
+
let bytes = 0;
|
|
65
|
+
let items = 0;
|
|
66
|
+
let responseStatus = 0;
|
|
67
|
+
const sessionId = randomUUID();
|
|
68
|
+
const request = () => route === 'captured-har'
|
|
69
|
+
? fetch(url, { method: 'POST', cache: 'no-store', credentials: 'omit', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ url: capturedRequestUrl.href, sessionId }) })
|
|
70
|
+
: fetch(url);
|
|
71
|
+
const warmup = await request();
|
|
72
|
+
if (!warmup.ok) throw new Error(`Mock endpoint returned HTTP ${warmup.status} during warm-up.`);
|
|
73
|
+
if (route === 'captured-har' && warmup.headers.get('X-SPFx-Workbench-HAR-Matched') !== 'true') {
|
|
74
|
+
throw new Error('No matching tenant HAR response was found for the requested SharePoint REST call.');
|
|
75
|
+
}
|
|
76
|
+
for (let i = 0; i < samples; i++) {
|
|
77
|
+
const start = performance.now();
|
|
78
|
+
const response = await request();
|
|
79
|
+
const bodyText = await response.text();
|
|
80
|
+
const elapsed = performance.now() - start;
|
|
81
|
+
if (!response.ok) throw new Error(`Mock endpoint returned HTTP ${response.status}.`);
|
|
82
|
+
if (route === 'captured-har' && response.headers.get('X-SPFx-Workbench-HAR-Matched') !== 'true') {
|
|
83
|
+
throw new Error('Tenant HAR match disappeared during the benchmark.');
|
|
84
|
+
}
|
|
85
|
+
const body = route === 'captured-har' ? null : JSON.parse(bodyText);
|
|
86
|
+
if (route === 'list-items' && !Array.isArray(body.value)) throw new Error('List-items mock response has no value array.');
|
|
87
|
+
if (route === 'web-title' && typeof body.Title !== 'string') throw new Error('Web-title mock response has no Title string.');
|
|
88
|
+
if (route === 'lists' && (!Array.isArray(body.value) || !body.value.every((list) => typeof list?.Id === 'string' && typeof list.Title === 'string' && Number.isSafeInteger(list.ItemCount)))) {
|
|
89
|
+
throw new Error('List metadata mock response does not match the documented fields.');
|
|
90
|
+
}
|
|
91
|
+
timings.push(elapsed);
|
|
92
|
+
source = response.headers.get('X-SPFx-Workbench-Data') ?? 'unknown';
|
|
93
|
+
bytes = Buffer.byteLength(bodyText);
|
|
94
|
+
responseStatus = response.status;
|
|
95
|
+
items = body?.value?.length;
|
|
96
|
+
}
|
|
97
|
+
timings.sort((a, b) => a - b);
|
|
98
|
+
const percentile = (p) => timings[Math.max(0, Math.ceil(p * timings.length) - 1)];
|
|
99
|
+
process.stdout.write(`${JSON.stringify({
|
|
100
|
+
kind: route === 'captured-har' ? 'local captured tenant HAR replay API only' : 'local synthetic mock API only', route, samples,
|
|
101
|
+
measuredAt: new Date().toISOString(),
|
|
102
|
+
environment: {
|
|
103
|
+
node: process.version, platform: process.platform, architecture: process.arch,
|
|
104
|
+
viteVersion: JSON.parse(await readFile(resolve(packageRoot, 'node_modules/vite/package.json'), 'utf8')).version,
|
|
105
|
+
},
|
|
106
|
+
...(route === 'captured-har' ? { requestMatch: 'REST method/path/query; URL and query values omitted' } : { query: Object.fromEntries(url.searchParams.entries()) }),
|
|
107
|
+
source, ...(route === 'captured-har' ? { responseStatus } : {}), items, responseBytes: bytes,
|
|
108
|
+
latencyMs: { min: +timings[0].toFixed(2), median: +percentile(0.5).toFixed(2), p95: +percentile(0.95).toFixed(2), max: +timings.at(-1).toFixed(2) },
|
|
109
|
+
}, null, 2)}\n`);
|
|
110
|
+
} catch (error) {
|
|
111
|
+
process.stderr.write(`Mock API benchmark failed: ${error.message}\n`);
|
|
112
|
+
process.exitCode = 1;
|
|
113
|
+
}
|
|
114
|
+
}
|