Skip to content
Merged
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
48 changes: 48 additions & 0 deletions docs/content/docs/api-surface.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,8 @@ WebAPI.Observers WebAPI.Media WebAPI.WebAudio
WebAPI.Storage WebAPI.Messaging WebAPI.Workers
WebAPI.Crypto WebAPI.Performance WebAPI.ViewTransitions
WebAPI.DOMTree WebAPI.CSSOMCore
WebAPI.Touch WebAPI.DataTransfer WebAPI.FileEntries
WebAPI.FormData
WebAPI.History WebAPI.Location
WebAPI.SafeFetch
```
Expand Down Expand Up @@ -137,6 +139,52 @@ and Window for Window or Document methods. Existing operation features include
their required type features automatically.
An unrestricted WebAPI dependency elsewhere in the dependency graph enables all features.

## Narrow touch, clipboard and form-data features

Select `WebAPI.Touch` for Touch/TouchList and `WebAPI.FormData` for FormData and
its unboxed string/file entry values. Each depends only on basic DOM and compiles
five source modules including that dependency.

`WebAPI.DataTransfer` includes its item/list APIs, DOMTree for `setDragImage`,
and `WebAPI.FileEntries` for the existing `webkitGetAsEntry` operation.
FileEntries is the five-module legacy entry family, not the modern filesystem
handle or stream APIs. UIEvents, Fetch, and File continue to include all their
previous modules through these smaller features.

For React bindings selecting DOMTree, History, and Location, adding Touch,
DataTransfer, and FormData selects **27 WebAPI source modules**, rather than
102 with broad UIEvents and Fetch. These are source counts, not speed claims.
Basic DOM is unchanged. FileList operations still require WebAPI.File; a
DataTransfer's `files` field exposes the core file-list type and its length.

```json
{
"dependencies": [
{
"name": "@rescript/webapi",
"features": [
"WebAPI.DOMTree",
"WebAPI.History",
"WebAPI.Location",
"WebAPI.Touch",
"WebAPI.DataTransfer",
"WebAPI.FormData"
]
}
]
}
```

Use `Touch.init` for constructor options and `Touch.Direct` / `Touch.Stylus`
for its touch-type variant. Existing broad event and fetch APIs accept these
same types without casts. FormDataEntryValue remains an **unboxed** union;
it is not interchangeable with a separately defined boxed React variant.

The declared private empty FormData representation is unchanged. ReScript
13.0.0-alpha.7 still accepts an empty-record literal for this type, as it did
before this split; use the FormData constructor rather than constructing records.
The split does not claim to fix that existing compiler limitation.

## Fetch

Use `WebAPI.Fetch.fetch` for string URLs and `WebAPI.Fetch.fetchWithRequest`
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@
"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/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/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/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",
"docs": "astro dev",
"prebuild:docs": "node docs/llm.js",
"build:docs": "astro build"
Expand Down
44 changes: 31 additions & 13 deletions rescript.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,9 @@
"WebAPI.Geometry",
"Observers"
],
"WebAPI.UIEvents": ["WebAPI.DOMNodes", "WebAPI.File", "UIEvents"],
"WebAPI.Touch": ["WebAPI.DOM", "Touch"],
"WebAPI.DataTransfer": ["WebAPI.DOMTree", "WebAPI.FileEntries", "DataTransfer"],
"WebAPI.UIEvents": ["WebAPI.DOMNodes", "WebAPI.File", "WebAPI.Touch", "WebAPI.DataTransfer", "UIEvents"],
"WebAPI.Canvas": [
"WebAPI.Geometry",
"WebAPI.HTML",
Expand All @@ -62,9 +64,11 @@
"WebAPI.Workers",
"Navigator"
],
"WebAPI.File": ["WebAPI.Event", "File"],
"WebAPI.FileEntries": ["WebAPI.DOM", "FileEntries"],
"WebAPI.File": ["WebAPI.Event", "WebAPI.FileEntries", "File"],
"WebAPI.URL": ["WebAPI.DOM", "URL"],
"WebAPI.Fetch": ["WebAPI.Event", "WebAPI.File", "WebAPI.URL", "Fetch"],
"WebAPI.FormData": ["WebAPI.DOM", "FormData"],
"WebAPI.Fetch": ["WebAPI.Event", "WebAPI.File", "WebAPI.URL", "WebAPI.FormData", "Fetch"],
"WebAPI.SafeFetch": ["WebAPI.Fetch", "SafeFetch"],
"WebAPI.CSSFontLoading": ["WebAPI.Event", "CSSFontLoading"],
"WebAPI.Device": ["WebAPI.Event", "Device"],
Expand Down Expand Up @@ -350,8 +354,6 @@
"public": [
"BodyInit",
"Fetch",
"FormData",
"FormDataEntryValue",
"Headers",
"HeadersInit",
"Request",
Expand All @@ -372,10 +374,7 @@
"Blob",
"File",
"FileList",
"FileSystemDirectoryEntry",
"FileSystemDirectoryHandle",
"FileSystemDirectoryReader",
"FileSystemEntry",
"FileSystemFileHandle",
"FileSystemHandle",
"FileSystemWritableFileStream",
Expand Down Expand Up @@ -488,23 +487,42 @@
"WorkerLocation"
]
},
{
"dir": "src/touch",
"subdirs": true,
"feature": "Touch",
"public": ["Touch", "TouchList"]
},
{
"dir": "src/form-data",
"subdirs": true,
"feature": "FormData",
"public": ["FormData", "FormDataEntryValue"]
},
{
"dir": "src/file-entries",
"subdirs": true,
"feature": "FileEntries",
"public": ["FileSystemEntry", "FileSystemDirectoryEntry", "FileSystemDirectoryReader"]
},
{
"dir": "src/data-transfer",
"subdirs": true,
"feature": "DataTransfer",
"public": ["DataTransfer", "DataTransferItem", "DataTransferItemList"]
},
{
"dir": "src/ui-events",
"subdirs": true,
"feature": "UIEvents",
"public": [
"CompositionEvent",
"DataTransfer",
"DataTransferItem",
"DataTransferItemList",
"FocusEvent",
"InputEvent",
"KeyboardEvent",
"MouseEvent",
"PointerEvent",
"Touch",
"TouchEvent",
"TouchList",
"UIEvent",
"WheelEvent"
]
Expand Down
21 changes: 21 additions & 0 deletions scripts/check-consumer.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import os from "node:os";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { validateReleaseArtifact } from "./validate-release-artifact.mjs";
import { dataFeatureConsumers } from "./data-feature-consumers.mjs";

const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const packageJson = JSON.parse(readFileSync(path.join(repoRoot, "package.json"), "utf8"));
Expand Down Expand Up @@ -193,6 +194,14 @@ const checkConsumers = async () => {

if (!negativeOnly) {
const scenarios = [
...dataFeatureConsumers.map((consumer) => ({
...consumer,
fixture: `scripts/${consumer.fixture}`,
expectedFailure:
consumer.missingModule === undefined
? null
: `The module or file WebAPI.${consumer.missingModule} can\'t be found.`,
})),
{ name: "default", fixture: "scripts/consumer-default.res", features: null },
{
name: "concrete public types",
Expand Down Expand Up @@ -240,6 +249,18 @@ const checkConsumers = async () => {
projectDirectory,
);
console.log(`[ok] packed consumer runtime using ReScript ${compilerVersion}`);
writeProject(projectDirectory, "scripts/consumer-data-form-runtime.res", ["WebAPI.FormData"]);
compile(projectDirectory);
runCommand(
process.execPath,
[
"--input-type=module",
"--eval",
`await import(${JSON.stringify(pathToFileURL(path.join(projectDirectory, "src/Consumer.js")).href)} + "?formdata")`,
],
projectDirectory,
);
console.log("[ok] packed narrow FormData runtime");
}

const negativeCases = JSON.parse(
Expand Down
31 changes: 30 additions & 1 deletion scripts/check-features.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
mkdtempSync,
mkdirSync,
readFileSync,
readdirSync,
rmSync,
statSync,
symlinkSync,
Expand All @@ -14,6 +15,8 @@ import path from "node:path";
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";

import { dataFeatureConsumers } from "./data-feature-consumers.mjs";

const scriptPath = fileURLToPath(import.meta.url);
const repoRoot = path.resolve(path.dirname(scriptPath), "..");
const configPath = path.join(repoRoot, "rescript.json");
Expand Down Expand Up @@ -42,6 +45,10 @@ const expectedFeatureOwners = new Map([
["WebAPI.Fetch", "Fetch"],
["WebAPI.SafeFetch", "SafeFetch"],
["WebAPI.UIEvents", "UIEvents"],
["WebAPI.Touch", "Touch"],
["WebAPI.FormData", "FormData"],
["WebAPI.DataTransfer", "DataTransfer"],
["WebAPI.FileEntries", "FileEntries"],
["WebAPI.Observers", "Observers"],
["WebAPI.Media", "Media"],
["WebAPI.WebAudio", "WebAudio"],
Expand Down Expand Up @@ -304,7 +311,14 @@ export const isMissingModuleDiagnostic = (output, moduleName) =>
export const isMissingSafeFetchDiagnostic = (output) =>
isMissingModuleDiagnostic(output, "SafeFetch");

const runConsumerCheck = ({ name, features, fixture, shouldCompile, missingModule }) => {
const runConsumerCheck = ({
name,
features,
fixture,
shouldCompile,
missingModule,
expectedSources,
}) => {
const directory = mkdtempSync(path.join(os.tmpdir(), "webapi-feature-consumer-"));
try {
prepareConsumer(directory, features, fixture);
Expand All @@ -313,6 +327,17 @@ const runConsumerCheck = ({ name, features, fixture, shouldCompile, missingModul
encoding: "utf8",
});
const output = `${result.stdout ?? ""}\n${result.stderr ?? ""}`;
if (result.status === 0 && expectedSources !== undefined) {
const sourceArtifacts = path.join(directory, "node_modules/@rescript/webapi/lib/bs/src");
const count = readdirSync(sourceArtifacts, { recursive: true }).filter((file) =>
file.endsWith(".cmj"),
).length;
if (count !== expectedSources)
return {
_tag: "Failure",
message: `${name}: expected ${expectedSources} sources, got ${count}`,
};
}
const passed = shouldCompile
? result.status === 0
: result.status !== null &&
Expand Down Expand Up @@ -371,6 +396,10 @@ if (process.argv[1] !== undefined && path.resolve(process.argv[1]) === scriptPat
}

for (const consumer of [
...dataFeatureConsumers.map((consumer) => ({
...consumer,
shouldCompile: consumer.missingModule === undefined,
})),
{
name: "SafeFetch consumer",
features: ["WebAPI.SafeFetch"],
Expand Down
17 changes: 17 additions & 0 deletions scripts/check-features.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,20 @@ test("does not accept an unrelated compiler failure mentioning SafeFetch", () =>
);
assert.equal(isMissingSafeFetchDiagnostic("SafeFetch consumer has a type error."), false);
});

test("narrow data features preserve broad feature umbrellas", () => {
assert.deepEqual(validateConfig(config), []);
assert.deepEqual(config.features["WebAPI.Touch"], ["WebAPI.DOM", "Touch"]);
assert.deepEqual(config.features["WebAPI.FormData"], ["WebAPI.DOM", "FormData"]);
assert.deepEqual(config.features["WebAPI.FileEntries"], ["WebAPI.DOM", "FileEntries"]);
assert.deepEqual(config.features["WebAPI.DataTransfer"], [
"WebAPI.DOMTree",
"WebAPI.FileEntries",
"DataTransfer",
]);
assert.ok(config.features["WebAPI.UIEvents"].includes("WebAPI.Touch"));
assert.ok(config.features["WebAPI.UIEvents"].includes("WebAPI.DataTransfer"));
assert.ok(config.features["WebAPI.UIEvents"].includes("WebAPI.File"));
assert.ok(config.features["WebAPI.File"].includes("WebAPI.FileEntries"));
assert.ok(config.features["WebAPI.Fetch"].includes("WebAPI.FormData"));
});
6 changes: 6 additions & 0 deletions scripts/consumer-data-combined.res
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
let data = (): WebAPI.DataTransfer.t => WebAPI.DataTransfer.make()
let touch = (list: WebAPI.TouchList.t) => list->WebAPI.TouchList.item(0)
let form = (): WebAPI.FormData.t => WebAPI.FormData.make()
let location = (location: WebAPI.Location.t) => location.pathname
let history = (history: WebAPI.History.t) => history.state
let element = (element: WebAPI.DOMTree.element) => element
1 change: 1 addition & 0 deletions scripts/consumer-data-disabled-fetch.res
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
let fetch = WebAPI.Fetch.fetch
1 change: 1 addition & 0 deletions scripts/consumer-data-disabled-filelist.res
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
let item = WebAPI.FileList.item
1 change: 1 addition & 0 deletions scripts/consumer-data-disabled-inputevent.res
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
let make = WebAPI.InputEvent.make
1 change: 1 addition & 0 deletions scripts/consumer-data-disabled-readablestream.res
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
let make = WebAPI.ReadableStream.make
1 change: 1 addition & 0 deletions scripts/consumer-data-disabled-touchevent.res
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
let make = WebAPI.TouchEvent.make
1 change: 1 addition & 0 deletions scripts/consumer-data-disabled-window.res
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
let location = WebAPI.Window.location
5 changes: 5 additions & 0 deletions scripts/consumer-data-entries.res
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
let getParent = (entry: WebAPI.FileSystemEntry.t) =>
entry->WebAPI.FileSystemEntry.getParent(~successCallback=parent => ignore(parent.name))
let read = (directory: WebAPI.FileSystemDirectoryEntry.t) =>
directory->WebAPI.FileSystemDirectoryEntry.createReader
->WebAPI.FileSystemDirectoryReader.readEntries(~successCallback=ignore)
22 changes: 22 additions & 0 deletions scripts/consumer-data-form-runtime.res
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
open WebAPI
@new external blob: array<string> => DOM.blob = "Blob"
let form = FormData.make()
form->FormData.append(~name="text", ~value="hello")
form->FormData.appendBlob(~name="file", ~blobValue=blob(["contents"]), ~filename="sample.txt")
assert(form->FormData.get("missing")->Null.toOption == None)

assert(switch form->FormData.get("text")->Null.toOption {
| Some(String("hello")) => true
| _ => false
})

assert(switch form->FormData.get("file")->Null.toOption {
| Some(File(file)) => file.name == "sample.txt" && file.size == 8
| _ => false
})

let values = form->FormData.getAll("text")
assert(values->Array.length == 1)
let entry: FormDataEntryValue.t = String("unboxed")
let isUnboxed = (_value: FormDataEntryValue.t): bool => %raw(`_value === "unboxed"`)
assert(isUnboxed(entry))
12 changes: 12 additions & 0 deletions scripts/consumer-data-form.res
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
let make = (): WebAPI.FormData.t => WebAPI.FormData.make()
let appendBlob = (form: WebAPI.FormData.t, blob: WebAPI.DOM.blob) =>
form->WebAPI.FormData.appendBlob(~name="file", ~blobValue=blob, ~filename="file.txt")
let entry = (value: WebAPI.FormDataEntryValue.t) =>
switch value {
| String(text) => text
| File(file) => file.name
}
let get = (form: WebAPI.FormData.t): Null.t<WebAPI.FormDataEntryValue.t> =>
form->WebAPI.FormData.get("name")
let entries = (form: WebAPI.FormData.t): iterable<(string, WebAPI.FormDataEntryValue.t)> =>
form->WebAPI.FormData.entries
5 changes: 5 additions & 0 deletions scripts/consumer-data-touch.res
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
let make = (target: WebAPI.DOM.eventTarget): WebAPI.Touch.t =>
WebAPI.Touch.make({identifier: 1, target, touchType: WebAPI.Touch.Direct})
let item = (list: WebAPI.TouchList.t): Null.t<WebAPI.Touch.t> =>
list->WebAPI.TouchList.item(0)
let target = (touch: WebAPI.Touch.t): WebAPI.DOM.eventTarget => touch.target
13 changes: 13 additions & 0 deletions scripts/consumer-data-transfer.res
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
let make = (): WebAPI.DataTransfer.t => WebAPI.DataTransfer.make()
let addFile = (data: WebAPI.DataTransfer.t, file: WebAPI.DOM.file) =>
data.items->WebAPI.DataTransferItemList.addFile(file)
let getFile = (item: WebAPI.DataTransferItem.t): Null.t<WebAPI.DOM.file> =>
item->WebAPI.DataTransferItem.getAsFile
let legacyEntry = (item: WebAPI.DataTransferItem.t): Null.t<WebAPI.FileSystemEntry.t> =>
item->WebAPI.DataTransferItem.webkitGetAsEntry
let dragImage = (data: WebAPI.DataTransfer.t, element: WebAPI.DOMTree.element) =>
data->WebAPI.DataTransfer.setDragImage(~image=element, ~x=0, ~y=0)
let mutate = (data: WebAPI.DataTransfer.t) => {
data.dropEffect = "copy"
data.effectAllowed = "copyMove"
}
Loading
Loading