Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,31 @@ versioning and publication.
browser's successful result is `undefined`, not a database.
- `WebAPI.Notification.t` no longer contains a static permission field. Read that value through
`WebAPI.Notification.permission`.
- Native browser-instance record construction and record-update copies are being restricted with
private record views. Reads remain direct; writes to protected mutable properties require typed
setters such as `canvas->WebAPI.HTMLCanvasElement.setWidth(640)` to avoid warning 111. ReScript
`13.0.0-alpha.7` rejects ordinary explicit coercions (`:>`) into private records, including
structural upcasts between distinct private-record types; use supported typed conversion helpers.
Options, initializers, callback dictionaries, and plain data records remain public. This is a
compile-time restriction, not a security boundary against unsafe casts or JavaScript fabrication.
- Native `asNode`/`asBlob`/event/audio upcasts now require concrete native receivers. Use the
helpers on concrete modules; public `Impl` functors no longer export unrestricted identity casts.
Generic functor method receivers are not yet constrained; that separate boundary is tracked in
[#417](https://github.com/rescript-lang/experimental-rescript-webapi/issues/417).
- `FillStyle.toCanvasGradient`/`toCanvasPattern` and
`IntersectionObserverRoot.toElement`/`toDocument` now return checked options. The checks recognize
instances in the current JavaScript realm; alternatively use each module's `decode` function.
- Stream readers/writers and rendering-context placeholders have abstract identities rather than
`unknown`. Performance entry lists are arrays of native entries. `NodeFilter.t` is a public
`{acceptNode: node => int}` callback dictionary rather than a private empty record.
- `MessageEvent.make` returns a nullable payload (`t<Null.t<'t>>`) because omitted data defaults
to null. `Navigator.requestMediaKeySystemAccess` returns the concrete native access type rather
than a caller-selected type. Public media, DOM-node, and geometry setters preserve supported
writes without private-field warnings.
- Use `DOMImplementation.documentTypeAsNode` and `xmlDocumentAsDocument` for inherited DOM
operations, `HTMLOptionsCollection.asHTMLCollection` for typed collection access, and
`Worklet.fromAudioWorklet` for inherited worklet operations. `HTMLOptionsCollection.setLength`
preserves the native writable-length behavior.

For the intended installation, compiler range, runtime/browser checks, and known limitations,
see the [project status](https://rescript-lang.github.io/experimental-rescript-webapi/project-status/)
Expand Down
41 changes: 1 addition & 40 deletions docs/components/signature.astro
Original file line number Diff line number Diff line change
@@ -1,47 +1,8 @@
---
import SignatureItem from "./signatureItem.astro";


function tokenize(input) {
// Split by special characters while keeping them
const regex = /([<>,])/g;
return input
.split(regex)
.map((token) => token.trim())
.filter(Boolean);
}

function parseTokens(tokens) {
let index = 0;

const parseNode = () => {
const path = tokens[index++]; // Read the current token and increment index
let genericTypeParameters = [];

if (tokens[index] === "<") {
// Check for generics
index++; // Consume "<"
while (tokens[index] !== ">") {
genericTypeParameters.push(parseNode());
if (tokens[index] === ",") index++; // Consume ","
}
index++; // Consume ">"
}

return { path, genericTypeParameters };
};

return parseNode();
}

function parse(input) {
const tokens = tokenize(input);
return parseTokens(tokens);
}


const { signature, typesInOwnModule } = Astro.props;
const tree = parse(signature);
const tree = { kind: "rendered", signature };
---

<div class="signature">
Expand Down
47 changes: 47 additions & 0 deletions docs/content/docs/contributing/api-modelling.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,53 @@ Keep null and empty states explicit when they are part of the browser contract.
for nullable results and variants for meaningful empty values; do not replace native results
with invented defaults or unchecked casts.

## Native instance types

Model browser-owned objects as private records at both the backing declaration and every public
record view. Keep direct field reads when useful, but expose typed native setters for writable
properties instead of asking callers to mutate a private field:

```ReScript
let canvas = WebAPI.Document.createElement(document, "canvas")->WebAPI.HTMLCanvasElement.classify
switch canvas {
| Some(canvas) =>
let width = canvas.width
canvas->WebAPI.HTMLCanvasElement.setWidth(width + 1)
| None => ()
}
```

Use names such as `setWidth`, preserve the JavaScript property name and existing field type, and
keep throwing behavior on setters whose native operation can throw. Put shared properties on the
existing `Impl` chain so derived interfaces reuse their base setters. Do not make initializer
dictionaries, option records, callback data, or ordinary result records private merely because they
are exported beside a native interface.

For `CSSStyleDeclaration`, keep direct reads but use its existing `setProperty` operation for
individual declarations, using CSS property names such as `"background-color"` rather than the
camel-cased IDL field name. Both `float` and `cssFloat` address the `"float"` CSS property.
Replacing the complete declaration block uses `CSSStyleDeclaration.setCssText`; do not route that
operation through `setProperty`.

```ReScript
style->WebAPI.CSSStyleDeclaration.setProperty(~property="background-color", ~value="red")
style->WebAPI.CSSStyleDeclaration.setProperty(~property="float", ~value="left")
style->WebAPI.CSSStyleDeclaration.setCssText("background-color: blue")
```

ReScript `13.0.0-alpha.7` rejects ordinary explicit coercions (`:>`) into private records, including
structural upcasts between distinct private-record types. Use the existing typed conversion helpers
for supported native derived-to-base conversions. Field reads remain available; callers must use
typed setters for protected writes to avoid warning 111. Dictionaries and caller-owned data records
remain public. Private records are a compile-time restriction, not a security boundary against
unsafe casts or JavaScript fabrication.

Do not put unconstrained native identity conversions in public `Impl(T)` functors. Keep upcast
helpers on the concrete modules with a concrete native receiver type, including inherited helpers.
Use checked narrowing for union projections instead of `%identity` downcasts. The inventory also
tracks broader callback, generic-method, and unknown-result modeling gaps; private records alone
do not make those bindings sound.

## Verification

Add compile-only, Node runtime, or browser runtime fixtures according to the API being modeled.
Expand Down
8 changes: 4 additions & 4 deletions docs/content/docs/contributing/testing.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -77,10 +77,10 @@ The development compiler and the exact version exercised by this check are ReScr
`13.0.0-alpha.7`. The peer range `>=13.0.0-alpha.7 <13.0.0` admits later `13.0.0` prereleases;
it does not claim support for earlier compilers or stable `13.0.0`.

The consumer checks reject installation with ReScript 12 and the former alpha.5 baseline.
They also verify that a public record shape cannot be coerced into the private native Response
type, while native construction, field reads, outward coercion to a public shape, and the
supported File-to-Blob conversion still work.
The consumer checks reject installation with ReScript 12 and verify private-record behavior on
alpha.7: ordinary coercions into private records, including structural upcasts between distinct
private-record types, are rejected. Native construction, field reads, outward coercion to a public
shape, and supported typed conversions such as File-to-Blob remain available.

## Why add tests?

Expand Down
33 changes: 30 additions & 3 deletions docs/content/docs/project-status.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,36 @@ implementation modules and internal type-holder modules are not part of that pub
Bindings are maintained and corrected by hand as well as generated; the generator is not a
reproducible source of truth for every checked-in binding.

Approximately 80 bindings still carry private-record TODOs; a blanket conversion is deferred
because the current compiler reports mutation warning 111. Generator reproducibility is also
follow-up work, not an alpha release gate.
The private-record migration in [#404](https://github.com/rescript-lang/experimental-rescript-webapi/pull/404)
has a bounded contract: protected native records reject ordinary literals, record-update copies,
and structural coercions into those types. Instances retain direct reads and use typed setters
for audited supported writes; caller-owned options and initializer records remain constructible.
ReScript `13.0.0-alpha.7` rejects ordinary explicit coercions
(`:>`) into private records, including structural upcasts between distinct private-record types;
supported native conversions use concrete-receiver helpers rather than unrestricted `Impl`
identity conversions. Dictionaries remain public, including the caller-implemented `NodeFilter`
callback interface. This compile-time restriction is not a security boundary against JavaScript or
unsafe casts. Generator reproducibility remains separate follow-up work.

Stream readers/writers and the rendering-context placeholder types now have abstract native
identities. Performance entry lists are ordinary arrays containing private native entries, not
branded containers. Checked Canvas style and intersection-root conversions return options.

This contract does not establish package-wide native-instance soundness. In particular, generic
binding-functor instantiation remains outside the construction guarantee: arbitrary receivers can
still yield mis-typed native results through native-returning methods. Enforcing that public
boundary is tracked separately in
[#417](https://github.com/rescript-lang/experimental-rescript-webapi/issues/417), not a prerequisite
for the narrower record construction/write migration.

Event listeners also allow caller-selected payload types unrelated to the event descriptor.
Unknown native unions and result positions remain in canvas owners, stylesheet owner nodes,
IndexedDB sources/cursors, DOM label lists, media providers, message sources, and generic crypto
results. Those broader typing concerns remain follow-up work under
[#403](https://github.com/rescript-lang/experimental-rescript-webapi/issues/403). Input placeholders
such as stream source/sink/strategy types, request information, IDB keys, and algorithm identifiers
also remain separate modeling work. The checked native-instance inventory records these gaps explicitly;
passing its declaration checks is not proof that every exported binding is sound.

CI uses Node 26 for ReScript compilation and Node runtime fixtures. Its Playwright suite runs
compiled Chromium regressions for the confirmed alpha contracts, including typed byte/audio
Expand Down
21 changes: 20 additions & 1 deletion docs/signatureParts.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,25 @@ const text = (value) => ({ text: value });
const separated = (items, render) =>
items.flatMap((item, index) => [...(index === 0 ? [] : [text(", ")]), ...render(item)]);

// Field signatures are text, not structured compiler type nodes. Preserve their syntax
// (especially function arrows) and attach links only to complete identifier paths.
const renderedParts = (signature) => {
const tokens = [
...signature.matchAll(/"(?:\\.|[^"\\])*"|'[\w]+|#[\w]+|[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*/g),
];
if (tokens.length === 0) return [text(signature)];
return tokens.flatMap((token, index) => {
const previous = tokens[index - 1];
const start = previous ? previous.index + previous[0].length : 0;
const value = token[0];
return [
text(signature.slice(start, token.index)),
/^[A-Za-z_]/.test(value) ? { text: value, path: value } : text(value),
...(index === tokens.length - 1 ? [text(signature.slice(token.index + value.length))] : []),
];
});
};

export const parameterParts = (parameter) => [
...(parameter.label ? [text(`~${parameter.label}: `)] : []),
...signatureParts(parameter.type),
Expand All @@ -23,7 +42,7 @@ export const signatureParts = (item) => {
case "variable":
return [text(`'${item.name}`)];
case "rendered":
return [text(item.signature)];
return renderedParts(item.signature);
case "tuple":
return [text("("), ...separated(item.elements, signatureParts), text(")")];
case "function":
Expand Down
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,12 @@
"test:browser": "rescript clean && npm run build && playwright test",
"test:negative": "node scripts/check-consumer.mjs --negative-only",
"build": "rescript",
"check:features": "node --test scripts/check-features.test.mjs && node scripts/check-features.mjs",
"check:features": "node --test scripts/check-features.test.mjs scripts/check-native-instance-inventory.test.mjs && node scripts/check-features.mjs && node scripts/check-native-instance-inventory.mjs",
"check:consumer": "node scripts/check-consumer.mjs",
"check:release": "node --test scripts/validate-release-artifact.test.mjs scripts/check-release.test.mjs && node scripts/check-release.mjs",
"check:docs-links": "node --test scripts/check-doc-links.test.mjs scripts/check-doc-type-links.test.mjs && node scripts/check-doc-links.mjs",
"format": "rescript format && oxfmt ./tests/index.js ./tests/fixtures.json ./tests/browser/*.mjs ./scripts/negative-fixtures.json ./scripts/validate-release-artifact.mjs ./scripts/validate-release-artifact.test.mjs ./playwright.config.mjs ./astro.config.mjs ./scripts/check-consumer.mjs ./scripts/check-release.mjs ./scripts/check-release.test.mjs ./scripts/check-features.mjs ./scripts/check-features.test.mjs ./scripts/data-feature-consumers.mjs ./scripts/check-doc-links.mjs ./scripts/check-doc-links.test.mjs ./scripts/check-doc-type-links.test.mjs ./package.json ./README.md ./CHANGELOG.md ./docs && prettier --write .github/workflows/*.yml ./docs/pages",
"format:check": "rescript format --check && oxfmt ./tests/index.js ./tests/fixtures.json ./tests/browser/*.mjs ./scripts/negative-fixtures.json ./scripts/validate-release-artifact.mjs ./scripts/validate-release-artifact.test.mjs ./playwright.config.mjs ./astro.config.mjs ./scripts/check-consumer.mjs ./scripts/check-release.mjs ./scripts/check-release.test.mjs ./scripts/check-features.mjs ./scripts/check-features.test.mjs ./scripts/data-feature-consumers.mjs ./scripts/check-doc-links.mjs ./scripts/check-doc-links.test.mjs ./scripts/check-doc-type-links.test.mjs ./package.json ./README.md ./CHANGELOG.md ./docs --check && prettier --check .github/workflows/*.yml ./docs/pages",
"format": "rescript format && oxfmt ./tests/index.js ./tests/fixtures.json ./tests/browser/*.mjs ./scripts/negative-fixtures.json ./scripts/native-instance-inventory.json ./scripts/check-native-instance-inventory*.mjs ./scripts/validate-release-artifact.mjs ./scripts/validate-release-artifact.test.mjs ./playwright.config.mjs ./astro.config.mjs ./scripts/check-consumer.mjs ./scripts/check-release.mjs ./scripts/check-release.test.mjs ./scripts/check-features.mjs ./scripts/check-features.test.mjs ./scripts/data-feature-consumers.mjs ./scripts/check-doc-links.mjs ./scripts/check-doc-links.test.mjs ./scripts/check-doc-type-links.test.mjs ./package.json ./README.md ./CHANGELOG.md ./docs && prettier --write .github/workflows/*.yml ./docs/pages",
"format:check": "rescript format --check && oxfmt ./tests/index.js ./tests/fixtures.json ./tests/browser/*.mjs ./scripts/negative-fixtures.json ./scripts/native-instance-inventory.json ./scripts/check-native-instance-inventory*.mjs ./scripts/validate-release-artifact.mjs ./scripts/validate-release-artifact.test.mjs ./playwright.config.mjs ./astro.config.mjs ./scripts/check-consumer.mjs ./scripts/check-release.mjs ./scripts/check-release.test.mjs ./scripts/check-features.mjs ./scripts/check-features.test.mjs ./scripts/data-feature-consumers.mjs ./scripts/check-doc-links.mjs ./scripts/check-doc-links.test.mjs ./scripts/check-doc-type-links.test.mjs ./package.json ./README.md ./CHANGELOG.md ./docs --check && prettier --check .github/workflows/*.yml ./docs/pages",
"docs": "astro dev",
"prebuild:docs": "node docs/llm.js",
"build:docs": "astro build"
Expand Down
3 changes: 3 additions & 0 deletions rescript.json
Original file line number Diff line number Diff line change
Expand Up @@ -207,8 +207,11 @@
"ImageBitmapRenderingContext",
"ImageData",
"OffscreenCanvas",
"OffscreenCanvasRenderingContext2D",
"Path2D",
"VideoColorSpace",
"WebGLRenderingContext",
"WebGL2RenderingContext",
"VideoFrame"
]
},
Expand Down
41 changes: 40 additions & 1 deletion scripts/check-consumer.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ const writeProject = (directory, sourceFile, features) => {
dependencies:
features === null ? ["@rescript/webapi"] : [{ name: "@rescript/webapi", features }],
"experimental-features": { LetUnwrap: true },
warnings: { error: "+8" },
warnings: { error: "+8+111" },
"package-specs": { module: "esmodule", "in-source": true },
},
null,
Expand All @@ -81,6 +81,29 @@ const writeProject = (directory, sourceFile, features) => {
const compilerCli = (directory) =>
path.join(directory, "node_modules", "rescript", "cli", "rescript.js");

const verifyPrivateRecordRelaxation = (directory) => {
const backingFile = path.join(
directory,
"node_modules",
"@rescript",
"webapi",
"src/core/DOM.res",
);
const source = readFileSync(backingFile, "utf8");
const privateDeclaration = "type domTokenList = private {";
if (source.split(privateDeclaration).length !== 2) {
throw new Error("Expected exactly one private DOM.domTokenList backing declaration.");
}
writeFileSync(backingFile, source.replace(privateDeclaration, "type domTokenList = {"));
writeProject(directory, "scripts/fixtures/negative/DOMTokenListBackingRouteIsPrivate.res", [
"WebAPI.DOM",
]);
compile(directory);
console.log(
"[ok] DOM backing-route fixture compiles when only its privacy restriction is relaxed",
);
};

const compile = (directory, expectedFailure = null) => {
const cli = compilerCli(directory);
const clean = spawnSync(process.execPath, [cli, "clean"], { cwd: directory });
Expand Down Expand Up @@ -208,6 +231,21 @@ const checkConsumers = async () => {
fixture: "scripts/consumer-concrete-types.res",
features: null,
},
{
name: "native setters and constructible request options",
fixture: "scripts/consumer-native-setters.res",
features: null,
},
{
name: "public media, DOM, and geometry setters",
fixture: "scripts/consumer-native-setter-gaps.res",
features: null,
},
{
name: "concrete native upcasts and handle identities",
fixture: "scripts/consumer-native-identities.res",
features: null,
},
{
name: "Fetch-only",
fixture: "scripts/consumer-fetch.res",
Expand Down Expand Up @@ -274,6 +312,7 @@ const checkConsumers = async () => {
compile(projectDirectory, negativeCase.expectedDiagnostic);
console.log(`[ok] expected rejection: ${negativeCase.name}`);
}
verifyPrivateRecordRelaxation(projectDirectory);
console.log(`[ok] tarball contents (${packagedFiles.length} files)`);
} finally {
rmSync(tempDirectory, { recursive: true, force: true });
Expand Down
11 changes: 11 additions & 0 deletions scripts/check-doc-type-links.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,17 @@ test("retains support for parsed record field signatures", () => {
);
});

test("preserves callback field syntax without linking the arrow as part of a type", () => {
const signature = "(WebAPI.DOMTree.node, ~value: option<'t>) => array<WebAPI.Element.t>";
const parts = signatureParts({ kind: "rendered", signature });
assert.equal(signatureText(parts), signature);
assert.deepEqual(
parts.filter((part) => part.path?.startsWith("WebAPI.")).map((part) => part.path),
["WebAPI.DOMTree.node", "WebAPI.Element.t"],
);
assert.ok(!parts.some((part) => part.path === "t"));
});

test("fails visibly on an unsupported compiler signature kind", () => {
assert.throws(
() => signatureParts({ kind: "unexpected" }),
Expand Down
Loading
Loading