Writing scripts
A HyperMap service can ship code with its resources, as the Web does with pages. Clients run it, sandboxed, whatever user agent they use. Scripts can stream updates, compute values, validate input, or handle controls entirely on the client.
Declaring scripts
List script URLs in a node's scripts attribute:
{
"#": { "scripts": ["/js/portfolio-summary.js"] },
"AAPL": {
"#": { "href": "/stocks/AAPL", "scripts": ["/js/price-stream.js"] },
"price": 187.42
},
"GOOG": {
"#": { "href": "/stocks/GOOG", "scripts": ["/js/price-stream.js"] },
"price": 141.80
}
}
Each node that declares a script gets its own instance of it: here, one
price stream per stock, and a portfolio summary for the whole resource. Lists
and values can declare scripts too, through their parent's children
attribute:
{
"#": { "children": { "history": { "scripts": ["/js/sparkline.js"] } } },
"history": [187.1, 187.9, 187.42]
}
Script modules
A script is an ES module that exports a function named start, called once
for each instance:
// /js/price-stream.js
export const start = (hypermap, { signal }) => {
const socket = new WebSocket(new URL('stream', hypermap.url));
socket.onmessage = (event) => {
hypermap.root.at('price').value = JSON.parse(event.data).price;
};
signal.addEventListener('abort', () => socket.close());
};
hypermap.rootis the node that declared the script.hypermap.urlis the resource's URL, to resolve relative URLs against.signalis aborted when the instance stops: when its node is removed, itsscriptschange, or the client navigates away. Clean up timers and connections with it.
The function can be async, and modules can import other modules, such as
packages from a CDN, as long as they don't need the HTML DOM.
The tree
Scripts use the same interface as pages using the polyfill:
const root = hypermap.root;
root.at('price').value; // read
root.at('price').value = 188.03; // change a value
root.set('status', 'filled'); // add or replace a child
root.delete('status'); // remove one
root.at('history').append(188.03); // lists have append, insert, prepend
hypermap.node('/history/0'); // JSON Pointer paths, from your node
Your instance reads and writes its tree synchronously. Its changes reach the client's tree, its observers and other scripts' instances moments later.
The interface is available as globals in every script: HypermapMutationObserver,
HypermapMap, HypermapValue and the rest.
Events
Scripts respond to what the client does through events, which bubble up the
tree as DOM events do, to hypermap itself.
use fires at a control the client uses. Calling preventDefault()
stops the request, so a script can handle a control itself. A control with
"control": true and no href exists just for scripts:
{
"#": { "scripts": ["/js/refresh.js"] },
"price": 187.42,
"refresh": { "#": { "control": true } }
}
// /js/refresh.js
export const start = (hypermap) => {
hypermap.root.at('refresh').addEventListener('use', async () => {
const response = await fetch(new URL('price', hypermap.url));
hypermap.root.at('price').value = (await response.json()).price;
});
};
beforeinput and input fire when the client changes a value,
before and after the change. Their value is the new value, and cancelling
beforeinput rejects it:
hypermap.root.at('quantity').addEventListener('beforeinput', (event) => {
if (!Number.isInteger(event.value) || event.value < 1) {
event.preventDefault();
}
});
Scripts can act too, with hypermap.input() and hypermap.use(), but only
the client decides to go somewhere. A script's use() of a control with an
href works only while it's handling the client's use of a control in its
subtree, once, and for a few seconds; otherwise it rejects with
NotAllowedError. So a script can send a form to a different control:
hypermap.root.at('search').addEventListener('use', (event) => {
if (hypermap.node('/search/advanced').value) {
event.preventDefault();
hypermap.use('/advancedSearch');
}
});
Changes made by scripts don't fire events. To see every change, whoever made
it, use a HypermapMutationObserver, as pages do:
new HypermapMutationObserver(() => {
const prices = [...hypermap.root.at('history').values()].map((n) => n.value);
hypermap.root.at('high').value = Math.max(...prices);
}).observe(hypermap.root.at('history'), { children: true, values: true });
Scope and isolation
An instance can only see and change the node that declared it, and everything below. That keeps scripts safe, but it also makes a node and its script a self-contained component that works wherever the node appears.
Scripts run in a sandbox:
- Each script URL runs in its own realm, with an opaque origin: no cookies, storage or other state of the client's. Instances of the same script share a realm, and so the module's state.
- Network requests carry no credentials,
Origin: nulland noReferer, and can only go to the resource's origin and the script's own. Serve scripts and anything they fetch withAccess-Control-Allow-Origin: *. - Capabilities never reach scripts, and changing a control's
hreformethodmeans its capability isn't sent. - There's no
location:import.meta.urlis the script's own URL, andhypermap.urlis the resource's. - Each instance works on its own copy of its subtree, which it reads and writes synchronously. The user agent keeps the copies in sync.
The spec has the full model.