diff --git a/.claude/CLAUDE.md b/.claude/CLAUDE.md index a6a3d7d2..36486806 100644 --- a/.claude/CLAUDE.md +++ b/.claude/CLAUDE.md @@ -138,6 +138,7 @@ The "no Node.js / no Bun" rules in the language policy table have two approved e | Path | Banned thing(s) used | Rationale | Unblock condition | |---|---|---|---| | `packages/affinescript-cli/mod.js` | `process.platform`/`process.arch`/`process.env`, `node:fs/promises`, `node:child_process`, `Bun.spawn`, `Bun.file`, `Bun.write` | The shim is the **compiler-distribution front door**. Its consumers — LSP installers, IDE extensions, CI scripts wiring AffineScript into a build pipeline — overwhelmingly live in Node and Bun ecosystems, not Deno. Forcing them to install Deno solely to fetch+verify+exec a binary defeats the shim's "ergonomic install" purpose. The branches are guarded by single-line runtime detection at module load; nothing else in the repo depends on this pattern. | None — this is the intended steady state. The shim's whole job is to be runtime-agnostic. | +| `test/e2e/userscript/*.mjs` | `node:fs`, `node:module`, `node:url`, `node:path`; optionally `playwright` (headless Chromium) or `jsdom` | The **userscript target's page fixture** (`--target userscript`). The emitted artefact is a classic script, so the only way to assert its real behaviour — div append/teardown, menu-command lifetime, storage fallback, add/remove listener balance — is to run it in a page. Compiled-output test harnesses, not shipped code or build tooling; same role as the existing `tests/codegen-*/*.harness.mjs`. `dom_harness.mjs` executes the emitted `stdlib/UserscriptDom.affine` against a recording fake DOM (no engine needed); `harness.mjs` drives a page. | None — test-harness steady state. It reads a build artefact and drives a page; it is never imported by anything in `lib/`, `bin/` or `stdlib/`. | | `editors/vscode/test/**/*.js` | `node:*`, Mocha, `@vscode/test-electron` (Electron-based VS Code download + launch) | The **in-editor smoke harness** for issue #139 — loads the compiled `out/extension.cjs` in a real VS Code extension host and asserts activation, command registration, `restartLsp` cycling, and `deactivate` teardown. The VS Code extension host is npm/Node-native; `@vscode/test-electron` (the official runner) downloads a real Electron VS Code and launches it under `xvfb-run`. No Deno equivalent exists, and the test cannot be expressed in any other runtime. Scope is strictly `editors/vscode/test/` — no production code uses Node. | None — this is the intended steady state, paralleling the `affine-vscode-publish.yml` workflow that already uses npm at publish time (#104). | Browsers and Cloudflare Workers are NOT supported and never will be (the shim's purpose — fetch, save to disk, exec a native binary — cannot be done in a sandboxed JS runtime). The JSR runtime-compatibility checkboxes for this package should be: Deno ✅, Bun ✅, Node ✅, Workers ❌, Browsers ❌. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a4f501a3..9b84751a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -141,6 +141,21 @@ jobs: cd affinescript-router/e2e bun install --frozen-lockfile --ignore-scripts opam exec -- bun test --timeout 60000 + - name: Userscript target fixture (single-file IIFE, headless Chromium) + # Compiles test/e2e/userscript/probe.affine with --target userscript and + # runs the artefact in a real page: div append + teardown, menu command, + # setting round-trip, style release, listener spy (no listener left + # behind) — once under @grant none, once under @grant GM_*, once on a + # page that denies storage. Also gates the single-file contract (no + # import/export/dynamic import/eval/top-level await), the --iife / + # --target equivalence, --banner happy path + both refusals, the + # --wasm-gc conflict (E0827) and the two planted negatives. + # Reuses the Chromium pinned by affinescript-tea/e2e (installed above), + # so this adds no browser download; AFFINESCRIPT_E2E_STRICT turns a + # missing engine into a failure instead of a skip. + env: + AFFINESCRIPT_E2E_STRICT: "1" + run: opam exec -- ./tools/run_userscript_tests.sh - name: Run face-transformer regression tests run: opam exec -- ./tools/run_face_transformer_tests.sh - name: Issue #35 Phase 3 — block extension.ts regression diff --git a/bin/main.ml b/bin/main.ml index 90546db6..80e05fb8 100644 --- a/bin/main.ml +++ b/bin/main.ml @@ -510,13 +510,102 @@ let repl_cmd_fn () = Format.eprintf "REPL not yet implemented@."; `Error (false, "REPL not yet implemented") +(** Read and validate a [==UserScript==] banner file. + + The banner is prepended verbatim, so it must be a complete metadata + block: an opening [==UserScript==] line, a closing [==/UserScript==] + line, and the opening before the closing. Anything else is a mistake + that would ship a script the manager cannot parse, so it is refused + rather than pasted through. *) +let read_userscript_banner (banner : string option) : (string, string) result = + match banner with + | None -> Ok "" + | Some path -> + (match (try Ok (read_file path) with Sys_error e -> Error e) with + | Error e -> Error (Printf.sprintf "cannot read --banner %s: %s" path e) + | Ok text -> + let contains needle = + let nl = String.length needle and tl = String.length text in + let rec scan i = + if i + nl > tl then false + else if String.sub text i nl = needle then true + else scan (i + 1) + in + scan 0 + in + if not (contains "==UserScript==") then + Error (Printf.sprintf + "--banner %s is not a ==UserScript== metadata block \ + (no `// ==UserScript==` opener)" path) + else if not (contains "==/UserScript==") then + Error (Printf.sprintf + "--banner %s has no `// ==/UserScript==` terminator" path) + else + let open_at = + try Some (Str.search_forward (Str.regexp_string "==UserScript==") text 0) + with Not_found -> None + in + let close_at = + try Some (Str.search_forward (Str.regexp_string "==/UserScript==") text 0) + with Not_found -> None + in + match (open_at, close_at) with + | (Some o, Some c) when c < o -> + Error (Printf.sprintf + "--banner %s closes before it opens (==/UserScript== \ + precedes ==UserScript==)" path) + | _ -> Ok text) + (** Compile a file. With [--json], emits diagnostics for any compilation errors. With [--wasm-gc], targets the WebAssembly GC - proposal instead of WASM 1.0 linear memory. *) + proposal instead of WASM 1.0 linear memory. + + [--target userscript] (alias [--iife]) selects the single-file + userscript target; the LLVM-triple reading of [--target] is unchanged + for every other value. *) let compile_file face json wasm_gc vscode_ext vscode_adapter vscode_no_lc - deno_esm bun_esm target path output = + deno_esm bun_esm iife banner target path output = let face = resolve_face ~quiet:json face path in - if deno_esm || Filename.check_suffix output ".deno.js" then + (* `--target userscript` / `--target iife` / `--iife` are target *modes*, + not LLVM triples (documented in the CLI reference). *) + let userscript = + iife + || (match target with Some "userscript" | Some "iife" -> true | _ -> false) + in + (* 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 + let banner_text, banner_error = + if userscript then + match read_userscript_banner banner with + | Ok t -> (Some t, None) + | Error m -> (None, Some m) + else (None, None) + in + if userscript && wasm_gc then + let message = + "--target userscript emits a single JS file and has no wasm module; \ + it cannot be combined with --wasm-gc" in + if json then + json_finish [{ Affinescript.Json_output.severity = Error; + code = "E0827"; message; + span = Affinescript.Span.dummy; help = None; labels = [] }] + else begin + Format.eprintf "@[Backend selection error: %s@]@." message; + `Error (false, "Backend selection error") + end + else if (match banner_error with Some _ -> true | None -> false) then + let message = Option.get banner_error in + if json then + json_finish [{ Affinescript.Json_output.severity = Error; + code = "E0827"; message; + span = Affinescript.Span.dummy; help = None; labels = [] }] + else begin + Format.eprintf "@[Userscript banner error: %s@]@." message; + `Error (false, "Userscript banner error") + end + else if deno_esm || Filename.check_suffix output ".deno.js" then let message = "Deno-ESM was removed; use --bun-esm (and a .bun.js output path)" in if json then json_finish [{ Affinescript.Json_output.severity = Error; @@ -581,7 +670,38 @@ let compile_file face json wasm_gc vscode_ext vscode_adapter vscode_no_lc let is_why3 = Filename.check_suffix output ".mlw" in let is_lean = Filename.check_suffix output ".lean" in let is_spirv = Filename.check_suffix output ".spv" in - if is_bun then begin + if userscript then begin + (* Reachability check FIRST: it walks the module graph the + resolver loaded, so a refusal can name the module. *) + match Affinescript.Codegen_userscript.check_reachable + ~loader ~root_name:path prog with + | errs when errs <> [] -> + List.iter (fun (u : Affinescript.Codegen_userscript.unsupported) -> + add { severity = Error; code = "E0827"; + message = Printf.sprintf + "userscript target: unsupported %s" + (Affinescript.Codegen_userscript.show_unsupported u); + span = Affinescript.Span.dummy; + help = Some "a userscript is one non-module file; \ + remove the construct or build that module \ + for another target"; + labels = [] }) errs + | _ -> + let banner = + match banner_text with + | Some t when t <> "" -> Some t + | _ -> None + in + (match Affinescript.Codegen_userscript.codegen_userscript + ?banner flat_prog resolve_ctx.symbols with + | Error msg -> + add { severity = Error; code = "E0827"; message = msg; + span = Affinescript.Span.dummy; help = None; labels = [] } + | Ok js -> + let oc = open_out_bin output in + output_string oc js; + close_out oc) + end else if is_bun then begin match Affinescript.Codegen_deno.codegen_bun flat_prog resolve_ctx.symbols with | Error msg -> add { severity = Error; code = "E0825"; @@ -815,7 +935,37 @@ let compile_file face json wasm_gc vscode_ext vscode_adapter vscode_no_lc let is_why3 = Filename.check_suffix output ".mlw" in let is_lean = Filename.check_suffix output ".lean" in let is_spirv = Filename.check_suffix output ".spv" in - if is_bun then + if userscript then + (match Affinescript.Codegen_userscript.check_reachable + ~loader ~root_name:path prog with + | errs when errs <> [] -> + List.iter (fun (u : Affinescript.Codegen_userscript.unsupported) -> + Format.eprintf "@[userscript target: unsupported %s@]@." + (Affinescript.Codegen_userscript.show_unsupported u)) errs; + Format.eprintf + "@[A userscript is a single non-module file: no import/export, \ + no dynamic import, no eval, no top-level await.@. Every reachable module must be expressible in plain JS with \ + only the documented userscript bindings.@]@."; + `Error (false, "Userscript target error") + | _ -> + let banner = + match banner_text with + | Some t when t <> "" -> Some t + | _ -> None + in + (match Affinescript.Codegen_userscript.codegen_userscript + ?banner flat_prog resolve_ctx.symbols with + | Error msg -> + Format.eprintf "@[userscript codegen error: %s@]@." msg; + `Error (false, "Userscript codegen error") + | Ok js -> + let oc = open_out_bin output in + output_string oc js; + close_out oc; + Format.printf "Compiled %s -> %s (userscript, %d bytes)@." + path output (String.length js); + `Ok ())) + else if is_bun then (match Affinescript.Codegen_deno.codegen_bun flat_prog resolve_ctx.symbols with | Error e -> Format.eprintf "@[%s@]@." e; @@ -1249,8 +1399,11 @@ let output_arg = Arg.(value & opt string "out.wasm" & info ["o"; "output"] ~docv:"FILE" ~doc:"Output file") let target_arg = - Arg.(value & opt (some string) None & info ["target"] ~docv:"TRIPLE" - ~doc:"LLVM target triple for native (.ll) output. Overrides the \ + Arg.(value & opt (some string) None & info ["target"] ~docv:"TRIPLE|MODE" + ~doc:"Target selection. $(b,userscript) (alias $(b,iife)) selects the \ + single-file userscript target (see $(b,--iife)); those two words \ + are reserved and never read as triples. Any other value is an \ + LLVM target triple for native (.ll) output. Overrides the \ AFFINESCRIPT_LLVM_TRIPLE env var; default is x86_64-unknown-linux-gnu. \ Accepts a full triple verbatim (e.g. riscv64-unknown-linux-gnu) or a \ shorthand: x86_64, aarch64/arm64, aarch64-android/android, riscv64, \ @@ -1301,6 +1454,27 @@ let bun_esm_arg = Deno runtime shim. A `.bun.js` output extension selects this \ backend implicitly.") +(* Userscript target: `--target userscript` (alias `--iife`) emits ONE + ES2020 IIFE file — no import/export, no dynamic import, no eval, no + top-level await — suitable for Tampermonkey/Greasemonkey/Violentmonkey. *) +let iife_arg = + Arg.(value & flag & info ["iife"] + ~doc:"Emit a single-file ES2020 userscript (shorthand for \ + $(b,--target userscript)). The output is one IIFE with no \ + import/export, no dynamic import, no eval and no top-level await; \ + a construct the target cannot lower fails the build, naming the \ + module and the construct. Pair with $(b,--banner) for the \ + $(b,==UserScript==) metadata block.") + +let banner_arg = + Arg.(value & opt (some string) None & info ["banner"] ~docv:"FILE" + ~doc:"With $(b,--target userscript)/$(b,--iife), prepend the contents of \ + FILE verbatim. FILE must be a complete $(b,==UserScript==) \ + metadata block: an opening $(b,// ==UserScript==) line and a \ + closing $(b,// ==/UserScript==) line. Declare $(b,@grant none) \ + there unless the script needs the manager bindings in \ + $(b,stdlib/Userscript.affine).") + (** Shared --face flag: select the parser surface-syntax face. *) let face_arg = let faces = Arg.enum [ @@ -1339,7 +1513,7 @@ let face_arg = ($(b,function)/$(b,set...to)/$(b,if...then)/$(b,end)/$(b,is)/$(b,and)/etc.). \ $(b,lucid)/$(b,lucidscript)/$(b,purescript) — PureScript-style \ ($(b,module … where)/$(b,data)/$(b,class)/$(b,instance)/$(b,case … of)/\ - $(b,\\x ->)/$(b,let … in)/$(b,True)/$(b,--) comments). \ + $(b,\\\\x ->)/$(b,let … in)/$(b,True)/$(b,--) comments). \ $(b,cafe)/$(b,cafescripto)/$(b,coffee)/$(b,coffeescript) — CoffeeScript-style \ ($(b,->)/$(b,=>)/$(b,@)/$(b,unless)/$(b,until)/postfix-if/postfix-unless/\ $(b,Yes)/$(b,No)/$(b,On)/$(b,Off)/$(b,#) comments/$(b,###) blocks). \ @@ -1644,11 +1818,11 @@ let repl_cmd = Cmd.v info Term.(ret (const repl_cmd_fn $ const ())) let compile_cmd = - let doc = "Compile a file to WebAssembly (1.0 or GC proposal), native Bun ESM (.bun.js/--bun-esm), Julia (.jl), JavaScript (.js), C (.c), a WGSL compute kernel (.wgsl), a Faust DSP program (.dsp), or an ONNX model (.onnx)" in + let doc = "Compile a file to WebAssembly (1.0 or GC proposal), native Bun ESM (.bun.js/--bun-esm), a single-file userscript (--target userscript/--iife), Julia (.jl), JavaScript (.js), C (.c), a WGSL compute kernel (.wgsl), a Faust DSP program (.dsp), or an ONNX model (.onnx)" in let info = Cmd.info "compile" ~doc in Cmd.v info Term.(ret (const compile_file $ face_arg $ json_arg $ wasm_gc_arg $ vscode_ext_arg $ vscode_adapter_arg $ vscode_no_lc_arg $ deno_esm_arg - $ bun_esm_arg $ target_arg $ path_arg $ output_arg)) + $ bun_esm_arg $ iife_arg $ banner_arg $ target_arg $ path_arg $ output_arg)) let fmt_cmd = let doc = "Format a file" in diff --git a/docs/CAPABILITY-MATRIX.adoc b/docs/CAPABILITY-MATRIX.adoc index 849c9e8c..c03a6f7f 100644 --- a/docs/CAPABILITY-MATRIX.adoc +++ b/docs/CAPABILITY-MATRIX.adoc @@ -212,6 +212,21 @@ under Bun. `tools/run_codegen_deno_tests.sh` (historical name) compiles Migration and host-contract details: link:guides/bun-esm-migration.adoc[guides/bun-esm-migration.adoc]. +|Userscript (browser) |works |`lib/codegen_userscript.ml`, +`--target userscript` / `--iife` / `--banner FILE`. Direct AST→ES2020 +single-file IIFE for userscript managers: no import/export, no dynamic +import, no `eval`, no top-level `await` (all four are checked on every +build). Host surface is a closed allowlist — `stdlib/Userscript.affine`'s +`us_*`/`dom_*` externs — and anything else is a build error naming the +construct and module (E0827); effect handlers, `unsafe` and float-cell +records are refused rather than miscompiled. `use prelude::*` is safe in a +page-injected file because the target prunes to what `main` reaches +(reachability, not minification). No WASM: the constructs that would need +linear memory are refused, and `wasm-unsafe-eval` is not available in the +page CSP a userscript inherits. Runtime fixture runs the compiled script in a +page under `@grant none`, `@grant GM_*` and a storage-denying page. +Guide: link:guides/userscript-target.adoc[guides/userscript-target.adoc]. + |Node-CJS |works |`lib/codegen_node.ml`; CJS shim, handle table, the `.affine` VS Code extension compiles through it. Live-host smoke harness for the compiled extension landed via PR #317 / issue #139: @@ -268,6 +283,7 @@ test is deleted or renamed without this section (and CI) noticing. |Codegen (golden snapshots) |`test/test_golden.ml` |Deno / JS host backends |`test/test_deno_builtins_consistency.ml`, `test/test_int_div_js.ml` |Bun-ESM host backend |`tools/run_codegen_bun_tests.sh` +|Userscript target |`tools/run_userscript_tests.sh`; fixtures `test/e2e/userscript/probe.affine`, `test/e2e/userscript/reachability.affine`, negatives `test/e2e/userscript/negatives/missing_binding.affine`, `test/e2e/userscript/negatives/handle_leak.affine` |Solo core (executable metatheory) |`test/test_solo_cesk.ml` |=== diff --git a/docs/NAVIGATION.adoc b/docs/NAVIGATION.adoc index 15be3376..6a7a3042 100644 --- a/docs/NAVIGATION.adoc +++ b/docs/NAVIGATION.adoc @@ -46,7 +46,8 @@ This guide helps you navigate the AffineScript repository structure. |**docs/specs/** |Language specifications |**docs/governance/** |Community and contribution docs |**docs/standards/** |Design decisions, roadmap, releases -|**docs/guides/** |Testing reports and guides +|**docs/guides/** |Testing reports and guides; link:guides/userscript-target.adoc[shipping a userscript] covers the `--target userscript` build, `stdlib/Userscript.affine` and its page-injected contract +|**docs/reference/** |ABI/FFI, compiler capabilities; link:reference/JSON-AND-YAML.adoc[JSON and YAML conventions] records the I-JSON + JCS (`ijson-jcs`) and kyaml rules for machine-readable output |**wiki/** |Extended documentation and wiki content |=== diff --git a/docs/guides/userscript-target.adoc b/docs/guides/userscript-target.adoc new file mode 100644 index 00000000..8db55702 --- /dev/null +++ b/docs/guides/userscript-target.adoc @@ -0,0 +1,377 @@ +// SPDX-License-Identifier: CC-BY-SA-4.0 +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell (hyperpolymath) += Shipping a userscript with AffineScript +:toc: macro +:toclevels: 3 + +toc::[] + +A *userscript* is one JavaScript file, loaded into somebody else's page by a +manager (Tampermonkey, Greasemonkey, Violentmonkey, Userscripts/Safari). The +manager injects it as a classic script: no module loader, no bundler, no +build step on the user's machine, and a metadata block that decides which host +capabilities (`@grant`) the script may touch. The `userscript` target emits +exactly that artefact from an AffineScript module — one ES2020 IIFE, plus an +optional `// ==UserScript==` banner. + +[source,bash] +---- +affinescript compile src/probe.affine --target userscript -o probe.user.js +affinescript compile src/probe.affine --iife -o probe.user.js # same build +affinescript compile src/probe.affine --target userscript \ + --banner src/probe.meta.js -o probe.user.js +---- + +`userscript` and `iife` are reserved words for `--target`; every other +`--target` value is still an LLVM triple (see `affinescript compile --help`). +The default output name for this target is `out.user.js`. + +== The single-file contract + +The emitted file is one capsulated IIFE in strict mode: + +[source,javascript] +---- +// Generated by AffineScript compiler (userscript target). +// SPDX-License-Identifier: MPL-2.0 +(function () { + "use strict"; + // ---- AffineScript userscript runtime + // ... only the runtime sections the program reaches ... + // ... your functions ... + try { + const __as_result = main(); + if (__as_result && typeof __as_result.then === "function") { + __as_result.catch((e) => console.error("[affinescript] main failed", e)); + } + } catch (e) { + console.error("[affinescript] main failed", e); + } +})(); +---- + +What the artefact never contains — all four are checked on every build, not +just documented: + +[cols="1,3"] +|=== +|Absent |Why + +|`import` / `export` |A userscript is not a module; a manager injects a +classic script, and `export` outside a module is a syntax error. + +|`import(...)` (dynamic import) |Async module loading from a page-injected +script is blocked by page CSP and by manager sandboxing. + +|`eval` / `new Function` |Requires `unsafe-eval` in the page CSP, which a +userscript cannot grant itself. + +|top-level `await` |Only legal in modules. An `async` `main` is *observed* +(the returned promise is caught) rather than awaited. +|=== + +The runtime is emitted section by section: a script that never touches +`GM_*` storage never carries the storage helpers, and a script with no DOM +calls carries no DOM helpers. + +== `--banner FILE`: the metadata block + +`--banner FILE` prepends `FILE` verbatim, so the block is complete and yours +to own: + +[source,javascript] +---- +// ==UserScript== +// @name AffineScript userscript fixture +// @namespace https://affinescript.dev/e2e/userscript +// @version 1.0.0 +// @match https://affinescript.test/probe +// @grant none +// ==/UserScript== +---- + +The file must be a complete metadata block: a `// ==UserScript==` opener, a +`// ==/UserScript==` closer, and the opener first. A banner that does not open, +never closes, or closes before it opens is refused (exit non-zero, `E0827` +with `--json`) — a half-parsed metadata block would silently ship a script +that a manager treats as ungranted. Nothing inside the block is rewritten: +`@grant`, `@match`, `@run-at` reach the manager exactly as written. + +== `stdlib/Userscript.affine`: the host surface + +A userscript runs in a page it does not control, so *whether a capability +exists* is a runtime question. The stdlib turns that into data and typed +errors instead of `typeof`-sniffing sprinkled through the program. + +[source,affine] +---- +use Userscript::{ + Node, MenuCommand, body, element, set_attribute, set_text, append, remove, + capabilities, describe_error, get_setting, set_setting, storage_backend, + register_menu_command, release_menu_command, listen_window_once +}; + +pub fn main() -> Unit { + let host = body(); + let box = element("div"); + set_attribute(box, "id", "affinescript-userscript-probe"); + set_text(box, "AffineScript userscript is running"); + append(host, box); + + match set_setting("affinescript-userscript-probe", "42") { + Ok(_) => println("setting-written"), + Err(e) => println("setting-write-failed=" ++ describe_error(e)) + }; + + match register_menu_command("Probe", fn() => println("clicked")) { + Ok(command) => { /* ... release it on teardown ... */ }, + Err(e) => println("menu-unavailable=" ++ describe_error(e)) + } +} +---- + +=== Capabilities + +`capabilities()` reports what this page's manager exposes +(`manager`, `gm_storage`, `local_storage`, `menu`, `style`, `notification`), +and `storage_backend()` names the backend a setting will actually use: +`"manager"`, `"localStorage"` or `"none"`. Every stdlib operation consults it +first, so the same compiled file behaves correctly under `@grant none` and +under a full grant list — which is why the fixture is compiled once and run +three ways (see <<_testing_this_target>>). + +=== Typed errors, never swallowed + +Every operation returns `Result<_, UserscriptError>`: + +[cols="1,3"] +|=== +|Case |Meaning + +|`ManagerMissing(String)` |The manager grants no such capability (checked with +`GM_*` feature detection, never assumed). + +|`HostRejected(String)` |Granted, but the host call itself failed. Carries the +host's message. + +|`StorageDenied(String)` |`localStorage` exists but the page refuses access +(opaque origin, private-mode quota 0). + +|`InvalidKey(String)` |The setting key is empty, longer than 128 characters, or +contains a control character — rejected before the host is touched. +|=== + +`describe_error` renders one for a log line. Nothing throws out of the +capsule: `main` is wrapped, so an unexpected host error becomes a +`console.error("[affinescript] main failed", e)` line instead of a broken page. + +=== Settings: manager first, `localStorage` second + +`get_setting` / `set_setting` / `delete_setting` prefer `GM_getValue` / +`GM_setValue` / `GM_deleteValue` and fall back to `localStorage`, so a script +still remembers things under `@grant none`. `Ok(None)` means "not set" and is +never conflated with `""` or with an error. Structured manager values come +back as their JSON text. + +=== Affine handles + +Everything that outlives a statement — a menu command, an injected style, a +notification, an event listener, a timer — arrives as a handle and leaves +through its release function: + +[source,affine] +---- +pub fn inject(css: String) -> Unit { + match add_style(css) { + Ok(sheet) => { + @linear let style = sheet; // exactly one release, proven statically + match release_style(style) { + Ok(_) => println("style released"), + Err(e) => println(describe_error(e)) + } + }, + Err(e) => println("style-unavailable=" ++ describe_error(e)) + } +} +---- + +Bind the handle `@linear` and the quantity checker (`lib/quantity.ml`) proves +the release statically: a dropped handle and a double release are both +compile errors. `test/e2e/userscript/negatives/handle_leak.affine` is the +planted negative control. + +A one-shot page event is the case where a handle would be circular (the +handler would have to release the listener it is part of). `listen_window_once` +and `listen_element_once` exist for it: the emitted runtime removes the +listener *before* running the handler, so there is nothing to release and no +leak. + +=== DOM surface + +`body`, `element`, `text_node`, `query` (→ `Option`), +`append`, `remove`, `set_attribute`, `remove_attribute`, `set_text`, +`add_class`, `remove_class`. `Node` is opaque in AffineScript; at runtime it +is an ordinary DOM node, or `null` when the page has no document. The helpers +return `null` instead of throwing, so a script that runs on the wrong page +degrades quietly instead of blowing up. + +== What is refused at build time + +The target is deliberately narrower than the other JS backends: anything it +cannot express in one non-module file is a *build* error naming the construct +and the module, never an optimistic same-named JS call that would throw in the +page, in front of a user. + +[cols="1,3"] +|=== +|Refused |Reason + +|`extern fn` without a userscript binding |The host surface is a closed +allowlist (the `us_*`, `gm_*` and `dom_*` functions declared in +`stdlib/Userscript.affine`). Diagnostic: +``userscript target: unsupported `extern fn us_not_a_capability` (no +userscript binding) (in module …)``. + +|Effect handlers (`handle`/`resume`) |No lowering outside the WASM backends; +the runtime is a plain JS IIFE with no continuation machinery. + +|`unsafe` blocks |There is no linear memory to point at. + +|Float-cell records |No cell lowering in this target. + +|`--wasm-gc` |The target emits one JS file and no module; combining the two is +refused rather than silently ignored. +|=== + +All of these report `E0827` under `--json`. + +== Reachability, not minification + +`use prelude::*` and a broad `use Userscript::{...}` are fine: the target +prunes to what `main` reaches. Unreachable top-level functions and the runtime +sections only they used disappear; constants, types, impls and externs are +always kept (they are declarations, not code). Nothing is renamed, folded, or +inlined — this is reachability, and `test/e2e/userscript/reachability.affine` +pins both halves of it (live path present, dead helper and unused manager +section absent). + +== WASM delivery: not used, and why + +The userscript target emits *pure JavaScript*. No WASM module, no base64 +payload, no embedder. + +* There is nothing to put in a module. The target's lowerings are DOM + operations, event listeners, storage and timers — none needs linear memory, + and the constructs that would (handles, `resume`, `unsafe`) are refused at + build time rather than miscompiled. +* Page CSP is not negotiable. `WebAssembly.instantiate` needs + `wasm-unsafe-eval` in the page's `script-src`. A userscript runs in the + *page's* CSP context; a manager's sandbox does not lift it. A base64 module + would therefore work on some pages and fail on the rest — as a load-time + failure in somebody else's page. +* Size. The pure-JS artefact for the CI fixture is 18,325 bytes (the + hello-DOM script is 4,142 bytes, the reachability script 4,153 bytes). The + same program as a module would add a base64 payload (≈ +33% on the module) + plus a loader and a JS fallback path, and the fallback would have to be + maintained anyway. + +*If* a future program genuinely needs numeric throughput that JS cannot give, +the recipe is the ordinary web one, and it stays outside this target: ship the +module as an `@resource`, guard `typeof WebAssembly === "object"` plus a +`try/catch` around `WebAssembly.instantiate`, and fall back to the pure-JS +build when the page blocks it. Nothing in the target or the stdlib assumes +WASM, so that fallback is the artefact this compiler already produces. + +== The ESM DOM runtime (`packages/affine-js`) does not bundle to an IIFE + +`packages/affine-js` is the JS interop layer for **WASM** modules (loader, +marshalling, `sandbox.js`); `affinescript-dom` is its guest-side virtual DOM. +It is published as ESM. An IIFE build of it for userscripts was attempted and +is blocked by the code itself, not by tooling preference: + +[source,bash] +---- +$ esbuild packages/affine-js/mod.js --bundle --format=iife --global-name=AffineJS +▲ [WARNING] "import.meta" is not available with the "iife" output format +✘ [ERROR] Could not resolve "node:fs/promises" (packages/affine-js/loader.js:112) +✘ [ERROR] Could not resolve "node:url" (packages/affine-js/loader.js:113) +---- + +The loader reads `import.meta.url` for its base path and reaches for +`node:fs/promises` and `node:url` through dynamic `import()`. Neither exists in +a page, and `import.meta` is empty in IIFE output — so an "IIFE build" would +have to be a rewritten loader (new JS, and a semantic change to a published +package), and the emitted dynamic imports would violate the same no-dynamic- +import rule the target enforces. That rewrite is out of scope here. + +What a userscript gets instead is the target's own inlined DOM runtime — the +`__as_dom*` helpers in the artefact, which are exactly the operations +`stdlib/Userscript.affine` declares — plus a reconciler authored in +AffineScript: **`stdlib/UserscriptDom.affine`**. + +`UserscriptDom` is the IIFE-buildable answer to `affinescript-dom` for this +target: `Spec`/`Element`/`Group` values over opaque `Node` handles, with +`create`, `patch` (attributes added *and* removed, text rewritten only when it +changed), `unmount`, and `Group.reconcile` (patch by position, append the +surplus, remove what the new list no longer reaches). It is a reconciler, not a +vdom diff: an `Element` remembers what it was created with, which is what makes +an in-place patch possible without a vnode tree — the target has no +`get_attribute`, and a recursive vnode type is not expressible. + +Because it is ordinary AffineScript, it is compiled by this target into the +same single file as the rest of the script: no loader, no wasm, no byte budget +of its own (only what it reaches is emitted). Keep `affine-js` where a WASM +module is actually being loaded. + +== Testing this target + +[source,bash] +---- +./test/e2e/userscript/run.sh # or: ./tools/run_userscript_tests.sh +---- + +The runner compiles `probe.affine`, checks the single-file contract, the +`--target`/`--iife` equivalence, the banner happy path and both refusal cases, +the `--wasm-gc` conflict, both negative controls, and reachability; then runs +the compiled script in a page and asserts the whole lifecycle: + +. a `
` is appended and carries its text, +. a setting round-trips (manager store under `@grant GM_*`, `localStorage` + under `@grant none`, typed error on a page that denies storage), +. a menu command registers and is released exactly once, +. an injected style is released, +. teardown removes the `
`, and the listener spy shows the one-shot + listener removed with nothing live afterwards. + +Two engines, same assertions: `playwright` (headless Chromium — the CI path, +reusing the pinned install from `affinescript-tea/e2e`) and `jsdom` (a DOM +implementation, for machines that cannot download a browser). With neither +available the runtime half prints a loud `SKIP` and the static and refusal +checks still run; `AFFINESCRIPT_E2E_STRICT=1` (set in CI) turns that skip into +a failure. + +The runner then does the same for the runtime itself: `dom.affine` is compiled +with `--target userscript`, held to the single-capsule/size rules, and executed +by `dom_harness.mjs` against a *recording fake DOM* — no browser, no jsdom. It +needs nothing but the JS runtime the compiler already requires, so the answers +that matter (was the dropped attribute removed? did reconcile append and remove +the right children? is the page empty after teardown?) are checked on every +machine, not only where a browser is installed. + +`len` and `show` are typechecker builtins with no extern declaration to lower +through; this target lowers them to `.length` and `__as_show(...)` itself. A +program that declares its own `len`/`show` shadows that, as it does elsewhere. + +== Measured sizes + +[cols="1,1,3"] +|=== +|Program |Bytes |Contents + +|`hello` (DOM append) |4,318 |capsule + 4 DOM helpers + `main` +|`reachability.affine` |4,351 |same, plus pruning proof +|`dom.affine` (fixture) |7,991 |`UserscriptDom`: create, patch, reconcile, teardown +|`probe.affine` (fixture) |18,523 |full lifecycle: DOM, storage, menu, style, +one-shot listener, typed errors +|`probe.affine --banner banner.txt` |18,861 |above + a 9-line metadata block +|=== diff --git a/docs/reference/JSON-AND-YAML.adoc b/docs/reference/JSON-AND-YAML.adoc new file mode 100644 index 00000000..b50cc00c --- /dev/null +++ b/docs/reference/JSON-AND-YAML.adoc @@ -0,0 +1,144 @@ +// SPDX-License-Identifier: CC-BY-SA-4.0 +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell (hyperpolymath) += JSON and YAML conventions +:toc: macro + +toc::[] + +Machine-readable output in this repo follows two estate standards. This page +records them, where they already hold, and what is left to convert. + +== JSON: I-JSON + JCS (`hyperpolymath/ijson-jcs`, D306) + +Every JSON document the compiler writes for a machine is *I-JSON* (RFC 7493) +and *JCS-canonical* (RFC 8785), as defined by the estate standard +https://github.com/hyperpolymath/ijson-jcs[`hyperpolymath/ijson-jcs`] — I-JSON +validation plus JCS canonicalisation, shipped there as a Rust library with +`check`/`fix`/`canon` in its CLI. + +Why both halves matter: + +* **I-JSON** removes the parts of JSON that let two parsers disagree: duplicate + object keys, lone surrogates and malformed UTF-8, and `NaN`/`Infinity`. +* **JCS** removes the parts that let two *writers* disagree: key order, string + escaping, and number spelling. Two runs that produce equal values produce + equal bytes, which is what content addressing, signed payloads, and + byte-level diffing need. + +The rules, stated concretely (these are the ones that bite): + +[cols="1,3"] +|=== +|Rule |Detail + +|Key order |Lexicographic over **UTF-16 code units** — the order ECMAScript's +default `sort` gives, *not* UTF-8 byte order and *not* locale order. Above the +BMP the two disagree: a key containing an emoji (high surrogate U+D83D) sorts +*before* one containing U+E000. + +|Strings |Escaped exactly as `JSON.stringify` escapes them: `\"`, `\\`, the +five short control escapes (`\b \f \n \r \t`), `\u00xx` (lower-case hex) for +the rest of C0, everything else verbatim UTF-8. + +|Numbers |ECMAScript `Number::toString`, not C `%g`: `1e21` → +`1e+21`, `1e20` → `100000000000000000000`, `2e-3` → `0.002`, `-0` → `0`, +`1.7976931348623157e308` → `1.7976931348623157e+308`. Plain notation while +the decimal exponent is in `[-6, 21)`, exponent form outside it. + +|No whitespace |No spaces, no newlines inside the document. + +|Rejections |Duplicate keys, lone surrogates / bad UTF-8, `NaN`, `±Infinity` +are errors, never silently coerced. +|=== + +=== Current state in this tree + +[cols="2,1,3"] +|=== +|Site |Status |Note + +|`lib/json_output.ml` |*canonical* |All five serialisation sites now go +through `Jcs.to_string_exn`: the two `--json` report emitters (stderr) and the +three LSP response emitters — `emit_hover`, `emit_goto_def`, +`emit_completions` (stdout). + +|`lib/lsp_server.ml` |*canonical* |JSON-RPC frames go through +`Jcs.to_string_exn` too. `Content-Length` is computed from the serialised body, +so canonical output keeps framing byte-exact by construction. + +|`lib/jcs.ml` |*wired, vector-checked* |The RFC 7493 + RFC 8785 serialiser, +in `lib/dune`'s `(modules ...)` list. Built and run against the vectors below +as a standalone `dune` + `yojson` project: all six byte-identical to an +independent JCS implementation, and all four I-JSON rejections fire. The full +repository build has not been re-run here — see *Building the toolchain*. + +|`--json` stream |stderr |Unchanged by this convention: the compiler's +`Compiled …` messages own stdout, so the machine document stays on stderr. +|=== + +The toolchain is hermetic (no Cargo, no crates.io), so `ijson-jcs`'s Rust +library cannot be linked and shelling out to its CLI would make `--json` +depend on what is installed on the machine. `lib/jcs.ml` is therefore a port +of the two RFCs, not a binding; the CLI remains the out-of-band conformance +oracle, to be driven by `tools/run_jcs_conformance.sh` (planned: run `canon` +over the corpus below when it is on `PATH`, skip loudly otherwise). + +=== What does not break + +Canonical output changes key order and whitespace only, and both are +insignificant to consumers. The greps in this repo keep matching: + +* `tools/run_codegen_bun_tests.sh` → `grep -q '"success":false'` +* `test/e2e/userscript/run.sh` → `grep -q '"code":"E0827"'` + +=== Pinned corpus + +These vectors were produced by an independent JCS implementation (node's own +`JSON.stringify` for ES6 strings/numbers, default `sort` for UTF-16 key +order) and matched by a step-for-step mirror of `lib/jcs.ml`'s algorithm. +They are the corpus `test/test_jcs.ml` asserts (as `Alcotest` cases). + +[source,text] +---- +{"literals":[null,true,false],"numbers":[333333333.3333333,1e+30,4.5,0.002,1e-27],"string":"€$\u000f\nA'B\"\\\\\"/"} +{"":5,"A":3,"a":2,"aa":4,"b":1} +{"e":2,"z":[1,2,{"y":null}],"é":1} +{"astral":1,"😀":2,"":4,"":3} <- U+E000 and U+FFFD, emitted verbatim +[0,0,1e+21,100000000000000000000,1e-7,0.000001,5e-324,1.7976931348623157e+308,123456789012345680000,-2.5,0.1] +{"nested":{"k1":{"y":[null],"z":1},"k2":[true,"x"]}} +---- + +The fourth line is the UTF-16 ordering case: `😀` (U+1F600) precedes +U+E000 even though its code point is larger. The fifth covers the ES6 number +placement rule at both switch points, subnormals, and `-0`. + +== Building the toolchain + +The checks above were run with a from-source toolchain, because this +environment has no opam switch: `tools/bootstrap-ocaml-toolchain.sh` builds +OCaml 4.14.2, dune, and the findlib packages this repo needs straight from +upstream tarballs into one prefix (`--prefix`, `--stage core|shims|libs`, +`--verify`), with no opam and no user-wide switch. Its header records the +traps (dune bootstraps without `--release`; `ocaml-compiler-libs` v0.17 is +OCaml-5-only; `cppo` is needed by `ppx_deriving`; fmt's tarballs are +topkg-only; `seq`/`result` must be stdlib re-export shims). + +One step cannot complete behind a restrictive egress policy: sedlex +regenerates its Unicode tables by downloading `UnicodeData.txt` from +`unicode.org`. On a machine with ordinary internet access that is a no-op; on +an air-gapped runner, pre-seed the file or install sedlex from a distribution +package. + +== YAML: kyaml (external standard) + +YAML this repo emits is kyaml. **kyaml is not defined in this estate** — it is +an upstream standard, unlike ijson-jcs above, which is ours (D306). So there is +no estate repository to pin here, only the upstream one, and no version to +track in `dune`/`opam`: kyaml governs the *shape* of the YAML we emit, not a +linked dependency. + +Nothing in this tree generates YAML today (the CI workflows and manifests are +hand-written YAML; `.deed` manifests are DEED), so nothing is blocked on +pinning the exact upstream link. When a tool starts emitting YAML, it emits +kyaml rather than hand-rolling a writer — and this page gains the upstream +pointer at that point. diff --git a/lib/codegen_userscript.ml b/lib/codegen_userscript.ml new file mode 100644 index 00000000..85f12c2c --- /dev/null +++ b/lib/codegen_userscript.ml @@ -0,0 +1,1378 @@ +(* SPDX-License-Identifier: MPL-2.0 *) +(* SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell *) + +(** Userscript code generator (`--target userscript`, alias `--iife`). + + A userscript is a *single* non-module file that an arbitrary page's + userscript manager (Tampermonkey / Greasemonkey / Violentmonkey) injects + into a page. That shape forbids everything an ES module emitter relies + on: no [import]/[export], no dynamic [import()], no [eval], no + [new Function], and no top-level [await]. This backend therefore emits + + {v + (function () { "use strict"; ; ; })(); + v} + + — one IIFE, ES2020 syntax, no module system — plus an optional + verbatim banner (the [==UserScript==] metadata block) prepended by the + caller. + + Unlike {!Codegen_deno} (the Bun-ESM host profile, which lowers an + unknown [extern fn] to an optimistic same-named host call), this target + is a closed capability surface: only the extern names listed in + {!extern_lowerings} are lowered, and every other host operation is a + build error that names the module and the construct + ({!check_reachable}). That is deliberate: a userscript runs inside + somebody else's page, so "silently call whatever global happens to be + named [tea_query]" is exactly the failure mode we must not have. + + Reachability is computed over the module graph the resolver already + loaded ({!Module_loader}), before import flattening erases provenance — + that is why the diagnostic can name the module a construct came from. + + Non-goals: no source maps, no minification, no framework bindings, no + change to any other target's output. *) + +open Ast + +(* ============================================================================ + Unsupported-construct reporting + ============================================================================ *) + +(** A construct the userscript target cannot honour, and where it lives. *) +type unsupported = { + u_module : string; (** module display name, e.g. [Bun] or the source file *) + u_construct : string; (** source-level construct, e.g. [extern fn `bun_run`] *) +} + +let show_unsupported (u : unsupported) : string = + Printf.sprintf "%s (in module %s)" u.u_construct u.u_module + +(* ============================================================================ + Expression walker: constructs with no userscript lowering + ============================================================================ *) + +(** Report the first construct in [e] that this backend cannot lower. + + Effect handlers ({!ExprHandle}/{!ExprResume}) need a runtime dispatch + mechanism and [unsafe] memory operations need a linear-memory host; both + are rejected rather than approximated (the same fail-loudly stance + {!Js_codegen} takes for handlers, but reported with module provenance + by {!check_reachable}). *) +let opt_to_list = function Some x -> [ x ] | None -> [] + +let rec expr_unsupported (e : expr) : string option = + let first (es : expr list) : string option = List.find_map expr_unsupported es in + let blocks (bs : block list) : string option = List.find_map block_unsupported bs in + let arm_list (arms : match_arm list) : expr list = + List.concat_map + (fun (a : match_arm) -> a.ma_body :: opt_to_list a.ma_guard) arms + in + match e with + | ExprHandle _ -> Some "effect handler (`handle { ... }`)" + | ExprResume _ -> Some "`resume` (only valid inside `handle`)" + | ExprUnsafe _ -> Some "`unsafe` operation (no linear memory in a userscript)" + | ExprLet { el_value; el_body; _ } -> first (el_value :: opt_to_list el_body) + | ExprIf { ei_cond; ei_then; ei_else } -> + first (ei_cond :: ei_then :: opt_to_list ei_else) + | ExprMatch { em_scrutinee; em_arms } -> first (em_scrutinee :: arm_list em_arms) + | ExprLambda { elam_body; _ } -> expr_unsupported elam_body + | ExprApp (f, args) -> first (f :: args) + | ExprField (r, _) | ExprTupleIndex (r, _) -> expr_unsupported r + | ExprIndex (a, i) | ExprFloatIndex (a, i) -> first [ a; i ] + | ExprTuple es | ExprArray es | ExprFloatArray es -> first es + | ExprRecord { er_fields; er_spread } -> + first (List.filter_map (fun (_, v) -> v) er_fields @ opt_to_list er_spread) + | ExprCellRecord fields -> first (List.map (fun (_, e, _) -> e) fields) + | ExprRowRestrict (e, _) -> expr_unsupported e + | ExprBinary (a, _, b) | ExprStringConcat (a, b) | ExprStringRel (a, b, _) + | ExprFloatBinary (a, _, b) | ExprStringEq (a, b, _) -> first [ a; b ] + | ExprCellTuple cells -> first (List.map fst cells) + | ExprCellTupleIndex (e, _, _) -> expr_unsupported e + | ExprCellField _ -> Some "float-bearing record field access" + | ExprUnary (_, e) -> expr_unsupported e + | ExprBlock blk -> block_unsupported blk + | ExprReturn (Some e) -> expr_unsupported e + | ExprReturn None -> None + | ExprTry { et_body; et_catch; et_finally } -> + (match block_unsupported et_body with + | Some m -> Some m + | None -> + (match first (arm_list (Option.value ~default:[] et_catch)) with + | Some m -> Some m + | None -> blocks (opt_to_list et_finally))) + | ExprSpan (e, _) -> expr_unsupported e + | ExprLit _ | ExprVar _ | ExprVariant _ | ExprBreak _ | ExprContinue _ -> None + +and block_unsupported (blk : block) : string option = + match List.find_map stmt_unsupported blk.blk_stmts with + | Some m -> Some m + | None -> (match blk.blk_expr with Some e -> expr_unsupported e | None -> None) + +and stmt_unsupported (stmt : stmt) : string option = + match stmt with + | StmtLet { sl_value; _ } -> expr_unsupported sl_value + | StmtExpr e -> expr_unsupported e + | StmtAssign (a, _, b) -> + (match expr_unsupported a with Some m -> Some m | None -> expr_unsupported b) + | StmtWhile (c, body) -> + (match expr_unsupported c with Some m -> Some m | None -> block_unsupported body) + | StmtFor (_, iter, body) -> + (match expr_unsupported iter with Some m -> Some m | None -> block_unsupported body) + +(* ============================================================================ + Capability surface: the extern names this target can lower + ============================================================================ *) + +(** Every [extern fn] name this backend knows how to lower, grouped by the + runtime helper it becomes. Anything not listed here is a build error, so + adding a binding is a one-line, reviewable act. *) +let extern_lowerings : (string * (string list -> string)) list = [ + (* ── DOM: the host side of `Userscript`'s element constructors ───────── *) + ("dom_body", (fun _ -> "__as_domBody()")); + ("dom_create_element", (fun a -> Printf.sprintf "__as_domCreate(%s)" (List.nth a 0))); + ("dom_create_text", (fun a -> Printf.sprintf "__as_domText(%s)" (List.nth a 0))); + ("dom_query", (fun a -> Printf.sprintf "__as_domQuery(%s)" (List.nth a 0))); + ("dom_append", (fun a -> Printf.sprintf "(__as_domAppend(%s, %s), Unit)" (List.nth a 0) (List.nth a 1))); + ("dom_remove", (fun a -> Printf.sprintf "(__as_domRemove(%s, %s), Unit)" (List.nth a 0) (List.nth a 1))); + ("dom_set_attribute", (fun a -> Printf.sprintf "(__as_domAttr(%s, %s, %s), Unit)" (List.nth a 0) (List.nth a 1) (List.nth a 2))); + ("dom_remove_attribute",(fun a -> Printf.sprintf "(__as_domRemoveAttr(%s, %s), Unit)" (List.nth a 0) (List.nth a 1))); + ("dom_set_text", (fun a -> Printf.sprintf "(__as_domTextSet(%s, %s), Unit)" (List.nth a 0) (List.nth a 1))); + ("dom_add_class", (fun a -> Printf.sprintf "(__as_domClassAdd(%s, %s), Unit)" (List.nth a 0) (List.nth a 1))); + ("dom_remove_class", (fun a -> Printf.sprintf "(__as_domClassRemove(%s, %s), Unit)" (List.nth a 0) (List.nth a 1))); + ("dom_is_null", (fun a -> Printf.sprintf "((%s) == null)" (List.nth a 0))); + (* ── Event listeners (release = `us_off`) ────────────────────────────── *) + ("us_on_window", (fun a -> Printf.sprintf "__as_onWindow(%s, %s)" (List.nth a 0) (List.nth a 1))); + ("us_on_element", (fun a -> Printf.sprintf "__as_onElement(%s, %s, %s)" (List.nth a 0) (List.nth a 1) (List.nth a 2))); + ("us_on_window_once", (fun a -> Printf.sprintf "__as_onWindowOnce(%s, %s)" (List.nth a 0) (List.nth a 1))); + ("us_on_element_once", (fun a -> Printf.sprintf "__as_onElementOnce(%s, %s, %s)" (List.nth a 0) (List.nth a 1) (List.nth a 2))); + ("us_off", (fun a -> Printf.sprintf "(__as_off(%s), Unit)" (List.nth a 0))); + (* ── Timers (release = `us_clear_timeout`) ──────────────────────────── *) + ("us_set_timeout", (fun a -> Printf.sprintf "__as_setTimeout(%s, %s)" (List.nth a 0) (List.nth a 1))); + ("us_clear_timeout", (fun a -> Printf.sprintf "(__as_clearTimeout(%s), Unit)" (List.nth a 0))); + (* ── Capability probes ──────────────────────────────────────────────── *) + ("us_gm_has", (fun a -> Printf.sprintf "__as_gmHas(%s)" (List.nth a 0))); + ("us_key_valid", (fun a -> Printf.sprintf "__as_keyOk(%s)" (List.nth a 0))); + ("us_local_available", (fun _ -> "__as_localAvailable()")); + (* ── Manager storage (GM_getValue / GM_setValue / GM_deleteValue) ───── *) + ("us_gm_get", (fun a -> Printf.sprintf "__as_gmGet(%s)" (List.nth a 0))); + ("us_gm_set", (fun a -> Printf.sprintf "__as_gmSet(%s, %s)" (List.nth a 0) (List.nth a 1))); + ("us_gm_delete", (fun a -> Printf.sprintf "__as_gmDelete(%s)" (List.nth a 0))); + (* ── localStorage fallback ──────────────────────────────────────────── *) + ("us_local_get", (fun a -> Printf.sprintf "__as_localGet(%s)" (List.nth a 0))); + ("us_local_set", (fun a -> Printf.sprintf "__as_localSet(%s, %s)" (List.nth a 0) (List.nth a 1))); + ("us_local_delete", (fun a -> Printf.sprintf "__as_localDelete(%s)" (List.nth a 0))); + (* ── GM_registerMenuCommand ─────────────────────────────────────────── *) + ("us_gm_register_menu", (fun a -> Printf.sprintf "__as_gmMenu(%s, %s)" (List.nth a 0) (List.nth a 1))); + ("us_gm_unregister_menu",(fun a -> Printf.sprintf "__as_gmUnmenu(%s)" (List.nth a 0))); + (* ── GM_addStyle ────────────────────────────────────────────────────── *) + ("us_gm_add_style", (fun a -> Printf.sprintf "__as_gmStyle(%s)" (List.nth a 0))); + ("us_gm_remove_style", (fun a -> Printf.sprintf "__as_gmUnstyle(%s)" (List.nth a 0))); + (* ── GM_notification ────────────────────────────────────────────────── *) + ("us_gm_notify", (fun a -> Printf.sprintf "__as_gmNotify(%s, %s)" (List.nth a 0) (List.nth a 1))); + ("us_gm_close_notification",(fun a -> Printf.sprintf "__as_gmCloseNotify(%s)" (List.nth a 0))); +] + +let extern_table : (string, string list -> string) Hashtbl.t = + let h = Hashtbl.create 64 in + List.iter (fun (n, f) -> Hashtbl.replace h n f) extern_lowerings; + h + +let is_known_extern (name : string) : bool = Hashtbl.mem extern_table name + +(** Declarations this backend refuses, as (module-local) construct strings. + A [FnExtern] body is [extern fn] in either spelling ([TopExternFn] or a + bodiless [TopFn]). *) +let decl_unsupported (d : top_level) : string option = + let extern_name = function + | Some n when is_known_extern n -> None + | Some n -> Some (Printf.sprintf "`extern fn %s` (no userscript binding)" n) + | None -> None + in + match d with + | TopExternFn { ef_name; _ } -> extern_name (Some ef_name.name) + | TopFn fd when fd.fd_body = FnExtern -> extern_name (Some fd.fd_name.name) + | TopFn fd -> + (match fd.fd_body with + | FnExpr e -> expr_unsupported e + | FnBlock blk -> block_unsupported blk + | FnExtern -> None) + | TopConst { tc_value; _ } -> expr_unsupported tc_value + | TopImpl ib -> + List.find_map (function + | ImplFn fd -> + (match fd.fd_body with + | FnExpr e -> expr_unsupported e + | FnBlock blk -> block_unsupported blk + | FnExtern -> None) + | ImplType _ -> None) ib.ib_items + | TopType _ | TopEffect _ | TopTrait _ | TopExternType _ -> None + +let program_unsupported ~(module_name : string) (prog : program) : unsupported list = + List.filter_map (fun d -> + match decl_unsupported d with + | Some c -> Some { u_module = module_name; u_construct = c } + | None -> None) prog.prog_decls + +(* ============================================================================ + Reachability + ============================================================================ *) + +let import_path_names (imp : import_decl) : string list = + let path = match imp with + | ImportSimple (p, _) | ImportList (p, _) | ImportGlob p -> p + in + List.map (fun (id : ident) -> id.name) path + +(** Walk the module graph from [root] through everything the resolver loaded, + and report every unsupported construct with the module it came from. + + The walk happens *before* [Module_loader.flatten_imports] (which inlines + bodies and discards provenance), so a diagnostic can say "in module Bun" + rather than "somewhere in the flattened program". Modules the resolver + never loaded are reported as unresolved imports so a missing dependency + cannot silently produce a smaller script. *) +let check_reachable ~(loader : Module_loader.t) ~(root_name : string) + (root : program) : unsupported list = + let seen = Hashtbl.create 16 in + let errors = ref [] in + let report (origin : string) (prog : program) = + errors := !errors @ program_unsupported ~module_name:origin prog + in + let rec visit (origin : string) (prog : program) = + if not (Hashtbl.mem seen origin) then begin + Hashtbl.replace seen origin (); + report origin prog; + List.iter (fun imp -> + let path = import_path_names imp in + let key = String.concat "." path in + match Hashtbl.find_opt loader.Module_loader.loaded path with + | Some lm -> visit key lm.Module_loader.mod_program + | None -> ()) prog.prog_imports + end + in + visit root_name root; + !errors + +(* ============================================================================ + Emitted-artifact guard + ============================================================================ *) + +(** The module-shaped constructs a userscript must never contain. Checked on + the finished text as a belt-and-braces invariant: the emitter structurally + cannot produce them, and a future edit that reintroduces one fails the + build instead of shipping a file the manager will refuse to run. *) +let forbidden_artifact_lines : (string * (string -> bool)) list = [ + ("import declaration", fun line -> + let l = String.trim line in + String.length l >= 7 && String.sub l 0 7 = "import "); + ("export declaration", fun line -> + let l = String.trim line in + String.length l >= 7 && String.sub l 0 7 = "export "); + ("top-level await", fun line -> + let l = String.trim line in + String.length l >= 6 && String.sub l 0 6 = "await "); + ("dynamic import()", fun line -> + let l = String.trim line in + String.length l >= 8 && String.sub l 0 8 = "import(" ); + ("eval()", fun line -> + let l = String.trim line in + String.length l >= 5 && String.sub l 0 5 = "eval("); + ("new Function()", fun line -> + let l = String.trim line in + let needle = "new Function" in + let nl = String.length needle in + String.length l >= nl && String.sub l 0 nl = needle); + ("CommonJS require()", fun line -> + let l = String.trim line in + let needle = "require(" in + let nl = String.length needle in + String.length l >= nl && String.sub l 0 nl = needle); +] + +(** Scan [text] line by line for the forbidden constructs above. Only + *line-leading* forms are matched, which is precise here because the + emitter puts every statement on its own line and never starts a line + with a string literal. *) +let find_forbidden (text : string) : string option = + let lines = String.split_on_char '\n' text in + List.find_map (fun line -> + List.find_map (fun (name, pred) -> if pred line then Some name else None) + forbidden_artifact_lines) lines + +let verify_artifact (text : string) : (unit, string) result = + match find_forbidden text with + | None -> Ok () + | Some construct -> + Error (Printf.sprintf + "userscript target: emitted artifact contains a %s, which \ + Tampermonkey/Greasemonkey/Violentmonkey will not run \ + (a userscript is a single non-module file)" construct) + +(* ============================================================================ + Runtime prelude + ============================================================================ *) + +(** Always-emitted core: the Option/Result constructors the other JS-family + backends supply from their preamble, plus the result-shape builders the + host bindings return. Kept small; everything else is emitted only when a + reachable [extern fn] needs it. *) +let core_prelude = {|// ---- AffineScript userscript runtime ---------------------------------- +const Some = (value) => ({ tag: "Some", value }); +const None = { tag: "None" }; +const Ok = (value) => ({ tag: "Ok", value }); +const Err = (error) => ({ tag: "Err", error }); +const Unit = null; +const __as_concat = (a, b) => + (typeof a === "string" || typeof b === "string") ? String(a) + String(b) : a.concat(b); +const print = (s) => { console.log(String(s)); }; +const println = (s) => { console.log(String(s)); }; +// Every host access below is feature-detected: under `@grant none` the +// manager injects no GM_* globals at all, and guessing would throw. +const __as_has = (name) => { + try { return typeof globalThis[name] === "function"; } catch (_) { return false; } +}; +const __as_msg = (e) => (e && e.message ? String(e.message) : String(e)); +// `show` (a typechecker builtin, like `len`) prints strings as-is and +// everything else the way the other JS backends do. +const __as_show = (v) => (typeof v === "string" ? v : JSON.stringify(v)); +const __as_readFound = (v) => ({ found: true, value: v == null ? "" : String(v), error: "" }); +const __as_readMissing = () => ({ found: false, value: "", error: "" }); +const __as_readError = (e) => ({ found: false, value: "", error: __as_msg(e) }); +const __as_writeOk = () => ({ ok: true, error: "" }); +const __as_writeError = (e) => ({ ok: false, error: __as_msg(e) }); +const __as_handleOk = (id) => ({ ok: true, id: id, error: "" }); +const __as_handleError = (e) => ({ ok: false, id: 0, error: __as_msg(e) }); +|} + +(** Prelude sections keyed by the extern names that need them. A section is + emitted only when the program (or a module it inlines) calls one of its + externs, so an unrelated script does not pay for the GM surface. *) +let prelude_sections : (string list * string) list = [ + ([ "dom_body"; "dom_create_element"; "dom_create_text"; "dom_query"; + "dom_append"; "dom_remove"; "dom_set_attribute"; "dom_remove_attribute"; + "dom_set_text"; "dom_add_class"; "dom_remove_class"; "dom_is_null" ], + {|// ---- DOM host (returns null instead of throwing when there is no document) +const __as_doc = () => { try { return globalThis.document || null; } catch (_) { return null; } }; +const __as_domBody = () => { const d = __as_doc(); return d ? d.body : null; }; +const __as_domCreate = (tag) => { const d = __as_doc(); return d ? d.createElement(String(tag)) : null; }; +const __as_domText = (s) => { const d = __as_doc(); return d ? d.createTextNode(String(s)) : null; }; +const __as_domQuery = (sel) => { + const d = __as_doc(); + if (!d) return null; + try { return d.querySelector(String(sel)); } catch (_) { return null; } +}; +const __as_domAppend = (parent, child) => { + if (parent && child && typeof parent.appendChild === "function") parent.appendChild(child); + return 0; +}; +const __as_domRemove = (parent, child) => { + try { if (parent && child && typeof parent.removeChild === "function") parent.removeChild(child); } + catch (_) { /* already detached */ } + return 0; +}; +const __as_domAttr = (el, name, value) => { + if (el && typeof el.setAttribute === "function") el.setAttribute(String(name), String(value)); + return 0; +}; +const __as_domRemoveAttr = (el, name) => { + if (el && typeof el.removeAttribute === "function") el.removeAttribute(String(name)); + return 0; +}; +const __as_domTextSet = (node, text) => { if (node) node.textContent = String(text); return 0; }; +const __as_domClassAdd = (el, cls) => { if (el && el.classList) el.classList.add(String(cls)); return 0; }; +const __as_domClassRemove = (el, cls) => { + if (el && el.classList) el.classList.remove(String(cls)); + return 0; +}; +|}); + ([ "us_on_window"; "us_on_element"; "us_on_window_once"; "us_on_element_once"; "us_off" ], + {|// ---- Event listeners: one registry, released by handle (`us_off`) +const __as_listeners = new Map(); +let __as_listenSeq = 0; +const __as_onTarget = (target, event, handler) => { + if (!target || typeof target.addEventListener !== "function") return 0; + const name = String(event); + const wrapped = () => { + try { handler(); } catch (e) { console.error("[affinescript] listener failed", e); } + }; + target.addEventListener(name, wrapped, false); + const id = ++__as_listenSeq; + __as_listeners.set(id, { target: target, event: name, handler: wrapped }); + return id; +}; +const __as_onWindow = (event, handler) => __as_onTarget(globalThis, event, handler); +const __as_onElement = (el, event, handler) => __as_onTarget(el, event, handler); +// A *once* listener releases itself before the handler runs, so a script can +// react to a one-shot page event without owning a handle for it. +const __as_onTargetOnce = (target, event, handler) => { + if (!target || typeof target.addEventListener !== "function") return 0; + const name = String(event); + let id = 0; + const wrapped = () => { + if (id) __as_off(id); + try { handler(); } catch (e) { console.error("[affinescript] listener failed", e); } + }; + target.addEventListener(name, wrapped, false); + id = ++__as_listenSeq; + __as_listeners.set(id, { target: target, event: name, handler: wrapped }); + return id; +}; +const __as_onWindowOnce = (event, handler) => __as_onTargetOnce(globalThis, event, handler); +const __as_onElementOnce = (el, event, handler) => __as_onTargetOnce(el, event, handler); +const __as_off = (id) => { + const key = Number(id); + const entry = __as_listeners.get(key); + if (!entry) return 0; + __as_listeners.delete(key); + try { entry.target.removeEventListener(entry.event, entry.handler, false); } + catch (_) { /* target vanished with its document */ } + return 1; +}; +|}); + ([ "us_set_timeout"; "us_clear_timeout" ], + {|// ---- Timers +const __as_setTimeout = (handler, ms) => { + if (typeof globalThis.setTimeout !== "function") return 0; + return Number(globalThis.setTimeout(() => { + try { handler(); } catch (e) { console.error("[affinescript] timer failed", e); } + }, Number(ms))); +}; +const __as_clearTimeout = (id) => { + if (typeof globalThis.clearTimeout === "function") globalThis.clearTimeout(Number(id)); + return 0; +}; +|}); + ([ "us_local_available"; "us_local_get"; "us_local_set"; "us_local_delete" ], + {|// ---- localStorage fallback (the `@grant none` path). Access can throw on +// an opaque origin, so every call is wrapped and reports a typed error. +const __as_localStore = () => { try { return globalThis.localStorage || null; } catch (_) { return null; } }; +const __as_localAvailable = () => { + const store = __as_localStore(); + if (!store) return false; + try { + const probe = "__affinescript_userscript_probe__"; + store.setItem(probe, "1"); + store.removeItem(probe); + return true; + } catch (_) { return false; } +}; +const __as_localGet = (key) => { + const store = __as_localStore(); + if (!store) return __as_readError("localStorage is not available"); + try { + const value = store.getItem(String(key)); + return value === null ? __as_readMissing() : __as_readFound(value); + } catch (e) { return __as_readError(e); } +}; +const __as_localSet = (key, value) => { + const store = __as_localStore(); + if (!store) return __as_writeError("localStorage is not available"); + try { store.setItem(String(key), String(value)); return __as_writeOk(); } + catch (e) { return __as_writeError(e); } +}; +const __as_localDelete = (key) => { + const store = __as_localStore(); + if (!store) return __as_writeError("localStorage is not available"); + try { store.removeItem(String(key)); return __as_writeOk(); } + catch (e) { return __as_writeError(e); } +}; +|}); + ([ "us_key_valid" ], + {|// Setting keys are validated here so every storage backend agrees on what a +// key is: non-empty, <= 128 chars, no control characters. +const __as_keyOk = (key) => { + const k = String(key); + if (k.length === 0 || k.length > 128) return false; + for (let i = 0; i < k.length; i += 1) { + const c = k.charCodeAt(i); + if (c < 0x20 || c === 0x7f) return false; + } + return true; +}; +|}); + ([ "us_gm_has"; "us_gm_get"; "us_gm_set"; "us_gm_delete" ], + {|// ---- GM_getValue / GM_setValue / GM_deleteValue +const __as_gmHas = (suffix) => __as_has("GM_" + String(suffix)); +const __as_gmGet = (key) => { + if (!__as_has("GM_getValue")) return __as_readError("GM_getValue is not available"); + try { + const value = globalThis.GM_getValue(String(key), undefined); + if (value === undefined || value === null) return __as_readMissing(); + return __as_readFound(typeof value === "string" ? value : JSON.stringify(value)); + } catch (e) { return __as_readError(e); } +}; +const __as_gmSet = (key, value) => { + if (!__as_has("GM_setValue")) return __as_writeError("GM_setValue is not available"); + try { globalThis.GM_setValue(String(key), String(value)); return __as_writeOk(); } + catch (e) { return __as_writeError(e); } +}; +const __as_gmDelete = (key) => { + if (!__as_has("GM_deleteValue")) return __as_writeError("GM_deleteValue is not available"); + try { globalThis.GM_deleteValue(String(key)); return __as_writeOk(); } + catch (e) { return __as_writeError(e); } +}; +|}); + ([ "us_gm_register_menu"; "us_gm_unregister_menu" ], + {|// ---- GM_registerMenuCommand (released by handle via GM_unregisterMenuCommand) +const __as_menu = new Map(); +let __as_menuSeq = 0; +const __as_gmMenu = (label, handler) => { + if (!__as_has("GM_registerMenuCommand")) { + return __as_handleError("GM_registerMenuCommand is not available"); + } + try { + const id = ++__as_menuSeq; + const wrapped = () => { + try { handler(); } catch (e) { console.error("[affinescript] menu command failed", e); } + }; + const native = globalThis.GM_registerMenuCommand(String(label), wrapped); + __as_menu.set(id, { native: native === undefined ? id : native, wrapped: wrapped }); + return __as_handleOk(id); + } catch (e) { return __as_handleError(e); } +}; +const __as_gmUnmenu = (id) => { + const key = Number(id); + const entry = __as_menu.get(key); + if (!entry) return __as_writeError("unknown menu-command handle " + key); + __as_menu.delete(key); + if (!__as_has("GM_unregisterMenuCommand")) { + return __as_writeError("GM_unregisterMenuCommand is not available"); + } + try { globalThis.GM_unregisterMenuCommand(entry.native); return __as_writeOk(); } + catch (e) { return __as_writeError(e); } +}; +|}); + ([ "us_gm_add_style"; "us_gm_remove_style" ], + {|// ---- GM_addStyle (released by handle: the injected