@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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 SPFx Workbench contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,241 @@
1
- # Temporary Holding Version
1
+ # SPFx Workbench
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A local SharePoint Workbench-style page editor with a canvas, toolbox, and property pane. It supports SharePoint column layouts, responsive breakpoints, section emphasis, local section width presets, and a synthetic document-library web part. The consumer CLI can load a compatible React component or invoke a subset of SPFx web-part lifecycle hooks with explicit JSON properties and a narrow synthetic context. It does not create the SharePoint service scope or claim to reproduce the full SPFx host.
4
+
5
+ ## Run locally
6
+
7
+ Use Node.js `^20.19.0 || >=22.12.0` (Vite's supported range), then:
8
+
9
+ ```sh
10
+ npm install
11
+ npm run dev
12
+ ```
13
+
14
+ Vite serves the preview on `http://127.0.0.1:4173`. `npm run build` builds the static prototype; `npm run preview` serves that build on port 4174.
15
+
16
+ ## Current behavior
17
+
18
+ - SharePoint page-grid breakpoints at 320, 1024, 1366, and 1920 px, with a 1204 px content maximum; the documented 480, 640, and 768 px layouts are also supported. Sections reflow to one, two, or three columns. The local section-width control provides one-third, one-half, two-thirds, full-page, and full-screen widths; ratio presets expand on narrow screens. These ratio presets are a workbench convenience, not a claim about native SharePoint section types.
19
+ - A circled plus sits between sections. It inserts a new section at that position, matching Microsoft's documented section-border affordance. Touch targets are at least 44 × 44 px.
20
+ - Section background choices are None, Neutral, Soft, and Strong. The local theme picker starts with SharePoint blue and includes Teal and Purple preview palettes; these are local presets, not a connected tenant's theme.
21
+ - The synthetic Document Library web part supports List, Compact list, and Tiles views, filtering, and a visible fixture/capture source. “Local simulation” labels make clear that no tenant host context or APIs are active.
22
+ - Mock list rows follow the SP REST `value[]` shape for `Id`, `Title`, `FileLeafRef`, and `Modified`; `Id` uses the `Edm.Int32` range, and displayed timestamps use an explicit UTC format for repeatable rendering.
23
+ - Local preview requests use the committed synthetic library fixture or an ignored local override; consumer `spHttpClient` calls use captured local replay or declared synthetic fallbacks.
24
+ - When `--component` is supplied, the consumer component appears in the first section of this editor; toolbox, section settings, and the property pane stay available. React Fast Refresh updates the component locally, not a web part running on a SharePoint page.
25
+
26
+ ## Preview a consumer component
27
+
28
+ The npm package name is `@spfx-fast/spfx-workbench`. Its manifest is configured for public version `0.1.0`; publish that release before using the registry install command. To use this checkout in an SPFx project, install its local path and run the CLI from that project's root:
29
+
30
+ ```sh
31
+ npm install --save-dev /path/to/spfx-workbench
32
+ npx spfx-workbench --component src/components/HelloWorld.tsx
33
+ ```
34
+
35
+ After an authorized release, the registry install command will be:
36
+
37
+ ```sh
38
+ npm install --save-dev @spfx-fast/spfx-workbench
39
+ ```
40
+
41
+ Pass deterministic component props from a project-local JSON object no larger than 1 MB with `--props-file`:
42
+
43
+ ```sh
44
+ npx spfx-workbench --component src/components/HelloWorld.tsx --props-file .spfx-workbench/preview-props.json
45
+ ```
46
+
47
+ The wrapper passes those values as React component props and supplies its own `context`; a props file cannot override it. Class-based web parts use a local lifecycle adapter. The typed `SimulatorContext` subset is documented in [src/contracts/simulator-context.d.ts](src/contracts/simulator-context.d.ts): fixed `pageContext.web/site/user` values, stable `instanceId`, `domElement`, `manifest`, edit `displayMode`, local SharePoint-host indicators, read-only `spHttpClient.get`, and captured read-only `spHttpClient.post` routes. It is derived from pinned SPFx 1.24.1 declarations. The doctor reports this declaration coverage as unknown for other releases. Common public runtime imports in generated SPFx web parts use small simulator shims; `localizedResources` from `config/config.json` resolves the `en-us` resource, falling back to its matching `src` file before a Heft build. The local preview does not load the real SharePoint host or package internals. Values are fixed synthetic placeholders. Unsupported context reads and mutation attempts throw diagnostics. The `.test` URLs and `.invalid` user are not tenant identity or permission evidence.
48
+
49
+ `context.spHttpClient.get(url, configuration)` replays HTTP(S) SharePoint `/_api/` GET URLs from captured tenants by API path and query, preserving occurrence order, response status, body, and usable response headers. Captured read-only POST routes also replay by route and canonical JSON body for `SiteUserInfoList/GetItems`, `RenderListDataAsStream`, and `RenderExtendedListFormData`. The routes are capture-derived; Microsoft documents `RenderListDataAsStream`. During an active capture the simulator reads `.spfx-workbench/captures/tenant-live.json`; after capture it reads `.spfx-workbench/captures/tenant.har`. The Vite process refreshes its index when either file changes, so new responses can be replayed without restarting the preview. Host and site prefix are not part of the match key. Requests go only to the local replay server; `Set-Cookie` and transport headers are excluded from the localhost response. If no HAR entry matches, list-item, web-title, and documented list-metadata GETs use deterministic synthetic routes; other calls return a local 404. POST is not forwarded to SharePoint: page-write, coauthoring, and telemetry routes are rejected, request options are limited, and the simulator supplies no authentication or server-side state. Captured tenant responses stay verbatim in the ignored capture files. See [capture and replay](docs/mock-data-and-capture.md) for matching and storage details.
50
+
51
+ The CLI serves on loopback port `4176` by default; use `--port` to choose another port. A default export may be a compatible React component or a class with SPFx-style `onInit`, `render`, `onAfterResize`, and `onDispose` methods. The local lifecycle adapter runs initialization, render, resize, and disposal hooks. It does not construct the SharePoint service scope, invoke property pane or display-mode lifecycle hooks, or load first-party web-part implementations. The `spfx-workbench-doctor --component <file>` command reports detected lifecycle methods and SDK/context gaps. The simulator supplies only the documented context subset; it does not create a full SPFx host or patch a live SharePoint web part. Fast Refresh is intended for component modules with consistent React component exports. With the pinned `@vitejs/plugin-react`, incompatible refresh boundaries produce a reasoned `hmr invalidate` diagnostic in the Vite terminal (for example, an incompatible export); if an update cannot be accepted, Vite may reload the page. See the plugin's [consistent component export guidance](https://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-react#consistent-components-exports). React Fast Refresh behavior in the local preview is separate from Heft rebuild and modern-page reload.
52
+
53
+ The consumer component is rendered inside the first section of the local page editor. Its nearest SPFx `*.manifest.json` supplies the displayed title and “In development” label. The toolbox contains the component and the deterministic document library fixture. SharePoint built-in web parts run when loaded by SharePoint; this canvas does not imitate them. Section controls remain local and file edits use React Fast Refresh. This canvas does not modify a SharePoint page. For whole-page traffic, use the Playwright HAR workflow below; that records the browser context, including web parts and extensions.
54
+
55
+ The CLI serves only on loopback and limits Vite filesystem requests to the workbench package and consumer project. It resolves the selected component and every Vite `/@fs/` request through real paths so symlinks cannot expand that boundary. Synthetic captures are read from the consumer project's `.spfx-workbench/captures/`; add that directory to a repository `.gitignore` file before importing. The importer verifies that a repository `.gitignore` rule covers both the final capture and its temporary file; it does not accept a machine-wide or repository-private exclude as a substitute.
56
+
57
+ Inspect the consumer's installed runtime versions and an optional component entry before previewing:
58
+
59
+ ```sh
60
+ npx spfx-workbench-doctor --component src/components/HelloWorld.tsx --props-file .spfx-workbench/preview-props.json
61
+ ```
62
+
63
+ The command emits JSON with per-check `supported`, `unsupported`, or `unknown` status plus mock coverage and provenance. For a props file, it reports the project-relative path and property names, never values, and flags a `context` override. It scans installed `@microsoft/sp-*` packages, including nested `node_modules`, requires every installed version to be SPFx 1.24+ and match `@microsoft/sp-core-library` exactly, and checks React and React DOM against 18.3.1. It also checks the current Node.js version against Microsoft's documented SPFx 1.24.1 compatibility: Node 22.14.0 or later within 22.x, 24.x, or 26.x. That check is `unknown` for other SPFx releases until their compatibility source is recorded. This is separate from the package's Vite engine range, which permits Node `^20.19.0 || >=22.12.0`; Node versions valid for Vite may still be unsupported by the consumer's Heft toolchain. Missing package metadata is `unknown` and summarized as incomplete. It does not test every SPFx behavior or infer component prop types/API usage.
64
+
65
+ This is an early consumer-loader slice. It supports explicit JSON props and the documented read-only simulator context subset; it does not create full SPFx host context or infer an arbitrary TypeScript props contract. Broader SPFx compatibility checks and live SharePoint validation remain incomplete.
66
+
67
+ ## How this fits with the SPFx Fast tools
68
+
69
+ Use [`@spfx-fast/ide`](packages/ide/README.md) as the thin developer and agent entry point. `spfx-ide` routes to focused tools; installing it as a project devDependency or globally automatically installs shared Agent Skills guidance for supported coding agents (unless package-manager lifecycle scripts are disabled). The guide routes to maintained SPFx knowledge and workflows. Use Workbench as the local development loop: it owns component preview, the synthetic context and API replay, diagnostics, capture, and Heft launch. The focused companion packages have separate jobs:
70
+
71
+ - [`@spfx-fast/playwright`](https://www.npmjs.com/package/%40spfx-fast/playwright) runs authenticated browser tests against a real SharePoint page.
72
+ - [`@spfx-fast/knowledge`](https://www.npmjs.com/package/%40spfx-fast/knowledge) provides the SPFx agent skill and debugging references; use it to guide the tools, not as a runtime dependency.
73
+ - [`@spfx-fast/ide`](packages/ide/README.md) depends on the focused Playwright and knowledge packages and routes to optional artifact and recurring-fix tools when installed.
74
+ - [`@spfx-fast/core`](https://www.npmjs.com/package/%40spfx-fast/core) and [`@spfx-fast/sharepoint-ui`](https://www.npmjs.com/package/%40spfx-fast/sharepoint-ui) are optional application libraries. Workbench does not require either.
75
+ - [`agent-efficiency-tools`](https://www.npmjs.com/package/agent-efficiency-tools) and [`hermes-harness`](https://www.npmjs.com/package/hermes-harness) are optional repository-level agent utilities, not Workbench dependencies.
76
+
77
+ Keep dependencies pointed from an application or tool to code it imports. Link the tools through install guidance and agent knowledge when no shared runtime code is needed.
78
+
79
+ ## Capture and replay
80
+
81
+ ### Whole-page SharePoint HAR
82
+
83
+ Install the package in the consuming project and add `.spfx-workbench/captures/` to that project's `.gitignore`. Tenant states live once per user under `~/.playwright-auth/<tenant>.json` (resolved from the OS home directory) and can be reused by every project. The integrated command can sign in, refresh, and check state without printing cookie values:
84
+
85
+ ```sh
86
+ npx spfx-workbench-auth login workswithagents --fresh
87
+ npx spfx-workbench-auth refresh workswithagents
88
+ npx spfx-workbench-auth check workswithagents
89
+ ```
90
+
91
+ `login --fresh` opens a clean Playwright browser. Complete Microsoft sign-in yourself and choose **Yes** for “Stay signed in?”. The existing JSON is replaced only after SharePoint confirms the sign-in. `refresh` loads the saved state and rewrites it only after the tenant confirms the session; `check` is read-only. POSIX files are written with mode `600`; Windows uses the current user's inherited ACL. The package exposes `@spfx-fast/spfx-workbench/auth` so project scripts can use the same tenant state:
92
+
93
+ ```js
94
+ import { launchTenantBrowser } from '@spfx-fast/spfx-workbench/auth';
95
+
96
+ const { browser, context, close } = await launchTenantBrowser('workswithagents', {
97
+ headless: true,
98
+ contextOptions: { viewport: { width: 1023, height: 900 } },
99
+ });
100
+ const page = await context.newPage();
101
+ try { await page.goto('https://workswithagents.sharepoint.com/sites/spfx-validation-lab'); }
102
+ finally { await close(); }
103
+ ```
104
+
105
+ The capture command accepts a tenant name to reuse this shared state, or an explicit `--storage-state` path for a separate state file:
106
+
107
+ ```sh
108
+ npx spfx-workbench-capture --watch \
109
+ --page 'https://tenant.sharepoint.com/sites/site/SitePages/page.aspx' \
110
+ --tenant workswithagents --edit --duration 30
111
+ ```
112
+
113
+ The capture writes an incrementally refreshed `.spfx-workbench/captures/tenant-live.json` containing fetch/XHR calls while recording the full page, web-part, and extension traffic into `.spfx-workbench/captures/tenant.har`. Before replacing an existing HAR, capture archives it; after capture it archives the new HAR too. Archives stay in the ignored capture directory until removed. Component replay reads the live API snapshot as it changes; full-page replay reads the current HAR and automatically loads older local archives. Capture and replay use the package's Playwright-managed Chromium, installed on first use, on macOS, Windows, and Linux. `--duration <seconds>` ends a recording after the page loads and edit-mode entry is attempted; it accepts 1–3600 seconds. `--once` keeps the four-second default. `--measure` additionally records section/web-part geometry and spacing at 320, 390, 639, 640, 768, 1023, 1024, 1366, and 1920 px in the ignored `.spfx-workbench/captures/tenant-measurements.json`. Captured HARs and auth JSON remain local under `.gitignore` and the home directory. Cross-platform paths are implemented; this checkout's automated browser evidence is from macOS only.
114
+
115
+ See [mock-data-and-capture.md](docs/mock-data-and-capture.md) for the capture and replay command details.
116
+ New captures include a versioned manifest and API initiator trace; compare dated HARs with `--diff` as SharePoint changes.
117
+
118
+ Replay the page offline at a chosen viewport:
119
+
120
+ ```sh
121
+ npx spfx-workbench-replay --capture .spfx-workbench/captures/tenant.har --width 1023 --height 900 --once
122
+ ```
123
+
124
+ Replay automatically loads the local dated archive. Use repeated `--fallback-capture` flags only for HARs stored elsewhere; the current capture takes precedence.
125
+
126
+ Inventory captured API calls in request order without printing body values:
127
+
128
+ ```sh
129
+ npx spfx-workbench-capture --summary --capture .spfx-workbench/captures/tenant.har \
130
+ --initiators .spfx-workbench/captures/tenant-initiators.json --no-values
131
+ ```
132
+
133
+ The summary includes fetch/XHR calls, repeated-call numbers, resource type, status, byte counts, JSON request/response shapes, and masked SharePoint route families in request order. `--initiators` joins each route to compact script-callsite evidence from the matching CDP trace. Add `--baseline <earlier.har>` to report newly observed route families, routes not present in the current page capture, and counts for shared routes. New routes are queued for source review; that does not establish they are undocumented. Use `--values` for bounded input/output values (each JSON value is capped at 512 bytes with a short preview when larger), or `--raw-values` for up to 1,000 characters per body. The full HAR remains the source for offline page rendering. See the [dated 2026-11-15 SharePoint behavior snapshot](docs/sharepoint-behavior-snapshot-2026-11-15-1455Z.md) for the captured edit-mode call order and evidence status.
134
+
135
+ Replay uses Playwright's HAR routing, blocks service workers so their requests cannot bypass replay, and aborts requests missing from the capture. It reports response status counts, failed request origins and paths (without query strings), page errors, canvas/webpart counts, and viewport overflow. Playwright routing disables the browser HTTP cache; the HAR itself is the replay cache. Repeated calls to the same method and URL are preserved in the compact before/after diff:
136
+
137
+ ```sh
138
+ npx spfx-workbench-capture --diff \
139
+ --before .spfx-workbench/captures/before.har \
140
+ --after .spfx-workbench/captures/tenant.har
141
+ ```
142
+
143
+ Add `--values` when the agent needs to see what changed: it includes before/after values for changed JSON paths and compact values for added/removed calls. Large values are bounded. `--raw-values` includes the original request/response body text (up to 1,000 characters per body). The default reports paths, statuses, and byte counts while the complete HAR stays local.
144
+
145
+ ### Synthetic component API replay
146
+
147
+ The fixture shape follows Microsoft’s documented list-items request: `$select=Id,Title,FileLeafRef,Modified`. The committed fixture contains invented example rows. To create a local replay from your own **synthetic-only** response capture:
148
+
149
+ ```sh
150
+ npm run capture:synthetic -- --input path/to/synthetic-capture.json
151
+ ```
152
+
153
+ The importer accepts only a source marked `synthetic`, only GET list-item calls, only a successful status, only the four allowlisted fields, and input files up to 1 MB. It reads at most 1 MB plus one byte before rejecting oversized input. After saving, it prints a field-level contract diff showing retained allowlisted fields and how many unrecognized response fields were stripped; it never prints captured values or unknown field names. It drops request URLs, query strings other than the safe field selection/top count, headers, cookies, tokens, unrecognized fields, and response metadata. It requires repository `.gitignore` rules to cover both the final and temporary paths, rejects machine-wide and repository-private ignore substitutes, and rejects symlinked destination directories and output files. It atomically writes `.spfx-workbench/captures/library-items.json` without imposing a file-mode policy. The running Vite workbench picks up that file on its next request and labels it “Local capture”. Remove it to return to the committed generic fixture.
154
+
155
+ In a consumer project, import with `npx spfx-workbench-capture --input path/to/synthetic-capture.json`. Add `.spfx-workbench/captures/` to a repository `.gitignore` file first; a machine-wide ignore or `.git/info/exclude` entry alone is not sufficient. The consumer CLI points replay at this project-local capture directory.
156
+
157
+ The dev and preview servers serve the mock response at `/__spfx_workbench/api/library-items`. It is a local-only fixture endpoint; it does not proxy or contact SharePoint. The `captured-har` benchmark exercises the local component replay endpoint against an existing capture and omits the request URL and query values from its output:
158
+
159
+ ```sh
160
+ npm run benchmark:mock-api -- --route captured-har \
161
+ --url http://127.0.0.1:4176/__spfx_workbench/api/captured \
162
+ --request-url "$SPFX_CAPTURED_REQUEST_URL" --samples 50
163
+ ```
164
+
165
+ Measure the synthetic import path using isolated temporary Git consumers:
166
+
167
+ ```sh
168
+ npm run benchmark:capture-import -- --samples 5
169
+ ```
170
+
171
+ The benchmark reports Node version, platform, architecture, sample count, and min/median/p95/max. It includes process startup, validation, the safe contract diff, the Git-ignore check, and the temporary local write. It does not contact SharePoint or use consumer data.
172
+
173
+ Check one component update through Vite's WebSocket module-update event:
174
+
175
+ ```sh
176
+ npm run benchmark:consumer-hmr
177
+ ```
178
+
179
+ The check edits a synthetic consumer component, measures its Vite update event, and confirms the transformed module contains the new revision. It also verifies the served React Refresh runtime and injects an incompatible-export reason through Vite's `vite:invalidate` handler to check the terminal diagnostic. The injected message does not prove browser detection or fallback. This check does not measure repeated edits, React application, state retention, navigation, or live SharePoint iteration; `npm run check:browser-hmr` exercises 20 real browser edits and checks those behaviors.
180
+
181
+ Verify React Fast Refresh in a real browser with:
182
+
183
+ ```sh
184
+ npm run check:browser-hmr
185
+ ```
186
+
187
+ The check uses Playwright-managed Chromium, installed on first use, and does not require a system Chrome path. It edits a synthetic consumer component 20 times at a 1023 px viewport and confirms each React update applies, component state survives every edit, and the page does not navigate. It then adds an incompatible named export and confirms Vite reports the boundary reason, the browser reloads once, and the updated component appears. It reports min, median, p95, and max for compatible browser updates; it does not measure the full developer workflow or SharePoint. Set `--samples` to an integer from 1 to 100. `npm run check:responsive` additionally checks the five local section-width options with a synthetic web part at nine viewport widths and verifies the insertion control on touch input. `npm run check:release` runs the local gates, browser HMR check, and responsive layout check. It still does not start real Heft, establish tenant parity, or publish the package.
188
+
189
+ Measure that endpoint while the dev server is running:
190
+
191
+ ```sh
192
+ npm run benchmark:mock-api -- --samples 50
193
+ npm run benchmark:mock-api -- --route web-title --samples 50
194
+ npm run benchmark:mock-api -- --route lists --samples 50
195
+ ```
196
+
197
+ The warm-up request is excluded. `list-items` is the default route; add `--select Id,Title --top 2` to measure a projected, limited response. `web-title` measures the separate `/_api/web?$select=Title` fixture. `lists` measures the documented `/_api/web/lists` projection/filter/order query. Use `--url http://127.0.0.1:4175/__spfx_workbench/api/library-items` to target another loopback server. Output is JSON with route, sample count, UTC timestamp, Node/Vite/platform versions, latency statistics, payload size, query, and fixture source. The command rejects non-loopback URLs. These are local synthetic timings, not SharePoint latency measures.
198
+
199
+ ## Real SharePoint debugging
200
+
201
+ SPFx 1.22+ uses Heft. The modern SharePoint page/debug-manifest flow is separate from this Vite preview. To start the local component preview and the consuming project's installed Heft together, run this from the consumer root:
202
+
203
+ ```sh
204
+ npx spfx-workbench-debug --component src/webparts/example/Example.tsx -- --serve-config default
205
+ ```
206
+
207
+ The launcher resolves the consumer's local `@rushstack/heft` before starting the preview, serves on loopback port `4176`, verifies that Vite can transform the entry, simulator wrapper, and consumer component, then invokes that Heft installation's `start` command with options after `--`. If Heft is missing, the preview is not started. It will stop before Heft starts if the component cannot be transformed. Pass `--port` and `--props-file` before `--` to configure the preview. Heft retains its normal behavior: a serve configuration may open its modern SharePoint page and prompt to allow debug scripts. For the web-part manifest flow, pass `-- --nobrowser` and follow Microsoft's instructions to open the modern page with `loadSPFX=true` and the local `debugManifestsFile`. Ctrl+C stops both processes. This does not authenticate, select a tenant target, modify a page, or patch a live web part; validate those steps in the consumer's normal authorized workflow.
208
+
209
+ To inspect a target configured by an existing SPFx project, run from that project's directory:
210
+
211
+ ```sh
212
+ npx spfx-workbench-heft-target --serve-config default
213
+ ```
214
+
215
+ Pass `--config path/to/serve.json` when the file is elsewhere. The command returns root `initialPage` when present; otherwise it returns the named `serveConfigurations.<name>.pageUrl`. For Microsoft's documented `{tenantDomain}` placeholder, it uses `SPFX_SERVE_TENANT_DOMAIN` and reports an actionable error if the variable is missing or malformed. It validates an absolute HTTP(S) target and gives a clear error for missing or malformed configurations. Add `--json` for a machine-readable result with the selected URL, source field, and configuration name. It does not alter or launch the URL. See Microsoft's [Heft-based SPFx setup guidance](https://learn.microsoft.com/en-us/sharepoint/dev/spfx/set-up-your-development-environment) for the environment variable format.
216
+
217
+ Microsoft’s current guidance: [Debug SharePoint Framework solutions on modern SharePoint pages](https://learn.microsoft.com/en-us/sharepoint/dev/spfx/debug-modern-pages). Never use a production package pointed at localhost. Tenant-backed validation requires an active, authorized storage state and a confirmed target.
218
+
219
+ When the page is in edit mode during an SPFx debug session, the [SharePoint Framework Developer Toolbar](https://learn.microsoft.com/en-us/sharepoint/dev/spfx/debug-toolbar) adds a Web Part menu for the selected part. It can show that instance's JSON, HTML, and manifest details; it can also open the developer dashboard. This is useful for matching a real web part's configuration and rendered markup. It does not export the whole page's theme, section geometry, or spacing, and the workbench does not automatically import these values. Treat JSON/HTML dumps as potentially sensitive; the synthetic capture importer does not accept them.
220
+
221
+ ## Project status
222
+
223
+ See [the engineering report](reports/sharepoint-simulator-engineering-report.html) for verified implementation, unmeasured baselines, known gaps, and release status. [Local section measurements](reports/section-layout-sizes.html) list the synthetic editor's section/web-part dimensions; [tenant page measurements](reports/tenant-page-layout-sizes.html) list read-only live view-mode section/ControlZone boxes at nine viewport widths.
224
+
225
+ Run the automated local release checks together with:
226
+
227
+ ```sh
228
+ npm run check:local
229
+ ```
230
+
231
+ This builds the workbench, runs `npm test` (temporary-consumer regressions and a synthetic local-CDP auth capture check), measures 20 consumer Vite HMR events, and installs the clean npm tarball into a disposable consumer. It does not verify browser React apply/state retention; use `npm run check:release` for the additional Chrome gate. Neither command proves a real Heft session, live-page parity, or every release criterion below.
232
+
233
+ Check the current npm tarball from a clean temporary consumer before changing release status:
234
+
235
+ ```sh
236
+ npm run check:tarball
237
+ ```
238
+
239
+ This packs the public-configured source manifest, checks every packed path against `package.json` `files`, requires consumer docs/fixtures/source and all declared binaries, verifies the MIT license matches the installed tarball and manifest, and checks that the Node.js engine range survives packing. It installs the package as a devDependency, checks each npm command shim, launches the packaged preview with a synthetic consumer component and props file, verifies the context wrapper, captured HAR response replay, and synthetic fallback, runs compact HAR diff through the installed capture command, and confirms tests, reports, captures, and specs are absent. Its JSON result includes the public package status, contents/license checks, packaged diff result, and install/time-to-first-usable-preview timings. The engineering report records setup timings against each artifact hash; these local warm-cache samples do not establish a general setup success rate or baseline comparison. It does not publish the package.
240
+
241
+ Original simulator code is MIT licensed; see [LICENSE](LICENSE).
@@ -0,0 +1,143 @@
1
+ #!/usr/bin/env node
2
+ import { chmod, mkdir, rename, rm, writeFile, access } from 'node:fs/promises';
3
+ import { homedir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { randomUUID } from 'node:crypto';
6
+ import { chromium } from 'playwright-core';
7
+ import { AUTH_TENANTS, resolveTenantAuthStatePath } from '../src/auth-state.mjs';
8
+ import { resolveChromiumExecutable } from '../scripts/resolve-chromium.mjs';
9
+
10
+ const [action, tenant, ...flags] = process.argv.slice(2);
11
+ const supportedTenants = Object.keys(AUTH_TENANTS);
12
+ const authDirectory = join(homedir(), '.playwright-auth');
13
+ const fresh = flags.includes('--fresh');
14
+ const allowedDomains = ['login.microsoftonline.com', 'login.live.com', 'sharepoint.com', 'visualstudio.com', 'dev.azure.com'];
15
+
16
+ function usage() {
17
+ process.stdout.write(`Usage: spfx-workbench-auth login <${supportedTenants.join('|')}> [--fresh] | refresh <tenant> | check [tenant]\n`);
18
+ }
19
+
20
+ function allowedCookie(cookie) {
21
+ const domain = cookie.domain.replace(/^\./, '').toLowerCase();
22
+ return allowedDomains.some((allowed) => domain === allowed || domain.endsWith(`.${allowed}`));
23
+ }
24
+
25
+ async function whoAmI(page, url) {
26
+ const isAdo = /visualstudio\.com|dev\.azure\.com/.test(url);
27
+ const endpoint = isAdo ? `${url}/_apis/connectionData` : `${url}/_api/web/currentuser?$select=Email,LoginName`;
28
+ const response = await page.request.get(endpoint, {
29
+ maxRedirects: 0,
30
+ headers: isAdo ? undefined : { accept: 'application/json;odata=nometadata' },
31
+ }).catch(() => undefined);
32
+ if (!response?.ok()) return false;
33
+ try {
34
+ const data = await response.json();
35
+ return isAdo ? Boolean(data.authenticatedUser) : Boolean(data.Email || data.LoginName);
36
+ } catch { return false; }
37
+ }
38
+
39
+ async function saveState(context, tenantName) {
40
+ const cookies = (await context.cookies()).filter(allowedCookie);
41
+ const destination = resolveTenantAuthStatePath(tenantName);
42
+ await mkdir(authDirectory, { recursive: true, mode: 0o700 });
43
+ const temporary = join(authDirectory, `.${tenantName}-${randomUUID()}.tmp`);
44
+ try {
45
+ await writeFile(temporary, `${JSON.stringify({ cookies, origins: [] }, null, 2)}\n`, { flag: 'wx', mode: 0o600 });
46
+ if (process.platform !== 'win32') await chmod(temporary, 0o600);
47
+ await rename(temporary, destination);
48
+ if (process.platform !== 'win32') await chmod(destination, 0o600);
49
+ } finally {
50
+ await rm(temporary, { force: true }).catch(() => {});
51
+ }
52
+ return cookies;
53
+ }
54
+
55
+ async function inspectTenant(browser, tenantName, { waitForLogin = false, loadExisting = true } = {}) {
56
+ const statePath = resolveTenantAuthStatePath(tenantName);
57
+ let savedStateExists = false;
58
+ try { await access(statePath); savedStateExists = true; } catch {}
59
+ const context = await browser.newContext({
60
+ viewport: null,
61
+ ...(loadExisting && savedStateExists ? { storageState: statePath } : {}),
62
+ });
63
+ const page = await context.newPage();
64
+ try {
65
+ for (const url of AUTH_TENANTS[tenantName]) {
66
+ await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 45_000 }).catch(() => undefined);
67
+ let signedIn = await whoAmI(page, url);
68
+ const deadline = waitForLogin ? Date.now() + 15 * 60_000 : Date.now();
69
+ if (!signedIn && waitForLogin) process.stdout.write(`${tenantName}: complete the sign-in in the opened browser; the state file is written after verification.\n`);
70
+ while (!signedIn && Date.now() < deadline && !page.isClosed()) {
71
+ await new Promise((resolve) => setTimeout(resolve, 3000));
72
+ signedIn = await whoAmI(page, url);
73
+ }
74
+ if (!signedIn) throw new Error(`${tenantName}: not signed in. Run: spfx-workbench-auth login ${tenantName} --fresh`);
75
+ }
76
+ return { context };
77
+ } catch (error) {
78
+ await context.close().catch(() => {});
79
+ throw error;
80
+ }
81
+ }
82
+
83
+ async function main() {
84
+ if (action === '--help' || action === '-h' || !action) return usage();
85
+ if (!['login', 'refresh', 'check'].includes(action)) throw new Error('Unknown auth command.');
86
+ if (action === 'check') {
87
+ const tenants = tenant ? [tenant] : supportedTenants;
88
+ if (flags.length || tenants.some((name) => !Object.hasOwn(AUTH_TENANTS, name))) throw new Error('Unknown check option or tenant.');
89
+ for (const tenantName of tenants) {
90
+ let browser;
91
+ try {
92
+ await access(resolveTenantAuthStatePath(tenantName));
93
+ const executablePath = await resolveChromiumExecutable();
94
+ browser = await chromium.launch({ headless: false, executablePath });
95
+ const { context } = await inspectTenant(browser, tenantName);
96
+ await context.close();
97
+ process.stdout.write(`${tenantName}: signed in\n`);
98
+ } catch (error) {
99
+ process.stdout.write(`${tenantName}: not signed in\n`);
100
+ process.exitCode = 1;
101
+ } finally { await browser?.close().catch(() => {}); }
102
+ }
103
+ return;
104
+ }
105
+ if (!Object.hasOwn(AUTH_TENANTS, tenant) || (action === 'refresh' && flags.length) || (action === 'login' && flags.some((flag) => flag !== '--fresh'))) {
106
+ usage();
107
+ process.exitCode = 2;
108
+ return;
109
+ }
110
+
111
+ let browser;
112
+ let context;
113
+ try {
114
+ if (action === 'refresh') {
115
+ try { await access(resolveTenantAuthStatePath(tenant)); }
116
+ catch { throw new Error(`No saved sign-in for ${tenant}. Run: spfx-workbench-auth login ${tenant} --fresh`); }
117
+ }
118
+ const executablePath = await resolveChromiumExecutable();
119
+ browser = await chromium.launch({ headless: action === 'refresh', executablePath });
120
+ const inspected = await inspectTenant(browser, tenant, {
121
+ waitForLogin: action === 'login',
122
+ loadExisting: action === 'refresh' || !fresh,
123
+ });
124
+ context = inspected.context;
125
+ const cookies = await saveState(context, tenant);
126
+ const persistent = cookies.find(({ name }) => name === 'ESTSAUTHPERSISTENT');
127
+ process.stdout.write(`${tenant}: saved ${resolveTenantAuthStatePath(tenant)}\n`);
128
+ if (persistent) {
129
+ const days = persistent.expires < 0 ? undefined : Math.max(0, Math.floor((persistent.expires - Date.now() / 1000) / 86400));
130
+ process.stdout.write(`Microsoft persistent sign-in: ${days === undefined ? 'session only' : `${days} days`}\n`);
131
+ } else {
132
+ process.stdout.write('Microsoft persistent sign-in cookie was not present; this file will not support silent sign-in after the SharePoint cookies expire.\n');
133
+ }
134
+ } finally {
135
+ await context?.close().catch(() => {});
136
+ await browser?.close().catch(() => {});
137
+ }
138
+ }
139
+
140
+ main().catch((error) => {
141
+ process.stderr.write(`Auth failed: ${String(error?.message ?? error).replace(/(?:https?|wss?):\/\/[^\s"'<>]+/g, '[URL]')}\n`);
142
+ process.exitCode = 1;
143
+ });
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ if (process.argv.includes('--watch')) await import('../scripts/watch-sharepoint-capture.mjs');
3
+ else if (process.argv.includes('--summary')) await import('../scripts/diff-captures.mjs');
4
+ else if (process.argv.includes('--diff')) await import('../scripts/diff-captures.mjs');
5
+ else await import('../scripts/import-synthetic-capture.mjs');
@@ -0,0 +1,155 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from 'node:child_process';
3
+ import { access, readFile, realpath } from 'node:fs/promises';
4
+ import { dirname, resolve } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+
7
+ const args = process.argv.slice(2);
8
+ const separator = args.indexOf('--');
9
+ const workbenchArgs = separator < 0 ? args : args.slice(0, separator);
10
+ const heftArgs = separator < 0 ? [] : args.slice(separator + 1);
11
+ const valueAfter = (values, flag) => {
12
+ const index = values.indexOf(flag);
13
+ return index < 0 ? undefined : values[index + 1];
14
+ };
15
+
16
+ if (workbenchArgs.includes('--help') || workbenchArgs.includes('-h')) {
17
+ process.stdout.write('Usage: spfx-workbench-debug --component <project-relative-file> [--props-file <project-relative-json>] [--port <port>] [-- heft-start-options...]\nStarts the local component preview, then the consuming project\'s local Heft `start` command. Heft options go after `--`; for example `-- --serve-config=default` or `-- --nobrowser`.\n');
18
+ process.exit(0);
19
+ }
20
+
21
+ const component = valueAfter(workbenchArgs, '--component');
22
+ const propsFile = valueAfter(workbenchArgs, '--props-file');
23
+ const port = Number(valueAfter(workbenchArgs, '--port') ?? 4176);
24
+ const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');
25
+ const previewCli = resolve(packageRoot, 'bin/spfx-workbench.mjs');
26
+ const projectRoot = resolve(process.cwd());
27
+ const children = [];
28
+ const childOutcomes = new WeakMap();
29
+ let interruptedBy;
30
+
31
+ function stopChildren(signal = 'SIGTERM') {
32
+ for (const child of children) {
33
+ if (child.exitCode === null && child.signalCode === null) child.kill(signal);
34
+ }
35
+ }
36
+
37
+ const onInterrupt = () => { interruptedBy = 'SIGINT'; stopChildren('SIGINT'); };
38
+ const onTerminate = () => { interruptedBy = 'SIGTERM'; stopChildren('SIGTERM'); };
39
+ process.once('SIGINT', onInterrupt);
40
+ process.once('SIGTERM', onTerminate);
41
+
42
+ function startNode(script, childArgs) {
43
+ const child = spawn(process.execPath, [script, ...childArgs], { cwd: projectRoot, stdio: 'inherit' });
44
+ const outcome = new Promise((resolveExit, rejectExit) => {
45
+ child.once('error', rejectExit);
46
+ child.once('exit', (code, signal) => resolveExit({ code, signal }));
47
+ });
48
+ outcome.catch(() => {});
49
+ childOutcomes.set(child, outcome);
50
+ children.push(child);
51
+ return child;
52
+ }
53
+
54
+ function waitForExit(child) {
55
+ return childOutcomes.get(child);
56
+ }
57
+
58
+ async function waitForPreview(child) {
59
+ const base = `http://127.0.0.1:${port}/`;
60
+ const deadline = Date.now() + 15_000;
61
+ while (Date.now() < deadline) {
62
+ if (child.exitCode !== null || child.signalCode !== null) throw new Error('The local component preview exited before becoming ready.');
63
+ let response;
64
+ try {
65
+ response = await fetch(base);
66
+ } catch {
67
+ await new Promise((resolveDelay) => setTimeout(resolveDelay, 75));
68
+ continue;
69
+ }
70
+ if (!response.ok) {
71
+ await new Promise((resolveDelay) => setTimeout(resolveDelay, 75));
72
+ continue;
73
+ }
74
+ const entryResponse = await fetch(new URL('src/main.jsx', base));
75
+ if (!entryResponse.ok) throw new Error('The local component preview could not load its Vite entry module.');
76
+ const entry = await entryResponse.text();
77
+ const virtualPath = entry.match(/from "([^"]*virtual[^"]*)"/)?.[1];
78
+ if (!virtualPath) throw new Error('The local component preview entry did not load its simulator wrapper.');
79
+ const wrapperResponse = await fetch(new URL(virtualPath, base));
80
+ if (!wrapperResponse.ok) throw new Error('The local component preview could not transform its simulator wrapper.');
81
+ const wrapper = await wrapperResponse.text();
82
+ const componentPath = wrapper.match(/import Component from "([^"]+)"/)?.[1];
83
+ if (!componentPath) throw new Error('The local component preview wrapper did not load its consumer component.');
84
+ const componentResponse = await fetch(new URL(componentPath, base));
85
+ if (!componentResponse.ok) throw new Error('The local component preview could not transform the consumer component.');
86
+ return;
87
+ }
88
+ throw new Error('The local component preview did not become ready within 15 seconds.');
89
+ }
90
+
91
+ async function findHeftEntrypoint(root) {
92
+ let directory = root;
93
+ while (true) {
94
+ const packagePath = resolve(directory, 'node_modules/@rushstack/heft/package.json');
95
+ try {
96
+ const metadata = JSON.parse(await readFile(packagePath, 'utf8'));
97
+ const bin = typeof metadata.bin === 'string' ? metadata.bin : metadata.bin?.heft;
98
+ if (!bin) throw new Error('The installed @rushstack/heft package does not declare its heft command.');
99
+ const entrypoint = resolve(dirname(packagePath), bin);
100
+ await access(entrypoint);
101
+ return await realpath(entrypoint);
102
+ } catch (error) {
103
+ if (error.code !== 'ENOENT') throw error;
104
+ }
105
+ const parent = dirname(directory);
106
+ if (parent === directory) break;
107
+ directory = parent;
108
+ }
109
+ throw new Error('Could not find the consuming project\'s local @rushstack/heft installation. Install the project dependencies first.');
110
+ }
111
+
112
+ async function main() {
113
+ if (!component || !Number.isInteger(port) || port < 1 || port > 65535) {
114
+ throw new Error('Provide --component <file> and a valid --port (default 4176).');
115
+ }
116
+ const previewArgs = ['--component', component, '--port', String(port)];
117
+ if (propsFile) previewArgs.push('--props-file', propsFile);
118
+
119
+ const heftEntrypoint = await findHeftEntrypoint(projectRoot);
120
+ if (interruptedBy) {
121
+ process.exitCode = interruptedBy === 'SIGINT' ? 130 : 143;
122
+ return;
123
+ }
124
+ const preview = startNode(previewCli, previewArgs);
125
+ await Promise.race([
126
+ waitForPreview(preview),
127
+ waitForExit(preview).then(({ code, signal }) => {
128
+ throw new Error(`The local component preview exited before becoming ready${signal ? ` from ${signal}` : ` with code ${code}`}.`);
129
+ }),
130
+ ]);
131
+ if (interruptedBy) {
132
+ stopChildren(interruptedBy);
133
+ await Promise.all(children.map((child) => waitForExit(child).catch(() => undefined)));
134
+ process.exitCode = interruptedBy === 'SIGINT' ? 130 : 143;
135
+ return;
136
+ }
137
+ process.stdout.write('Local component preview is ready. Starting the consumer project\'s Heft start command.\n');
138
+ const heft = startNode(heftEntrypoint, ['start', ...heftArgs]);
139
+ const firstExit = await Promise.race([waitForExit(preview), waitForExit(heft)]);
140
+ stopChildren(firstExit.signal ?? 'SIGTERM');
141
+ await Promise.all(children.map(waitForExit));
142
+ process.exitCode = interruptedBy === 'SIGINT' ? 130 : interruptedBy === 'SIGTERM' ? 143 : firstExit.code ?? 1;
143
+ }
144
+
145
+ try {
146
+ await main();
147
+ } catch (error) {
148
+ stopChildren('SIGTERM');
149
+ await Promise.all(children.map((child) => waitForExit(child).catch(() => undefined)));
150
+ if (!interruptedBy) process.stderr.write(`SPFx Workbench debug launcher: ${error.message}\n`);
151
+ process.exitCode = interruptedBy === 'SIGINT' ? 130 : interruptedBy === 'SIGTERM' ? 143 : 1;
152
+ } finally {
153
+ process.off('SIGINT', onInterrupt);
154
+ process.off('SIGTERM', onTerminate);
155
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import '../scripts/diagnose-consumer.mjs';
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import '../scripts/resolve-serve-target.mjs';
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import '../scripts/replay-sharepoint-capture.mjs';