Repository navigation
Arena/6362b41e affinescript - #865
Conversation
…scriptDom.affine)
Item (4) of the userscript brief, in the only form that fits the target: the
ESM runtime (packages/affine-js) cannot be bundled to an IIFE (import.meta,
dynamic import("node:fs/promises"), import("node:url")), so the reconciler is
authored in AffineScript and compiled into the same single file.
- UserscriptDom: Attr/Spec/Element/Group over opaque Node handles; create,
patch (attribute add *and* remove, text only when changed), set_text_of,
unmount, group/reconcile/unmount_all, member_count. A reconciler, not a vdom
diff: an Element remembers its state, which is what makes in-place patching
possible without get_attribute or a recursive vnode type.
- lib/codegen_userscript.ml: lower the `len` typechecker builtin to .length.
It has no extern declaration to be lowered through, so without this any
reachable `len` emitted a call to an undefined global.
- docs: the guide now points at UserscriptDom as the IIFE-buildable runtime.
NOTE: not compiled yet — the sandbox still cannot build (sedlex fetches
UnicodeData.txt from unicode.org); test/test_stdlib_aot.ml picks every
stdlib/*.affine up automatically, so `dune test` is its first check.
Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
…it exposed The DOM runtime is no longer authored blind: the toolchain now builds here (sedlex 3.2 install fixed, see below), so everything in this commit was compiled and run before it was written down. - test/e2e/userscript/dom.affine: create -> patch (attribute dropped, text changed) -> text-only patch -> reconcile 0->3 and 3->2 -> teardown. - test/e2e/userscript/dom_harness.mjs: runs that artefact against a recording fake DOM. UserscriptDom only reaches the page through createElement/ appendChild/removeChild/*Attribute/textContent, so no browser and no jsdom are needed -- 12 checks (markers, attribute add/remove sequence, empty page after teardown) run anywhere a compiler does. - run.sh: compiles the fixture, holds it to the single-capsule/no-import/ size-budget rules, then runs the harness. Suite: 57 -> 69 checks. - lib/codegen_userscript.ml: `show` is a typechecker builtin like `len`, so it reached the emitter with no extern to lower through and emitted a call to an undefined global. Lower it to `__as_show`, matching the other JS backends, and define that in the runtime. - stdlib/UserscriptDom.affine: `for`/`if` statements do not take a trailing semicolon -- parsing caught it, `check` now passes. - tools/bootstrap-ocaml-toolchain.sh: `sedlex.ppx` is a public_name inside the `sedlex` package, not a package; naming it as an install target failed the sedlex step with "Unknown package sedlex.ppx". Measured: dom.affine 7,991 B; probe 18,523 B; probe+banner 18,861 B; reachability 4,351 B; hello 4,318 B (budget 24,576). Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
|
Review these changes at https://app.gitnotebooks.com/hyperpolymath/affinescript/pull/865 |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Caution Review failedThe pull request is closed.
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. |
Signed-off-by: Jonathan D.A. Jewell <6759885+hyperpolymath@users.noreply.github.com>
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5d9ca65a08
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| const probe = "__affinescript_userscript_probe__"; | ||
| store.setItem(probe, "1"); | ||
| store.removeItem(probe); |
There was a problem hiding this comment.
Preserve localStorage data while probing availability
When the host page already has a value under __affinescript_userscript_probe__, every call to capabilities() overwrites that value and then deletes it. Since userscripts run against arbitrary pages and capabilities() is called by each settings operation, this can silently corrupt page-owned localStorage; preserve and restore any prior value or use a collision-resistant temporary key.
Useful? React with 👍 / 👎.
| | Some g -> " && (" ^ gen_expr ctx g ^ ")" | ||
| | None -> "" | ||
| in | ||
| let body = gen_expr ctx arm.ma_body in | ||
| "if (" ^ cond ^ guard ^ ") { " ^ bindings ^ "return " ^ body ^ "; } else " |
There was a problem hiding this comment.
Bind match variables before evaluating arm guards
For a guarded arm such as Some(x) if x > 0 => ..., the generated condition evaluates the guard before the branch emits const x = __scrut.value, causing a ReferenceError (or reading an unrelated outer binding). This affects both expression and statement matches; test the pattern first, introduce its bindings, and only then evaluate the guard before selecting the arm.
Useful? React with 👍 / 👎.
| let can_read = us_gm_has("getValue"); | ||
| let can_write = us_gm_has("setValue"); | ||
| Caps #{ | ||
| manager: can_read, | ||
| gm_storage: can_read, | ||
| local_storage: us_local_available(), |
There was a problem hiding this comment.
Select storage capabilities per operation
With partial userscript grants, gm_storage is true solely when GM_getValue exists, while the computed can_write is ignored and GM_deleteValue is not checked at all. For example, a script granted only GM_getValue with usable localStorage routes set_setting and delete_setting to missing GM functions and returns HostRejected instead of using the documented localStorage fallback; each operation needs to check its corresponding GM capability.
Useful? React with 👍 / 👎.
| | ExprApp (func, args) -> | ||
| let arg_strs = List.map (gen_expr ctx) args in | ||
| (match func with | ||
| | ExprVar id when id.name = "len" && List.length arg_strs = 1 -> |
There was a problem hiding this comment.
Let local definitions shadow intrinsic lowerings
When a program defines its own len, calls are still unconditionally rewritten to .length; for example, the repository's supported fn len(xs: IntList) -> Int shape would produce an invalid result under this target. The same name-only dispatch also affects show and every userscript extern name, so intrinsic lowering should be suppressed when the flattened program contains a same-named local function or constant.
Useful? React with 👍 / 👎.
| (* The default output path is a wasm module; a userscript is one .js file, | ||
| so an unspecified -o becomes out.user.js instead of silently writing a | ||
| JS source file called out.wasm. *) | ||
| let output = if userscript && output = "out.wasm" then "out.user.js" else output in |
There was a problem hiding this comment.
Honor explicit output paths equal to the default
When a caller explicitly supplies -o out.wasm with the userscript target, this equality check treats the requested path as if it were an omitted option and writes out.user.js instead. Build scripts that always pass an output path will then fail to find the promised artifact; the CLI needs to retain whether -o was supplied rather than inferring omission from its value.
Useful? React with 👍 / 👎.
| pub fn patch_from(el: Element, s: Spec) -> Element { | ||
| patch(el, s.attrs, s.text) | ||
| } |
There was a problem hiding this comment.
Replace elements when a patched spec changes the tag
patch_from discards s.html_tag, so patching an existing <p> with a Spec for <div> updates attributes and text but leaves a <p> in the page. Because the public API accepts an arbitrary Spec and documents no same-tag precondition, it must either replace the DOM node when the tag changes or reject such a patch explicitly.
Useful? React with 👍 / 👎.
| // here rather than awaited, because top-level `await` is not allowed in a | ||
| // non-module script. | ||
| try { | ||
| const __as_result = main(); |
There was a problem hiding this comment.
Reject parameterized userscript entry points
The generated capsule always invokes main() with no arguments, but the target never validates that the source main has zero parameters. A program with fn main(x: Int) therefore compiles successfully and runs with x === undefined, producing invalid values or delayed runtime failures instead of a build diagnostic.
Useful? React with 👍 / 👎.
| match v with | ||
| | `Null -> Buffer.add_string buf "null"; Ok () | ||
| | `Bool b -> Buffer.add_string buf (if b then "true" else "false"); Ok () | ||
| | `Int i -> Buffer.add_string buf (string_of_int i); Ok () |
There was a problem hiding this comment.
Reject integers outside the interoperable JCS range
The Int branch emits arbitrary OCaml integers verbatim, including values such as 9007199254740993 that cannot be represented by the IEEE-754 number model required by JCS/I-JSON consumers. Such a consumer parses that value as 9007199254740992 and canonicalizes different bytes, defeating the promised cross-implementation canonical form; reject non-interoperable integers or require them to be represented as strings.
Useful? React with 👍 / 👎.
| (match fd.fd_body with | ||
| | FnExpr e -> expr_unsupported e | ||
| | FnBlock blk -> block_unsupported blk | ||
| | FnExtern -> None) |
There was a problem hiding this comment.
Reject unbound extern methods inside impl blocks
A bodiless ImplFn is explicitly treated as supported regardless of its name, unlike top-level extern functions. An impl containing an extern method with no userscript lowering therefore passes the build-time closed-capability check and is emitted as a function that only throws at runtime; run these methods through extern_name so unsupported host access is rejected during compilation.
Useful? React with 👍 / 👎.
| manager: can_read, | ||
| gm_storage: can_read, | ||
| local_storage: us_local_available(), | ||
| menu: us_gm_has("registerMenuCommand"), |
There was a problem hiding this comment.
Require unregister capability before issuing menu handles
capabilities().menu checks only GM_registerMenuCommand, so a script granted registration but not GM_unregisterMenuCommand receives a handle that the API says must be released, yet release_menu_command can only fail and leave the native menu active. Require both capabilities before registering a releasable command, or provide a release path that does not depend on the missing grant.
Useful? React with 👍 / 👎.




Summary
Closes #
Type of change
How has this been verified?
Checklist
git commit -S).SPDX-License-Identifier(code/configMPL-2.0,prose
CC-BY-SA-4.0); I did not relicense existing files.Notes for reviewers