novinzodevelopers
Plugins

Admin screens

Build a self-contained dashboard screen with native browser APIs and the Novinzo message-port protocol.

A plugin serves one self-contained HTML document at GET /admin/ui. Novinzo embeds it in the seller dashboard and relays its API requests.

A message port is a private channel between two documents. This guide implements the screen side with native browser APIs.

A plugin can also serve a store-less screen to accounts acting for other sellers' stores. See Partner screens.

How the dashboard embeds a screen

Coordinate registration with Novinzo. The catalog needs hasAdminScreens: true and any supported adminSlots.

The dashboard fetches /plugins/<code>/admin/ui. The admin proxy authenticates the seller, selects the store, and requires an installation.

The proxy sends GET /admin/ui with x-novinzo-store-id, x-novinzo-plugin-invocation and x-novinzo-admin-store-role. Your Worker returns the HTML document.

The dashboard uses srcDoc with sandbox="allow-scripts allow-forms allow-downloads allow-popups allow-popups-to-escape-sandbox" and allow="clipboard-write". The frame has an opaque origin because allow-same-origin is absent.

On the first frame load, the dashboard transfers one MessagePort with novinzo:admin-connect. All subsequent messages use that port.

The dashboard sends context and hides the frame until it receives novinzo:admin-ready.

You must send novinzo:admin-ready

Send ready after the initial content renders, including an initial error state. Without it, the dashboard never shows the screen.

Accept the connection only when event.source === window.parent, its message type matches, and exactly one port arrives. Accept only the first connection.

The current handshake has no nonce or origin field. Do not invent one or accept requests through window messages after connecting.

The dashboard targets "*" because an opaque frame origin has no usable target origin. The transferred port identifies the connected document.

The dashboard closes the port on another frame load or unmount. It cancels outstanding relays and drops late answers.

A new store, plugin, or document gets a fresh frame. Context updates change appearance or placement information, not the authenticated store.

Serving the document

Use a standalone Worker project with Wrangler. Store the complete document below as screen.html beside worker.js.

worker.js
import screen from "./screen.html";

export default {
  async fetch(request) {
    const path = new URL(request.url).pathname;
    if (request.method === "GET" && path === "/admin/ui") {
      return new Response(screen, {
        headers: { "content-type": "text/html; charset=utf-8" },
      });
    }
    return new Response("Not found", { status: 404 });
  },
};
wrangler.jsonc
{
  "name": "acme-plugin",
  "main": "worker.js",
  "compatibility_date": "2026-10-01",
  "workers_dev": false,
  "preview_urls": false,
  "rules": [{ "type": "Text", "globs": ["**/*.html"], "fallthrough": true }],
}

Install public tooling with npm install --save-dev wrangler. Coordinate deployment and dispatch registration with Novinzo, as described in Deployment.

Deploy the document before Novinzo enables the catalog flag. Plugin authors do not edit Novinzo database rows or run migrations.

Revalidating the document

Serve one document for every store. The dashboard keeps one copy per plugin, may request it before it knows the store, and shows it on every store with the plugin installed. Store data reaches the screen through its context and requests.

The dashboard keeps a copy of the document together with its ETag, and before each use asks whether the copy is current by sending that tag in If-None-Match. The admin proxy forwards if-none-match for this purpose.

Send an ETag and Cache-Control: no-cache with the document. Answer 304 Not Modified without a body while the copy is current. The dashboard then downloads the document again only after you deploy a new one. A document served without an ETag is downloaded on every page load.

Compare If-None-Match weakly. A proxy on the way can turn your tag into W/"…" before it is sent back.

This version of worker.js derives the tag from the document's SHA-256 digest:

worker.js
import screen from "./screen.html";

let etag;

async function documentTag() {
  if (etag === undefined) {
    const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(screen));
    const hex = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0"));
    etag = `"${hex.join("")}"`;
  }
  return etag;
}

const matches = (ifNoneMatch, tag) =>
  ifNoneMatch !== null &&
  ifNoneMatch
    .split(",")
    .map((candidate) => candidate.trim().replace(/^W\//, ""))
    .some((candidate) => candidate === "*" || candidate === tag);

export default {
  async fetch(request) {
    const path = new URL(request.url).pathname;
    if (request.method === "GET" && path === "/admin/ui") {
      const tag = await documentTag();
      const headers = { etag: tag, "cache-control": "no-cache" };
      if (matches(request.headers.get("if-none-match"), tag)) {
        return new Response(null, { status: 304, headers });
      }
      return new Response(screen, {
        headers: { ...headers, "content-type": "text/html; charset=utf-8" },
      });
    }
    return new Response("Not found", { status: 404 });
  },
};

Novinzo's first-party plugins answer their screen documents the same way. The dashboard's own API relays use cache: "no-store", so this applies only to the document.

Placements and slots

The same document serves every registered placement. Its context selects the UI to render.

placementShown onadminSlots value
{ type: "page" }Plugin pageNo slot required
{ type: "product", productId }Saved product editorproduct
{ type: "product-variant", productId, variantId }Saved variant editorproduct-variant
{ type: "product-variant", productId, variantId }What the buyer getsproduct-variant-delivery
{ type: "new-product" }Product create pageproduct
{ type: "new-product-variant" }Unsaved variantEither variant slot
{ type: "overview" }Store overviewoverview
{ type: "order", orderId }Order pageorder
{ type: "customer", customerId }Customer pagecustomer

product-variant gives your screen a tab of its own in the variant editor. List product-variant-delivery instead when your plugin hands the buyer something, such as license keys: the screen then sits among the variant's What the buyer gets, beside its files and the message on the buyer's order page. Both slots use the same product-variant placement, so the screen does not tell them apart.

Product, variant and order identifiers are UUIDs. A context without placement means { type: "page" } for compatibility with earlier dashboards.

new-product is the editor of a product that does not exist yet. The dashboard keeps the frame hidden, without a loader, until the screen posts novinzo:admin-ready. A screen that does not handle this placement can ignore the context, and it never appears on the create page. A screen that does handle it holds the seller's choice and saves it through the page's Save once the product exists (see Page saves).

new-product-variant is the editor of a variant that is not saved yet: a variant of a product being created, or one the seller has just added to a saved product. Until your screen posts { type: "novinzo:admin-ready", placement: "new-product-variant" }, the dashboard shows a button that saves the product and opens your screen for the saved variant. A screen that does not handle this placement never names it, and the seller keeps that button. With the screen SDK, the component that draws for it calls useReportReady(ready, "new-product-variant"); useReportReady(ready) and EmptyPlacement name nothing. A screen that does handle it holds what the seller sets up and saves it through the page's Save once the variant exists (see Page saves). The frame keeps this placement until those changes are saved, then gets the variant's product-variant placement.

overview is a widget on the store's overview. Listing the slot offers the widget to the store's owner, who chooses whether to put it on the overview, where, and at what size. The dashboard frames it in a card under your plugin's name, so the widget needs no heading of its own; it scrolls inside the card when it is taller. To chart the store's sales in it, request analytics:read and call GetAnalytics from your plugin's admin route, the query behind the overview's own charts (see Reading dashboard data).

order and customer are cards on an order's and a customer's page, below what the page shows itself. The dashboard frames each in a card under your plugin's name. The placement carries the order's or customer's id; read what you need about it through core-for-plugins, such as the order list, with the permissions the store granted. Use these slots to show, for example, a customer's balance or linked Discord account, or an order's refund requests.

When your screen changes the order, such as by marking a line shipped, post novinzo:admin-changed (reportChanged() in the screen SDK): the order page then shows the order, its timeline and its status as they now stand. The page opens the order slot again whenever the order's status moves, so your screen reads the order as it now is. Other pages ignore the message.

Apply the context's light or dark class and color-scheme. Use transparent document and body backgrounds for slots.

Context contains placement, appearance and currencyIsoCode. Where they apply, it also carries pageSave: true (see Page saves), readOnly: true and sections (see Message protocol), and draft (see Agent drafts). It contains no credential or invocation token.

Page saves

In the product editor, its variant slots included, and on the product create page, the context carries pageSave: true: the page has one Save for everything on it. In such a context:

  1. Show no Save button. Report changes with { type: "novinzo:admin-unsaved", unsaved: true, savesWithPage: true }.
  2. When the seller saves the page, the dashboard posts { type: "novinzo:admin-save", id, placement }. Save for that placement. On the create page it names the product just created, not the frame's new-product; in a variant slot it names the variant's product, which the page saved first. A frame with the new-product-variant placement is told the product-variant the page has just saved.
  3. Answer { type: "novinzo:admin-saved", id, error }, where error is null once everything is saved, or a message for the seller. If any screen answers with an error, the page's save fails and shows the error under your plugin's name. Answer within 30 seconds: a save left unanswered fails as "The screen did not answer in time".

Without pageSave (the plugin page, or a dashboard from before page saves), keep your own Save. If you leave savesWithPage out, the dashboard guards your changes as before and does not save them.

Page views

A plugin page can have several views, such as tabs. The dashboard keeps the open view in the page's URL as ?view=, so a reload, the browser's back and forward buttons, and a shared link show the same view.

On the plugin page, the placement carries the view: { type: "page", view: "catalog" }, or view: null for your default view.

To open another view, post { type: "novinzo:admin-open-view", view: "catalog" }, or view: null for the default. The dashboard adds a history entry, updates the URL and posts a new context with the view.

Render the view the context names, not the one you asked for. The browser's back button changes the view without a message from your screen.

To head the page with a view's own name, such as the coupon it shows, post { type: "novinzo:admin-view-title", view: "coupon/<id>", title: "SUMMER10" }. The dashboard heads the page with title while its URL names that view, and with your plugin's name otherwise, so a title sent for a view the seller has just left is never shown. title is 1 to 120 characters, or null to head the view with your plugin's name again.

To open one of the store's orders in the dashboard, such as the order a return came from, post { type: "novinzo:admin-open-order", orderId }. The dashboard reads the order with the store's own access, so an id of no order of the store shows none.

RuleDetail
FormatA lowercase name starting with a letter, such as catalog, optionally followed by /-separated segments such as resellers/<id>.
LengthAt most 200 characters.
Invalid URLA ?view= that does not match the format opens the default view.
ScopeOnly the plugin page acts on novinzo:admin-open-view, novinzo:admin-view-title and novinzo:admin-open-order. Slots ignore them.
NavigationMoving between views stays on the page, so the dashboard does not ask about unsaved changes.

A context without view comes from a dashboard that predates views. That dashboard ignores novinzo:admin-open-view, so keep the view in your screen's own state in that case.

The frame stays loaded across view changes; only its context changes.

Message protocol

Every message is a plain object with type. Only novinzo:admin-connect uses the window message event.

Dashboard to screen

typeFieldsMeaning
novinzo:admin-connectOne port in event.ports[0]Connect this document once.
novinzo:admin-contextplacement, appearance, currencyIsoCode, pageSave?, readOnly?, sections?, draft?Initial context and later updates.
novinzo:admin-saveid, placementThe page was saved. Save what you reported with savesWithPage. See Page saves.
novinzo:admin-responseid, status, contentType, bodyHTTP answer, including error statuses. contentType is a string or null.
novinzo:admin-request-failedid, reasonNo HTTP answer was relayed.
novinzo:admin-confirmedid, confirmed, waitingForOutcome?Boolean confirmation answer. Dismissal or an already open dialog returns false. See Confirmations.
Failure reasonMeaning
invalid-requestThe message carried an id but did not decode as a request.
path-not-allowedPath resolves outside this plugin's /admin surface.
store-not-allowedThe request named a store, which an admin screen may not do.
unreachableRelay failed or exceeded its 30-second timeout.
request-too-largeRequest body exceeds 1 MiB in UTF-8 bytes.
response-too-largeResponse body exceeds 5 MiB.
busySix requests are active, or the request reuses an active identifier.

An admin proxy 502 is an HTTP answer, not unreachable. Handle HTTP status failures separately from transport failures.

The proxy answers 403 to a team member the store's owner has kept out of apps, and forwards nothing to your plugin.

An analyst is a team member who sees the store and changes nothing. The proxy cannot see what your routes do, so for an analyst it forwards GET and HEAD requests and answers 403 to every other method. Keep each GET free of anything the caller would count as a change. If a route only looks something up but takes a POST body, list its path in adminReadPaths when you register the plugin and the proxy forwards an analyst's POST to it too. A path listed there that changes something lets analysts change it.

A store's owner can also let a teammate open only some of the store's apps. The proxy answers 403 for an app they were not given, and the dashboard does not list it for them.

To let an owner grant part of your app, such as its analytics without its settings, declare adminSections when you register the plugin: each section has an id, a label the team page shows, and the admin API paths it covers (a path covers itself and everything under it). A teammate granted only some sections reaches GET /admin/ui and those paths, and gets 403 everywhere else in your admin API. Their context carries sections, the ids they were granted: show only those views, and make no request outside their paths.

A section can be granted down to your own records, such as one product's sales. Give the section a scope: a label naming what the owner picks ("Products") and an optionsPath, an admin API path outside the section whose GET answers the store's records as [{ "id": "…", "label": "…" }]. An id holds letters, digits, hyphens and underscores, at most 64. The owner picks records on the team page, and every request the proxy forwards to the section's paths carries the picked ids in x-novinzo-admin-scope, separated by commas. A scoped section is never granted whole. Two sections scoped by different kinds of record, which is by different optionsPaths, must not cover the same path: the header names ids alone, so the proxy refuses a teammate granted records of both there. Answer only about those records, within the store the request is for, and answer 403 when the header is missing: the owner and teammates with your whole app get none, and they read the same data through your other routes.

The context carries readOnly: true for an analyst. Hide or disable what changes your data when it is set, so an analyst is not offered a button that ends in a 403.

Every other team member reaches your admin API. The proxy tells you who is calling in x-novinzo-admin-store-role: owner for the store's owner and for an app API key, member for anyone the owner invited. Only the proxy sets it. Refuse a route that moves money, shows or replaces a secret, or hands the store's data to someone else unless the header says owner; treat a missing header as member.

To let an owner give one of those routes to a teammate, such as adjusting a reseller's balance, declare adminPermissions when you register the plugin: each permission has an id, and a label and description the team page shows. The owner gives permissions to teammates one by one, and the proxy names the ones the caller holds in x-novinzo-admin-app-permissions, comma-separated ids such as money. It names only permissions you declared, and none for the owner. Let such a route through when the role is owner or the header names its permission, and refuse it otherwise, a missing header included.

Screen to dashboard

typeFieldsPurpose
novinzo:admin-requestid, method, path, body?, contentType?Relay text or JSON to your admin API. Methods: GET, POST, PUT, PATCH, DELETE.
novinzo:admin-cancelidCancel a relay. No answer follows.
novinzo:admin-resizeheightReport finite, nonnegative CSS pixels from document.body.scrollHeight.
novinzo:admin-confirmid, title, message, confirmLabel, destructive, description?, tone?, waitsForOutcome?Open the dashboard confirmation dialog. See Confirmations.
novinzo:admin-confirm-settledid, errorClose a dialog that waits for its outcome, or show what failed.
novinzo:admin-unsavedunsaved, savesWithPage?Protect unsaved changes from dashboard navigation or tab closure.
novinzo:admin-savedid, errorAnswer to novinzo:admin-save: null once saved, or a message for the seller.
novinzo:admin-readyplacement?, a placement type such as "new-product-variant"Reveal initial content or an initial error. A new-product-variant frame is shown only once it names that placement.
novinzo:admin-open-viewviewOpen another view of the plugin page. See Page views.
novinzo:admin-view-titleview, titleHead the plugin page with a view's name. See Page views.
novinzo:admin-open-orderorderIdOpen one of the store's orders. See Page views.
novinzo:admin-changedNo fieldsYou changed what the page shows, such as an order you shipped.
novinzo:admin-draft-takenidA form took the agent's draft. See Agent drafts.

The dashboard resolves paths before appending /plugins/<code>. Traversal cannot reach another plugin or surface.

The relay uses the seller session, explicit original store selection, and cache: "no-store". The proxy forwards allowed content headers and attaches store and invocation headers.

Forward the inbound invocation token unchanged when your Worker calls Core API. The signed token identifies the plugin and store.

Confirmations

novinzo:admin-confirm opens the dashboard's own dialog, a bottom sheet on phones. Beside title, message, confirmLabel and destructive, it takes optional fields:

FieldMeaning
descriptionThe consequence, on a line of its own above the message, such as This can't be undone. Leave it out where the message already says it.
toneWhat kind of action it is, which picks the mark above the title: caution (the default), delete, archive, restore, approve, key (creating, rotating or revoking a key, token or secret) or remove-person (taking a person's access away).
waitsForOutcometrue to run the action in the dialog.

By default the dialog closes on the answer, and your screen runs the action and says how it went on its own page. With waitsForOutcome: true, the dashboard answers a confirmation with { type: "novinzo:admin-confirmed", id, confirmed: true, waitingForOutcome: true } and keeps the dialog open with its button pending. Run the action, then post { type: "novinzo:admin-confirm-settled", id, error }: error is null once the action is done, which closes the dialog, or what failed in your words, such as Couldn't archive the coupon, which the dialog shows as its only line. The seller can then confirm again, answered with another confirmed: true for the same id, or dismiss the dialog, answered confirmed: false.

A dashboard from before waitsForOutcome ignores it, as it ignores description and tone, and closes the dialog on the answer. Its answer then carries no waitingForOutcome: say the outcome on your own page.

Agent drafts

The dashboard's agent can draft a call of a first-party plugin's admin endpoint instead of making it. The screen's context then carries draft: { id, endpoint, request }, where endpoint is the endpoint's name and request its params, query and payload in JSON form. Open the form that sends that endpoint, filled in and unsaved, and post { type: "novinzo:admin-draft-taken", id }. The dashboard then stops sending the draft, so no other form, and no later visit to the page, fills in with it again. Only first-party plugins whose admin API the agent calls receive drafts; any other screen can ignore the field.

Limits

LimitValue
Requests in flight per screen6
Request body1 MiB, UTF-8 bytes
Response body, including the document5 MiB
Relay timeout30 seconds
Frame height20,000 CSS pixels; taller content scrolls inside

The proxy returns 401 without a seller session or installation, and 400 for an invalid store selector.

It returns 404 outside /admin or without a deployed Worker, and 502 for an unreachable Worker or redirect.

What's unavailable in the frame

  • Storage APIs and cookies are unavailable in the opaque origin. Keep persistent state in your plugin API.
  • Direct backend calls lack the dashboard's session. Send requests through the port.
  • Relative scripts and styles have no usable base URL. Inline all document resources.
  • Native alert, confirm, and prompt are blocked. Use the dashboard confirmation protocol instead of frame-local modals.
  • Camera access is not granted. Use another supported surface for camera features.
  • Clipboard reads are blocked. Writing to the clipboard is allowed, so copy buttons work.

Downloads and links opening a new tab are allowed.

Native browser bridge

This complete screen is an admin API console. It calls the example Worker's real /admin/ui route by default.

Change the path to your implemented admin endpoints. The console displays HTTP errors, handles cancellation, protects drafts, and requests confirmation before non-GET calls.

Project layout

Keep worker.js, wrangler.jsonc, and screen.html in your own project. No framework or private build configuration is required.

The client pattern

screen.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width,initial-scale=1" />
    <title>Admin API console</title>
    <style>
      :root {
        color-scheme: light;
        font: 16px system-ui;
        background: #fff;
        color: #111;
      }
      :root.dark {
        background: #171717;
        color: #eee;
      }
      body {
        margin: 0;
        padding: 16px;
      }
      label {
        display: block;
        margin: 12px 0;
      }
      input,
      textarea,
      select,
      button {
        font: inherit;
      }
      textarea {
        width: 100%;
        box-sizing: border-box;
      }
      pre {
        white-space: pre-wrap;
        overflow-wrap: anywhere;
      }
    </style>
  </head>
  <body>
    <h1>Admin API console</h1>
    <p id="context">Waiting for dashboard context</p>
    <form id="form">
      <label
        >Method
        <select id="method">
          <option>GET</option>
          <option>POST</option>
          <option>PUT</option>
          <option>PATCH</option>
          <option>DELETE</option>
        </select></label
      >
      <label>Path <input id="path" value="/admin/ui" required /></label>
      <label>JSON body <textarea id="body" rows="4"></textarea></label>
      <button id="send">Send</button>
      <button id="cancel" type="button" disabled>Cancel request</button>
      <button id="discard" type="button">Discard draft</button>
    </form>
    <pre id="result" role="status">Ready to send a request.</pre>
    <script>
      const pending = new Map();
      const waiting = [];
      const listeners = new Set();
      const outgoing = [];
      let port = null,
        context = null,
        active = 0,
        disposed = false;
      let ready = false;
      const aborted = () => new DOMException("Request aborted", "AbortError");
      const post = (message) => {
        if (disposed) throw new Error("Screen disposed");
        if (port) port.postMessage(message);
        else outgoing.push(message);
      };
      function ask(message, signal) {
        return new Promise((resolve, reject) => {
          if (signal?.aborted) return reject(signal.reason ?? aborted());
          const id = String(++ask.sequence);
          const abort = () => {
            pending.delete(id);
            post({ type: "novinzo:admin-cancel", id });
            reject(signal.reason ?? aborted());
          };
          signal?.addEventListener("abort", abort, { once: true });
          pending.set(id, {
            kind: message.type,
            resolve,
            reject,
            cleanup: () => signal?.removeEventListener("abort", abort),
          });
          post({ ...message, id });
        });
      }
      ask.sequence = 0;
      function takeTurn(signal) {
        return new Promise((resolve, reject) => {
          if (disposed) return reject(new Error("Screen disposed"));
          if (signal?.aborted) return reject(signal.reason ?? aborted());
          if (active < 6) {
            active++;
            resolve();
            return;
          }
          const turn = { resolve, reject, cleanup: () => {} };
          const abort = () => {
            waiting.splice(waiting.indexOf(turn), 1);
            reject(signal.reason ?? aborted());
          };
          turn.cleanup = () => signal?.removeEventListener("abort", abort);
          signal?.addEventListener("abort", abort, { once: true });
          waiting.push(turn);
        });
      }
      function endTurn() {
        const next = waiting.shift();
        if (next) {
          next.cleanup();
          next.resolve();
        } else active--;
      }
      async function bridgeFetch(path, init = {}) {
        const request = new Request(new URL(path, "https://admin-screen.invalid"), init);
        const url = new URL(request.url);
        if (
          url.origin !== "https://admin-screen.invalid" ||
          !(url.pathname === "/admin" || url.pathname.startsWith("/admin/"))
        ) {
          throw new TypeError("Use a local /admin path");
        }
        if (!["GET", "POST", "PUT", "PATCH", "DELETE"].includes(request.method)) {
          throw new TypeError("Unsupported method");
        }
        const body = request.body === null ? undefined : await request.text();
        await takeTurn(request.signal);
        try {
          const reply = await ask(
            {
              type: "novinzo:admin-request",
              method: request.method,
              path: url.pathname + url.search,
              body,
              contentType: request.headers.get("content-type") ?? undefined,
            },
            request.signal,
          );
          if (reply.type === "novinzo:admin-request-failed") {
            throw new TypeError("Relay failed: " + reply.reason);
          }
          return new Response([204, 205, 304].includes(reply.status) ? null : reply.body, {
            status: reply.status,
            headers: reply.contentType === null ? {} : { "content-type": reply.contentType },
          });
        } finally {
          endTurn();
        }
      }
      function receive(event) {
        const m = event.data;
        if (!m || typeof m !== "object") return;
        if (m.type === "novinzo:admin-context") {
          if (!["light", "dark"].includes(m.appearance) || typeof m.currencyIsoCode !== "string")
            return;
          const p = m.placement ?? { type: "page" };
          const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
          const slots = [
            "page",
            "product",
            "product-variant",
            "new-product",
            "new-product-variant",
            "overview",
            "order",
            "customer",
          ];
          if (!p || !slots.includes(p.type)) return;
          if (["product", "product-variant"].includes(p.type) && !uuid.test(p.productId)) return;
          if (p.type === "product-variant" && !uuid.test(p.variantId)) return;
          if (p.type === "order" && !uuid.test(p.orderId)) return;
          if (p.type === "customer" && !uuid.test(p.customerId)) return;
          context = { ...m, placement: p };
          const root = document.documentElement;
          root.classList.remove("light", "dark");
          root.classList.add(m.appearance);
          root.style.colorScheme = m.appearance;
          root.style.background = document.body.style.background =
            p.type === "page" ? "" : "transparent";
          listeners.forEach((listener) => listener(context));
          return;
        }
        if (typeof m.id !== "string") return;
        const job = pending.get(m.id);
        if (!job) return;
        const response =
          job.kind === "novinzo:admin-request" &&
          m.type === "novinzo:admin-response" &&
          Number.isInteger(m.status) &&
          m.status >= 200 &&
          m.status <= 599 &&
          typeof m.body === "string" &&
          (m.contentType === null || typeof m.contentType === "string");
        const failed =
          job.kind === "novinzo:admin-request" &&
          m.type === "novinzo:admin-request-failed" &&
          [
            "invalid-request",
            "path-not-allowed",
            "store-not-allowed",
            "unreachable",
            "request-too-large",
            "response-too-large",
            "busy",
          ].includes(m.reason);
        const confirmed =
          job.kind === "novinzo:admin-confirm" &&
          m.type === "novinzo:admin-confirmed" &&
          typeof m.confirmed === "boolean";
        if (!response && !failed && !confirmed) return;
        pending.delete(m.id);
        job.cleanup();
        job.resolve(m);
      }
      function connect(event) {
        if (
          disposed ||
          port ||
          event.source !== window.parent ||
          event.data?.type !== "novinzo:admin-connect" ||
          event.ports.length !== 1
        )
          return;
        port = event.ports[0];
        port.onmessage = receive;
        port.start();
        outgoing.splice(0).forEach((message) => port.postMessage(message));
      }
      const resize = new ResizeObserver(() =>
        post({
          type: "novinzo:admin-resize",
          height: document.body.scrollHeight,
        }),
      );
      window.addEventListener("message", connect);
      resize.observe(document.body);
      function dispose() {
        if (disposed) return;
        if (port) {
          for (const [id, job] of pending) {
            if (job.kind === "novinzo:admin-request")
              port.postMessage({ type: "novinzo:admin-cancel", id });
          }
          port.postMessage({ type: "novinzo:admin-unsaved", unsaved: false });
          port.close();
        }
        disposed = true;
        resize.disconnect();
        window.removeEventListener("message", connect);
        for (const job of pending.values()) {
          job.cleanup();
          job.reject(new Error("Screen disposed"));
        }
        pending.clear();
        for (const turn of waiting.splice(0)) {
          turn.cleanup();
          turn.reject(new Error("Screen disposed"));
        }
        outgoing.length = 0;
        listeners.clear();
      }
      window.addEventListener("pagehide", dispose, { once: true });

      const form = document.getElementById("form");
      const method = document.getElementById("method");
      const path = document.getElementById("path");
      const body = document.getElementById("body");
      const result = document.getElementById("result");
      const send = document.getElementById("send");
      const cancel = document.getElementById("cancel");
      let controller = null;
      listeners.add((next) => {
        document.getElementById("context").textContent =
          JSON.stringify(next.placement) + " · " + next.currencyIsoCode;
        if (!ready) {
          ready = true;
          post({ type: "novinzo:admin-ready" });
        }
      });
      form.addEventListener("input", () => post({ type: "novinzo:admin-unsaved", unsaved: true }));
      document.getElementById("discard").onclick = async () => {
        try {
          const reply = await ask({
            type: "novinzo:admin-confirm",
            title: "Discard draft?",
            message: "Your request draft will be lost.",
            confirmLabel: "Discard",
            destructive: true,
          });
          if (reply.confirmed) {
            form.reset();
            post({ type: "novinzo:admin-unsaved", unsaved: false });
          }
        } catch (error) {
          result.textContent = error.message;
        }
      };
      cancel.onclick = () => controller?.abort();
      form.onsubmit = async (event) => {
        event.preventDefault();
        send.disabled = true;
        try {
          if (method.value !== "GET") {
            const reply = await ask({
              type: "novinzo:admin-confirm",
              title: "Send request?",
              message: "This request can change plugin data.",
              confirmLabel: "Send",
              destructive: true,
            });
            if (!reply.confirmed) return;
          }
          const init = { method: method.value };
          if (method.value !== "GET" && body.value) {
            JSON.parse(body.value);
            init.body = body.value;
            init.headers = { "content-type": "application/json" };
          }
          controller = new AbortController();
          init.signal = controller.signal;
          cancel.disabled = false;
          const response = await bridgeFetch(path.value, init);
          result.textContent = "HTTP " + response.status + "\n" + (await response.text());
          if (response.ok) post({ type: "novinzo:admin-unsaved", unsaved: false });
        } catch (error) {
          result.textContent = error.message;
        } finally {
          controller = null;
          cancel.disabled = true;
          send.disabled = false;
        }
      };
    </script>
  </body>
</html>

The console renders its initial content before reporting ready. Data-driven screens report ready after their initial data or error renders instead.

The example queues requests beyond six, correlates replies, cancels aborted requests, applies context updates, and closes resources on disposal.

There is no novinzo:admin-dispose message. Disposal is local cleanup; the dashboard independently closes its session.

React is optional. Bundle React and every stylesheet into the same HTML document if your screen uses them.

Use your own components and styles. For API handlers, see Core API; for protocol exercises, see Testing.

On this page