flutter-lens-dev 0.0.0-stage → 0.1.0-alpha.6
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 +93 -2
- package/SECURITY.md +5 -0
- package/bin/lens.mjs +2 -0
- package/bin/mcp.mjs +2 -0
- package/package.json +53 -4
- package/server.json +37 -0
- package/skills/flutter-lens/SKILL.md +40 -0
- package/skills/flutter-lens/scripts/artifacts.mjs +49 -0
- package/skills/flutter-lens/scripts/compose.mjs +34 -0
- package/skills/flutter-lens/scripts/core.mjs +69 -0
- package/skills/flutter-lens/scripts/flutter-plan.mjs +23 -0
- package/skills/flutter-lens/scripts/flutter.mjs +107 -0
- package/skills/flutter-lens/scripts/index.mjs +29 -0
- package/skills/flutter-lens/scripts/lens.mjs +46 -0
- package/skills/flutter-lens/scripts/mcp.mjs +98 -0
- package/skills/flutter-lens/scripts/png.mjs +106 -0
- package/skills/flutter-lens/scripts/swiftui.mjs +62 -0
- package/src/core.mjs +2 -0
- package/src/flutter.mjs +2 -0
- package/src/index.mjs +2 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Flutter Lens 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,94 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Flutter Lens
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**Give coding agents eyes for the interfaces they build.**
|
|
4
|
+
|
|
5
|
+
Render actual Flutter UI to PNGs, without opening a phone, emulator or browser. Flutter Lens is a local-first agent skill, CLI and optional MCP server.
|
|
6
|
+
|
|
7
|
+
[](https://github.com/mullermnm/flutter-lens/actions/workflows/ci.yml) [](LICENSE)
|
|
8
|
+
|
|
9
|
+
> **Developer preview — alpha.6 (development).** Real Flutter rendering, MCP PNG responses and skill installation passed in [Linux CI](https://github.com/mullermnm/flutter-lens/actions/runs/46934380249). All three OS unit jobs and release packaging passed in [CI](https://github.com/mullermnm/flutter-lens/actions/runs/46983527623); actual agent-client visual review remains a stable-release gate (not verified in this alpha). Do not rely on this as your only native-device test.
|
|
10
|
+
|
|
11
|
+
## Actual render evidence
|
|
12
|
+
|
|
13
|
+
The example Flutter screenshots and a standalone macOS SwiftUI preview were visually inspected. See [verification evidence](docs/VERIFICATION-EVIDENCE.md) for the downloadable real PNG artifacts, test results, and limitations. These are not generated mockups.
|
|
14
|
+
|
|
15
|
+
## Install — one command
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
npx skills add mullermnm/flutter-lens --skill flutter-lens -g -y
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Run this once to install the skill in supported detected coding agents. Requires Node.js 20+ and a Flutter SDK on PATH for rendering. Restart or reload your agent if it does not discover the new skill immediately. No manual repo clone or separate Flutter Lens npm package is needed. For project-only installation, omit `-g`. For agent selection, omit `-y`.
|
|
22
|
+
|
|
23
|
+
### Use it naturally
|
|
24
|
+
|
|
25
|
+
> Build the dashboard and visually verify it using Flutter Lens.
|
|
26
|
+
|
|
27
|
+
Or just request a Flutter UI change. The skill description instructs compatible agents to invoke the renderer proactively during relevant UI work. Automatic invocation depends on the agent's skill selection, permissions and available image-reading tools.
|
|
28
|
+
|
|
29
|
+
**Edit → Render → Inspect actual PNG → Improve → Repeat.**
|
|
30
|
+
|
|
31
|
+
The skill bundles its own zero-dependency CLI. It discovers candidate widgets, builds temporary widget-test harnesses and saves actual PNGs in a temporary directory. It supports fixtures for complex app states and custom viewports.
|
|
32
|
+
|
|
33
|
+
## Optional: MCP for direct image responses
|
|
34
|
+
|
|
35
|
+
No manual clone required. Use the public GitHub package through npm exec:
|
|
36
|
+
|
|
37
|
+
```sh
|
|
38
|
+
codex mcp add flutter-lens -- npx -y --package=github:mullermnm/flutter-lens flutter-lens-mcp --root /absolute/path/to/trusted/project --trusted-workspace
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
```sh
|
|
42
|
+
claude mcp add flutter-lens -- npx -y --package=github:mullermnm/flutter-lens flutter-lens-mcp --root /absolute/path/to/trusted/project --trusted-workspace
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
This fetches a GitHub package, not a published npm registry release. Review the repository before trusting it; you may pin a commit using a GitHub package specifier. The MCP server returns image content to compatible clients; actual Codex/Claude image handling is not yet verified. Prefer the installed skill for the simplest workflow.
|
|
46
|
+
|
|
47
|
+
## Standalone CLI
|
|
48
|
+
|
|
49
|
+
Run from a trusted Flutter project:
|
|
50
|
+
|
|
51
|
+
```sh
|
|
52
|
+
npx -y --package=github:mullermnm/flutter-lens flutter-lens doctor
|
|
53
|
+
npx -y --package=github:mullermnm/flutter-lens flutter-lens discover
|
|
54
|
+
npx -y --package=github:mullermnm/flutter-lens flutter-lens render --trusted --file lib/screens/home.dart --widget HomePage
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
The render command returns JSON with the screenshot's absolute path. Add `--out preview.png` to save to a chosen new file. Existing files are never overwritten.
|
|
58
|
+
|
|
59
|
+
### Complex widgets and real app states
|
|
60
|
+
|
|
61
|
+
For required constructor arguments, providers, routes, themes or mock data, use an isolated Dart fixture exporting `Widget buildPreview()`. See [the fixture example](examples/basic/lib/preview.dart). Use `--fixture path/to/preview.dart` instead of `--file` and `--widget`. Choose `--device compact|phone|tablet`, `--width`, `--height`, `--pixel-ratio`, `--theme light|dark`, `--settle-ms` and `--font-file` as needed.
|
|
62
|
+
|
|
63
|
+
## Trust and limitations
|
|
64
|
+
|
|
65
|
+
Rendering executes project code with your local permissions. Only render trusted projects; this is not a sandbox. No cloud or telemetry is included. The test engine can differ from a real mobile device, especially fonts, platform views, native plugins, safe areas, application state and animations. Declared app fonts and available Flutter SDK Material fonts are loaded for previews; exact device fonts may differ. Discovery is heuristic. A complex widget may require a fixture. See [security](SECURITY.md).
|
|
66
|
+
|
|
67
|
+
## Troubleshooting
|
|
68
|
+
|
|
69
|
+
- **The agent does not find the skill:** restart the agent or run the install command with `-a codex`, `-a claude-code`, or the relevant supported agent selected explicitly.
|
|
70
|
+
- **Flutter is unavailable:** install the Flutter SDK and ensure `flutter --version` works from the agent's shell. The skill's `doctor` command reports missing prerequisites.
|
|
71
|
+
- **The widget needs dependencies:** ask the agent to create an isolated preview fixture that supplies its theme, providers and mock state.
|
|
72
|
+
- **The screenshot is not visible:** use the PNG path returned by the CLI and open it with an image-reading tool. Never infer visual quality from a successful command alone.
|
|
73
|
+
|
|
74
|
+
## Contributors
|
|
75
|
+
|
|
76
|
+
For development only, clone the repository and run `npm run lint`, `npm test`, and `npm run test:flutter` with Flutter installed. The latter creates real screenshots; set LENS_ARTIFACT_DIR to retain artifacts. [GitHub Actions](https://github.com/mullermnm/flutter-lens/actions) records CI when available.
|
|
77
|
+
|
|
78
|
+
Start with [CONTRIBUTING.md](CONTRIBUTING.md), [architecture](docs/ARCHITECTURE.md) and [roadmap](docs/ROADMAP.md). The implementation is inside the skill's scripts directory, with thin root CLI and module entry points. Contributions to font handling, fixture coverage, cross-platform support and real agent integration are welcome.
|
|
79
|
+
|
|
80
|
+
Flutter is the first verified backend on Linux. The experimental SwiftUI/macOS adapter produced PNG screenshots in [CI](https://github.com/mullermnm/flutter-lens/actions/runs/46982492783); macOS SwiftUI is not iOS simulation. Experimental Android Compose/Paparazzi has passed actual PNG capture and visual review in [CI](https://github.com/mullermnm/flutter-lens/actions/runs/46984427589). A separate React Native Skia canvas research prototype has passed its own test, but is not part of this alpha. General React Native rendering is not implemented. See [universal rendering](docs/UNIVERSAL-RENDERING.md) and [maintainer publishing](docs/PUBLISHING.md). The verified alpha release artifact and account-authorized publication steps are in [the publishing guide](docs/PUBLISHING.md). npm and MCP Registry publication are pending owner execution.
|
|
81
|
+
|
|
82
|
+
[MIT License](LICENSE)
|
|
83
|
+
|
|
84
|
+
## Development: visual regression
|
|
85
|
+
|
|
86
|
+
This unreleased alpha.5 development branch adds `inspect --file preview.png` and `compare --before baseline.png --after preview.png --out diff.png --threshold 8` to the CLI, plus MCP `inspect_png` and `compare_screens`. Pixel comparison uses same-size 8-bit non-interlaced grayscale/RGB/RGBA images composited on white. It reports changed pixels, percentage, bounds and maximum/mean differences; the optional PNG highlights pixels over threshold. The validator checks CRC, critical chunks and bounded decompression. These changes require fresh CI and are not part of the verified alpha.4 artifact.
|
|
87
|
+
|
|
88
|
+
Alpha.5 also adds `matrix --trusted --file lib/page.dart --widget Page --variants phone:light,compact:dark,tablet:light` with per-variant timing, PNGs and a JSON manifest. MCP `render_screen` accepts an optional `outputFile` (new project-relative PNG in an existing directory). Actual Flutter rendering is now tested on Windows/macOS as well as Linux; results for new jobs are pending.
|
|
89
|
+
|
|
90
|
+
## Alpha.6 development
|
|
91
|
+
|
|
92
|
+
Read-only Flutter `plan` provides constructor and dependency hints. Opt-in `--diagnostics` returns bounded actual render-tree findings, not an accessibility audit. Source/PNG hashes and elapsed time are included; source hashes alone do not establish deterministic rendering. CI verifies deliberately truncated text. The React Native research code is now in the main repository under `research/` but is not installed as a supported backend.
|
|
93
|
+
|
|
94
|
+
The local stdio server now has bounded incoming messages and queued requests, cancellation support and a CI smoke test using the official MCP v1 SDK client. It remains a dependency-free legacy-protocol server; full SDK server migration and modern protocol conformance are separate tasks.
|
package/SECURITY.md
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
# Security
|
|
2
|
+
|
|
3
|
+
Flutter Lens executes arbitrary Dart project code using the invoking user's permissions. It is not a sandbox. Only authorize trusted workspaces; never point it at an entire home directory. Do not run elevated. No external service or telemetry is included. Path validation, timeouts and temporary harness cleanup are defense in depth, not isolation.
|
|
4
|
+
|
|
5
|
+
Report vulnerabilities using GitHub's private vulnerability reporting if enabled, or contact the maintainer privately. Do not post exploit details or credentials in public issues. The alpha has no security-support SLA.
|
package/bin/lens.mjs
ADDED
package/bin/mcp.mjs
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,55 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "flutter-lens-dev",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0-alpha.6",
|
|
4
|
+
"description": "Give AI coding agents eyes for Flutter UI: local headless screenshot renderer, skill and MCP.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"engines": {
|
|
8
|
+
"node": ">=20"
|
|
9
|
+
},
|
|
10
|
+
"bin": {
|
|
11
|
+
"flutter-lens": "bin/lens.mjs",
|
|
12
|
+
"flutter-lens-mcp": "bin/mcp.mjs",
|
|
13
|
+
"flutter-lens-dev": "bin/mcp.mjs"
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"bin",
|
|
17
|
+
"src",
|
|
18
|
+
"skills",
|
|
19
|
+
"README.md",
|
|
20
|
+
"LICENSE",
|
|
21
|
+
"SECURITY.md",
|
|
22
|
+
"server.json"
|
|
23
|
+
],
|
|
24
|
+
"scripts": {
|
|
25
|
+
"test": "node --test test/unit.test.mjs",
|
|
26
|
+
"test:flutter": "node --test test/flutter.test.mjs",
|
|
27
|
+
"lint": "node --check skills/flutter-lens/scripts/lens.mjs && node --check skills/flutter-lens/scripts/mcp.mjs && node --check skills/flutter-lens/scripts/flutter.mjs && node --check skills/flutter-lens/scripts/core.mjs && node --check skills/flutter-lens/scripts/index.mjs && node --check skills/flutter-lens/scripts/swiftui.mjs && node --check scripts/check-release.mjs && node --check skills/flutter-lens/scripts/compose.mjs && node --check skills/flutter-lens/scripts/png.mjs && node --check skills/flutter-lens/scripts/artifacts.mjs && node --check skills/flutter-lens/scripts/flutter-plan.mjs",
|
|
28
|
+
"test:swiftui": "node --test test/swiftui.test.mjs",
|
|
29
|
+
"check:release": "node scripts/check-release.mjs",
|
|
30
|
+
"prepack": "npm run lint && npm run check:release",
|
|
31
|
+
"test:compose": "node --test test/compose.test.mjs"
|
|
32
|
+
},
|
|
33
|
+
"repository": {
|
|
34
|
+
"type": "git",
|
|
35
|
+
"url": "https://github.com/mullermnm/flutter-lens.git"
|
|
36
|
+
},
|
|
37
|
+
"keywords": [
|
|
38
|
+
"flutter",
|
|
39
|
+
"agent-skills",
|
|
40
|
+
"mcp",
|
|
41
|
+
"screenshots",
|
|
42
|
+
"headless",
|
|
43
|
+
"ai",
|
|
44
|
+
"visual-testing"
|
|
45
|
+
],
|
|
46
|
+
"bugs": {
|
|
47
|
+
"url": "https://github.com/mullermnm/flutter-lens/issues"
|
|
48
|
+
},
|
|
49
|
+
"homepage": "https://github.com/mullermnm/flutter-lens",
|
|
50
|
+
"mcpName": "io.github.mullermnm/flutter-lens",
|
|
51
|
+
"publishConfig": {
|
|
52
|
+
"access": "public",
|
|
53
|
+
"tag": "next"
|
|
54
|
+
}
|
|
55
|
+
}
|
package/server.json
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
|
|
3
|
+
"name": "io.github.mullermnm/flutter-lens",
|
|
4
|
+
"title": "Flutter Lens",
|
|
5
|
+
"description": "Render Flutter widgets to real PNGs for coding agents, locally and without an emulator.",
|
|
6
|
+
"repository": {
|
|
7
|
+
"url": "https://github.com/mullermnm/flutter-lens",
|
|
8
|
+
"source": "github"
|
|
9
|
+
},
|
|
10
|
+
"version": "0.1.0-alpha.6",
|
|
11
|
+
"packages": [
|
|
12
|
+
{
|
|
13
|
+
"registryType": "npm",
|
|
14
|
+
"identifier": "flutter-lens-dev",
|
|
15
|
+
"version": "0.1.0-alpha.6",
|
|
16
|
+
"transport": {
|
|
17
|
+
"type": "stdio"
|
|
18
|
+
},
|
|
19
|
+
"runtimeHint": "npx",
|
|
20
|
+
"environmentVariables": [
|
|
21
|
+
{
|
|
22
|
+
"name": "FLUTTER_LENS_ROOT",
|
|
23
|
+
"description": "Absolute path to the specific local project you authorize the server to read.",
|
|
24
|
+
"format": "filepath",
|
|
25
|
+
"isRequired": true
|
|
26
|
+
},
|
|
27
|
+
{
|
|
28
|
+
"name": "FLUTTER_LENS_TRUSTED",
|
|
29
|
+
"description": "Set true only if you explicitly trust this project and authorize execution of its code.",
|
|
30
|
+
"format": "boolean",
|
|
31
|
+
"default": "false",
|
|
32
|
+
"isRequired": false
|
|
33
|
+
}
|
|
34
|
+
]
|
|
35
|
+
}
|
|
36
|
+
]
|
|
37
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: flutter-lens
|
|
3
|
+
description: Automatically render and visually inspect actual Flutter screenshots whenever building, editing, debugging, reviewing or comparing Flutter screens, widgets, layouts, themes or responsive UI. Use before declaring UI work complete, even if the user did not explicitly ask for a screenshot. No emulator, phone or browser needed for supported previews.
|
|
4
|
+
---
|
|
5
|
+
# Flutter Lens
|
|
6
|
+
|
|
7
|
+
Use this skill for visual verification as part of normal Flutter UI development. This skill includes a self-contained Node CLI; no separate Flutter Lens package, repo clone or MCP setup is required. Node 20+ and the Flutter SDK are prerequisites.
|
|
8
|
+
|
|
9
|
+
## When to use
|
|
10
|
+
|
|
11
|
+
After creating or materially changing a Flutter screen, and whenever you need to know what it actually looks like, render and inspect it. Use before claiming visual completion or fidelity to a reference. Do not render unrelated backend-only changes. Respect the user's permission settings, workspace trust and available tools.
|
|
12
|
+
|
|
13
|
+
## Workflow
|
|
14
|
+
|
|
15
|
+
Resolve the absolute path to this installed SKILL.md's directory (the skill base directory reported by your agent). Run the bundled script using that directory, not a guessed path and not a project-local clone. In examples, SKILL_DIR denotes that absolute directory. Run commands from the Flutter project root or pass --root.
|
|
16
|
+
|
|
17
|
+
1. If prerequisites are uncertain, run:
|
|
18
|
+
`node "<SKILL_DIR>/scripts/lens.mjs" doctor --root .`
|
|
19
|
+
If dependencies are missing, run flutter pub get only in an authorized project. Never silently install an SDK or bypass permissions.
|
|
20
|
+
2. Locate the screen using the source or:
|
|
21
|
+
`node "<SKILL_DIR>/scripts/lens.mjs" discover --root .`
|
|
22
|
+
3. In a trusted project, render a public zero-argument widget:
|
|
23
|
+
`node "<SKILL_DIR>/scripts/lens.mjs" render --root . --trusted --file lib/screens/home.dart --widget HomePage`
|
|
24
|
+
The JSON response includes the absolute path to a real PNG in a temporary directory. You can specify --out for a new output file. If a Flutter Lens MCP server is configured, prefer its render_screen tool for direct image delivery.
|
|
25
|
+
4. For dependencies, app theme, routing or state, create an isolated test fixture exporting a top-level Widget buildPreview() returning the intended widget tree. Render with --fixture path/to/fixture.dart instead of --file and --widget. Use realistic mocked data, not private live data. Do not change production code merely to enable a preview.
|
|
26
|
+
5. Open the exact returned PNG with the agent's image-reading tool and inspect it visually. A file path, test result, or generated image is not a visual review. If image reading is unavailable, explain that limitation.
|
|
27
|
+
6. Review clipping, spacing, typography, hierarchy, alignment, colors and fidelity. Correct observed problems and re-render. Test a second viewport when layout or responsiveness matters. Use --device compact, phone, or tablet; --theme light or dark; and --font-file for a project-relative font where test typography differs.
|
|
28
|
+
7. Report evidence and unresolved limitations. Do not claim native-device parity, successful rendering or visual inspection without actual evidence.
|
|
29
|
+
|
|
30
|
+
## Safety and limitations
|
|
31
|
+
|
|
32
|
+
Rendering runs trusted project code with local permissions. The --trusted flag is an explicit acknowledgement, not a sandbox. Do not pass it for unknown or untrusted repositories. Respect all host approvals. Keep secrets and private screenshots local. Temporary harnesses are removed; screenshot paths remain available for inspection. Flutter widget tests may not support platform views, native plugins or production initialization without a fixture. Fonts can differ from the device. If rendering fails, provide the real diagnostic and use normal testing or a real device when appropriate.
|
|
33
|
+
|
|
34
|
+
## Verify changes against a baseline
|
|
35
|
+
|
|
36
|
+
If a previous screenshot of the same viewport is available, use the bundled CLI `compare --before baseline.png --after preview.png --out diff.png --threshold 8` or MCP `compare_screens` with workspace-relative PNG paths. Review the actual screenshot and highlighted diff. Pixel changes do not establish whether a design is better; use the user's reference and visual judgment. Never compare different viewport sizes as if identical. The comparison composites transparency over white and supports common non-interlaced 8-bit PNGs. `inspect --file preview.png` validates PNG integrity and reports dimensions and hash. Do not silently overwrite baseline files.
|
|
37
|
+
|
|
38
|
+
For responsive verification, use `matrix --trusted --file lib/page.dart --widget Page --variants phone:light,compact:dark,tablet:light`. Read the manifest and inspect each successful PNG; report failed variants. Use a fixture instead if necessary. For successive MCP renders, use `outputFile` with a new project-relative PNG path in an existing directory; use the returned workspacePath for compare_screens. No existing image is overwritten.
|
|
39
|
+
|
|
40
|
+
For unclear constructors and state dependencies, use `plan --file lib/page.dart --widget Page` before attempting direct rendering. The hints are heuristic; create an explicit authorized fixture for unresolved state. For a Flutter preview, add `--diagnostics` (or MCP diagnostics: true) to request bounded actual render-tree findings such as line truncation and small or unlabeled semantic tap targets. Inspect the PNG and treat warnings as review hints, not certification. No text content is copied into diagnostics. Source and PNG hashes and elapsed time are returned; these are not a complete dependency fingerprint or a cache key.
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import {realpath,stat,writeFile,mkdir,mkdtemp} from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import {devices,within} from './core.mjs';
|
|
5
|
+
import {render} from './index.mjs';
|
|
6
|
+
|
|
7
|
+
export async function workspaceOutput(root,relative){
|
|
8
|
+
if(typeof relative!=='string'||!relative||path.isAbsolute(relative)||/^[A-Za-z]:/.test(relative)||relative.includes('\\')||!relative.endsWith('.png')||relative.split('/').some(p=>!p||p==='.'||p==='..'||p.includes(':')))throw new Error('Use a forward-slash workspace-relative .png outputFile with an existing parent directory.');
|
|
9
|
+
root=await realpath(root);
|
|
10
|
+
const parent=await realpath(path.resolve(root,path.dirname(relative)));
|
|
11
|
+
if(!within(root,parent)||!(await stat(parent)).isDirectory())throw new Error('Output path escapes project root or parent is not a directory.');
|
|
12
|
+
return path.join(parent,path.basename(relative));
|
|
13
|
+
}
|
|
14
|
+
export async function saveWorkspacePng(root,relative,image){
|
|
15
|
+
const output=await workspaceOutput(root,relative);
|
|
16
|
+
await writeFile(output,image,{flag:'wx'});
|
|
17
|
+
return output;
|
|
18
|
+
}
|
|
19
|
+
export function parseVariants(spec='phone:light,compact:dark,tablet:light'){
|
|
20
|
+
if(typeof spec!=='string')throw new Error('Expected comma-separated device:theme variants.');
|
|
21
|
+
const items=spec.split(',');
|
|
22
|
+
if(items.length<1||items.length>6)throw new Error('Render matrix supports 1–6 variants.');
|
|
23
|
+
const seen=new Set();
|
|
24
|
+
return items.map(item=>{
|
|
25
|
+
const [device,theme,...rest]=item.trim().split(':');
|
|
26
|
+
if(rest.length||!Object.hasOwn(devices,device)||!['light','dark'].includes(theme)||seen.has(device+':'+theme))throw new Error('Invalid or duplicate matrix variant: '+item);
|
|
27
|
+
seen.add(device+':'+theme);return {device,theme};
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
export async function renderMatrix(input,{renderer=render}={}){
|
|
31
|
+
if(input.trusted!==true)throw new Error('Explicit trusted: true is required.');
|
|
32
|
+
const variants=parseVariants(input.variants);
|
|
33
|
+
if(input.width!==undefined||input.height!==undefined||input.device!==undefined||input.theme!==undefined)throw new Error('Matrix variants determine device and theme; do not pass width, height, device or theme.');
|
|
34
|
+
const dir=input.outDir?path.resolve(input.outDir):await mkdtemp(path.join(os.tmpdir(),'flutter-lens-matrix-'));
|
|
35
|
+
if(input.outDir)await mkdir(dir); // Existing directories are intentionally rejected.
|
|
36
|
+
const {variants:_,outDir:__,...base}=input,results=[];
|
|
37
|
+
for(const variant of variants){
|
|
38
|
+
const start=performance.now();
|
|
39
|
+
try{
|
|
40
|
+
const {image,...info}=await renderer({...base,...variant});
|
|
41
|
+
const output=path.join(dir,variant.device+'-'+variant.theme+'.png');
|
|
42
|
+
await writeFile(output,image,{flag:'wx'});
|
|
43
|
+
results.push({ok:true,...variant,...info,path:output,elapsedMs:Math.round(performance.now()-start)});
|
|
44
|
+
}catch(e){results.push({ok:false,...variant,error:String(e.message??e).slice(0,4000),elapsedMs:Math.round(performance.now()-start)});}
|
|
45
|
+
}
|
|
46
|
+
const manifest={ok:results.every(x=>x.ok),directory:dir,results};
|
|
47
|
+
await writeFile(path.join(dir,'manifest.json'),JSON.stringify(manifest,null,2)+'\n',{flag:'wx'});
|
|
48
|
+
return manifest;
|
|
49
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import {realpath,stat,mkdtemp,readFile,rm} from 'node:fs/promises';
|
|
4
|
+
import {resolveInside,normalizeViewport,run,checkPng} from './core.mjs';
|
|
5
|
+
|
|
6
|
+
const taskPattern=/^:(?:[A-Za-z0-9_-]+:)*test[A-Za-z0-9_]*UnitTest$/;
|
|
7
|
+
const classPattern=/^(?:[A-Za-z_][A-Za-z0-9_]*\.)+[A-Za-z_][A-Za-z0-9_]*$/;
|
|
8
|
+
export async function renderCompose(input,{runner=run,platform=process.platform}={}){
|
|
9
|
+
if(input.trusted!==true)throw new Error('Rendering executes project code. Explicit trusted: true is required.');
|
|
10
|
+
if(!['linux','darwin'].includes(platform))throw new Error('Experimental Compose rendering currently requires Linux or macOS, JDK and Android SDK.');
|
|
11
|
+
if(!taskPattern.test(input.gradleTask??'')||!classPattern.test(input.testClass??''))throw new Error('Provide an explicit Gradle unit-test task and fully qualified preview test class.');
|
|
12
|
+
for(const key of ['file','widget','fixture','sources','settleMs','fontFile'])if(input[key]!==undefined)throw new Error('Compose uses gradleTask and testClass; unsupported option: '+key);
|
|
13
|
+
const root=await realpath(input.root??process.cwd());
|
|
14
|
+
if(!(await stat(root)).isDirectory())throw new Error('Expected a Gradle project directory.');
|
|
15
|
+
const viewport=normalizeViewport(input),theme=input.theme??'light';
|
|
16
|
+
if(![1,2,3].includes(viewport.pixelRatio)||!['light','dark'].includes(theme))throw new Error('Compose fixture requires integer pixel ratio 1, 2 or 3 and light or dark theme.');
|
|
17
|
+
let wrapper;
|
|
18
|
+
try{wrapper=await resolveInside(root,'gradlew');if(!(await stat(wrapper)).isFile())throw new Error('gradlew is not a file.');}
|
|
19
|
+
catch(e){if(e.code!=='ENOENT')throw e;}
|
|
20
|
+
const command=wrapper?'bash':'gradle';
|
|
21
|
+
const args=[...(wrapper?[wrapper]:[]),input.gradleTask,'--tests',input.testClass,'--rerun-tasks','--no-daemon','--no-configuration-cache','--console=plain'];
|
|
22
|
+
const tmp=await mkdtemp(path.join(os.tmpdir(),'lens-compose-'));
|
|
23
|
+
try{
|
|
24
|
+
const output=path.join(tmp,'capture.png');
|
|
25
|
+
const env={...process.env,FLUTTER_LENS_PNG:output,FLUTTER_LENS_WIDTH:String(viewport.width),FLUTTER_LENS_HEIGHT:String(viewport.height),FLUTTER_LENS_PIXEL_RATIO:String(viewport.pixelRatio),FLUTTER_LENS_THEME:theme};
|
|
26
|
+
await runner(command,args,{cwd:root,timeout:480000,env});
|
|
27
|
+
let info;try{info=await stat(output);}catch(e){if(e.code==='ENOENT')throw new Error('Preview test did not write FLUTTER_LENS_PNG. Add the explicit Paparazzi fixture described in docs/UNIVERSAL-RENDERING.md.');throw e;}
|
|
28
|
+
if(!info.isFile()||info.size>16000000)throw new Error('Invalid PNG output or size exceeds 16 MB.');
|
|
29
|
+
const image=await readFile(output),dimensions=checkPng(image);
|
|
30
|
+
if(dimensions.width!==viewport.width*viewport.pixelRatio||dimensions.height!==viewport.height*viewport.pixelRatio)throw new Error('Compose screenshot dimensions do not match requested viewport: '+JSON.stringify(dimensions));
|
|
31
|
+
return {image,mimeType:'image/png',dimensions,framework:'compose',viewport,warnings:['Experimental Paparazzi/Layoutlib backend; real integration verification pending.','Requires an explicitly configured preview test and installed Android/Gradle tooling.','Not native-device parity. Existing Gradle tasks execute with local permissions.']};
|
|
32
|
+
}finally{await rm(tmp,{recursive:true,force:true});}
|
|
33
|
+
}
|
|
34
|
+
export const composeAdapter={id:'compose',discover:async()=>{throw new Error('Compose discovery is not implemented; provide an explicit preview test class.');},render:renderCompose};
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { readFile, realpath, stat, readdir } from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { spawn } from 'node:child_process';
|
|
4
|
+
import {parsePng} from './png.mjs';
|
|
5
|
+
export const devices = Object.freeze({phone:{width:390,height:844,pixelRatio:2},compact:{width:360,height:800,pixelRatio:2},tablet:{width:768,height:1024,pixelRatio:1}});
|
|
6
|
+
export function within(root,file){const r=path.relative(root,file);return r!=='..'&&!r.startsWith('..'+path.sep)&&!path.isAbsolute(r);}
|
|
7
|
+
export async function resolveInside(root,input){
|
|
8
|
+
if(typeof input!=='string'||!input||path.isAbsolute(input))throw new Error('Use a relative project path.');
|
|
9
|
+
root=await realpath(root);
|
|
10
|
+
const target=await realpath(path.resolve(root,input));
|
|
11
|
+
if(!within(root,target))throw new Error('Path escapes project root.');
|
|
12
|
+
return target;
|
|
13
|
+
}
|
|
14
|
+
export async function projectRoot(root){
|
|
15
|
+
const dir=await realpath(root);const yaml=await readFile(await resolveInside(dir,'pubspec.yaml'),'utf8');
|
|
16
|
+
if(!/^\s*name:\s*([a-z][a-z0-9_]*)\s*(?:#.*)?$/m.test(yaml))throw new Error('Expected a Flutter project with a simple pubspec name.');
|
|
17
|
+
return dir;
|
|
18
|
+
}
|
|
19
|
+
export function normalizeViewport(input={}){
|
|
20
|
+
if(!Object.hasOwn(devices,input.device??'phone'))throw new Error('Unknown device.');
|
|
21
|
+
const v={...devices[input.device??'phone']};
|
|
22
|
+
for(const key of ['width','height','pixelRatio'])if(input[key]!==undefined)v[key]=input[key];
|
|
23
|
+
if(!Number.isInteger(v.width)||!Number.isInteger(v.height)||v.width<100||v.height<100||v.width>1600||v.height>2400||!Number.isFinite(v.pixelRatio)||v.pixelRatio<1||v.pixelRatio>3||v.width*v.height*v.pixelRatio**2>12000000)throw new Error('Invalid or excessively large viewport.');
|
|
24
|
+
return v;
|
|
25
|
+
}
|
|
26
|
+
export function checkPng(buffer){const {width,height}=parsePng(buffer);return {width,height};}
|
|
27
|
+
export function run(command,args,{cwd,timeout=120000,env=process.env,signal}={}){
|
|
28
|
+
return new Promise((resolve,reject)=>{
|
|
29
|
+
if(signal?.aborted)return reject(new Error('Render cancelled.'));
|
|
30
|
+
let out='',err='',timedOut=false,cancelled=false;
|
|
31
|
+
const win=process.platform==='win32'&&command==='flutter';
|
|
32
|
+
if(win&&args.some(a=>!/^[-a-zA-Z0-9_./]+$/.test(a)))return reject(new Error('Unsafe Windows command argument.'));
|
|
33
|
+
const child=spawn(win?'cmd.exe':command,win?['/d','/s','/c','flutter '+args.join(' ')]:args,{cwd,env,windowsHide:true,detached:process.platform!=='win32',stdio:['ignore','pipe','pipe']});
|
|
34
|
+
child.stdout.on('data',x=>{out=(out+x).slice(-24000)});child.stderr.on('data',x=>{err=(err+x).slice(-24000)});
|
|
35
|
+
function terminate(){
|
|
36
|
+
try{
|
|
37
|
+
if(!child.pid)return;
|
|
38
|
+
if(process.platform==='win32'){
|
|
39
|
+
const killer=spawn('taskkill',['/PID',String(child.pid),'/T','/F'],{windowsHide:true,stdio:'ignore'});
|
|
40
|
+
killer.on('error',()=>{try{child.kill();}catch{}});
|
|
41
|
+
killer.unref();
|
|
42
|
+
}else process.kill(-child.pid,'SIGKILL');
|
|
43
|
+
}catch{try{child.kill();}catch{}}
|
|
44
|
+
}
|
|
45
|
+
const onAbort=()=>{cancelled=true;terminate();};
|
|
46
|
+
const timer=setTimeout(()=>{timedOut=true;terminate();},timeout);
|
|
47
|
+
signal?.addEventListener('abort',onAbort,{once:true});
|
|
48
|
+
if(signal?.aborted)onAbort();
|
|
49
|
+
function cleanup(){clearTimeout(timer);signal?.removeEventListener('abort',onAbort);}
|
|
50
|
+
child.once('error',e=>{cleanup();reject(new Error(command+': '+e.message));});
|
|
51
|
+
child.once('close',code=>{cleanup();if(cancelled||timedOut||code!==0)reject(new Error((cancelled?'Render cancelled':timedOut?'Render timed out':command+' exited '+code)+'\n'+out+'\n'+err));else resolve({out,err});});
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
export async function discover(root){
|
|
55
|
+
root=await realpath(root);
|
|
56
|
+
const lib=await resolveInside(root,'lib');const found=[];let scanned=0;
|
|
57
|
+
async function walk(dir){for(const entry of (await readdir(dir,{withFileTypes:true})).sort((a,b)=>a.name.localeCompare(b.name))){
|
|
58
|
+
if(scanned>=1500||found.length>=300)return;
|
|
59
|
+
if(entry.isSymbolicLink())continue;const p=path.join(dir,entry.name);
|
|
60
|
+
if(entry.isDirectory())await walk(p);
|
|
61
|
+
else if(entry.isFile()&&p.endsWith('.dart')&&!/\.(g|freezed)\.dart$/.test(p)){
|
|
62
|
+
scanned++;if((await stat(p)).size>512000)continue;
|
|
63
|
+
for(const m of (await readFile(p,'utf8')).matchAll(/\bclass\s+([A-Z]\w*)\s+extends\s+(?:StatelessWidget|StatefulWidget|ConsumerWidget|ConsumerStatefulWidget)\b/g)){
|
|
64
|
+
found.push({file:path.relative(root,p).split(path.sep).join('/'),widget:m[1],likelyScreen:/Page$|Screen$|View$/.test(m[1])});if(found.length>=300)break;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}}
|
|
68
|
+
await walk(lib);return found.sort((a,b)=>Number(b.likelyScreen)-Number(a.likelyScreen));
|
|
69
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import {readFile,stat} from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import {projectRoot,resolveInside,within} from './core.mjs';
|
|
4
|
+
const ident=/^[A-Z][A-Za-z0-9_]*$/;
|
|
5
|
+
const sanitize=s=>s.replace(/\/\*[\s\S]*?\*\//g,' ').replace(/\/\/[^\n]*/g,' ').replace(/'(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*"/g,' ');
|
|
6
|
+
export async function planFlutter({root='.',file,widget}){
|
|
7
|
+
root=await projectRoot(root);
|
|
8
|
+
const source=await resolveInside(root,file);
|
|
9
|
+
if(!within(path.join(root,'lib'),source)||!source.endsWith('.dart')||!ident.test(widget??'')||(await stat(source)).size>512000)throw new Error('Expected a public widget in a Dart file under lib/.');
|
|
10
|
+
const raw=await readFile(source,'utf8'),clean=sanitize(raw);
|
|
11
|
+
const declaration=new RegExp('\\bclass\\s+'+widget+'\\b[^\\{]*\\{').exec(clean);
|
|
12
|
+
if(!declaration)throw new Error('Could not locate widget declaration.');
|
|
13
|
+
const tail=clean.slice(declaration.index+declaration[0].length);
|
|
14
|
+
// Deliberately conservative: this is a source hint, not Dart AST resolution.
|
|
15
|
+
const ctor=new RegExp('\\b(?:const\\s+)?'+widget+'\\s*\\(').exec(tail);
|
|
16
|
+
let signature=null;
|
|
17
|
+
if(ctor){let start=ctor.index+ctor[0].length,depth=1,i=start;for(;i<tail.length&&depth;i++){if(tail[i]==='(')depth++;if(tail[i]===')')depth--;}if(!depth)signature=tail.slice(start,i-1).trim();}
|
|
18
|
+
const requiredNamed=signature===null?[]:[...signature.matchAll(/\brequired\s+(?:(?:this|super)\.)?([A-Za-z_]\w*)(?:\s+([A-Za-z_]\w*))?/g)].map(m=>m[2]??m[1]);
|
|
19
|
+
const dependencies=[];
|
|
20
|
+
for(const [id,pattern] of [['provider',/package:provider\//],['riverpod',/package:(?:flutter_)?riverpod\//],['bloc',/package:flutter_bloc\//],['router',/package:go_router\//],['firebase',/package:firebase_/]])if(pattern.test(raw))dependencies.push(id);
|
|
21
|
+
const direct=signature!==null&&(signature===''||/^\{\s*(?:(?:super\.key|Key\?\s+key)\s*,?\s*)?\}$/.test(signature))&&dependencies.length===0;
|
|
22
|
+
return {file:file.split(path.sep).join('/'),widget,constructorSignature:signature,requiredNamed,dependencyHints:dependencies,directCandidate:direct,confidence:'heuristic',recommendation:direct?'Try direct render; runtime may still need a fixture.':'Provide an explicit buildPreview fixture with real constructor values and necessary providers, routing and theme.',notes:['Source hints only; no code executed, no production files changed.','Imports and constructors do not resolve inherited dependencies or runtime initialization. Never invent credentials or business state.']};
|
|
23
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import {mkdir,mkdtemp,readFile,writeFile,rm,stat,realpath,rmdir} from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import {createHash} from 'node:crypto';
|
|
4
|
+
import {fileURLToPath,pathToFileURL} from 'node:url';
|
|
5
|
+
import {projectRoot,resolveInside,within,normalizeViewport,run,checkPng,discover} from './core.mjs';
|
|
6
|
+
const ident=/^[A-Z][A-Za-z0-9_]*$/;
|
|
7
|
+
const dartString=s=>"'"+s.replaceAll('\\','\\\\').replaceAll("'","\\'").replaceAll('$','\\$').replaceAll('\n','\\n').replaceAll('\r','\\r')+"'";
|
|
8
|
+
// Resolve existing SDK fonts without downloading or redistributing font files.
|
|
9
|
+
export async function sdkMaterialFonts(root){
|
|
10
|
+
try{
|
|
11
|
+
const config=path.join(root,'.dart_tool','package_config.json');
|
|
12
|
+
const pkg=JSON.parse(await readFile(config,'utf8')).packages.find(x=>x.name==='flutter');
|
|
13
|
+
if(!pkg||typeof pkg.rootUri!=='string')return {};
|
|
14
|
+
const uri=new URL(pkg.rootUri,pathToFileURL(config));
|
|
15
|
+
if(uri.protocol!=='file:')return {};
|
|
16
|
+
const directory=path.resolve(fileURLToPath(uri),'..','..','bin','cache','artifacts','material_fonts');
|
|
17
|
+
const families={Roboto:['Roboto-Regular.ttf','Roboto-Medium.ttf','Roboto-Bold.ttf','Roboto-Italic.ttf','Roboto-MediumItalic.ttf','Roboto-BoldItalic.ttf'],RobotoCondensed:['RobotoCondensed-Regular.ttf','RobotoCondensed-Bold.ttf'],MaterialIcons:['MaterialIcons-Regular.otf']};
|
|
18
|
+
const found={};
|
|
19
|
+
for(const [family,names] of Object.entries(families)){
|
|
20
|
+
for(const name of names){const file=path.join(directory,name);try{if((await stat(file)).isFile())(found[family]??=[]).push(file);}catch{}}
|
|
21
|
+
}
|
|
22
|
+
return found;
|
|
23
|
+
}catch{return {};}
|
|
24
|
+
}
|
|
25
|
+
export function harness({importUri,widget,fixture=false,viewport:v,dark=false,settleMs=300,fontFile,sdkFonts={},output='OUTPUT_PLACEHOLDER',diagnosticsOutput}){
|
|
26
|
+
const expression=fixture?'preview.buildPreview()':'preview.'+widget+'()';
|
|
27
|
+
const target=fixture?'target':'MaterialApp(debugShowCheckedModeBanner: false, theme: ThemeData(brightness: Brightness.'+(dark?'dark':'light')+(fontFile?", fontFamily: 'LensPreview'":"")+'), home: target)';
|
|
28
|
+
return [
|
|
29
|
+
"import 'dart:io';","import 'dart:ui' as ui;","import 'dart:typed_data';","import 'dart:convert';",
|
|
30
|
+
"import 'package:flutter/material.dart';","import 'package:flutter/rendering.dart';","import 'package:flutter/services.dart';",
|
|
31
|
+
"import 'package:flutter_test/flutter_test.dart';","import "+dartString(importUri)+" as preview;",
|
|
32
|
+
"void main() { testWidgets('Flutter Lens capture', (tester) async {",
|
|
33
|
+
"tester.view.devicePixelRatio = "+v.pixelRatio+";",
|
|
34
|
+
diagnosticsOutput?"final semantics = tester.ensureSemantics(); try {":"",
|
|
35
|
+
"tester.view.physicalSize = const Size("+v.width*v.pixelRatio+", "+v.height*v.pixelRatio+");",
|
|
36
|
+
"addTearDown(tester.view.resetPhysicalSize); addTearDown(tester.view.resetDevicePixelRatio);",
|
|
37
|
+
"await tester.runAsync(() async {",
|
|
38
|
+
"final loaded = <String>{};",
|
|
39
|
+
"try { final manifest = jsonDecode(await rootBundle.loadString('FontManifest.json')) as List;",
|
|
40
|
+
"for (final item in manifest) { final family = item['family'] as String; try { final loader = FontLoader(family);",
|
|
41
|
+
"for (final font in item['fonts'] as List) { loader.addFont(rootBundle.load(font['asset'] as String)); } await loader.load(); loaded.add(family); } catch (e) { debugPrint('Flutter Lens font warning: '+e.toString()); } }",
|
|
42
|
+
"} catch (e) { debugPrint('Flutter Lens font warning: '+e.toString()); }",
|
|
43
|
+
...Object.entries(sdkFonts).map(([family,paths])=>"if (!loaded.contains("+dartString(family)+")) { try { final loader = FontLoader("+dartString(family)+"); "+paths.map(file=>"loader.addFont(Future.value(ByteData.sublistView(File("+dartString(file)+").readAsBytesSync())));").join(' ')+" await loader.load(); } catch (e) { debugPrint('Flutter Lens SDK font warning: '+e.toString()); } }"),
|
|
44
|
+
fontFile?"final fallback = FontLoader('LensPreview'); fallback.addFont(Future.value(ByteData.sublistView(File("+dartString(fontFile)+").readAsBytesSync()))); await fallback.load();":"",
|
|
45
|
+
"}); final key = GlobalKey(); final target = "+expression+";",
|
|
46
|
+
"await tester.pumpWidget(RepaintBoundary(key: key, child: "+target+"));",
|
|
47
|
+
"await tester.pump(); await tester.pump(const Duration(milliseconds: "+settleMs+"));",
|
|
48
|
+
"final boundary = key.currentContext!.findRenderObject()! as RenderRepaintBoundary;",
|
|
49
|
+
diagnosticsOutput?[
|
|
50
|
+
"final items = <Map<String, Object?>>[]; final seenSemantics = <int>{}; int scanned = 0;",
|
|
51
|
+
"void inspect(RenderObject node) { if (++scanned > 20000 || items.length >= 300) return;",
|
|
52
|
+
"if (node is RenderBox && node.hasSize && node.attached) {",
|
|
53
|
+
"final rect = MatrixUtils.transformRect(node.getTransformTo(boundary), Offset.zero & node.size);",
|
|
54
|
+
"if (rect.isFinite && rect.width > 0 && rect.height > 0 && rect.overlaps(Offset.zero & boundary.size)) {",
|
|
55
|
+
"final bounds = {'x': rect.left, 'y': rect.top, 'width': rect.width, 'height': rect.height};",
|
|
56
|
+
"if (node is RenderParagraph && node.didExceedMaxLines) items.add({'kind':'text-truncated','bounds':bounds,'confidence':'render-engine','note':'Paragraph exceeds its configured line limit; may be intentional.'});",
|
|
57
|
+
"final semantic = node.debugSemantics; if (semantic != null && seenSemantics.add(semantic.id)) {",
|
|
58
|
+
"final data = semantic.getSemanticsData();",
|
|
59
|
+
"if (data.hasAction(ui.SemanticsAction.tap) && (rect.width < 48 || rect.height < 48)) items.add({'kind':'small-tap-target','bounds':bounds,'confidence':'heuristic','note':'Semantic tap node render bounds below 48 logical pixels; verify actual hit area.'});",
|
|
60
|
+
"if (data.hasAction(ui.SemanticsAction.tap) && data.label.trim().isEmpty) items.add({'kind':'unlabeled-tap-target','bounds':bounds,'confidence':'heuristic','note':'Tap node has empty semantics label; verify merged semantics.'});",
|
|
61
|
+
"} } } node.visitChildren(inspect); } inspect(boundary);",
|
|
62
|
+
"File("+dartString(diagnosticsOutput)+").writeAsStringSync(jsonEncode({'schemaVersion':1,'scanned':scanned,'truncated':scanned>20000||items.length>=300,'findings':items,'coordinateSpace':'logical-pixels'}));"
|
|
63
|
+
].join('\n'):"",
|
|
64
|
+
"await tester.runAsync(() async { final image = await boundary.toImage(pixelRatio: "+v.pixelRatio+");",
|
|
65
|
+
"try { final bytes = await image.toByteData(format: ui.ImageByteFormat.png);",
|
|
66
|
+
"if (bytes == null) throw StateError('PNG encoding failed');",
|
|
67
|
+
"File("+dartString(output)+").writeAsBytesSync(bytes.buffer.asUint8List(bytes.offsetInBytes, bytes.lengthInBytes));",
|
|
68
|
+
"} finally { image.dispose(); } });",
|
|
69
|
+
"final error = tester.takeException(); if (error != null) throw StateError('Flutter render exception: '+error.toString());",
|
|
70
|
+
diagnosticsOutput?"} finally { semantics.dispose(); }":"",
|
|
71
|
+
"}); }"
|
|
72
|
+
].join('\n');
|
|
73
|
+
}
|
|
74
|
+
export const flutterAdapter={id:'flutter',discover:async({root})=>discover(await projectRoot(root)),render};
|
|
75
|
+
export async function render(input,{runner=run}={}){
|
|
76
|
+
if(input.trusted!==true)throw new Error('Rendering executes project code. Explicit trusted: true is required.');
|
|
77
|
+
const root=await projectRoot(input.root??process.cwd());
|
|
78
|
+
const fixture=input.fixture!==undefined;
|
|
79
|
+
if(fixture&&(input.file!==undefined||input.widget!==undefined))throw new Error('Choose file/widget or fixture, not both.');
|
|
80
|
+
const file=await resolveInside(root,fixture?input.fixture:input.file);
|
|
81
|
+
if(!file.endsWith('.dart')||!(await stat(file)).isFile())throw new Error('Expected a Dart file.');
|
|
82
|
+
if(!fixture&&!ident.test(input.widget??''))throw new Error('Provide a public widget class name.');
|
|
83
|
+
if(!fixture&&!within(path.join(root,'lib'),file))throw new Error('Widget source must be under lib/.');
|
|
84
|
+
const viewport=normalizeViewport(input),settleMs=input.settleMs??300;
|
|
85
|
+
if(input.diagnostics!==undefined&&typeof input.diagnostics!=='boolean')throw new Error('diagnostics must be boolean.');
|
|
86
|
+
if(!Number.isInteger(settleMs)||settleMs<0||settleMs>10000)throw new Error('Invalid settleMs.');
|
|
87
|
+
if(input.theme!==undefined&&!['light','dark'].includes(input.theme))throw new Error('Invalid theme.');
|
|
88
|
+
const fontFile=input.fontFile?await resolveInside(root,input.fontFile):undefined;
|
|
89
|
+
const sdkFonts=await sdkMaterialFonts(root);
|
|
90
|
+
const testRoot=path.join(root,'test');let madeTestRoot=false;
|
|
91
|
+
try{await mkdir(testRoot);madeTestRoot=true;}catch(e){if(e.code!=='EEXIST')throw e;}
|
|
92
|
+
if(await realpath(testRoot)!==testRoot)throw new Error('Symlinked test directory is not supported.');
|
|
93
|
+
const tmp=await mkdtemp(path.join(testRoot,'lens_'));
|
|
94
|
+
try{
|
|
95
|
+
const testFile=path.join(tmp,'capture_test.dart'),png=path.join(tmp,'capture.png'),diagnosticsOutput=input.diagnostics?path.join(tmp,'diagnostics.json'):undefined;
|
|
96
|
+
const pub=await readFile(path.join(root,'pubspec.yaml'),'utf8'),pkg=pub.match(/^\s*name:\s*([a-z][a-z0-9_]*)\s*(?:#.*)?$/m)[1];
|
|
97
|
+
const importUri=within(path.join(root,'lib'),file)?'package:'+pkg+'/'+path.relative(path.join(root,'lib'),file).split(path.sep).join('/'):path.relative(tmp,file).split(path.sep).join('/');
|
|
98
|
+
await writeFile(testFile,harness({importUri,widget:input.widget,fixture,viewport,dark:input.theme==='dark',settleMs,fontFile,sdkFonts,output:png,diagnosticsOutput}),{flag:'wx'});
|
|
99
|
+
await runner('flutter',['test','--no-pub','--reporter','expanded',path.relative(root,testFile).split(path.sep).join('/')],{cwd:root,timeout:120000});
|
|
100
|
+
if((await stat(png)).size>16000000)throw new Error('PNG exceeds 16 MB. Choose a smaller viewport.');
|
|
101
|
+
const image=await readFile(png),dimensions=checkPng(image);
|
|
102
|
+
if(dimensions.width!==Math.ceil(viewport.width*viewport.pixelRatio)||dimensions.height!==Math.ceil(viewport.height*viewport.pixelRatio))throw new Error('Unexpected capture dimensions.');
|
|
103
|
+
const diagnostics=diagnosticsOutput?JSON.parse(await readFile(diagnosticsOutput,'utf8')):undefined;
|
|
104
|
+
const sourceSha256=createHash('sha256').update(await readFile(file)).digest('hex');
|
|
105
|
+
return {image,...(diagnostics?{diagnostics}:{}),provenance:{schemaVersion:1,sourceSha256,source:path.relative(root,file).split(path.sep).join('/'),theme:input.theme??'light',settleMs,fixture},mimeType:'image/png',dimensions,framework:'flutter',viewport,warnings:['Widget-test preview, not native-device parity.','Use a fixture for actual app theme, providers, routes and state.','Fonts may differ; declared app fonts and available SDK material fonts are loaded; provide fontFile for overrides.']};
|
|
106
|
+
}finally{await rm(tmp,{recursive:true,force:true});if(madeTestRoot){try{await rmdir(testRoot);}catch{}}}
|
|
107
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import {flutterAdapter} from './flutter.mjs';
|
|
2
|
+
import {swiftuiAdapter} from './swiftui.mjs';
|
|
3
|
+
import {composeAdapter} from './compose.mjs';
|
|
4
|
+
import {createHash} from 'node:crypto';
|
|
5
|
+
import {checkPng} from './core.mjs';
|
|
6
|
+
|
|
7
|
+
export const adapters=new Map([[flutterAdapter.id,flutterAdapter],[swiftuiAdapter.id,swiftuiAdapter],[composeAdapter.id,composeAdapter]]);
|
|
8
|
+
export const frameworks=Object.freeze([
|
|
9
|
+
{id:'flutter',status:'preview',platforms:['linux','darwin','win32'],note:'Real Linux rendering and installed-skill integration passed in GitHub CI; other hosts pending.'},
|
|
10
|
+
{id:'swiftui',status:'experimental',platforms:['darwin'],note:'Standalone macOS SwiftUI example passed CI and visual review; not iOS fidelity.'},
|
|
11
|
+
{id:'compose',status:'experimental',platforms:['linux','darwin'],note:'Explicit Paparazzi example passed Linux CI and visual review.'},
|
|
12
|
+
{id:'react-native',status:'planned',platforms:[],note:'No general native offscreen backend implemented.'}
|
|
13
|
+
]);
|
|
14
|
+
export function adapterFor(id='flutter'){const a=adapters.get(id);if(!a)throw new Error('Unsupported framework: '+id+'. See frameworks for available and experimental backends.');return a;}
|
|
15
|
+
export async function render(input,options){
|
|
16
|
+
const start=performance.now();
|
|
17
|
+
const adapter=adapterFor(input.framework);
|
|
18
|
+
const signal=options?.signal;
|
|
19
|
+
if(signal?.aborted)throw new Error('Render cancelled.');
|
|
20
|
+
const {run}=await import('./core.mjs');
|
|
21
|
+
const runner=options?.runner??run;
|
|
22
|
+
const result=await adapter.render(input,{...options,runner:(command,args,config)=>runner(command,args,{...config,signal})});
|
|
23
|
+
if(signal?.aborted)throw new Error('Render cancelled.');
|
|
24
|
+
if(result.framework!==adapter.id||result.mimeType!=='image/png'||!Buffer.isBuffer(result.image)||!Array.isArray(result.warnings))throw new Error('Invalid renderer response.');
|
|
25
|
+
const size=checkPng(result.image);
|
|
26
|
+
if(size.width!==result.dimensions?.width||size.height!==result.dimensions?.height)throw new Error('Renderer metadata does not match PNG dimensions.');
|
|
27
|
+
return {...result,imageSha256:createHash('sha256').update(result.image).digest('hex'),rendererVersion:'0.1.0-alpha.6',elapsedMs:Math.round(performance.now()-start)};
|
|
28
|
+
}
|
|
29
|
+
export async function discover(input){return adapterFor(input.framework).discover(input);}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {parseArgs} from 'node:util';
|
|
3
|
+
import {writeFile,mkdtemp,stat} from 'node:fs/promises';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
import {render,discover,frameworks} from './index.mjs';
|
|
7
|
+
import {devices,projectRoot,run} from './core.mjs';
|
|
8
|
+
import {readPng,inspectPng,comparePng} from './png.mjs';
|
|
9
|
+
import {renderMatrix} from './artifacts.mjs';
|
|
10
|
+
import {planFlutter} from './flutter-plan.mjs';
|
|
11
|
+
const usage='flutter-lens doctor [--root .]\nflutter-lens discover [--root .]\nflutter-lens plan --file lib/page.dart --widget Page\nflutter-lens render --trusted --file lib/page.dart --widget MyPage [--out preview.png]\nflutter-lens render --trusted --fixture lib/preview.dart [--out preview.png]\nflutter-lens matrix --trusted --file lib/page.dart --widget MyPage [--variants phone:light,compact:dark] [--out-dir new-folder]\nflutter-lens inspect --file preview.png\nflutter-lens compare --before baseline.png --after preview.png [--out diff.png] [--threshold 8]\nflutter-lens devices\nflutter-lens frameworks\nflutter-lens render --framework swiftui --trusted --fixture Preview.swift\nflutter-lens render --framework compose --trusted --gradle-task :app:testDebugUnitTest --test-class example.LensPreviewTest';
|
|
12
|
+
try{
|
|
13
|
+
const [command,...args]=process.argv.slice(2);if(!command||command==='--help'||command==='help'){console.log(usage);process.exit(0);}
|
|
14
|
+
const {values:v}=parseArgs({args,options:{diagnostics:{type:'boolean'},variants:{type:'string'},'out-dir':{type:'string'},before:{type:'string'},after:{type:'string'},threshold:{type:'string'},framework:{type:'string',default:'flutter'},source:{type:'string',multiple:true},'gradle-task':{type:'string'},'test-class':{type:'string'},root:{type:'string',default:'.'},file:{type:'string'},widget:{type:'string'},fixture:{type:'string'},out:{type:'string'},device:{type:'string'},theme:{type:'string'},width:{type:'string'},height:{type:'string'},'pixel-ratio':{type:'string'},'font-file':{type:'string'},'settle-ms':{type:'string'},trusted:{type:'boolean',default:false}},strict:true});
|
|
15
|
+
if(command==='plan'){
|
|
16
|
+
if(v.framework!=='flutter')throw new Error('plan currently supports Flutter.');
|
|
17
|
+
console.log(JSON.stringify(await planFlutter(v),null,2));
|
|
18
|
+
}else if(command==='inspect'){
|
|
19
|
+
if(!v.file)throw new Error('--file is required');
|
|
20
|
+
console.log(JSON.stringify(inspectPng(await readPng(v.file)),null,2));
|
|
21
|
+
}else if(command==='compare'){
|
|
22
|
+
if(!v.before||!v.after)throw new Error('--before and --after are required');
|
|
23
|
+
const {image,...info}=comparePng(await readPng(v.before),await readPng(v.after),{threshold:v.threshold===undefined?0:Number(v.threshold),makeDiff:!!v.out});
|
|
24
|
+
if(image)await writeFile(v.out,image,{flag:'wx'});
|
|
25
|
+
console.log(JSON.stringify({...info,...(image?{path:path.resolve(v.out)}:{})},null,2));
|
|
26
|
+
}else if(command==='frameworks')console.log(JSON.stringify(frameworks,null,2));
|
|
27
|
+
else if(command==='doctor'){
|
|
28
|
+
if(v.framework!=='flutter')throw new Error('doctor currently checks Flutter prerequisites; for SwiftUI use xcrun swiftc --version on macOS.');
|
|
29
|
+
const checks={node:{ok:Number(process.versions.node.split('.')[0])>=20,version:process.version}};
|
|
30
|
+
try{const root=await projectRoot(v.root);checks.project={ok:true,root};try{await stat(path.join(root,'.dart_tool','package_config.json'));checks.dependencies={ok:true};}catch{checks.dependencies={ok:false,fix:'Run flutter pub get in the trusted project.'};}}catch(e){checks.project={ok:false,fix:e.message};}
|
|
31
|
+
try{const r=await run('flutter',['--version'],{cwd:process.cwd(),timeout:30000});checks.flutter={ok:true,version:r.out.trim()};}catch(e){checks.flutter={ok:false,fix:'Install Flutter SDK, add flutter to PATH, and verify flutter --version.',detail:e.message};}
|
|
32
|
+
const ok=Object.values(checks).every(x=>x.ok);console.log(JSON.stringify({ok,checks},null,2));if(!ok)process.exitCode=1;
|
|
33
|
+
}
|
|
34
|
+
else if(command==='discover')console.log(JSON.stringify(await discover({root:v.root,framework:v.framework}),null,2));
|
|
35
|
+
else if(command==='devices')console.log(JSON.stringify(devices,null,2));
|
|
36
|
+
else if(command==='matrix'){
|
|
37
|
+
const n=k=>v[k]===undefined?undefined:Number(v[k]);
|
|
38
|
+
const manifest=await renderMatrix({...v,sources:v.source,gradleTask:v['gradle-task'],testClass:v['test-class'],width:n('width'),height:n('height'),pixelRatio:n('pixel-ratio'),settleMs:n('settle-ms'),fontFile:v['font-file'],outDir:v['out-dir']});
|
|
39
|
+
console.log(JSON.stringify(manifest,null,2));if(!manifest.ok)process.exitCode=1;
|
|
40
|
+
}else if(command==='render'){
|
|
41
|
+
const n=k=>v[k]===undefined?undefined:Number(v[k]);
|
|
42
|
+
const {image,...info}=await render({...v,sources:v.source,gradleTask:v['gradle-task'],testClass:v['test-class'],width:n('width'),height:n('height'),pixelRatio:n('pixel-ratio'),settleMs:n('settle-ms'),fontFile:v['font-file']});
|
|
43
|
+
const output=v.out??path.join(await mkdtemp(path.join(os.tmpdir(),'flutter-lens-')),'preview.png');
|
|
44
|
+
await writeFile(output,image,{flag:'wx'});console.log(JSON.stringify({...info,path:path.resolve(output)},null,2));
|
|
45
|
+
}else throw new Error('Unknown command.\n'+usage);
|
|
46
|
+
}catch(e){console.error(e.message);process.exitCode=1;}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {parseArgs} from 'node:util';
|
|
3
|
+
import {realpath} from 'node:fs/promises';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import {render,discover,frameworks} from './index.mjs';
|
|
6
|
+
import {devices,within,resolveInside} from './core.mjs';
|
|
7
|
+
import {readPng,inspectPng,comparePng} from './png.mjs';
|
|
8
|
+
import {saveWorkspacePng,workspaceOutput} from './artifacts.mjs';
|
|
9
|
+
import {planFlutter} from './flutter-plan.mjs';
|
|
10
|
+
const {values:config}=parseArgs({options:{root:{type:'string'},'trusted-workspace':{type:'boolean'}},strict:true});
|
|
11
|
+
const configuredRoot=config.root??process.env.FLUTTER_LENS_ROOT;
|
|
12
|
+
const trusted=config['trusted-workspace']===true||process.env.FLUTTER_LENS_TRUSTED==='true';
|
|
13
|
+
if(trusted&&!configuredRoot)throw new Error('Explicit --root or FLUTTER_LENS_ROOT required for trusted rendering.');
|
|
14
|
+
const root=await realpath(configuredRoot??process.cwd());
|
|
15
|
+
const props={diagnostics:{type:'boolean',description:'Flutter only: opt in to bounded render-tree layout/semantics diagnostics without copying text.'},outputFile:{type:'string',description:'Optional new project-relative PNG path. Parent must exist; never overwrites.'},framework:{type:'string',enum:['flutter','swiftui','compose']},gradleTask:{type:'string'},testClass:{type:'string'},sources:{type:'array',items:{type:'string'},maxItems:16},project:{type:'string',description:'Relative project folder inside the configured workspace. Defaults to .'},file:{type:'string'},widget:{type:'string'},fixture:{type:'string'},device:{type:'string',enum:Object.keys(devices)},theme:{type:'string',enum:['light','dark']},width:{type:'integer'},height:{type:'integer'},pixelRatio:{type:'number'},settleMs:{type:'integer'},fontFile:{type:'string'}};
|
|
16
|
+
const tools=[{name:'plan_flutter_preview',description:'Read-only heuristic constructor and dependency hints for an existing Flutter widget.',inputSchema:{type:'object',properties:{file:{type:'string'},widget:{type:'string'},project:props.project},required:['file','widget'],additionalProperties:false}},{name:'inspect_png',description:'Validate an existing workspace PNG and return dimensions and hash.',inputSchema:{type:'object',properties:{file:{type:'string'}},required:['file'],additionalProperties:false}},{name:'compare_screens',description:'Compare two existing workspace-relative PNG screenshots of the same viewport; returns change metrics and a highlighted PNG diff.',inputSchema:{type:'object',properties:{before:{type:'string'},after:{type:'string'},threshold:{type:'integer',minimum:0,maximum:255}},required:['before','after'],additionalProperties:false}},{name:'list_frameworks',description:'List supported, experimental and planned frameworks.',inputSchema:{type:'object',properties:{},additionalProperties:false}},{name:'list_devices',description:'List headless viewport presets.',inputSchema:{type:'object',properties:{},additionalProperties:false}},{name:'discover_screens',description:'Find candidate Flutter widgets by source inspection (heuristic).',inputSchema:{type:'object',properties:{project:props.project},additionalProperties:false}},{name:'render_screen',description:'Render a trusted Flutter preview to a real PNG. For Flutter use file and widget or fixture; experimental SwiftUI requires framework swiftui, macOS and an explicit Swift fixture; Compose requires framework compose, gradleTask and testClass.',inputSchema:{type:'object',properties:props,additionalProperties:false}}];
|
|
17
|
+
const text=t=>({type:'text',text:t});
|
|
18
|
+
async function call(name,args={},signal){
|
|
19
|
+
if(!args||typeof args!=='object'||Array.isArray(args))throw new Error('Invalid arguments.');
|
|
20
|
+
const allowed=name==='render_screen'?Object.keys(props):name==='discover_screens'?['project']:name==='plan_flutter_preview'?['project','file','widget']:name==='inspect_png'?['file']:name==='compare_screens'?['before','after','threshold']:[];
|
|
21
|
+
if(Object.keys(args).some(k=>!allowed.includes(k)))throw new Error('Unknown tool argument.');
|
|
22
|
+
if(name==='inspect_png')return {content:[text(JSON.stringify(inspectPng(await readPng(await resolveInside(root,args.file)))))]};
|
|
23
|
+
if(name==='compare_screens'){const {image,...metrics}=comparePng(await readPng(await resolveInside(root,args.before)),await readPng(await resolveInside(root,args.after)),{threshold:args.threshold??0,makeDiff:true});if(image.length>16000000)throw new Error('Diff PNG exceeds 16 MB.');return {content:[text(JSON.stringify(metrics)),{type:'image',mimeType:'image/png',data:image.toString('base64')}]};}
|
|
24
|
+
if(name==='list_frameworks')return {content:[text(JSON.stringify(frameworks))]};
|
|
25
|
+
if(name==='list_devices')return {content:[text(JSON.stringify(devices))]};
|
|
26
|
+
const project=await realpath(path.resolve(root,args.project??'.'));
|
|
27
|
+
if(!within(root,project))throw new Error('Project outside configured workspace.');
|
|
28
|
+
if(name==='plan_flutter_preview')return {content:[text(JSON.stringify(await planFlutter({...args,root:project})))]};
|
|
29
|
+
if(name==='discover_screens')return {content:[text(JSON.stringify(await discover({root:project})))]};
|
|
30
|
+
if(name==='render_screen'){
|
|
31
|
+
if(args.outputFile!==undefined){if(!trusted)throw new Error('Trusted workspace required.');await workspaceOutput(project,args.outputFile);}
|
|
32
|
+
const {outputFile,...input}=args;const {image,...info}=await render({...input,root:project,trusted},{signal});
|
|
33
|
+
if(outputFile!==undefined){info.path=await saveWorkspacePng(project,outputFile,image);info.workspacePath=path.relative(root,info.path).split(path.sep).join('/');}
|
|
34
|
+
return {content:[{type:'image',data:image.toString('base64'),mimeType:'image/png'},text(JSON.stringify(info))]};
|
|
35
|
+
}
|
|
36
|
+
throw new Error('Unknown tool.');
|
|
37
|
+
}
|
|
38
|
+
const send=obj=>process.stdout.write(JSON.stringify(obj)+'\n');
|
|
39
|
+
const versions=['2024-11-05','2025-03-26','2025-06-18','2025-11-25'];
|
|
40
|
+
let initialized=false;
|
|
41
|
+
const MAX_LINE=1024*1024,MAX_PENDING=16;
|
|
42
|
+
const pending=new Map(),queue=[];
|
|
43
|
+
let draining=false,drainPromise=Promise.resolve();
|
|
44
|
+
async function handle(msg,controller){
|
|
45
|
+
const base={jsonrpc:'2.0',id:msg.id};
|
|
46
|
+
try{
|
|
47
|
+
let result;
|
|
48
|
+
if(msg.method==='initialize'){
|
|
49
|
+
if(initialized){send({...base,error:{code:-32600,message:'Already initialized'}});return;}
|
|
50
|
+
initialized=true;result={protocolVersion:versions.includes(msg.params?.protocolVersion)?msg.params.protocolVersion:'2025-11-25',capabilities:{tools:{}},serverInfo:{name:'flutter-lens',version:'0.1.0-alpha.6'},instructions:'Render only trusted projects. Inspect PNGs; report preview limitations.'};
|
|
51
|
+
}else if(msg.method==='ping')result={};
|
|
52
|
+
else if(!initialized){send({...base,error:{code:-32002,message:'Initialize first'}});return;}
|
|
53
|
+
else if(msg.method==='tools/list')result={tools};
|
|
54
|
+
else if(msg.method==='tools/call'){
|
|
55
|
+
const name=msg.params?.name;
|
|
56
|
+
if(!tools.some(t=>t.name===name)){send({...base,error:{code:-32602,message:'Unknown tool'}});return;}
|
|
57
|
+
try{result=await call(name,msg.params?.arguments??{},controller.signal);}
|
|
58
|
+
catch(e){result={isError:true,content:[text(String(e.message??e).slice(0,24000))]};}
|
|
59
|
+
}else{send({...base,error:{code:-32601,message:'Method not found'}});return;}
|
|
60
|
+
if(!controller.signal.aborted)send({...base,result});
|
|
61
|
+
}catch(e){if(!controller.signal.aborted)send({...base,error:{code:-32603,message:String(e.message??e).slice(0,4000)}});}
|
|
62
|
+
}
|
|
63
|
+
function startDrain(){
|
|
64
|
+
if(draining)return;
|
|
65
|
+
draining=true;drainPromise=(async()=>{
|
|
66
|
+
try{while(queue.length){const {msg,controller}=queue.shift();try{if(!controller.signal.aborted)await handle(msg,controller);}finally{pending.delete(msg.id);}}}
|
|
67
|
+
finally{draining=false;}
|
|
68
|
+
})();
|
|
69
|
+
}
|
|
70
|
+
function receive(line){
|
|
71
|
+
let msg;try{msg=JSON.parse(line);}catch{send({jsonrpc:'2.0',id:null,error:{code:-32700,message:'Parse error'}});return;}
|
|
72
|
+
if(!msg||msg.jsonrpc!=='2.0'||typeof msg.method!=='string'){send({jsonrpc:'2.0',id:null,error:{code:-32600,message:'Invalid request'}});return;}
|
|
73
|
+
if(!Object.hasOwn(msg,'id')){
|
|
74
|
+
if(msg.method==='notifications/cancelled')pending.get(msg.params?.requestId)?.abort();
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
if(typeof msg.id!=='string'&&!(typeof msg.id==='number'&&Number.isSafeInteger(msg.id))){send({jsonrpc:'2.0',id:null,error:{code:-32600,message:'Invalid request id'}});return;}
|
|
78
|
+
if(pending.has(msg.id)||pending.size>=MAX_PENDING){send({jsonrpc:'2.0',id:msg.id,error:{code:-32000,message:'Duplicate id or request queue full'}});return;}
|
|
79
|
+
const controller=new AbortController();pending.set(msg.id,controller);queue.push({msg,controller});startDrain();
|
|
80
|
+
}
|
|
81
|
+
let chunks=[],size=0,discard=false;
|
|
82
|
+
function append(part){
|
|
83
|
+
if(discard)return;
|
|
84
|
+
size+=part.length;
|
|
85
|
+
if(size>MAX_LINE){chunks=[];discard=true;send({jsonrpc:'2.0',id:null,error:{code:-32600,message:'Request exceeds 1 MiB'}});}
|
|
86
|
+
else chunks.push(part);
|
|
87
|
+
}
|
|
88
|
+
for await(const raw of process.stdin){
|
|
89
|
+
const buffer=Buffer.isBuffer(raw)?raw:Buffer.from(raw);let start=0;
|
|
90
|
+
for(let i=0;i<buffer.length;i++)if(buffer[i]===10){
|
|
91
|
+
append(buffer.subarray(start,i));
|
|
92
|
+
if(!discard){const line=Buffer.concat(chunks,size).toString('utf8').trim();if(line)receive(line);}
|
|
93
|
+
chunks=[];size=0;discard=false;start=i+1;
|
|
94
|
+
}
|
|
95
|
+
append(buffer.subarray(start));
|
|
96
|
+
}
|
|
97
|
+
if(!discard&&size){const line=Buffer.concat(chunks,size).toString('utf8').trim();if(line)receive(line);}
|
|
98
|
+
await drainPromise;
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import {inflateSync,deflateSync} from 'node:zlib';
|
|
2
|
+
import {readFile,stat} from 'node:fs/promises';
|
|
3
|
+
import {createHash} from 'node:crypto';
|
|
4
|
+
|
|
5
|
+
const signature=Buffer.from([137,80,78,71,13,10,26,10]);
|
|
6
|
+
const MAX_FILE=16_000_000,MAX_PIXELS=12_000_000,MAX_RAW=100_000_000;
|
|
7
|
+
const channels={0:1,2:3,3:1,4:2,6:4};
|
|
8
|
+
const depths={0:[1,2,4,8,16],2:[8,16],3:[1,2,4,8],4:[8,16],6:[8,16]};
|
|
9
|
+
const table=Uint32Array.from({length:256},(_,i)=>{for(let k=0;k<8;k++)i=(i&1)?(0xedb88320^(i>>>1)):i>>>1;return i>>>0;});
|
|
10
|
+
export function crc32(data){let crc=0xffffffff;for(const x of data)crc=(crc>>>8)^table[(crc^x)&255];return (crc^0xffffffff)>>>0;}
|
|
11
|
+
function invalid(message){throw new Error('Invalid PNG: '+message);}
|
|
12
|
+
export function pngChunk(type,data){
|
|
13
|
+
const name=Buffer.from(type,'ascii'),out=Buffer.alloc(12+data.length);
|
|
14
|
+
out.writeUInt32BE(data.length,0);name.copy(out,4);data.copy(out,8);out.writeUInt32BE(crc32(out.subarray(4,8+data.length)),8+data.length);
|
|
15
|
+
return out;
|
|
16
|
+
}
|
|
17
|
+
function passes(width,height,bits,interlace){
|
|
18
|
+
const layouts=interlace?[[0,0,8,8],[4,0,8,8],[0,4,4,8],[2,0,4,4],[0,2,2,4],[1,0,2,2],[0,1,1,2]]:[[0,0,1,1]];
|
|
19
|
+
return layouts.map(([x,y,dx,dy])=>({width:Math.max(0,Math.ceil((width-x)/dx)),height:Math.max(0,Math.ceil((height-y)/dy))})).filter(p=>p.width&&p.height).map(p=>({...p,rowBytes:Math.ceil(p.width*bits/8)}));
|
|
20
|
+
}
|
|
21
|
+
export function parsePng(buffer,{decode=false}={}){
|
|
22
|
+
if(!Buffer.isBuffer(buffer)||buffer.length<45||buffer.length>MAX_FILE||!buffer.subarray(0,8).equals(signature))invalid('signature or file size');
|
|
23
|
+
let pos=8,header,ended=false,seenData=false,dataEnded=false,palette=false,transparency=false,animated=false;const data=[];let count=0;
|
|
24
|
+
while(pos<buffer.length){
|
|
25
|
+
if(++count>20000||pos+12>buffer.length)invalid('chunk bounds');
|
|
26
|
+
const len=buffer.readUInt32BE(pos),type=buffer.toString('ascii',pos+4,pos+8),end=pos+12+len;
|
|
27
|
+
if(!/^[A-Za-z]{4}$/.test(type)||end>buffer.length||len>MAX_FILE)invalid('chunk length or name');
|
|
28
|
+
if(crc32(buffer.subarray(pos+4,end-4))!==buffer.readUInt32BE(end-4))invalid('CRC mismatch in '+type);
|
|
29
|
+
const bytes=buffer.subarray(pos+8,end-4);
|
|
30
|
+
if(!header&&type!=='IHDR')invalid('IHDR must be first');
|
|
31
|
+
if(type==='IHDR'){
|
|
32
|
+
if(header||len!==13)invalid('duplicate or malformed IHDR');
|
|
33
|
+
const width=bytes.readUInt32BE(0),height=bytes.readUInt32BE(4),depth=bytes[8],colorType=bytes[9],interlace=bytes[12];
|
|
34
|
+
if(!width||!height||width*height>MAX_PIXELS||!depths[colorType]?.includes(depth)||bytes[10]!==0||bytes[11]!==0||![0,1].includes(interlace))invalid('unsupported header or dimensions');
|
|
35
|
+
header={width,height,depth,colorType,interlace};
|
|
36
|
+
}else if(type==='PLTE'){
|
|
37
|
+
if(palette||seenData||!len||len%3||len>768||[0,4].includes(header.colorType)||(header.colorType===3&&len/3>2**header.depth))invalid('palette');
|
|
38
|
+
palette=true;
|
|
39
|
+
}else if(type==='tRNS'){transparency=true;
|
|
40
|
+
}else if(type==='acTL'){animated=true;
|
|
41
|
+
}else if(type==='IDAT'){
|
|
42
|
+
if(dataEnded||(header.colorType===3&&!palette))invalid('IDAT ordering or missing palette');
|
|
43
|
+
seenData=true;data.push(bytes);
|
|
44
|
+
}else if(type==='IEND'){
|
|
45
|
+
if(len!==0||!seenData||end!==buffer.length)invalid('IEND or trailing data');
|
|
46
|
+
ended=true;break;
|
|
47
|
+
}else if(type[0]===type[0].toUpperCase())invalid('unknown critical chunk '+type);
|
|
48
|
+
if(seenData&&type!=='IDAT')dataEnded=true;
|
|
49
|
+
pos=end;
|
|
50
|
+
}
|
|
51
|
+
if(!ended)invalid('missing IEND');
|
|
52
|
+
const {width,height,depth,colorType,interlace}=header,bits=depth*channels[colorType];
|
|
53
|
+
const layout=passes(width,height,bits,interlace);
|
|
54
|
+
const expected=layout.reduce((sum,p)=>sum+(p.rowBytes+1)*p.height,0);
|
|
55
|
+
if(expected>MAX_RAW)invalid('decoded size exceeds limit');
|
|
56
|
+
let raw;try{raw=inflateSync(Buffer.concat(data),{maxOutputLength:expected});}catch{invalid('compressed image data');}
|
|
57
|
+
if(raw.length!==expected)invalid('decoded scanline size');
|
|
58
|
+
let offset=0;for(const p of layout)for(let y=0;y<p.height;y++){if(raw[offset]>4)invalid('scanline filter');offset+=p.rowBytes+1;}
|
|
59
|
+
if(!decode)return header;
|
|
60
|
+
if(transparency||animated)throw new Error('Pixel comparison does not yet support color-key/palette transparency or animated PNGs.');
|
|
61
|
+
if(interlace||depth!==8||![0,2,4,6].includes(colorType))throw new Error('Pixel comparison supports non-interlaced 8-bit grayscale, RGB and RGBA PNGs (palette PNGs are not supported).');
|
|
62
|
+
const bpp=channels[colorType],stride=width*bpp,pixels=Buffer.alloc(width*height*4),prior=Buffer.alloc(stride),row=Buffer.alloc(stride);
|
|
63
|
+
function paeth(a,b,c){const p=a+b-c,pa=Math.abs(p-a),pb=Math.abs(p-b),pc=Math.abs(p-c);return pa<=pb&&pa<=pc?a:pb<=pc?b:c;}
|
|
64
|
+
offset=0;
|
|
65
|
+
for(let y=0;y<height;y++){
|
|
66
|
+
const filter=raw[offset++];
|
|
67
|
+
for(let x=0;x<stride;x++){
|
|
68
|
+
const a=x>=bpp?row[x-bpp]:0,b=prior[x],c=x>=bpp?prior[x-bpp]:0;
|
|
69
|
+
const prediction=filter===0?0:filter===1?a:filter===2?b:filter===3?Math.floor((a+b)/2):paeth(a,b,c);
|
|
70
|
+
row[x]=(raw[offset++]+prediction)&255;
|
|
71
|
+
}
|
|
72
|
+
for(let x=0;x<width;x++){
|
|
73
|
+
const i=x*bpp,o=(y*width+x)*4;
|
|
74
|
+
if(colorType===0||colorType===4){pixels[o]=pixels[o+1]=pixels[o+2]=row[i];pixels[o+3]=colorType===4?row[i+1]:255;}
|
|
75
|
+
else{pixels[o]=row[i];pixels[o+1]=row[i+1];pixels[o+2]=row[i+2];pixels[o+3]=colorType===6?row[i+3]:255;}
|
|
76
|
+
}
|
|
77
|
+
row.copy(prior);
|
|
78
|
+
}
|
|
79
|
+
return {...header,pixels};
|
|
80
|
+
}
|
|
81
|
+
export function encodeRgba(width,height,pixels){
|
|
82
|
+
if(!Number.isInteger(width)||!Number.isInteger(height)||width<1||height<1||width*height>MAX_PIXELS||pixels.length!==width*height*4)throw new Error('Invalid RGBA image dimensions');
|
|
83
|
+
const header=Buffer.alloc(13);header.writeUInt32BE(width,0);header.writeUInt32BE(height,4);header[8]=8;header[9]=6;
|
|
84
|
+
const raw=Buffer.alloc((width*4+1)*height);
|
|
85
|
+
for(let y=0;y<height;y++)pixels.copy(raw,y*(width*4+1)+1,y*width*4,(y+1)*width*4);
|
|
86
|
+
return Buffer.concat([signature,pngChunk('IHDR',header),pngChunk('IDAT',deflateSync(raw)),pngChunk('IEND',Buffer.alloc(0))]);
|
|
87
|
+
}
|
|
88
|
+
export async function readPng(file){const info=await stat(file);if(!info.isFile()||info.size>MAX_FILE)throw new Error('Expected a PNG file up to 16 MB.');return readFile(file);}
|
|
89
|
+
export function inspectPng(buffer){const image=parsePng(buffer);return {...image,bytes:buffer.length,sha256:createHash('sha256').update(buffer).digest('hex')};}
|
|
90
|
+
export function comparePng(before,after,{threshold=0,makeDiff=false}={}){
|
|
91
|
+
if(!Number.isInteger(threshold)||threshold<0||threshold>255)throw new Error('threshold must be an integer between 0 and 255.');
|
|
92
|
+
const a=parsePng(before,{decode:true}),b=parsePng(after,{decode:true});
|
|
93
|
+
if(a.width!==b.width||a.height!==b.height)throw new Error('Screenshot dimensions differ; compare the same viewport and pixel ratio.');
|
|
94
|
+
// Composite both images on white: invisible transparent pixels are not changes.
|
|
95
|
+
const composite=(v,alpha)=>Math.round((v*alpha+255*(255-alpha))/255);
|
|
96
|
+
const total=a.width*a.height;let changed=0,maxDifference=0,sum=0;let minX=a.width,minY=a.height,maxX=-1,maxY=-1;
|
|
97
|
+
const diff=makeDiff?Buffer.alloc(total*4):null;
|
|
98
|
+
for(let i=0;i<total;i++){
|
|
99
|
+
const j=i*4;let d=0;
|
|
100
|
+
for(let c=0;c<3;c++){const delta=Math.abs(composite(a.pixels[j+c],a.pixels[j+3])-composite(b.pixels[j+c],b.pixels[j+3]));d=Math.max(d,delta);sum+=delta;}
|
|
101
|
+
maxDifference=Math.max(maxDifference,d);
|
|
102
|
+
if(d>threshold){changed++;const x=i%a.width,y=Math.floor(i/a.width);minX=Math.min(minX,x);minY=Math.min(minY,y);maxX=Math.max(maxX,x);maxY=Math.max(maxY,y);}
|
|
103
|
+
if(diff){const gray=Math.round((composite(b.pixels[j],b.pixels[j+3])+composite(b.pixels[j+1],b.pixels[j+3])+composite(b.pixels[j+2],b.pixels[j+3]))/3*.5+127);diff[j]=d>threshold?255:gray;diff[j+1]=d>threshold?40:gray;diff[j+2]=d>threshold?80:gray;diff[j+3]=255;}
|
|
104
|
+
}
|
|
105
|
+
return {width:a.width,height:a.height,threshold,changedPixels:changed,totalPixels:total,changedPercent:changed/total*100,maxDifference,meanAbsoluteChannelDifference:sum/(total*3),bounds:changed?{x:minX,y:minY,width:maxX-minX+1,height:maxY-minY+1}:null,background:'white',...(diff?{image:encodeRgba(a.width,a.height,diff)}:{})};
|
|
106
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import {realpath,stat,mkdtemp,writeFile,readFile,rm} from 'node:fs/promises';
|
|
4
|
+
import {resolveInside,normalizeViewport,run,checkPng} from './core.mjs';
|
|
5
|
+
|
|
6
|
+
export function swiftHarness(viewport,theme='light'){
|
|
7
|
+
return [
|
|
8
|
+
'import SwiftUI',
|
|
9
|
+
'import AppKit',
|
|
10
|
+
'import Foundation',
|
|
11
|
+
'enum LensFailure: Error { case imageUnavailable, invalidArguments }',
|
|
12
|
+
'@main struct FlutterLensCapture {',
|
|
13
|
+
' @MainActor static func main() throws {',
|
|
14
|
+
' guard CommandLine.arguments.count == 2 else { throw LensFailure.invalidArguments }',
|
|
15
|
+
' let view = buildPreview()',
|
|
16
|
+
' .frame(width: '+viewport.width+', height: '+viewport.height+')',
|
|
17
|
+
' .environment(\\.colorScheme, .'+theme+')',
|
|
18
|
+
' let renderer = ImageRenderer(content: view)',
|
|
19
|
+
' renderer.proposedSize = ProposedViewSize(width: '+viewport.width+', height: '+viewport.height+')',
|
|
20
|
+
' renderer.scale = '+viewport.pixelRatio,
|
|
21
|
+
' guard let cg = renderer.cgImage,',
|
|
22
|
+
' let png = NSBitmapImageRep(cgImage: cg).representation(using: .png, properties: [:])',
|
|
23
|
+
' else { throw LensFailure.imageUnavailable }',
|
|
24
|
+
' try png.write(to: URL(fileURLWithPath: CommandLine.arguments[1]), options: .atomic)',
|
|
25
|
+
' }',
|
|
26
|
+
'}'
|
|
27
|
+
].join('\n');
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export async function renderSwiftUI(input,{runner=run,platform=process.platform,arch=process.arch}={}){
|
|
31
|
+
if(input.trusted!==true)throw new Error('Rendering executes project code. Explicit trusted: true is required.');
|
|
32
|
+
if(platform!=='darwin')throw new Error('Experimental SwiftUI rendering requires macOS 13+ and Xcode command-line tools.');
|
|
33
|
+
if(!['arm64','x64'].includes(arch))throw new Error('Unsupported macOS architecture.');
|
|
34
|
+
if(input.file!==undefined||input.widget!==undefined||input.fontFile!==undefined||input.settleMs!==undefined)throw new Error('SwiftUI requires a fixture exporting buildPreview(); Flutter-only options are not supported.');
|
|
35
|
+
const root=await realpath(input.root??process.cwd());
|
|
36
|
+
if(!(await stat(root)).isDirectory())throw new Error('Expected a project directory.');
|
|
37
|
+
const viewport=normalizeViewport(input),theme=input.theme??'light';
|
|
38
|
+
if(!['light','dark'].includes(theme))throw new Error('Invalid theme.');
|
|
39
|
+
if(!Number.isInteger(viewport.width*viewport.pixelRatio)||!Number.isInteger(viewport.height*viewport.pixelRatio))throw new Error('SwiftUI requires integral pixel dimensions.');
|
|
40
|
+
const additional=input.sources??[];
|
|
41
|
+
if(!Array.isArray(additional)||additional.length>16)throw new Error('sources must be an array with at most 16 Swift file paths.');
|
|
42
|
+
const sources=[];
|
|
43
|
+
for(const relative of [input.fixture,...additional]){
|
|
44
|
+
const file=await resolveInside(root,relative);
|
|
45
|
+
const info=await stat(file);
|
|
46
|
+
if(!file.endsWith('.swift')||!info.isFile()||info.size>2_000_000)throw new Error('Expected a Swift source file no larger than 2 MB.');
|
|
47
|
+
if(!sources.includes(file))sources.push(file);
|
|
48
|
+
}
|
|
49
|
+
const tmp=await mkdtemp(path.join(os.tmpdir(),'lens-swiftui-'));
|
|
50
|
+
try{
|
|
51
|
+
const harness=path.join(tmp,'LensCapture.swift'),binary=path.join(tmp,'capture'),png=path.join(tmp,'capture.png');
|
|
52
|
+
await writeFile(harness,swiftHarness(viewport,theme),{flag:'wx'});
|
|
53
|
+
const target=(arch==='arm64'?'arm64':'x86_64')+'-apple-macosx13.0';
|
|
54
|
+
await runner('xcrun',['swiftc','-parse-as-library','-target',target,...sources,harness,'-o',binary],{cwd:root,timeout:120000});
|
|
55
|
+
await runner(binary,[png],{cwd:root,timeout:60000});
|
|
56
|
+
if((await stat(png)).size>16000000)throw new Error('PNG exceeds 16 MB.');
|
|
57
|
+
const image=await readFile(png),dimensions=checkPng(image);
|
|
58
|
+
if(dimensions.width!==viewport.width*viewport.pixelRatio||dimensions.height!==viewport.height*viewport.pixelRatio)throw new Error('Unexpected SwiftUI capture dimensions.');
|
|
59
|
+
return {framework:'swiftui',image,mimeType:'image/png',dimensions,viewport,warnings:['Experimental SwiftUI backend; standalone macOS fixture passed CI, visual review pending.','macOS SwiftUI rendering, not iOS simulation or native iPhone fidelity.','Requires standalone SwiftUI-compatible source; iOS-only APIs, app dependencies and UIKit are not supported.']};
|
|
60
|
+
}finally{await rm(tmp,{recursive:true,force:true});}
|
|
61
|
+
}
|
|
62
|
+
export const swiftuiAdapter={id:'swiftui',discover:async()=>{throw new Error('SwiftUI discovery is not implemented; provide an explicit Swift fixture exporting buildPreview().');},render:renderSwiftUI};
|
package/src/core.mjs
ADDED
package/src/flutter.mjs
ADDED
package/src/index.mjs
ADDED