Server-Sent Events

PageloveSSE attempts a Server-Sent Events connection and parses HTML Microdata mutation payloads. For a matching node it dispatches a cancelable PLMutation before default handling of supported methods. Cancellation, echo matching, missing targets and incomplete payloads can prevent a DOM change; a later PLMutationApplied notification is not proof of a change or a saved write.

When to reach for it

Use it as a starting point for a view that consumes document mutation events. Importing the module starts an automatic subscription attempt. A shared editor also needs source routing, draft protection, echo handling and recovery after a stream gap; the wrapper does not supply that complete workflow.

Loading the library

Add the module to the page:

<script type="module" src="https://pagelove.github.io/beta-js/pagelove/sse.mjs"></script>

Importing pagelove/sse.mjs auto-instantiates one PageloveSSE subscribed to the current page URL. The default instance is held internally and begins streaming as soon as the module evaluates. Application code must provide any additional routing, draft protection and recovery required by the view.

The PageloveSSE class

import { PageloveSSE } from 'https://pagelove.github.io/beta-js/pagelove/sse.mjs';

Constructors

Form Subscription target
new PageloveSSE() window.location.href with its fragment removed — the current page
new PageloveSSE(url) The given document URL

The constructor immediately opens an EventSource with withCredentials: true. This requests browser-permitted credentials; it does not configure a custom bearer header or grant access. The actual origin, credential policy and server authorization still determine whether the subscription opens.

Methods

Method Description
close() Closes this instance's EventSource and sets source to null. It does not remove its document-level echo listeners or close other instances. Construct a new instance to open another stream.

Properties

Property Type Description
url string The URL this client is subscribed to. Read-only.
source EventSource | null The underlying EventSource, or null after close(). Read-only.

Static methods

Method Description
PageloveSSE.parse(data) Parse an HTML Microdata mutation payload. Returns { method, selector, path, host, body, etag, destination, placement } or null.
PageloveSSE.parseReset(data) Parse a reset payload. Returns the reason string, or "unknown" if no reason is present.

DOM mutations

After parsing, the client looks for the first node matching the carried CSS selector. If a target exists and PLMutation is not canceled, its default handlers are:

Method Action
POST Appends all nodes parsed from the body to the matched element. Reports the first inserted node, if present. Its handler ignores placement.
PUT Replaces the match with only the first parsed element, or first node when there is no element. An empty body leaves the target unchanged.
DELETE Removes the matched element and reports element: null.
MOVE Looks up destination in the current document and moves the matched node before, after, into the beginning of, or into the end of that destination. placement selects before, after, prepend or append; omitted or unrecognized placement uses append. A missing destination leaves the node unchanged.

The inspected client applies selectors to the current document, without checking the event's host or path against the target element's source. No matching node means no DOM update or custom mutation notification. A matching selector alone does not establish the correct composed or remote source. Intercept PLMutation before applying a change when source routing or draft protection is required. The default POST handler always appends, ignoring placement; do not use it unchanged for prepend or sibling insertions.

The local echo queue is a heuristic: it matches method and selector, not host, path, actor or a unique request identity. Entries are removed on a match or PLMethodCompleted; entries older than 30 seconds are discarded when processing a mutation. A match skips the DOM change, but does not prove that a local write succeeded, and an unrelated change with the same method and selector can match. PLMutationApplied can still fire for a skipped echo with element: null; it is not a save receipt.

Server suppression is separate. The inspected client does not capture pagelove-connection or add its token to writes. For writes carrying the same non-empty session ID, the server fallback suppresses delivery to all subscribers sharing that session, including other tabs. Those tabs do not receive the event for local echo matching to repair. To distinguish connections, capture the server-issued token on the stream and send it on that connection's mutating requests as described in Echo suppression. Verify this integration, including token renewal on reconnect; the default wrapper does not provide it.

Events on document

Three custom events are dispatched on document. All three bubble and are composed.

Event When it fires Cancelable event.detail contains
PLMutation After parsing and finding a target, before default handling; this can also precede an echo skip or unsupported method yes — preventDefault() skips default handling and its Applied notification method, selector, path, host, body, etag, destination, placement, element
PLMutationApplied After supported default handling or an echo skip; it can fire without a DOM change no Same payload fields as PLMutation. element is the returned inserted/replacement/moved node, or null, including DELETE, echo skips, empty PUT and missing MOVE destination.
PLStreamReset When the server sends a reset event yes — preventDefault() suppresses the default location.reload() reason

PLMutation detail fields:

Field Type Description
method string Parsed method string. Default DOM handlers support POST, PUT, DELETE and MOVE; an unsupported method can reach PLMutation but has no default update or Applied event unless skipped as an echo.
selector string CSS selector of the target element.
body string HTML fragment to apply. Empty for DELETE.
path string Document path the mutation belongs to.
host string Virtual host the mutation belongs to.
etag string The page's ETag after the change, when supplied. It is the page's, not the element's. It is empty when an element replace on a page of 256 KiB or more read only that element, which happens for a #id, .class or exact attribute selector when nothing else on the page needs the edit to read it whole. A POST that read only the part of a page it changes does the same on a page of any size.
destination string Destination CSS selector used by MOVE. It is looked up in the current document.
placement string MOVE placement; the default POST handler ignores this field.
element Element For PLMutation, the first matching target. For PLMutationApplied, the handler result can instead be a node or null, as described above.

Listening for events

document.addEventListener('PLMutation', (event) => {
  const { method, selector, element } = event.detail;
  console.log(`incoming ${method} ${selector}`);
  // event.preventDefault(); // would skip the DOM change
});

PLMutationApplied follows the same payload shape but does not guarantee a change landed: echo skips, empty PUTs and missing MOVE destinations can emit it with element: null. PLStreamReset carries event.detail.reason; calling preventDefault() cancels the automatic reload.

Focus protection

The SSE wrapper has no dirty-draft protection: it can replace or remove a focused node directly. The Pagelove class defers some schema-to-view patches while a view contains focus, but the underlying schema may already have changed. In the tested text-input binding, its default blur commit could overwrite that schema change with the input’s retained value. Focus is not a dirty flag, retained draft, conflict check or proof of a saved write. flushPendingPatches() applies the current schema to deferred views; it does not merge drafts or confirm persistence.

For editable applications, retain the reviewed baseline, local draft and frozen pending submission independently. Intercept conflicting PLMutation events before DOM application, retain enough information to reconcile them, and keep incoming application separate from outgoing saves to avoid write-back loops. Do not copy a streamed page ETag into a fragment's reviewed save baseline merely because the wrapper assigns it to a returned node.

The default reset action is location.reload(), which can discard unsaved edits. Handle PLStreamReset synchronously and call preventDefault() before awaiting recovery if automatic reload would lose work. Canceling the reload does not restore stream continuity. Preserve recoverable edits, show a resynchronizing or authentication-required state, obtain an authorized fresh baseline, then reconcile before resuming editing or retrying an Unknown write.

Subscription ownership and cleanup

Importing this module also starts its internal default instance; manually constructing another instance does not replace it. The default instance is not exported, and sidebar.close() only closes that sidebar stream. Each instance installs document-level echo listeners that close() does not remove, so repeated construction is not complete disposal. Plan subscription ownership before loading this auto-starting module.

On sign-out, account or document changes, close streams you own and retire their handlers, queues and private rendered state under the application's recovery policy. Do not carry a previous actor's draft or connection token into a new actor's writes. This wrapper does not implement that lifecycle or expose a complete teardown of its default instance. Source inspection does not verify authentication transitions, draft recovery or accessibility; exercise them against the selected client and host.

Examples

Default — include the script

<script type="module" src="https://pagelove.github.io/beta-js/pagelove/sse.mjs"></script>

The module attempts to open the stream and apply supported events to matching nodes. Connection success, correct source routing, protected drafts and recovery after a gap require separate handling; including the script alone does not establish a safe shared editor.

Manual subscription to a different URL

<script type="module">
  import { PageloveSSE } from 'https://pagelove.github.io/beta-js/pagelove/sse.mjs';

  const sidebar = new PageloveSSE('/sidebar.html');

  document.addEventListener('PLMutationApplied', (event) => {
    if (event.detail.path === '/sidebar.html') {
      console.log('sidebar updated', event.detail.selector);
    }
  });

  // Later, when the sidebar is dismissed:
  // sidebar.close();
</script>

A second subscription is opened against /sidebar.html alongside the auto-instantiated default. Both operate on the current document. The example's PLMutationApplied path check filters its console message only, after application; it does not restrict where the wrapper applies the sidebar mutation. Establish source routing in a pre-mutation handler before using this pattern with unrelated or composed documents.

Verification scope

The client behavior above was exercised on November 6, 2026 in Chromium using captured public module bytes, controlled EventSource payloads and local discovery responses. The tests covered local callbacks, focus and blur, POST/PUT/DELETE/MOVE, cancellation, echo skips, missing nodes, empty PUT, unsupported methods, reset cancellation and ownership of close(). They did not establish live connection delivery, authentication transitions, reconnect continuity or cross-browser behavior. Test your selected module version and host before depending on those integrations.

See also