JavaScript in schemas

JavaScript in schemas lets you embed ES module source in a property's default, @read, @write, @validate, or @computed, and in a Method's implementation. The server evaluates the module on every write or read in an isolated context, sharing the request budget with Sessel. The same source is also browser-runnable, so a binding may also execute client-side under the future browser-side schema runtime.

When to reach for it

Reach for a JavaScript binding when the logic is more naturally expressed as a small ES module than a Sessel expression — for example, when reusing a familiar JavaScript idiom for string normalisation, when the same source needs to run unchanged on the server and (later) in the browser, or when the binding needs to construct schema instances via the pagelove:schema import.

JavaScript authors the default slot, the three pipeline slots (@read, @write, @validate), the schema-level @validate slot, computed properties (@computed), and method bodies (implementation). Other expression slots accept Sessel only at present: constraints, mutation handlers, and e:-attribute expression bindings in SSPI templates. A JavaScript module can also be the body of a QUERY request (see QUERY). Group constraints and shape constraints are not expressions in either language — they are declarative Microdata and CSS selector forms.

Shape

A JavaScript binding is a typed Microdata item with itemtype="https://pagelove.org/JavaScript/Module" placed in a property's default, @read, @write, or @validate slot. Its source child carries the ES module text, conventionally inside a <script type="module"> so the same string is also browser-runnable.

<div itemprop="default" itemscope itemtype="https://pagelove.org/JavaScript/Module">
  <script itemprop="source" type="module">
    export default () => String(Math.floor(100 + Math.random() * 500));
  </script>
</div>

The dispatcher selects the language by the itemtype URL of the typed item, never by <script type>. The <script> tag is a browser-execution affordance, not a server-data signal.

The export default contract

The module must have a default export, and that export must be a function — arrow or function form. The server:

  1. Evaluates the module in a fresh context.
  2. Reads the default export off the module namespace.
  3. Verifies it is a function.
  4. Calls it with the receiver and arguments for the specific slot listed below. The in-progress instance plus context contract belongs to default; it is not the argument contract for every hook.
  5. Converts the return value back to a dombase value.

ES modules always run in strict mode, so arrow functions do not bind their own this. A binding that needs to read this must use a function form:

export default function() { return this.firstname; }

A module with no default export, or a default export that is not a function, fails with the shape variant.

Slot semantics

Slot First argument / this Return value When it fires
default this is the in-progress instance; first positional argument is context The default value to inject when the property is absent At write time, before validation
@read First argument is the property value flowing through the chain The transformed value, passed to the next stage After fetch from storage, before the response is sent
@write First argument is the property value flowing through the chain The transformed value, passed to the next stage (throw an HTTPResponse to refuse the write with a status and message of your choosing — see below) After initial schema validation and before storage in the tested whole-document application PUT; do not rely on this transform to repair an input that validation rejects
@validate (property-level) First argument (and this) is the property's first value after defaults: a string, an object for a nested item, or undefined when the property is absent Truthy to accept; falsy or thrown to reject (throw an HTTPResponse to choose the status, message, body and headers the client sees — see below) On every HTTP write that stores the item (PUT, POST, and writes with Range: selector=), after defaults, cardinality and type checks. Never on a WebDAV write
@validate (schema-level) this is the instance, as an object of its properties; the positional context argument is undefined for this slot Truthy to accept; falsy or thrown to reject On the same writes, after cardinality, type and property-level @validate have all passed, and before group constraints

Checked ordering and context

In the live whole-document PUT check, a JavaScript lowercase-only validator rejected uppercase input with 422 before a JavaScript lowercase @write could repair it. The lowercase control was accepted. In a separate check, lowercase input passed the validator and an uppercase @write result was stored as uppercase. Do not assume the transformed result automatically runs through that same validator again. These checks do not establish the ordering for every request shape or hook combination.

A separate scalar @read probe that used document.createElement() failed with 503 and “document is not defined”; the same DOM construction worked in a j: composition binding. Available globals therefore depend on the calling context as well as the JavaScript language. See DOM availability.

Explaining why a value was rejected

A property-level @validate that simply returns a falsy value rejects the write, but the client is told only which property failed — not why. To give a reason, throw an HTTP response instead:

if (!allowed.includes(hostname)) {
  throw {
    schema_url: "https://pagelove.org/HTTPResponse",
    status: 422,
    message: `${hostname} is not on this platform`,
  };
}
return true;

The write still fails; the difference is that the status, message, body and headers are yours rather than a generic violation. With no message and no body, the body carries the status's standard reason phrase. A header that frames the message or reports its cost, such as Content-Length, is never sent; the Trigger page lists them. This is the same thing a Trigger or a Processor can do.

The status must be an error status, 400 to 599. If you leave the status out, or give any other status such as 200, the write is refused with the ordinary 422 violation instead, as if the validator had returned false. A refused write is never reported as a success.

Throw a plain object, not new HTTPResponse(...). HTTPResponse is not a JavaScript global — the only global the sandbox defines is DOMException, and schema classes reach JavaScript through a pagelove-schema: import rather than being predeclared. What the platform recognises is the shape: any thrown object carrying schema_url (or itemtype) set to https://pagelove.org/HTTPResponse, with status and message. The new HTTPResponse(status, message) form you will see elsewhere in these docs is Sessel's, and it does not carry over to JavaScript — written that way here it raises a ReferenceError, which is an ordinary failure, so you get the generic rejection instead of the status you asked for.

Throwing anything else — a mistake in your code, say — is an ordinary failure and still produces the standard rejection, so a bug in a validator cannot choose what the client sees.

A @write slot can refuse a write the same way. It is the natural place for a rule that needs to see more than one value at once, or that transforms and rejects in the same pass:

export default function(value) {
  if (!/^[A-Z]{1,2}[0-9]/.test(value)) {
    throw {
      schema_url: "https://pagelove.org/HTTPResponse",
      status: 422,
      message: `${value} is not a valid postcode`,
    };
  }
  return value.toUpperCase();
}

As with @validate, the write fails, the request's own write is not stored, and your status and message reach the client. The status must be an error status, 400 to 599. If you leave it out, or give any other status such as 200, the write is refused with a 422 instead. Its body is a SchemaViolation document that describes the throw and does not name the property. And as with @validate, only a thrown HTTPResponse does this — a @write that fails any other way is an internal error, so a bug in a transform cannot pick the response the client sees.

During an HTTP write, a validator of either kind can search the host's data with Class.search(). What Class.search() sees depends on the write. On a whole-page PUT or POST it reads the host's committed data, not the document being written; a Sessel validator also sees that document. On a write with Range: selector= whose body is a single value, it reads only the document as it would be after the write, as a Sessel validator does there. When the body of a selector write is a whole item, validators run twice, in both languages: first on the body alone, when a JavaScript search reads the committed data, then on the document as it would be after the write. A refusal from either stops the write. When server code builds an instance with new, a JavaScript validator gets no data at all, so a search finds nothing. A validator runs within what is left of the request's budget, or 5 seconds when the request sets no time budget; one that runs out of time fails the write with 503 and the https://pagelove.org/BudgetLimit document, not with 422. A refused value is answered 422. On a whole-page write the body is the https://pagelove.org/SchemaViolation document, naming the property and the @validate check, the same document a Sessel validator produces. On a write with Range: selector= and on a MOVE, the body is the https://dombase.pagelove.team/ns/error/Cardinality document, as it is for a Sessel validator there, except that a selector write whose body is a whole item refused on its own gets the SchemaViolation document from the first check.

For property-level @read, @write, and @validate, the first argument is the pipeline value, not the owning instance. For default, schema-level @validate, and @computed, this is the instance — so these must use a function form to read this (an arrow function in a strict-mode ES module does not bind its own this). Method bodies also bind this to the owning instance (the Class constructor for static methods) — see Method bodies below.

Computed properties (@computed)

An @computed slot makes a property's value always derived from a binding, with no value stored for it. The binding runs on every read; assigning to the property is rejected, since there is nothing to assign to.

<div itemprop="@computed" itemscope itemtype="https://pagelove.org/JavaScript/Module">
  <script itemprop="source" type="module">
    export default function() { return this.firstName + " " + this.lastName; }
  </script>
</div>

this is bound to the owning instance (a function form is required to read it). If a property declares both @computed and @read, @computed wins and @read never runs for it. A legacy, Sessel-only shorthand — an @read slot whose typed item is the bare https://pagelove.org/Sessel type — is also still recognized as a computed property for backward compatibility; new schemas should prefer @computed. See Property for the full behavior, including the legacy form.

Method bodies

A Method's implementation slot accepts a JavaScript module the same way a property binding does:

<div itemprop="property" itemscope itemtype="https://pagelove.org/Method">
  <meta itemprop="name" content="greet">
  <div itemprop="parameter" itemscope itemtype="https://pagelove.org/Parameter">
    <meta itemprop="name" content="greeting">
  </div>
  <div itemprop="implementation" itemscope itemtype="https://pagelove.org/JavaScript/Module">
    <script itemprop="source" type="module">
      export default function(greeting) { return greeting + ", " + this.name + "!"; }
    </script>
  </div>
</div>

this is bound to the calling object — the schema instance for an instance method, or the Class constructor for a static method. Parameters are forwarded positionally, in the method's declared parameter order (Sessel implementations instead read each parameter by name). A method body may be async; the engine drives its returned Promise to settlement the same way an async default export settles.

Method bodies also dispatch when a schema method is invoked through page composition — a namespaced method element (<ns:method>) or an ns:method="…" attribute. There, this is the host element the method was dispatched on (read-only), arguments bind by name from the dispatch element's attributes (rather than positionally), an ambient read-only document is available, and the return value is spliced into the page. See Method Elements for the composition-side contract, and Methods for the schema-level declaration.

A method body dispatches in a third context too: when the method is called from another server-side expression — a trigger's action, a processor, a mutation handler, or a nested method call made by another method (whether that caller is written in Sessel or JavaScript). Here the call behaves like a direct instance.method(...) call: arguments are forwarded positionally in declared order, this is the receiver, and the return value is the method's value. A read-only document global is available only when the receiver is an element; a typed schema instance receives no document global and operates on this.

A method body also dispatches in a fourth context: a text/sessel QUERY that calls a method on the results of search(). The edge proxy's group lookup is one such query, and it calls each group type's includes method this way. Here the method has these limits:

Before this, a JavaScript method in a QUERY failed. Now it works.

In this third context the method also has full access to the shared Context: it can read ambient entries such as Context.request, and any Context.foo = … assignment it makes is written back to the pass's Context — the same Context a Sessel method mutates in the same place — so a processor or trigger that reads Context afterwards observes the change. (Reading per-user request identity marks the response as user-specific, just as it does in composition.)

A Sessel expression can hand a JavaScript method an element it builds with new. This works from every caller, not only a QUERY: a trigger, a processor, a handler and a method all pass values the same way. The method receives the built element as a read-only DOM element. Only the top of the built tree is detached, so its parentNode is null. A child reaches its current ancestors, so closest() finds the item it sits in. If the expression removed a child from its tree, the child arrives alone and detached. If it moved a child, the child arrives under its new parent. The whole copied tree is read-only. Writing through parentElement or a sibling throws NoModificationAllowedError. The element reads with microdata() and the other read-only DOM methods. The copy is made node by node, except that raw HTML children are parsed once. The copy counts against the call's budget: each node, and the bytes of each run of text and each attribute value. An element read from a stored page arrives as a plain object of its microdata, as before. For a static method, this is the schema's class. When the runtime does not know the schema, this is a plain object such as { "@type": "urn:example:Note" }, so the method still runs.

A method can save data with the global Pagelove object when it is called from a trigger or processor action, from a Sessel write resolver (@write), or from a read resolver while a page is viewed. It cannot save while a page template is built, or from a when gate. See Saving data from JavaScript, which also explains that saves made while a page is viewed are not checked against your site's permission rules.

Whichever way a method is dispatched — through page composition (<ns:method> splicing its return into the page) or from another server-side expression — when it returns a typed schema instance it builds, that instance is treated exactly as new SchemaName { … }: its schema's @default values are filled in for any properties left unset, and it is validated against the schema (missing a required property with no default, or a wrong type, raises an error). So a method can construct and return an instance and rely on the same defaults and validation Sessel construction gives — you don't have to set defaulted properties yourself.

this and context for default

this — the in-progress instance

this is a read-only plain JS object view of the element being created. It exposes the schema-declared property keys that are already set — fields supplied by the client on the write, or fields set earlier in construction. Mutations to this inside a default expression are not preserved.

A default on one property may not read the value of another property whose default is also being computed in the same creation. Reading such a field returns undefined. Cross-property default ordering is not part of the public schema contract.

context — request and host information

context is a plain JS object passed as the first positional argument. The first cut carries a minimal set of well-known keys:

Key Type Meaning
document_html String The serialised source document being written, when one is available.

Authors must read only the keys they need and not enumerate or rely on the exact set. Future revisions may add keys.

The document global

Separately from context, a default expression also has access to a document global — a live view of the in-progress element that supports the same DOM methods as the JavaScript DOM API, including mutations (document.querySelector(...), appending or removing elements, and so on). Any changes made through document are kept: they're applied to the element being created.

Other binding kinds that also receive a document global (for example @write bindings) get a read-only version — calling a mutating method throws.

Chaining order

When a property has pipeline bindings at multiple levels of a schema inheritance chain, stages are chained:

Hook Order Combination rule
@read Ancestor-first (root → leaf) The output of one stage is the input to the next.
@write Child-first (leaf → root) The output of one stage is the input to the next.
@validate Ancestor-first (root → leaf) Every validator in the chain runs on the same value, and every failure is reported. A child's validator does not replace its parent's.

Pipeline chains can mix Sessel and JavaScript freely across the inheritance hierarchy. A parent's Sessel stage feeds a child's JavaScript stage, and vice versa, in the order above.

Importing schemas

A schema import uses the schema URL as the module specifier, with a fixed type import attribute of "https://pagelove.org/Schema":

import Note from "https://moodboard.pagelove.org/Note" with { type: "https://pagelove.org/Schema" };

The schema URL is an identifier, not a fetchable URL. The module loader resolves the import at evaluation time by looking up the schema in the host's schema cache. An unknown schema fails with the unknown-schema variant.

Each import yields a JavaScript class with the schema's short name (the last path segment of the itemtype URL). The class is synthesised at evaluation time and supports construction, property access, instanceof, and method dispatch.

All other import specifiers (relative paths, bare specifiers, HTTP URLs) are rejected with the import-not-allowed variant. There is no pagelove:host module.

Working with imported classes

Operation Behaviour
new Foo({...}) Constructor accepts a plain object whose keys are schema-declared property names. Undeclared properties are stored on the instance but do not trigger pipelines.
instance.prop Declared properties are readable and writable through ordinary getter/setter pairs backed by a Symbol-keyed store.
instance instanceof Bar Walks the prototype chain. If Foo extends Bar, new Foo() instanceof Bar is true.
instance.method() Schema-declared methods appear on the class prototype. Method bodies execute their declared implementation — Sessel or JavaScript — via the cross-language call path.

Schemas inheriting from https://pagelove.org/Map produce classes that extend Map, with keys, values, entries, and merge exposed. Undeclared property reads fall through to the Map backing store.

Note.search(criteria, options) finds the stored items of a class's type across your site, and gives them back as an array.

An item can name several types, such as itemtype="javascript:Note urn:Note". search() finds it by any of them. A script receives such an item as an instance of the first of its types that has a schema. Methods that a later type defines, and the first type does not, still work on it, and where two types define the same method the first type's runs. A property that only a later type declares can be read and assigned on the instance through that type's @read and @write, and an assignment is kept on save. A name an earlier type already uses, whether a property or a method, keeps the earlier type's meaning. The instance keeps all of its types when it goes back to Sessel or into a save. See Items with several types.

import Note from "https://moodboard.pagelove.org/Note" with { type: "https://pagelove.org/Schema" };

export default function () {
  Note.search();                                  // every Note
  Note.search({ title: "Alpha" });                // Notes titled Alpha
  Note.search([{ title: "Alpha" }, { x: 10 }]);   // titled Alpha, or with x of 10
  return Note.search({}, { isa: true }).length;   // Notes and every kind of Note
}

Each key in criteria names a property, and the item's value must equal the value you give. A string, number or boolean is compared as text, so { x: 10 } matches an x of 10. A Temporal value is compared by its stored form, as in Sessel, so Temporal.PlainMonthDay.from("09-30") matches --09-30. A Date is compared as the instant it stands for, such as 2026-01-01T00:00:00Z. An invalid Date, or one outside the years -9999 to 9999, throws a RangeError. A value of null or undefined is missing, and matches nothing: Note.search({ title: undefined }) finds nothing. In an array of objects, an object with a missing value is left out and the others still count. Any other value, such as an object or an array, throws a TypeError. A value may contain any characters, including quotes. It is always matched as text and cannot change what the search looks for.

search() takes the same two options as Sessel's search():

Any other option throws a TypeError, such as search() unknown option 'limit'. So does a value of the wrong type. The words are the same as in Sessel:

The type is Sessel's lowercase name for the kind of value: null, bool, integer, float, string, list or map. An array is a list, and an object or a Date is a map. A function as a value is a map too, but a function given as the whole options argument is refused as search() options must be a Map, got function. A BigInt or a Symbol as a value is reported as a map. A string that cannot be read as text, such as one with a lone surrogate, is refused with search() option '<key>' must be text that can be read, but it is not valid text. An option set to undefined counts as not given.

If the database fails while search() runs, it throws an Error whose message starts search() failed:. It does not give back an empty array, so "nothing found" always means nothing matched. You can catch the error. If you do not, or you throw that same error again, the database failure is reported as the server's, not as a problem with your data. In a property default, a @validate or a @read or @write pipeline, the request fails with the same status any database failure gets, never a validation error. In a WebDAV sign-in binding, the check counts as unable to run, so the site's auth-failure-mode decides: open lets the person in and logs it, and the default refuses. The operator guide explains this setting in its page on WebDAV auth fail-open recovery. If you throw a different error instead, the request fails with yours. In a trigger or processor when condition, a failed search() that you do not catch fails the condition, just as a failed read fails a Sessel condition. In a transition handler when condition, it refuses the save with the status a database failure gets, and nothing is stored. In a property default, a @validate or a @read or @write pipeline, a search() that uses up one of the request's allowances (time, work or memory) is not your error either: the request fails with the 503 budget response, whose pagelove.org/BudgetLimit Microdata says which allowance ran out. In a WebDAV sign-in binding, a search shares the check's 5 second time limit and has no operations or memory limit. A search that runs out of time answers 503 with Retry-After: 1, under both auth-failure-mode settings.

In a method that runs while a page is composed, and in a j: expression, the same two failures end the page view. A search that uses up an allowance gives the 503 budget response, even if your code catches the error and carries on. A database failure that you do not catch gives the status any database failure gets. If you throw your own error, the page fails with a 500 that carries your message. In a method that a QUERY calls, the budget gives the 503 response, a database failure gives its usual status, and your own error gives a 400 that says Sessel evaluation error. A method that a Sessel expression calls cannot be rescued by a Sessel try/catch from a budget overrun or a database failure. In a trigger action, any failed search fails the request with the TriggerError document (status 500). When the allowance ran out, its message names the limit, such as operations budget exceeded, even if your code caught the error. In a processor action, a search that uses up an allowance gives the 503 budget response with the pagelove.org/BudgetLimit document, even if your code caught the error. Any other failure of a processor action gives the ProcessorError document. A save you make from code follows the same rules: when uncaught, a refused save is your code's own error, a database failure under it is reported as a server fault, and running out of budget is reported as running out, unless you catch it and throw something else.

search() reads your data in property defaults filled in when an item is saved, in @validate during an HTTP write (what it sees depends on the kind of write, as described above), in @read and @write pipelines, in trigger, processor and transition handler when conditions, in trigger and processor actions, in WebDAV sign-in bindings, and in method bodies wherever they run: when a page is composed, when another expression calls them, and in a QUERY. A j: expression runs as a method, so it can search too. Searching only reads, so a method run while a page is composed, a gate or a j: expression still cannot save. In a method, a j: expression or a trigger or processor action, a search runs under one budget for that evaluation: the request's, or a 5 second limit when the request has none. A search that uses up the budget fails the request, and never gives back an empty array. In a WebDAV sign-in binding, a search shares the check's 5 second time limit and has no operations or memory limit. A search that runs out of time answers 503 with Retry-After: 1, under both auth-failure-mode settings. Elsewhere search() currently gives back an empty array. That includes @validate and defaults run when server code builds an instance with new.

Supported language features

Supported:

Not supported:

Math.random() and Date.now() are permitted and return legitimately different values on the server and the browser. Bindings commit logic over inputs, not clock or RNG agreement; the server's value is what gets stored.

Resource limits

Every evaluation runs under a per-request budget. In production the budget is read from the host's https://pagelove.org/TransactionBudget Microdata, shared with Sessel. A request touching one Sessel binding and one JavaScript binding sees a single shared budget, not two competing ones.

Limit Source in production Default in unbudgeted contexts Exhaustion error
Memory Remaining memory budget on the request 16 MB per context out-of-memory
Stack Per-thread default 256 KB per context threw (typically InternalError: stack overflow)
Time Remaining time budget on the request 5 seconds per call (the defaults of one saved body share one, and its validators share another, and the same holds for one item built in code with Sessel new or returned by a JavaScript method; the validators of one check of a selector write or a MOVE share one; the dynamic values of one trigger or processor outbound request share one, and so do the methods, defaults and validators one Sessel when condition runs) timeout
Ops Charged in batches against the request budget on every periodic interrupt Not charged for short, straight-line code at the top level. A nested level's leftover steps are charged Surfaces via the request budget

Each time your JavaScript reads a computed property, calls a method or runs a pipeline stage that runs another binding, the request pays 50,000 operations while that binding runs. The server gives them back when the binding finishes. That charge limits how deep your calls nest. A binding that calls itself is still stopped. The site's operations limit sets how deep calls can go. With the shipped limit of 1,000,000 operations, a chain that calls itself stops at about 20 levels. Your script can catch the error from a call that was refused, but the request has still run out. The server gives the refused charge back, yet it keeps the refusal, so the request fails with the budget error even if your script then finishes. A page, a query or a processor answers 503, and a trigger answers with its TriggerError. The server also keeps 1,000 operations for starting each call, and the steps the call ran, so a loop of many short calls is stopped by the operations limit too: the cheapest call costs about 3,600 operations, so the shipped limit allows about 260 of them. In the 503 body, consumed includes the refused charge and the levels still running, so it is above allocated. The X-Budget-Consumed-Ops header is read when the response is built, after charges are given back, so it can be below allocated.

A value that your code returns, or hands to Sessel as this or as an argument, is also charged. Each part of the value costs one operation and about the memory of one value, and a string costs its bytes. After every 1,024 parts the server checks the operations, memory and time budgets, and it fails the evaluation with the budget error when one has run out. One value may have at most 1,000,000 parts, whatever the budget. This stops a value that shares parts with itself, such as x = { a: x, b: x } nested forty times, which would otherwise have 2^40 parts to read.

Server JavaScript always has a time limit: what is left of the request's time budget, or 5 seconds if the request has none. This applies everywhere it runs, including methods called while a page is composed. While a page is composed and the request has no time limit, every script, j: expression and JavaScript method the page runs, including the methods a Sessel expression calls, shares one 5 seconds. When the request has no time limit, the defaults of one saved body share one 5 seconds and its validators share another 5 seconds. The same holds for one item built in code (Sessel new, or an item a JavaScript method returns). For a selector write or a MOVE, the validators of one check share one 5 seconds. A Sessel @validate has the same fallback. When Sessel calls a JavaScript method, a stop by that 5 second limit, or by the 16 MB default memory limit, counts as running out of budget, so a Sessel try/catch around the call cannot catch it. The dynamic values of one outbound request in a trigger or processor share one such limit. So do the JavaScript methods called from one Sessel when condition of a trigger, processor or transition handler, and the JavaScript defaults and validators that new runs there. All the transition handler when conditions of one save share one such limit. An endless loop is stopped with a timeout failure instead of running forever. A method that runs while a page is composed, and a j: expression, that run out of the request's time or operations fail the page with 503 and the https://pagelove.org/BudgetLimit document. Before, a composed method that ran out of time failed the page with a 500 that said it timed out. Memory has two answers there. A script that outgrows the heap the engine allows it is stopped by the engine, and the page fails with a 500 that names the memory budget. A method whose returned value is large enough that handing it back passes the request's memory allowance fails the page with 503 and the budget document, with memory as the resource. See Trigger and Processor for what the client gets when that happens. A transition handler when condition that runs out of the request's time, operations or memory refuses the save with 503 and stores nothing. Outside a when condition, a default, @validate, @read or @write binding that runs out of the request's time, operations or memory fails the request with 503 and the https://pagelove.org/BudgetLimit document, and its work is charged to the request. A @read that runs out never serves the unresolved value instead.

While an evaluation runs, its heap can grow by at most what the request has left of its memory budget, whatever the server already holds in memory for earlier work. If the request has no memory left, the evaluation fails with out-of-memory. When it finishes, the request is charged only for how much the JavaScript heap grew during the call. An evaluation that runs out of memory is charged the rest of its allowance, because the server cannot measure how far it got. That is a deliberate over-count, so the consumed figure in a memory 503 from JavaScript shows the request's whole allowance. A request with no memory limit is charged the 16 MB default. If the heap shrank, because memory from earlier work was freed during the call, the charge is zero. Freed memory is never credited back to the request.

Errors

Every failure is rendered to the client as an HTML Microdata document of type https://pagelove.org/BindingFailure, nested inside the https://pagelove.org/SchemaViolation envelope.

@validate, default, @read and @write are the exceptions. A @read or @write that runs out of time or memory fails the request with 503 and the https://pagelove.org/BudgetLimit document. A validator that throws or fails is reported as an execution error: … problem in the 422 violation document, with no nested BindingFailure, except that a thrown HTTPResponse with a status from 400 to 599 is sent as it is, and a database failure while it reads gets a 5xx status. An empty module is reported as compile error: … instead, because it fails before the validator runs. A validator or a default that runs out of time or memory fails the write with 503 and the https://pagelove.org/BudgetLimit document, not a 422. The same happens to a default that runs out while a page is shown, for an item a method returns. Inside a when condition, where new runs them, running out ends the condition instead, with the condition's own outcome. A default that fails any other way refuses the write with 500, except that a database failure while it reads gets the status any database failure gets.

A thrown null counts as running out of memory. The JavaScript engine throws null when it has no memory left even to build an error, and it gives no other sign, so a script that throws null itself, or an InternalError with an empty message, is treated the same way. Where the request answers running out directly, such as a save or a page view, a @validate, default, @read or @write that throws null or an InternalError with an empty message fails with the 503 budget response, not a 422 or a 500. In a processor, it stops the processor and fails the request with the 503 budget response. A save the request already stored stays stored. In a trigger, it fails the request with the TriggerError that names the limit.

Variant Trigger
parse The module source fails to parse as an ES module.
shape The module parsed but has no default export, or the default export is not a function.
threw The default function ran and threw. The message and (when available) stack are carried in the failure item. A thrown null, or a thrown InternalError with an empty message, is out-of-memory instead.
timeout The evaluation exceeded the time budget.
out-of-memory The evaluation exceeded the memory budget, threw null, or threw an InternalError with an empty message.
marshal An input value (a field of this, or a key of context) cannot be converted to a JavaScript value.
return-type The return value cannot be converted back into a dombase value. Functions, symbols, cyclic objects, and objects nested deeper than 64 levels all fall here.
import-not-allowed The module source contains an import specifier other than pagelove:schema.
unknown-schema A pagelove:schema import referenced a schema itemtype URL not found in the host's schema cache.
unknown-language The slot carried a typed item whose itemtype URL matches no registered language.

The rendered failure carries at minimum:

<div itemscope itemtype="https://pagelove.org/BindingFailure">
  <meta itemprop="language" content="https://pagelove.org/JavaScript/Module">
  <meta itemprop="variant" content="threw">
  <p itemprop="message">TypeError: Cannot read properties of undefined (reading 'foo')</p>
  <pre itemprop="stack">    at default (eval:2:17)</pre>
</div>

The stack property is present for threw when the engine provided one and absent otherwise. Sessel bindings produce structurally identical BindingFailure items with a different language value.

Tracing

Every JavaScript evaluation produces an OpenTelemetry-compatible span named dombase_js.evaluate:

Attribute Source
schema.itemtype The schema this binding belongs to, or "(none)".
binding.kind "default", "read", "write", "validate", "computed", "schema-@validate", or "method". (Other binding contexts — triggers, processors, WebDAV auth — use their own kind values; not covered here.)
binding.source_hash Short hex-encoded fingerprint of the source.
binding.source_len Length of the source string in bytes.
outcome "ok" on success, or the failure variant name.
budget.memory_delta_bytes Bytes the heap grew during evaluation, or zero if it shrank. This is the amount charged to the memory budget.
budget.time_nanos Wall-clock nanoseconds for the evaluation.

A child span dombase_js.compile wraps the compile step on the first use of a given source on a thread. Cross-language Sessel calls from within JavaScript nest as children of the dombase_js.evaluate span.

Marshalling

Values flow between dombase and JavaScript at every binding boundary:

Direction Behaviour
dombase → JS (inputs to this, context, pipeline argument) Each value is converted to its JavaScript equivalent. Values that cannot be converted fail the binding with marshal.
JS → dombase (return value) The value is converted back to a dombase value. Functions, symbols, cyclic objects, objects nested deeper than 64 levels, and an invalid or out-of-range Date fail with return-type.
Dates and times A Sessel temporal value arrives as the matching Temporal object, and a Temporal object returned becomes the matching Sessel value. A returned Date becomes the Temporal.Instant it stands for; an invalid Date, or one outside the years -9999 to 9999, fails with return-type.
Built elements A built element, or a child of one, arrives as a read-only DOM element. Only the top of the built tree has a null parentNode. A child reaches its current ancestors, a removed child arrives alone, and a moved child arrives under its new parent. Writing through parentElement or a sibling throws NoModificationAllowedError. A stored element arrives as a plain microdata object. A static method's this is the schema's class, or { "@type": … } when the schema is unknown. The copy counts against the budget: its nodes, text and attribute bytes. This holds for every Sessel call into JavaScript.
this traversal this is a placeholder object seeded only with the explicitly set schema-declared fields the marshaller currently understands. Rich traversal of the in-progress element's DOM subtree is not yet wired through.

First-cut exclusions

The following are out of scope for the current cut. Each is either a deferred feature or an interim limitation that will be lifted without breaking existing bindings:

Examples

Random coordinate default

<div itemprop="default" itemscope itemtype="https://pagelove.org/JavaScript/Module">
  <script itemprop="source" type="module">
    export default () => String(Math.floor(100 + Math.random() * 500));
  </script>
</div>

Timestamp default reading context

<div itemprop="default" itemscope itemtype="https://pagelove.org/JavaScript/Module">
  <script itemprop="source" type="module">
    export default function(context) {
      return `created at ${new Date().toISOString()}`;
    }
  </script>
</div>

Normalise on write

<div itemprop="@write" itemscope itemtype="https://pagelove.org/JavaScript/Module">
  <script itemprop="source" type="module">
    export default (val) => typeof val === 'string' ? val.trim().toLowerCase() : val;
  </script>
</div>

Format on read

<div itemprop="@read" itemscope itemtype="https://pagelove.org/JavaScript/Module">
  <script itemprop="source" type="module">
    export default (val) => typeof val === 'string' ? val.toUpperCase() : val;
  </script>
</div>

Validate on every write

<div itemprop="@validate" itemscope itemtype="https://pagelove.org/JavaScript/Module">
  <script itemprop="source" type="module">
    export default (val) => typeof val === 'string' && val.includes('@');
  </script>
</div>

Default that constructs a schema instance

<div itemprop="default" itemscope itemtype="https://pagelove.org/JavaScript/Module">
  <script itemprop="source" type="module">
    import Note from "https://moodboard.pagelove.org/Note" with { type: "https://pagelove.org/Schema" };
    export default () => new Note({ title: "untitled", x: 0, y: 0 });
  </script>
</div>

Computed property combining two fields

<div itemprop="@computed" itemscope itemtype="https://pagelove.org/JavaScript/Module">
  <script itemprop="source" type="module">
    export default function() { return this.firstName + " " + this.lastName; }
  </script>
</div>

Method body using a parameter and this

<div itemprop="implementation" itemscope itemtype="https://pagelove.org/JavaScript/Module">
  <script itemprop="source" type="module">
    export default function(greeting) { return greeting + ", " + this.name + "!"; }
  </script>
</div>

See also