Repository navigation
feat(fbuild): first-class data/ asset pipeline (#2284) - #2335
Conversation
📝 WalkthroughWalkthroughAdds a v1 sketch-local asset pipeline: a Python scanner parses Changes
Sequence Diagram(s)sequenceDiagram
participant Build as Build System
participant Scanner as Python Scanner
participant Data as Sketch data/
participant Manifest as Generated Manifest
participant CppReg as C++ Registration
Build->>Scanner: scan_sketch_assets(sketch_dir)
Scanner->>Data: list & read *.lnk
Data-->>Scanner: file contents
Scanner->>Scanner: parse URL, sha256, fallback
Scanner-->>Manifest: assemble manifest entries
Scanner-->>Build: AssetScanResult (manifest + warnings)
Build->>Manifest: write_manifest_json(), manifest_to_js_bootstrap(), manifest_to_cpp_header()
Manifest-->>CppReg: generated C++ registration code
sequenceDiagram
participant Sketch as Sketch Code
participant AssetRef as fl::asset_ref
participant Resolver as fl::resolve_asset
participant Registry as In-memory Registry
participant Filesys as Host/Stub Filesystem
participant Result as fl::url
Sketch->>AssetRef: FL_ASSET("data/track.mp3")
Sketch->>Resolver: resolve_asset(assetRef)
Resolver->>Registry: lookup(path)
alt Found in Registry
Registry-->>Result: return registered URL
else Not found
Resolver->>Filesys: check <cwd>/path (file)
alt File exists
Filesys-->>Result: return file URL
else Try <cwd>/path.lnk
Filesys-->>Resolver: .lnk content
Resolver-->>Result: parsed primary URL
else
Resolver-->>Result: invalid URL
end
end
Result-->>Sketch: fl::url
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related issues
Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 6
🧹 Nitpick comments (5)
ci/wasm_build.py (1)
1469-1469: Move the new scanner import to the module import block.This new local import should live with the other top-level local imports unless there is a deliberate lazy-import requirement.
Proposed cleanup
from ci.wasm_flags import get_link_flags, get_sketch_compile_flags from ci.wasm_tools import run_emcc +from ci.compiler.asset_scanner import scan_sketch_assets, write_manifest_json- from ci.compiler.asset_scanner import scan_sketch_assets, write_manifest_json - sketch_dir = PROJECT_ROOT / "examples" / example_nameAs per coding guidelines, “All system imports must be at the top of the file in proper order: standard library, third-party, local”.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@ci/wasm_build.py` at line 1469, The import "from ci.compiler.asset_scanner import scan_sketch_assets, write_manifest_json" is a local/module-level import that was added mid-file; move it into the file's top import block alongside other local imports (following standard library then third-party ordering) so it's a top-level import rather than a late/local one; verify there is no deliberate lazy-import dependency in functions referencing scan_sketch_assets or write_manifest_json before making the change.src/platforms/wasm/compiler/index.ts (1)
82-110: Useasync/awaitfor the manifest loader.The new loader uses a
.then()chain; please keep this path consistent with the project’s async style.Proposed rewrite
-(function loadFastledAssetManifest() { +(async function loadFastledAssetManifest() { // Idempotent: don't clobber a manifest that was injected earlier (e.g., by // server-side rendering or a test harness). if ((window as any).fastledAssetManifest) { console.log('🎛️ fastledAssetManifest already present, skipping fetch'); return; } - fetch('asset_manifest.json', { cache: 'no-cache' }) - .then((response) => { - if (!response.ok) { - // 404 is expected for sketches without a data/ dir; log at info level. - console.log(`🎛️ asset_manifest.json not present (${response.status}); continuing without manifest`); - (window as any).fastledAssetManifest = {}; - return null; - } - return response.json(); - }) - .then((manifest) => { - if (manifest) { - (window as any).fastledAssetManifest = manifest; - const count = Object.keys(manifest).length; - console.log(`🎛️ Loaded fastledAssetManifest with ${count} entries`); - } - }) - .catch((err) => { - console.warn('🎛️ asset_manifest.json fetch failed:', err); - (window as any).fastledAssetManifest = {}; - }); + try { + const response = await fetch('asset_manifest.json', { cache: 'no-cache' }); + if (!response.ok) { + // 404 is expected for sketches without a data/ dir; log at info level. + console.log(`🎛️ asset_manifest.json not present (${response.status}); continuing without manifest`); + (window as any).fastledAssetManifest = {}; + return; + } + + const manifest = await response.json(); + (window as any).fastledAssetManifest = manifest; + const count = Object.keys(manifest).length; + console.log(`🎛️ Loaded fastledAssetManifest with ${count} entries`); + } catch (err) { + console.warn('🎛️ asset_manifest.json fetch failed:', err); + (window as any).fastledAssetManifest = {}; + } })();As per coding guidelines, “Always use async/await for promises instead of .then() chains”.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/platforms/wasm/compiler/index.ts` around lines 82 - 110, Rewrite the immediately-invoked loadFastledAssetManifest function to use async/await: keep the idempotent check on (window as any).fastledAssetManifest and early return, then perform an await fetch('asset_manifest.json', { cache: 'no-cache' }) inside a try/catch, check response.ok and if false log the same info message and assign (window as any).fastledAssetManifest = {} and return, otherwise await response.json(), assign it to (window as any).fastledAssetManifest, compute Object.keys(manifest).length and log the loaded count; in the catch block log the warning and set fastledAssetManifest = {} — preserving all original messages and behavior but using async/await.tests/fl/asset.cpp (2)
71-114: Registry state persists between test cases — consider resetting.
fl::register_assetpushes into a process-global staticfl::vectorwith no cleanup hook. It happens to not collide with the subsequent tests today because the registered key (pipeline/a.mp3) is unique, andlookup_registryreturns on first match — but any future test that registers an overlapping key, or re-runs the same case, will accumulate entries and silently mask regressions (especially given the "first writer wins" lookup behavior — see the companion comment onsrc/fl/asset.cpp.hpp).If you want to keep the API registry-only, adding a
fl::clear_registered_assets()(or per-test RAII helper) and calling it in a fixture SetUp would make these tests hermetic.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@tests/fl/asset.cpp` around lines 71 - 114, The test suite mutates a process-global registry via fl::register_asset which persists across tests; add a function fl::clear_registered_assets() (or similar) in the asset registry implementation and call it from the test fixture SetUp/tearDown (or call it at top of each test before registering) to reset state; alternatively provide an RAII helper (e.g., RegisteredAssetsGuard) that calls fl::clear_registered_assets() in its destructor and use it in tests that call fl::register_asset to ensure lookup_registry behavior is hermetic between test cases.
88-108: Host-fallback tests depend on on-disk fixtures and working directory.Both
tests/fl/data/test_audio.oggandexamples/AudioUrl/data/track.mp3.lnkmust exist at exactly those repo-relative paths, and the test process CWD must be the project root. Nothing in the test asserts or sets that up, so a future move of either fixture (or running under a different CWD — e.g. a sub-test-binary from a build dir) will convert "unknown asset" into a silent false negative rather than a helpful failure.Consider either (a) asserting file existence at the top of each test with a clear message, or (b) constructing the fixtures in a
TemporaryDirectoryandchdir-ing for the duration of the test. The second option also makes the.lnkfallback assertion independent ofexamples/.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@tests/fl/asset.cpp` around lines 88 - 108, The tests "fl::resolve_asset - host fallback finds local file" and "fl::resolve_asset - host fallback finds sibling .lnk" depend on repo-relative fixtures and CWD; make them robust by either asserting the fixture files exist up-front or creating temporary fixtures and switching CWD for the test. Update the FL_TEST_CASEs that call fl::resolve_asset with asset_ref r to first check std::filesystem::exists("tests/fl/data/test_audio.ogg") and exists("examples/AudioUrl/data/track.mp3.lnk") (or create equivalent temp files and a .lnk content) and fail the test with a clear message if missing, or instead create the files in a TemporaryDirectory, chdir into it for the duration of the test, then call fl::resolve_asset and restore CWD; reference the test names and the fl::resolve_asset/asset_ref usage to locate where to add these setup/assertions.src/fl/stl/url.h (1)
274-377: DRY: line-splitting/trim logic is duplicated betweenparse_lnkandparse_lnk_with_metadata.The CRLF handling and whitespace trim loop (lines 282-299 vs 335-349) are identical. Since
parse_lnk_with_metadatais strictly a superset, consider makingparse_lnka one-liner wrapper:♻️ Proposed refactor
inline url parse_lnk(fl::string_view content) FL_NOEXCEPT { - fl::size pos = 0; - while (pos < content.size()) { - // … ~35 lines of line splitting / trimming / comment handling … - return url(line); - } - return url(); + return parse_lnk_with_metadata(content).primary; }Functionally equivalent, and keeps both parsers in lock-step going forward. Defer if you're wary of touching the existing hot path in v1.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/fl/stl/url.h` around lines 274 - 377, The parsing/trimming logic is duplicated between parse_lnk and parse_lnk_with_metadata; remove the duplication by making parse_lnk delegate to parse_lnk_with_metadata (call parse_lnk_with_metadata(content) and return its primary as a url) or by extracting the common line-splitting/trim routine into a helper used by both; update parse_lnk to be a simple one-liner that returns the primary URL from LnkMetadata (use LnkMetadata::primary and parse_lnk_with_metadata) so both stay in sync.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@ci/compiler/asset_scanner.py`:
- Around line 167-178: The try block around lnk_path.read_text(encoding="utf-8")
must handle KeyboardInterrupt before the other except clauses; add an except
KeyboardInterrupt as exc: that re-raises the exception (or simply "raise")
placed immediately before the UnicodeDecodeError and OSError handlers so
KeyboardInterrupt propagates instead of being caught and converted into a
warning appended to result.warnings.
- Around line 43-78: Add runtime type validation by decorating both dataclasses
AssetEntry and AssetScanResult with `@typechecked` (ensure the typechecked
decorator is imported), and replace the dict comprehension inside
AssetScanResult.to_json_dict with an explicit loop that constructs the result
dict (iterate over self.manifest items, call asdict(entry) for each, assign into
result mapping, then return result) to satisfy the "no comprehension" guideline.
In `@src/fl/asset.cpp.hpp`:
- Around line 50-61: lookup_registry currently returns the first matching entry
which makes registration behave as "first-writer-wins" despite the comment
claiming "last writer wins"; change lookup_registry to iterate the registry in
reverse (from r.size()-1 down to 0) so the most recently registered entry wins,
and audit/update any other similar lookups (the other loop mentioned around the
same area) to the same reverse-iteration pattern; also ensure the comment in
asset.h describing "Last writer wins" matches this behavior.
- Around line 92-110: The read result from fl::ifstream lnk is not validated:
after calling lnk.read(&content[0], sz) you must call lnk.gcount() (or check
lnk.good()/!lnk.fail()) and resize content to the actual bytes read or bail out
on failure; update the code around fl::ifstream lnk, the lnk.read(...) call, and
the subsequent return parse_lnk(...) so that you use the gcount result to set
content.size() (or return fl::url() on read failure) before passing the buffer
to parse_lnk.
In `@src/fl/asset.h`:
- Around line 173-174: The comment on register_asset promises "Last writer wins"
but asset_detail::lookup_registry currently returns the first match; change
lookup_registry to search newest-first (e.g., reverse-iterate the registry or
use rbegin/rend) so it returns the most recently registered asset and therefore
matches the register_asset doc, and ensure any test or call-sites expecting
lookup_registry (symbol: asset_detail::lookup_registry) still behave correctly
after reversing the iteration order.
In `@src/fl/stl/url.h`:
- Around line 361-374: The parser currently assigns key/value from the split
without trimming, causing mismatches versus the Python parser; modify the
parsing block so you trim whitespace from both fl::string_view key and value
(e.g., compute trimmed_key and trimmed_value from the existing key/value), then
use trimmed_key for the comparisons and trimmed_value when setting out.sha256
(constructing fl::string from trimmed_value) and out.fallback (constructing url
from trimmed_value); ensure unknown keys are still ignored.
---
Nitpick comments:
In `@ci/wasm_build.py`:
- Line 1469: The import "from ci.compiler.asset_scanner import
scan_sketch_assets, write_manifest_json" is a local/module-level import that was
added mid-file; move it into the file's top import block alongside other local
imports (following standard library then third-party ordering) so it's a
top-level import rather than a late/local one; verify there is no deliberate
lazy-import dependency in functions referencing scan_sketch_assets or
write_manifest_json before making the change.
In `@src/fl/stl/url.h`:
- Around line 274-377: The parsing/trimming logic is duplicated between
parse_lnk and parse_lnk_with_metadata; remove the duplication by making
parse_lnk delegate to parse_lnk_with_metadata (call
parse_lnk_with_metadata(content) and return its primary as a url) or by
extracting the common line-splitting/trim routine into a helper used by both;
update parse_lnk to be a simple one-liner that returns the primary URL from
LnkMetadata (use LnkMetadata::primary and parse_lnk_with_metadata) so both stay
in sync.
In `@src/platforms/wasm/compiler/index.ts`:
- Around line 82-110: Rewrite the immediately-invoked loadFastledAssetManifest
function to use async/await: keep the idempotent check on (window as
any).fastledAssetManifest and early return, then perform an await
fetch('asset_manifest.json', { cache: 'no-cache' }) inside a try/catch, check
response.ok and if false log the same info message and assign (window as
any).fastledAssetManifest = {} and return, otherwise await response.json(),
assign it to (window as any).fastledAssetManifest, compute
Object.keys(manifest).length and log the loaded count; in the catch block log
the warning and set fastledAssetManifest = {} — preserving all original messages
and behavior but using async/await.
In `@tests/fl/asset.cpp`:
- Around line 71-114: The test suite mutates a process-global registry via
fl::register_asset which persists across tests; add a function
fl::clear_registered_assets() (or similar) in the asset registry implementation
and call it from the test fixture SetUp/tearDown (or call it at top of each test
before registering) to reset state; alternatively provide an RAII helper (e.g.,
RegisteredAssetsGuard) that calls fl::clear_registered_assets() in its
destructor and use it in tests that call fl::register_asset to ensure
lookup_registry behavior is hermetic between test cases.
- Around line 88-108: The tests "fl::resolve_asset - host fallback finds local
file" and "fl::resolve_asset - host fallback finds sibling .lnk" depend on
repo-relative fixtures and CWD; make them robust by either asserting the fixture
files exist up-front or creating temporary fixtures and switching CWD for the
test. Update the FL_TEST_CASEs that call fl::resolve_asset with asset_ref r to
first check std::filesystem::exists("tests/fl/data/test_audio.ogg") and
exists("examples/AudioUrl/data/track.mp3.lnk") (or create equivalent temp files
and a .lnk content) and fail the test with a clear message if missing, or
instead create the files in a TemporaryDirectory, chdir into it for the duration
of the test, then call fl::resolve_asset and restore CWD; reference the test
names and the fl::resolve_asset/asset_ref usage to locate where to add these
setup/assertions.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: dd2949b9-a965-4987-8968-4e782bf7ba14
📒 Files selected for processing (14)
ci/compiler/asset_scanner.pyci/tests/test_asset_scanner.pyci/wasm_build.pyexamples/AudioUrl/AudioUrl.inosrc/fl/_build.cpp.hppsrc/fl/asset.cpp.hppsrc/fl/asset.hsrc/fl/build/fl.cppsrc/fl/stl/url.hsrc/fl/ui.cpp.hppsrc/fl/ui.hsrc/platforms/wasm/compiler/index.tstests/fl/asset.cpptests/fl/stl/url.cpp
| @dataclass | ||
| class AssetEntry: | ||
| """Resolved metadata for a single ``*.lnk`` file. | ||
|
|
||
| Attributes: | ||
| url: Primary URL from the first non-comment line of the ``.lnk``. | ||
| sha256: Optional hex digest declared in the ``.lnk`` (``sha256=...``). | ||
| v1 runtime ignores this; parser captures it for forward-compat. | ||
| fallback: Optional mirror URL declared in the ``.lnk`` (``fallback=...``). | ||
| v1 runtime ignores this; parser captures it for forward-compat. | ||
| """ | ||
|
|
||
| url: str | ||
| sha256: str | None = None | ||
| fallback: str | None = None | ||
|
|
||
|
|
||
| @dataclass | ||
| class AssetScanResult: | ||
| """Result of scanning a sketch's ``data/`` directory. | ||
|
|
||
| Attributes: | ||
| manifest: Dict mapping relative asset paths (POSIX form, e.g. | ||
| ``"data/track.mp3"``) to ``AssetEntry``. Missing ``data/`` or an | ||
| empty one yields an empty dict — not an error. | ||
| warnings: Non-fatal issues encountered during scanning (malformed | ||
| ``.lnk`` files, unreadable files, etc.). Callers should log them | ||
| but the build should NOT fail on these. | ||
| """ | ||
|
|
||
| manifest: dict[str, AssetEntry] = field(default_factory=dict) | ||
| warnings: list[str] = field(default_factory=list) | ||
|
|
||
| def to_json_dict(self) -> dict[str, dict[str, str | None]]: | ||
| """Return manifest as a plain nested dict for JSON serialization.""" | ||
| return {key: asdict(entry) for key, entry in self.manifest.items()} |
There was a problem hiding this comment.
Guideline violations: missing @typechecked and dict comprehension.
Two repo coding-guideline items apply here:
- Both
AssetEntry(line 43) andAssetScanResult(line 60) are@dataclassbut lack@typechecked. Guideline: "Use@typecheckeddecorator with@dataclassfor runtime type validation." to_json_dict(line 78) uses a dict comprehension. Guideline: "Use explicit loops instead of list comprehensions for code clarity and debuggability."
🔧 Proposed fix
import json
from dataclasses import asdict, dataclass, field
from pathlib import Path
+
+from typeguard import typechecked
-@dataclass
+@typechecked
+@dataclass
class AssetEntry:
…
-@dataclass
+@typechecked
+@dataclass
class AssetScanResult:
…
def to_json_dict(self) -> dict[str, dict[str, str | None]]:
"""Return manifest as a plain nested dict for JSON serialization."""
- return {key: asdict(entry) for key, entry in self.manifest.items()}
+ out: dict[str, dict[str, str | None]] = {}
+ for key, entry in self.manifest.items():
+ out[key] = asdict(entry)
+ return outAs per coding guidelines: "Use @typechecked decorator with @dataclass for runtime type validation" and "Use explicit loops instead of list comprehensions for code clarity and debuggability."
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| @dataclass | |
| class AssetEntry: | |
| """Resolved metadata for a single ``*.lnk`` file. | |
| Attributes: | |
| url: Primary URL from the first non-comment line of the ``.lnk``. | |
| sha256: Optional hex digest declared in the ``.lnk`` (``sha256=...``). | |
| v1 runtime ignores this; parser captures it for forward-compat. | |
| fallback: Optional mirror URL declared in the ``.lnk`` (``fallback=...``). | |
| v1 runtime ignores this; parser captures it for forward-compat. | |
| """ | |
| url: str | |
| sha256: str | None = None | |
| fallback: str | None = None | |
| @dataclass | |
| class AssetScanResult: | |
| """Result of scanning a sketch's ``data/`` directory. | |
| Attributes: | |
| manifest: Dict mapping relative asset paths (POSIX form, e.g. | |
| ``"data/track.mp3"``) to ``AssetEntry``. Missing ``data/`` or an | |
| empty one yields an empty dict — not an error. | |
| warnings: Non-fatal issues encountered during scanning (malformed | |
| ``.lnk`` files, unreadable files, etc.). Callers should log them | |
| but the build should NOT fail on these. | |
| """ | |
| manifest: dict[str, AssetEntry] = field(default_factory=dict) | |
| warnings: list[str] = field(default_factory=list) | |
| def to_json_dict(self) -> dict[str, dict[str, str | None]]: | |
| """Return manifest as a plain nested dict for JSON serialization.""" | |
| return {key: asdict(entry) for key, entry in self.manifest.items()} | |
| `@typechecked` | |
| `@dataclass` | |
| class AssetEntry: | |
| """Resolved metadata for a single ``*.lnk`` file. | |
| Attributes: | |
| url: Primary URL from the first non-comment line of the ``.lnk``. | |
| sha256: Optional hex digest declared in the ``.lnk`` (``sha256=...``). | |
| v1 runtime ignores this; parser captures it for forward-compat. | |
| fallback: Optional mirror URL declared in the ``.lnk`` (``fallback=...``). | |
| v1 runtime ignores this; parser captures it for forward-compat. | |
| """ | |
| url: str | |
| sha256: str | None = None | |
| fallback: str | None = None | |
| `@typechecked` | |
| `@dataclass` | |
| class AssetScanResult: | |
| """Result of scanning a sketch's ``data/`` directory. | |
| Attributes: | |
| manifest: Dict mapping relative asset paths (POSIX form, e.g. | |
| ``"data/track.mp3"``) to ``AssetEntry``. Missing ``data/`` or an | |
| empty one yields an empty dict — not an error. | |
| warnings: Non-fatal issues encountered during scanning (malformed | |
| ``.lnk`` files, unreadable files, etc.). Callers should log them | |
| but the build should NOT fail on these. | |
| """ | |
| manifest: dict[str, AssetEntry] = field(default_factory=dict) | |
| warnings: list[str] = field(default_factory=list) | |
| def to_json_dict(self) -> dict[str, dict[str, str | None]]: | |
| """Return manifest as a plain nested dict for JSON serialization.""" | |
| out: dict[str, dict[str, str | None]] = {} | |
| for key, entry in self.manifest.items(): | |
| out[key] = asdict(entry) | |
| return out |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@ci/compiler/asset_scanner.py` around lines 43 - 78, Add runtime type
validation by decorating both dataclasses AssetEntry and AssetScanResult with
`@typechecked` (ensure the typechecked decorator is imported), and replace the
dict comprehension inside AssetScanResult.to_json_dict with an explicit loop
that constructs the result dict (iterate over self.manifest items, call
asdict(entry) for each, assign into result mapping, then return result) to
satisfy the "no comprehension" guideline.
| try: | ||
| content = lnk_path.read_text(encoding="utf-8") | ||
| except UnicodeDecodeError as exc: | ||
| result.warnings.append( | ||
| f"asset-scan: {lnk_path}: not valid UTF-8 ({exc}); skipped" | ||
| ) | ||
| continue | ||
| except OSError as exc: | ||
| result.warnings.append( | ||
| f"asset-scan: {lnk_path}: read failed ({exc}); skipped" | ||
| ) | ||
| continue |
There was a problem hiding this comment.
try block is missing KeyboardInterrupt handling.
Repo guideline: "All Python try-catch blocks must handle KeyboardInterrupt before other exceptions." This block only catches UnicodeDecodeError and OSError. In practice read_text rarely raises KeyboardInterrupt, but the rule is absolute and static checkers/linters may flag this.
🔧 Proposed fix
try:
content = lnk_path.read_text(encoding="utf-8")
+ except KeyboardInterrupt:
+ raise
except UnicodeDecodeError as exc:
result.warnings.append(
f"asset-scan: {lnk_path}: not valid UTF-8 ({exc}); skipped"
)
continue
except OSError as exc:
result.warnings.append(
f"asset-scan: {lnk_path}: read failed ({exc}); skipped"
)
continueAs per coding guidelines: "All Python try-catch blocks must handle KeyboardInterrupt before other exceptions."
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| try: | |
| content = lnk_path.read_text(encoding="utf-8") | |
| except UnicodeDecodeError as exc: | |
| result.warnings.append( | |
| f"asset-scan: {lnk_path}: not valid UTF-8 ({exc}); skipped" | |
| ) | |
| continue | |
| except OSError as exc: | |
| result.warnings.append( | |
| f"asset-scan: {lnk_path}: read failed ({exc}); skipped" | |
| ) | |
| continue | |
| try: | |
| content = lnk_path.read_text(encoding="utf-8") | |
| except KeyboardInterrupt: | |
| raise | |
| except UnicodeDecodeError as exc: | |
| result.warnings.append( | |
| f"asset-scan: {lnk_path}: not valid UTF-8 ({exc}); skipped" | |
| ) | |
| continue | |
| except OSError as exc: | |
| result.warnings.append( | |
| f"asset-scan: {lnk_path}: read failed ({exc}); skipped" | |
| ) | |
| continue |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@ci/compiler/asset_scanner.py` around lines 167 - 178, The try block around
lnk_path.read_text(encoding="utf-8") must handle KeyboardInterrupt before the
other except clauses; add an except KeyboardInterrupt as exc: that re-raises the
exception (or simply "raise") placed immediately before the UnicodeDecodeError
and OSError handlers so KeyboardInterrupt propagates instead of being caught and
converted into a warning appended to result.warnings.
| inline fl::url lookup_registry(fl::string_view path) FL_NOEXCEPT { | ||
| auto& r = registry(); | ||
| for (fl::size i = 0; i < r.size(); ++i) { | ||
| // Compare as string_view on both sides to avoid any ambiguity in the | ||
| // fl::string / fl::string_view overload resolution. | ||
| fl::string_view candidate(r[i].path.c_str(), r[i].path.size()); | ||
| if (candidate == path) { | ||
| return r[i].url; | ||
| } | ||
| } | ||
| return fl::url(); | ||
| } |
There was a problem hiding this comment.
"Last writer wins" is documented, but implementation is first-writer-wins.
asset.h line 173 states: "Last writer wins for duplicate paths (scan then manually plug in tests)." — but register_asset only appends, and lookup_registry returns on the first matching entry. So if the generated manifest registers "data/foo.mp3" and a test later registers an override for the same path, the override is silently ignored — the opposite of what the doc promises.
Either fix the loop to walk in reverse (cheap), or dedupe on insert:
🔧 Proposed fix — reverse-iterate on lookup
- for (fl::size i = 0; i < r.size(); ++i) {
- // Compare as string_view on both sides to avoid any ambiguity in the
- // fl::string / fl::string_view overload resolution.
- fl::string_view candidate(r[i].path.c_str(), r[i].path.size());
+ for (fl::size i = r.size(); i > 0; --i) {
+ // Walk newest-first so a later register_asset() overrides an earlier
+ // one — matches the "last writer wins" contract documented in asset.h.
+ fl::string_view candidate(r[i - 1].path.c_str(), r[i - 1].path.size());
if (candidate == path) {
- return r[i].url;
+ return r[i - 1].url;
}
}Either way, the behavior and the comment in asset.h should agree.
Also applies to: 118-121
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/fl/asset.cpp.hpp` around lines 50 - 61, lookup_registry currently returns
the first matching entry which makes registration behave as "first-writer-wins"
despite the comment claiming "last writer wins"; change lookup_registry to
iterate the registry in reverse (from r.size()-1 down to 0) so the most recently
registered entry wins, and audit/update any other similar lookups (the other
loop mentioned around the same area) to the same reverse-iteration pattern; also
ensure the comment in asset.h describing "Last writer wins" matches this
behavior.
| fl::ifstream lnk(lnkPath.c_str(), fl::ios::in | fl::ios::binary); | ||
| if (!lnk.is_open()) { | ||
| return fl::url(); | ||
| } | ||
| // Read entire file. .lnk files are expected to be tiny (URL + a few | ||
| // metadata lines); cap the read at 8 KiB to avoid pathological inputs. | ||
| constexpr fl::size kMaxLnkBytes = 8 * 1024; | ||
| fl::size sz = lnk.size(); | ||
| if (sz > kMaxLnkBytes) { | ||
| sz = kMaxLnkBytes; | ||
| } | ||
| fl::string content; | ||
| content.resize(sz); | ||
| if (sz > 0) { | ||
| lnk.read(&content[0], sz); | ||
| } | ||
| lnk.close(); | ||
| return parse_lnk(fl::string_view(content.data(), content.size())); | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Check what fl::ifstream exposes (gcount, size, etc.) in the repo.
fd -e h -e hpp -e cpp 'fstream' src/fl/stl
rg -nP -C2 '\bgcount\b|\bifstream\b' src/fl/stlRepository: FastLED/FastLED
Length of output: 7365
🏁 Script executed:
# Find and examine the asset.cpp.hpp file around lines 92-110
fd -name "asset.cpp.hpp" src/flRepository: FastLED/FastLED
Length of output: 289
🏁 Script executed:
# Get the exact code snippet from asset.cpp.hpp
cat -n src/fl/asset.cpp.hpp | sed -n '85,115p'Repository: FastLED/FastLED
Length of output: 1142
🏁 Script executed:
# Check if fl::ifstream has a size() method
rg -n '\bsize\(' src/fl/stl/fstream.hRepository: FastLED/FastLED
Length of output: 267
Use gcount() after read() to verify the actual bytes read.
The code calls lnk.read(&content[0], sz) without verifying that sz bytes were actually read. If the read operation fails or returns fewer bytes (due to truncation, I/O error, or CRLF translation quirks in fl::ifstream::size()), the buffer will still have length sz with indeterminate trailing bytes, which parse_lnk() will then process as valid data.
Since fl::ifstream exposes gcount(), call it after read() to get the actual byte count and resize content accordingly. Alternatively, check lnk.good() or !lnk.fail() after the read and return fl::url() on failure.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/fl/asset.cpp.hpp` around lines 92 - 110, The read result from
fl::ifstream lnk is not validated: after calling lnk.read(&content[0], sz) you
must call lnk.gcount() (or check lnk.good()/!lnk.fail()) and resize content to
the actual bytes read or bail out on failure; update the code around
fl::ifstream lnk, the lnk.read(...) call, and the subsequent return
parse_lnk(...) so that you use the gcount result to set content.size() (or
return fl::url() on read failure) before passing the buffer to parse_lnk.
| /// Last writer wins for duplicate paths (scan then manually plug in tests). | ||
| void register_asset(fl::string_view path, const fl::url& u) FL_NOEXCEPT; |
There was a problem hiding this comment.
Doc contradicts implementation — fix alongside the registry-lookup change.
This comment says "Last writer wins for duplicate paths" but asset_detail::lookup_registry in src/fl/asset.cpp.hpp returns the first match, so it's actually first-writer-wins. Please resolve this together with the lookup-direction fix suggested on src/fl/asset.cpp.hpp lines 50-61 — either adjust the lookup to iterate newest-first (matching this doc) or weaken this comment to match the current behavior.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/fl/asset.h` around lines 173 - 174, The comment on register_asset
promises "Last writer wins" but asset_detail::lookup_registry currently returns
the first match; change lookup_registry to search newest-first (e.g.,
reverse-iterate the registry or use rbegin/rend) so it returns the most recently
registered asset and therefore matches the register_asset doc, and ensure any
test or call-sites expecting lookup_registry (symbol:
asset_detail::lookup_registry) still behave correctly after reversing the
iteration order.
| // Subsequent lines: look for "key=value" metadata. | ||
| fl::size eq = line.find('='); | ||
| if (eq == fl::string_view::npos) { | ||
| // Unknown non-kv line, ignore (forward-compat). | ||
| continue; | ||
| } | ||
| fl::string_view key = line.substr(0, eq); | ||
| fl::string_view value = line.substr(eq + 1); | ||
| if (key == "sha256") { | ||
| out.sha256 = fl::string(value.data(), value.size()); | ||
| } else if (key == "fallback") { | ||
| out.fallback = url(value); | ||
| } | ||
| // else: unknown key, ignore. |
There was a problem hiding this comment.
Trim mismatch between C++ and Python .lnk parsers.
ci/compiler/asset_scanner.py strips whitespace from both key and value (key = key.strip(); value = value.strip()), but this C++ path does neither. A .lnk containing sha256 = deadbeef will register sha256="deadbeef" on the Python/manifest side and sha256="" on the C++ host-fallback side — unknown key, then never recorded because " sha256 " != "sha256". v1 runtime ignores these fields so this isn't user-visible today, but when integrity/fallback enforcement lands in v2 the two paths will disagree.
🔧 Suggested fix — trim key and value symmetrically
fl::size eq = line.find('=');
if (eq == fl::string_view::npos) {
// Unknown non-kv line, ignore (forward-compat).
continue;
}
fl::string_view key = line.substr(0, eq);
fl::string_view value = line.substr(eq + 1);
+ // Match the Python scanner which strips key/value whitespace.
+ while (!key.empty() && (key[0] == ' ' || key[0] == '\t')) key = key.substr(1);
+ while (!key.empty() && (key[key.size()-1] == ' ' || key[key.size()-1] == '\t')) key = key.substr(0, key.size()-1);
+ while (!value.empty() && (value[0] == ' ' || value[0] == '\t')) value = value.substr(1);
+ while (!value.empty() && (value[value.size()-1] == ' ' || value[value.size()-1] == '\t')) value = value.substr(0, value.size()-1);
if (key == "sha256") {
out.sha256 = fl::string(value.data(), value.size());
} else if (key == "fallback") {
out.fallback = url(value);
}Adding a test case with sha256 = abc / fallback = https://... around spaces in both tests/fl/stl/url.cpp and ci/tests/test_asset_scanner.py would lock the contract down.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| // Subsequent lines: look for "key=value" metadata. | |
| fl::size eq = line.find('='); | |
| if (eq == fl::string_view::npos) { | |
| // Unknown non-kv line, ignore (forward-compat). | |
| continue; | |
| } | |
| fl::string_view key = line.substr(0, eq); | |
| fl::string_view value = line.substr(eq + 1); | |
| if (key == "sha256") { | |
| out.sha256 = fl::string(value.data(), value.size()); | |
| } else if (key == "fallback") { | |
| out.fallback = url(value); | |
| } | |
| // else: unknown key, ignore. | |
| // Subsequent lines: look for "key=value" metadata. | |
| fl::size eq = line.find('='); | |
| if (eq == fl::string_view::npos) { | |
| // Unknown non-kv line, ignore (forward-compat). | |
| continue; | |
| } | |
| fl::string_view key = line.substr(0, eq); | |
| fl::string_view value = line.substr(eq + 1); | |
| // Match the Python scanner which strips key/value whitespace. | |
| while (!key.empty() && (key[0] == ' ' || key[0] == '\t')) key = key.substr(1); | |
| while (!key.empty() && (key[key.size()-1] == ' ' || key[key.size()-1] == '\t')) key = key.substr(0, key.size()-1); | |
| while (!value.empty() && (value[0] == ' ' || value[0] == '\t')) value = value.substr(1); | |
| while (!value.empty() && (value[value.size()-1] == ' ' || value[value.size()-1] == '\t')) value = value.substr(0, value.size()-1); | |
| if (key == "sha256") { | |
| out.sha256 = fl::string(value.data(), value.size()); | |
| } else if (key == "fallback") { | |
| out.fallback = url(value); | |
| } | |
| // else: unknown key, ignore. |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/fl/stl/url.h` around lines 361 - 374, The parser currently assigns
key/value from the split without trimming, causing mismatches versus the Python
parser; modify the parsing block so you trim whitespace from both
fl::string_view key and value (e.g., compute trimmed_key and trimmed_value from
the existing key/value), then use trimmed_key for the comparisons and
trimmed_value when setting out.sha256 (constructing fl::string from
trimmed_value) and out.fallback (constructing url from trimmed_value); ensure
unknown keys are still ignored.
… path The esbuild alias `three=./vendor/three/three.module.js` and the direct relative imports in app.ts and fastled_background_worker.ts (both of which use `./vendor/three/build/three.module.js`) both pointed at paths that were never populated — the original vendor commit 7d5bb4e committed only `vendor/three/examples/jsm/` and missed the runtime module. Every WASM CI build has been failing at the esbuild step with "Could not resolve ./vendor/three/three.module.js". Fixes by: - Committing three.module.js (three.js v0.170.0, MIT) under vendor/three/build/, matching the actual import paths. - Adding an unignore rule so vendor/three/build/ isn't swept by the project-wide build/ ignore (follows the existing precedent for !src/fl/build/). - Updating the esbuild alias to the same path so bare `three` imports from examples/jsm files resolve to the identical module instance as the direct relative imports (no double-bundle). - Vendoring LICENSE alongside for attribution. Verified locally: bash compile wasm --examples AudioUrl now produces fastled.js + fastled.wasm + index.html (previously the final esbuild step failed, leaving those artifacts missing and breaking the "Check for required artifacts" step in build.yml). Unblocks CI for #2331, #2332, #2335, and every future PR. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Every WASM CI build was failing at the esbuild bundling step with "Could not resolve ./vendor/three/three.module.js (originally three)" because the path the existing alias in ci/esbuild_frontend.py has always pointed at was never populated. The original vendor commit 7d5bb4e committed only vendor/three/examples/jsm/ and missed the runtime module. The project's security-safe CI workflow copies only src/, examples/, and a handful of root manifests from PR head into the trusted tree — it does not copy ci/ or .gitignore, which means a fix that lives only under ci/ cannot unblock PRs at all. Fix, entirely under src/: - Vendor three.js v0.170.0 (MIT) at src/platforms/wasm/compiler/vendor/three/three.module.js — exactly the path the existing esbuild alias already points to, so bare `from 'three'` imports in examples/jsm/* resolve cleanly. - Retarget the three direct-relative imports (app.ts, fastled_background_worker.ts, scene.js) from ./vendor/three/build/three.module.js → ./vendor/three/three.module.js so every consumer resolves to the same on-disk file, which also means esbuild bundles three.js exactly once (no double-bundle, no instanceof surprises across worker/main bundles). - Ship three.js LICENSE alongside for MIT attribution. No ci/ changes, no .gitignore changes — the fix is self-contained in src/ and will survive the workflow's safe-file merge. Verified locally: bash compile wasm --examples AudioUrl now emits fastled.js, fastled.wasm, and index.html. Previously failed with esbuild exit 1, leaving those artifacts missing and breaking the "Check for required artifacts" step in build.yml. Unblocks #2331, #2335, and master CI. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
📊 Header Compilation PerformanceTotal Time: 785.47ms Top 5 Slowest Headers
Warnings
Full Report |
Adds the v1 asset pipeline so sketches can write
`fl::UIAudio audio("Audio", FL_ASSET("data/track.mp3"))` and have the
path resolved to a URL on WASM (via a build-time manifest) or to a local
file/URL on host/stub.
- `src/fl/asset.h` — `fl::asset_ref` handle, `FL_ASSET()` macro with
compile-time rejection of `..` paths via `static_assert`.
- `src/fl/asset.cpp.hpp` — runtime resolver: registry-first, then on
host/stub probe filesystem then sibling `*.lnk` as a fallback.
- `src/fl/stl/url.h` — add `parse_lnk_with_metadata()` returning URL +
optional `sha256=` / `fallback=` metadata (v1: parsed but not
enforced; reserved for future integrity/fallback features).
- `src/fl/ui.h` + `src/fl/ui.cpp.hpp` — new
`UIAudio(name, fl::asset_ref)` overload that resolves then forwards
to the existing url ctor.
- `ci/compiler/asset_scanner.py` — new fbuild-side scanner that walks
`<sketch>/data/` for `*.lnk` files and emits a JSON manifest +
`window.fastledAssetManifest` JS snippet + C++ header of
`fl::register_asset` calls.
- `ci/wasm_build.py` — emit `asset_manifest.json` alongside fastled.js.
- `src/platforms/wasm/compiler/index.ts` — fetch and inject
`window.fastledAssetManifest` at startup.
- Tests: `tests/fl/asset.cpp` covers compile-time `..` rejection,
runtime resolution, host filesystem probe, and sibling-`.lnk`
fallback. `tests/fl/stl/url.cpp` adds `parse_lnk_with_metadata()`
cases. `ci/tests/test_asset_scanner.py` covers the Python scanner.
- Example: keep the inline-`fl::url` path in
`examples/AudioUrl/AudioUrl.ino` (regression coverage) and document
the new `FL_ASSET()` variant in a commented-out line alongside. The
sketch's existing `data/track.mp3.lnk` stays in place.
v1 scope per issue #2284: WASM + host/stub only. ESP32 LittleFS is
tracked as future work (TODO comment in asset.cpp.hpp).
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
7191a2c to
ec35801
Compare
There was a problem hiding this comment.
Actionable comments posted: 3
♻️ Duplicate comments (4)
src/fl/asset.cpp.hpp (2)
50-57:⚠️ Potential issue | 🟡 MinorMake duplicate registration actually last-writer-wins.
register_asset()appends mappings, butlookup_registry()returns the first match. That contradicts thesrc/fl/asset.hline 173 contract and prevents tests/host code from overriding generated entries.Proposed lookup-order fix
inline fl::url lookup_registry(fl::string_view path) FL_NOEXCEPT { auto& r = registry(); - for (fl::size i = 0; i < r.size(); ++i) { + for (fl::size i = r.size(); i > 0; --i) { + const fl::size idx = i - 1; // Compare as string_view on both sides to avoid any ambiguity in the // fl::string / fl::string_view overload resolution. - fl::string_view candidate(r[i].path.c_str(), r[i].path.size()); + fl::string_view candidate(r[idx].path.c_str(), r[idx].path.size()); if (candidate == path) { - return r[i].url; + return r[idx].url; } } return fl::url(); }Also applies to: 118-121
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/fl/asset.cpp.hpp` around lines 50 - 57, lookup_registry currently scans the registry vector forward and returns the first matching entry, which makes earlier registrations win; to implement last-writer-wins (matching register_asset which appends), change lookup_registry to iterate the registry from back to front (e.g., for i = r.size(); i-- > 0) and return the first match found when scanning backwards; apply the same change to any other lookup overloads (the other occurrence around the second lookup block) so that newly appended mappings override earlier ones while preserving the existing fl::string_view comparison logic.
103-109:⚠️ Potential issue | 🟡 MinorValidate how many bytes were read before parsing
.lnk.
lnk.read(&content[0], sz)can read fewer bytes than requested; parsing the pre-sized buffer can then consume stale/trailing bytes. Checkgcount()or fail closed before callingparse_lnk().Proposed read validation
fl::string content; content.resize(sz); + fl::size bytes_read = 0; if (sz > 0) { lnk.read(&content[0], sz); + bytes_read = static_cast<fl::size>(lnk.gcount()); } lnk.close(); + if (bytes_read != sz) { + return fl::url(); + } + content.resize(bytes_read); return parse_lnk(fl::string_view(content.data(), content.size())); }Verify the local stream API shape before patching:
#!/bin/bash # Description: Confirm fl::ifstream exposes read-count/error APIs used for safe partial-read handling. # Expect: fl::ifstream has read(...) plus gcount() or equivalent post-read status APIs. rg -n -C3 '\bclass\s+ifstream\b|\bgcount\s*\(|\bread\s*\(|\bsize\s*\(' src/fl/stl🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/fl/asset.cpp.hpp` around lines 103 - 109, The code pre-sizes fl::string content and calls lnk.read(&content[0], sz) then parses the entire buffer with parse_lnk, but lnk.read may return fewer bytes than requested; update the read path to check the actual number of bytes read (e.g. via lnk.gcount() or the stream's equivalent) and resize/truncate content to that count or fail closed before calling parse_lnk; specifically modify the block that uses fl::string content, lnk.read(...), and the subsequent lnk.close()/return parse_lnk(...) so that parse_lnk receives only the bytes actually read (or an error is returned) rather than any leftover uninitialized/stale bytes.ci/compiler/asset_scanner.py (2)
33-78:⚠️ Potential issue | 🟡 MinorAdd
@typecheckedand avoid the dict comprehension.Both dataclasses are missing runtime type validation, and
to_json_dict()uses a comprehension where the repo asks for explicit loops.Proposed guideline fix
import json from dataclasses import asdict, dataclass, field from pathlib import Path + +from typeguard import typechecked @@ -@dataclass +@typechecked +@dataclass class AssetEntry: @@ -@dataclass +@typechecked +@dataclass class AssetScanResult: @@ def to_json_dict(self) -> dict[str, dict[str, str | None]]: """Return manifest as a plain nested dict for JSON serialization.""" - return {key: asdict(entry) for key, entry in self.manifest.items()} + result: dict[str, dict[str, str | None]] = {} + for key, entry in self.manifest.items(): + result[key] = asdict(entry) + return resultAs per coding guidelines: "Use
@typecheckeddecorator with@dataclassfor runtime type validation" and "Use explicit loops instead of list comprehensions for code clarity and debuggability."🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@ci/compiler/asset_scanner.py` around lines 33 - 78, Add runtime type validation by decorating both dataclasses AssetEntry and AssetScanResult with `@typechecked` (import the decorator from the appropriate typeguard/typechecking library) and update AssetScanResult.to_json_dict to avoid a dict comprehension: create an empty result dict, iterate over self.manifest.items() with an explicit for loop, convert each AssetEntry to a plain dict using asdict and assign into the result, then return it; keep the existing return type annotation dict[str, dict[str, str | None]] and preserve all field names (manifest, warnings).
167-178:⚠️ Potential issue | 🟡 MinorHandle
KeyboardInterruptbefore other exceptions.The repo guideline requires every Python try-catch block to include
KeyboardInterrupthandling first.Proposed guideline fix
try: content = lnk_path.read_text(encoding="utf-8") + except KeyboardInterrupt: + raise except UnicodeDecodeError as exc: result.warnings.append( f"asset-scan: {lnk_path}: not valid UTF-8 ({exc}); skipped"As per coding guidelines: "All Python try-catch blocks must handle KeyboardInterrupt before other exceptions."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@ci/compiler/asset_scanner.py` around lines 167 - 178, The try/except around lnk_path.read_text must handle KeyboardInterrupt first: add an except KeyboardInterrupt that re-raises the interrupt before the existing except UnicodeDecodeError and except OSError handlers so that lnk_path.read_text(...) doesn’t swallow Ctrl-C; update the block that appends to result.warnings (the handlers that reference result.warnings.append and the lnk_path variable) to come after the KeyboardInterrupt case.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@ci/compiler/asset_scanner.py`:
- Around line 216-217: The JSON payload produced by
json.dumps(scan.to_json_dict(), sort_keys=True) can contain the string
"</script>" which will terminate a surrounding <script> tag; after creating
payload (the variable named payload) replace occurrences of "</" with "<\/" (or
the equivalent safe escape such as "\u003c/") to neutralize script-closing
sequences, then return the bootstrapping string using that escaped payload
(update the line that builds and returns f"window.fastledAssetManifest =
{payload};\n" to use the escaped payload).
- Around line 116-122: The parser currently strips key and value after
partitioning which accepts entries like "sha256 = ..." that the C++ parser
ignores; to match C++ `src/fl/stl/url.h` behavior, strip the entire line first
(e.g., call line.strip() before partition) and then partition without stripping
key/value so keys must match exactly "sha256" or "fallback"; update the block
around the partition (variables key, value, sha256, fallback) to perform line =
line.strip() then key, _, value = line.partition("=") and remove the subsequent
key/value .strip() calls.
In `@src/fl/asset.h`:
- Around line 83-130: Make the unchecked constructor asset_ref(const char*,
fl::size) non-public (e.g., move it to private) so callers cannot bypass path
validation, and add/keep a single validated factory (the constexpr asset(const
char*) function) as the only public way to create asset_ref; inside that factory
ensure you first reject nullptr (if path == nullptr return empty asset_ref) and
only then call asset_detail::path_has_parent_segment(path) and
asset_detail::clen(path) to construct the private asset_ref; update any other
creation site (the other public overload referenced around lines 136-143) to use
this validated factory so resolve_asset() cannot receive unchecked paths.
---
Duplicate comments:
In `@ci/compiler/asset_scanner.py`:
- Around line 33-78: Add runtime type validation by decorating both dataclasses
AssetEntry and AssetScanResult with `@typechecked` (import the decorator from the
appropriate typeguard/typechecking library) and update
AssetScanResult.to_json_dict to avoid a dict comprehension: create an empty
result dict, iterate over self.manifest.items() with an explicit for loop,
convert each AssetEntry to a plain dict using asdict and assign into the result,
then return it; keep the existing return type annotation dict[str, dict[str, str
| None]] and preserve all field names (manifest, warnings).
- Around line 167-178: The try/except around lnk_path.read_text must handle
KeyboardInterrupt first: add an except KeyboardInterrupt that re-raises the
interrupt before the existing except UnicodeDecodeError and except OSError
handlers so that lnk_path.read_text(...) doesn’t swallow Ctrl-C; update the
block that appends to result.warnings (the handlers that reference
result.warnings.append and the lnk_path variable) to come after the
KeyboardInterrupt case.
In `@src/fl/asset.cpp.hpp`:
- Around line 50-57: lookup_registry currently scans the registry vector forward
and returns the first matching entry, which makes earlier registrations win; to
implement last-writer-wins (matching register_asset which appends), change
lookup_registry to iterate the registry from back to front (e.g., for i =
r.size(); i-- > 0) and return the first match found when scanning backwards;
apply the same change to any other lookup overloads (the other occurrence around
the second lookup block) so that newly appended mappings override earlier ones
while preserving the existing fl::string_view comparison logic.
- Around line 103-109: The code pre-sizes fl::string content and calls
lnk.read(&content[0], sz) then parses the entire buffer with parse_lnk, but
lnk.read may return fewer bytes than requested; update the read path to check
the actual number of bytes read (e.g. via lnk.gcount() or the stream's
equivalent) and resize/truncate content to that count or fail closed before
calling parse_lnk; specifically modify the block that uses fl::string content,
lnk.read(...), and the subsequent lnk.close()/return parse_lnk(...) so that
parse_lnk receives only the bytes actually read (or an error is returned) rather
than any leftover uninitialized/stale bytes.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 8f12f245-50f4-417d-8e19-39c00106d352
📒 Files selected for processing (14)
ci/compiler/asset_scanner.pyci/tests/test_asset_scanner.pyci/wasm_build.pyexamples/AudioUrl/AudioUrl.inosrc/fl/_build.cpp.hppsrc/fl/asset.cpp.hppsrc/fl/asset.hsrc/fl/build/fl.cppsrc/fl/stl/url.hsrc/fl/ui.cpp.hppsrc/fl/ui.hsrc/platforms/wasm/compiler/index.tstests/fl/asset.cpptests/fl/stl/url.cpp
✅ Files skipped from review due to trivial changes (4)
- src/fl/build/fl.cpp
- src/fl/_build.cpp.hpp
- examples/AudioUrl/AudioUrl.ino
- tests/fl/asset.cpp
🚧 Files skipped from review as they are similar to previous changes (7)
- src/fl/ui.cpp.hpp
- tests/fl/stl/url.cpp
- src/fl/stl/url.h
- src/fl/ui.h
- ci/tests/test_asset_scanner.py
- src/platforms/wasm/compiler/index.ts
- ci/wasm_build.py
| key, _, value = line.partition("=") | ||
| key = key.strip() | ||
| value = value.strip() | ||
| if key == "sha256": | ||
| sha256 = value | ||
| elif key == "fallback": | ||
| fallback = value |
There was a problem hiding this comment.
Keep Python .lnk metadata parsing aligned with C++.
src/fl/stl/url.h lines 325-377 trims the full line but does not trim key/value after partition("="). This scanner accepts sha256 = ... and fallback = ... entries that C++ ignores, despite the docstring saying it mirrors the C++ parser.
Proposed parity fix
key, _, value = line.partition("=")
- key = key.strip()
- value = value.strip()
if key == "sha256":
sha256 = value
elif key == "fallback":
fallback = value🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@ci/compiler/asset_scanner.py` around lines 116 - 122, The parser currently
strips key and value after partitioning which accepts entries like "sha256 =
..." that the C++ parser ignores; to match C++ `src/fl/stl/url.h` behavior,
strip the entire line first (e.g., call line.strip() before partition) and then
partition without stripping key/value so keys must match exactly "sha256" or
"fallback"; update the block around the partition (variables key, value, sha256,
fallback) to perform line = line.strip() then key, _, value =
line.partition("=") and remove the subsequent key/value .strip() calls.
| payload = json.dumps(scan.to_json_dict(), sort_keys=True) | ||
| return f"window.fastledAssetManifest = {payload};\n" |
There was a problem hiding this comment.
Escape script-closing sequences in the JS bootstrap payload.
The doc says callers splice this into a <script> tag. A .lnk URL containing </script> can terminate that tag even inside a JSON string, so escape </ after json.dumps().
Proposed script-safe escaping
def manifest_to_js_bootstrap(scan: AssetScanResult) -> str:
@@
- payload = json.dumps(scan.to_json_dict(), sort_keys=True)
+ payload = json.dumps(scan.to_json_dict(), sort_keys=True)
+ payload = payload.replace("</", "<\\/")
return f"window.fastledAssetManifest = {payload};\n"📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| payload = json.dumps(scan.to_json_dict(), sort_keys=True) | |
| return f"window.fastledAssetManifest = {payload};\n" | |
| payload = json.dumps(scan.to_json_dict(), sort_keys=True) | |
| payload = payload.replace("</", "<\\/") | |
| return f"window.fastledAssetManifest = {payload};\n" |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@ci/compiler/asset_scanner.py` around lines 216 - 217, The JSON payload
produced by json.dumps(scan.to_json_dict(), sort_keys=True) can contain the
string "</script>" which will terminate a surrounding <script> tag; after
creating payload (the variable named payload) replace occurrences of "</" with
"<\/" (or the equivalent safe escape such as "\u003c/") to neutralize
script-closing sequences, then return the bootstrapping string using that
escaped payload (update the line that builds and returns
f"window.fastledAssetManifest = {payload};\n" to use the escaped payload).
| class asset_ref { | ||
| public: | ||
| /// Construct from a pointer to a null-terminated string with known length. | ||
| /// The pointer MUST outlive the `asset_ref` — typically a string literal. | ||
| constexpr asset_ref(const char* path, fl::size length) FL_NOEXCEPT | ||
| : mPath(path), mLength(length) {} | ||
|
|
||
| /// Default-constructed handle refers to no asset. | ||
| constexpr asset_ref() FL_NOEXCEPT : mPath(nullptr), mLength(0) {} | ||
|
|
||
| /// Copy/move: trivial — pointer + length. Can't combine `constexpr` with | ||
| /// `= default` on the assignment operator pre-C++14, so we leave these as | ||
| /// the implicitly-declared operations (the class is trivially copyable). | ||
| asset_ref(const asset_ref&) FL_NOEXCEPT = default; | ||
| asset_ref& operator=(const asset_ref&) FL_NOEXCEPT = default; | ||
|
|
||
| /// True if this handle refers to an asset path. | ||
| constexpr explicit operator bool() const FL_NOEXCEPT { | ||
| return mPath != nullptr && mLength > 0; | ||
| } | ||
|
|
||
| /// The relative asset path as a string view (e.g. "data/track.mp3"). | ||
| fl::string_view path() const FL_NOEXCEPT { | ||
| return fl::string_view(mPath, mLength); | ||
| } | ||
|
|
||
| /// Pointer accessor — useful for JSON serialization. | ||
| constexpr const char* c_str() const FL_NOEXCEPT { return mPath; } | ||
| constexpr fl::size size() const FL_NOEXCEPT { return mLength; } | ||
|
|
||
| private: | ||
| const char* mPath; | ||
| fl::size mLength; | ||
| }; | ||
|
|
||
| /// Construct an asset handle from a relative sketch path at runtime. | ||
| /// | ||
| /// For **compile-time rejection** of `..` paths, use the `FL_ASSET()` macro | ||
| /// instead — it wraps this function with a `static_assert`. | ||
| /// | ||
| /// This overload accepts any `const char*` (including runtime-computed | ||
| /// pointers) and, for safety, returns an empty handle if the path contains | ||
| /// a `..` segment. Runtime resolution also refuses to walk past `data/`, so | ||
| /// this is defense-in-depth rather than the primary gate. | ||
| constexpr asset_ref asset(const char* path) FL_NOEXCEPT { | ||
| return asset_detail::path_has_parent_segment(path) | ||
| ? asset_ref() | ||
| : asset_ref(path, asset_detail::clen(path)); |
There was a problem hiding this comment.
Close the unchecked construction path and reject null input.
asset_ref(const char*, size) is public, so callers can bypass the .. validation with fl::asset_ref("../x", 4) and resolve_asset() will later use that path. Also, fl::asset(nullptr) reaches clen(nullptr) because path_has_parent_segment(nullptr) returns false.
Proposed validation-boundary fix
class asset_ref {
public:
- /// Construct from a pointer to a null-terminated string with known length.
- /// The pointer MUST outlive the `asset_ref` — typically a string literal.
- constexpr asset_ref(const char* path, fl::size length) FL_NOEXCEPT
- : mPath(path), mLength(length) {}
-
/// Default-constructed handle refers to no asset.
constexpr asset_ref() FL_NOEXCEPT : mPath(nullptr), mLength(0) {}
@@
private:
+ friend constexpr asset_ref asset(const char* path) FL_NOEXCEPT;
+
+ /// Construct from a validated pointer to a null-terminated string with known length.
+ constexpr asset_ref(const char* path, fl::size length) FL_NOEXCEPT
+ : mPath(path), mLength(length) {}
+
const char* mPath;
fl::size mLength;
};
@@
constexpr asset_ref asset(const char* path) FL_NOEXCEPT {
- return asset_detail::path_has_parent_segment(path)
+ return (path == nullptr || asset_detail::path_has_parent_segment(path))
? asset_ref()
: asset_ref(path, asset_detail::clen(path));
}
@@
static_assert( \
!::fl::asset_detail::path_has_parent_segment(LITERAL_PATH), \
"fl::asset path must not contain '..' segments"); \
- return ::fl::asset_ref( \
- (LITERAL_PATH), ::fl::asset_detail::clen(LITERAL_PATH)); \
+ return ::fl::asset(LITERAL_PATH); \
}())Also applies to: 136-143
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/fl/asset.h` around lines 83 - 130, Make the unchecked constructor
asset_ref(const char*, fl::size) non-public (e.g., move it to private) so
callers cannot bypass path validation, and add/keep a single validated factory
(the constexpr asset(const char*) function) as the only public way to create
asset_ref; inside that factory ensure you first reject nullptr (if path ==
nullptr return empty asset_ref) and only then call
asset_detail::path_has_parent_segment(path) and asset_detail::clen(path) to
construct the private asset_ref; update any other creation site (the other
public overload referenced around lines 136-143) to use this validated factory
so resolve_asset() cannot receive unchecked paths.
📊 Header Compilation PerformanceTotal Time: 1183.38ms Top 5 Slowest Headers
Warnings
Full Report |
Summary
v1 of the
data/asset pipeline from issue #2284. Sketches can now writefl::UIAudio audio("Audio", FL_ASSET("data/track.mp3"));and the pathresolves to a URL on WASM (via a build-time manifest) or to a local
file / sibling
.lnkURL on host/stub.v1 scope (per issue #2284):
.lnkformat:*.mp3.lnk— first non-blank line is the URL; subsequentkey=valuelines are metadata.sha256=/fallback=metadata is parsed but not enforced (reservedfor future integrity/retry features).
..path segments are rejected at compile time viastatic_asserton
FL_ASSET("..."). The constexprfl::asset(const char*)overloadreturns an empty handle for such inputs as defense-in-depth.
What's in the box
src/fl/asset.h—fl::asset_ref(trivially-copyable handle:const char*+fl::size),FL_ASSET()macro with compile-time..rejection,fl::resolve_asset()declaration,fl::register_asset().src/fl/asset.cpp.hpp— runtime resolver: process-local registry first,then (on host/stub only) local file probe + sibling
*.lnkfallback.src/fl/stl/url.h— newparse_lnk_with_metadata()returningLnkMetadata { primary, sha256, fallback }. Existingparse_lnk()unchanged — just reused.
src/fl/ui.h+src/fl/ui.cpp.hpp— newUIAudio(name, asset_ref)constructor that resolves to a
fl::urlthen forwards to the existingurl-based ctor. The existing url-based constructor is untouched.
ci/compiler/asset_scanner.py— walks<sketch>/data/for*.lnkfiles, emits a
{relative_path: {url, sha256, fallback}}manifest(JSON), a
window.fastledAssetManifest = {...}JS snippet, and a C++header of
fl::register_asset()calls for the generated C++ build.ci/wasm_build.py—generate_asset_manifest()writesasset_manifest.jsonalongsidefastled.jsat build time.src/platforms/wasm/compiler/index.ts— fetch and injectwindow.fastledAssetManifestat startup (idempotent, non-fatal on 404).tests/fl/asset.cpp— compile-time..rejection (static_assertmatrix), runtime resolution, host filesystem probe, sibling-
.lnkfallback.
tests/fl/stl/url.cpp—parse_lnk_with_metadatametadata cases.ci/tests/test_asset_scanner.py— 12 Python unit tests coveringparsing, scanning, JSON serialization, JS snippet, and C++ header
emission.
examples/AudioUrl/AudioUrl.ino— the existing inline-fl::urlvariant is KEPT (regression coverage). The
FL_ASSET(...)variant isdocumented in an adjacent commented-out line. The pre-existing
examples/AudioUrl/data/track.mp3.lnkstays in place.Decisions made during implementation
asset_refcopy semantics: trivially copyable — just aconst char*fl::size. No ownership. The scoping report didn't nail this down;this matches how
fl::string_viewis treated and letsFL_ASSET()produce a
constexpr-like handle.a generated C++ header full of
fl::register_asset(path, url)callsthat the link step compiles into the sketch. That keeps
fl::resolve_asset()fully C++-side — no EM_ASM to cross into JS.window.fastledAssetManifestis still injected for pure-JS consumersso both sides see the same source of truth.
fl::urlwrapping the filesystem path (fl::urlaccepts arbitrarystrings). If it doesn't, we read the sibling
<path>.lnk.parse_lnk()signature is preserved; the newmetadata-returning version is additive.
Test plan
bash test fl_asset— passes (8 cases incl. static_asserts).bash test fl_asset --debug— passes with ASAN/UBSAN.bash test url— passes (existing + new metadata cases).bash test audio_url— passes (existing url-based path).bash test audio/bash test ui— pass.uv run python -m pytest ci/tests/test_asset_scanner.py— 12/12 pass.bash lint— clean.bash compile wasm --examples AudioUrl— C++ side builds fine; theesbuild template step fails on a pre-existing
vendor/three/three.module.jsmissing-file bug, which is orthogonalto this PR.
🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Documentation
Tests