diff --git a/CHANGELOG.md b/CHANGELOG.md index cd3983ec0c..419f7b0138 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,6 +39,24 @@ browsers over plain http while your server says https, every call that is not a `GET` now fails; see [Fix an http Origin](https://citry.dev/advanced/web-frameworks/#fix-an-http-origin). +- Citry's browser code now sends a GET event call's State token in the + `X-Citry-State-Token` header instead of the URL, so server and proxy + access logs do not record it by default. The server still reads the + `_citry_state_token` query parameter, so clients that send it there + keep working. If a server from an earlier release answers + `invalid_state`, as during a deploy or after a rollback, the browser + sends the call once more with the token in the URL; a custom + transport's `send` then runs twice for that call. If your event URL is + on another origin and your CORS setup lists the allowed request + headers, add `X-Citry-State-Token`. When a GET call sends the header + and the handler sets its own `Cache-Control`, Citry makes the policy + `private` and drops `public`, `s-maxage`, and CDN-only headers such as + `CDN-Cache-Control`, so a CDN that ignores `Vary` cannot give one + visitor's answer to another. See + [Allow GET requests](https://citry.dev/events/routes/#expose-a-read-only-get-endpoint). +- Security: a GET event call whose header and query parameter carry + different State tokens is now refused with a `400` error, so a URL + cannot choose a token other than the one the browser sent. - Security: `actions.Dispatch` now raises `ValueError` for the name of a standard DOM event, such as `click`, `submit`, `input`, `change`, `keydown` or `focus`, because the event would run the page's own diff --git a/docs/design/events.md b/docs/design/events.md index cbb56cfb32..0090519a4f 100644 --- a/docs/design/events.md +++ b/docs/design/events.md @@ -1360,9 +1360,9 @@ declaring `state` on a component with no State class is a class-definition error. On a State-declaring component, POST calls always carry the token: pending two-way updates ride the next call and must be verified, applied, and re-signed whether or not the handler -reads state. GET calls carry the token in the query only when the -handler declares `state`, which is what keeps read-only GET URLs -pasteable and token-free. Token expiry is a property of the one shared +reads state. GET calls carry the token only when the handler declares +`state`, which is what keeps read-only GET URLs pasteable and +token-free, and they carry it in the `X-Citry-State-Token` header (6.2). Token expiry is a property of the one shared State, not of any handler, so it lives on State meta (`_max_age`, 3.2 and 7.1) alongside `_storage` and `_max_bytes`. @@ -4754,7 +4754,7 @@ registry keyed by content type; user codecs ride | Envelope | `application/citry-events+json` | v1 | The identity codec: the body already is the envelope. What the runtime sends. The vendor media type is what distinguishes an envelope from flat JSON, so classification never depends on body shape (a user schema could legitimately declare fields named `v` or `calls`). The batch route takes only the envelope and accepts it under plain `application/json` too, since a batch body has no flat reading. | | Flat JSON | `application/json` | v1 | Flat handler fields as one JSON object (`POST {"email": "a@b.c"}`), per-event route only: what an external API client sends without knowing the protocol. Fields bind per 3.3's JSON rules (native types, strict); the reserved `_citry_state_token` / `_citry_caller_render_id` keys map into the envelope like the form codec's. | | Form | `application/x-www-form-urlencoded` | v1 | Classic form posts: fields become the args payload; the reserved `_citry_state_token` / `_citry_caller_render_id` fields map into the envelope; the source-aware binding rule (3.3) turns the strings into typed values, including `int` / `float` / `bool` fields. | -| Query | GET query string | v1 | Args ride as query parameters, bound per the same source-aware rule (3.3); the state token rides `_citry_state_token` only when the handler declares State (3.5). Browser calls additionally reserve `_citry_protocol`, `_citry_request_id`, and JSON `_citry_capabilities` for the flattened envelope, plus `_citry_caller_render_id` and `_citry_send_sequence` for call metadata. | +| Query | GET query string | v1 | Args ride as query parameters, bound per the same source-aware rule (3.3); the state token counts only when the handler declares State (3.5), read from the `X-Citry-State-Token` header or the `_citry_state_token` parameter (two different values are refused with 400). Browser calls additionally reserve `_citry_protocol`, `_citry_request_id`, and JSON `_citry_capabilities` for the flattened envelope, plus `_citry_caller_render_id` and `_citry_send_sequence` for call metadata. | | Multipart | `multipart/form-data` | v1.x | File uploads: the envelope JSON rides as one part, each file as its own part, bound to `UploadedFile` fields ("Files, precisely" below). | | Msgpack | `application/msgpack` | candidate, unscheduled | A binary envelope for apps where payload size matters; would pair with symmetric response encoding negotiated via `Accept`. Open an issue when someone measures the need. | @@ -5047,8 +5047,11 @@ Rules, each closing a named prior-art hole: at 150 to 300 bytes (section 1.4), so a component approaching the cap is holding state that belongs in the database, and the error says so (keep an id in State, reload the rest in the rebuild). The one nearby - technical budget is GET handlers, whose token rides a query parameter - under practical URL length limits of roughly 2 KB. + technical budget is GET handlers, whose token rides the + `X-Citry-State-Token` header, which nginx, Apache and Gunicorn cap at + about 8 KB per header by default (the `_citry_state_token` query + parameter instead counts against the request-line limit, 4 KB in + Gunicorn and 8 KB in nginx). - Signed, not encrypted: State values are visible to their own user, like anything rendered into HTML. The docs lead with the symptom ("anything in State is visible in the page source"); the mitigations, in order: do @@ -5163,9 +5166,11 @@ component whose handlers only read State, renewal is what lets a copy outlive `_max_age`. The case that matters most is a handler that opts into GET (`@event(methods=("GET",))` or `Events._methods`) and declares `state`. A handler uses POST by default, so its token stays out of the URL. A GET -call carries the token in its query only when the handler declares `state` -(section 3.5), and that URL can land in server and proxy logs. Whoever -reads those logs can keep that token alive. Renewal does not change what a +call carries the token only when the handler declares `state` (section +3.5). Citry's browser code sends it in the `X-Citry-State-Token` header +(6.2), but the server still reads the `_citry_state_token` query +parameter, and a URL that carries it can land in server and proxy logs. +Whoever reads those logs can keep that token alive. Renewal does not change what a token permits, which is why every handler still checks permission. The token is bound to its component class and protocol version, not to a user, session, page, instance, or latest State revision. Handlers must therefore reload authoritative data and perform @@ -5339,12 +5344,23 @@ traversal of any object graph; extra arg keys are rejected, not absorbed. inject the CSRF token; this is that helper, absorbed.) - GET handlers are opt-in, csrf-exempt by nature, and read-only by contract; their args ride as query parameters, and the state token - rides as a `_citry_state_token` query parameter only when the handler - declares `state` in its signature (3.5), so read-only GET URLs stay - pasteable and token-free (the docs note URL length limits and the - id-plus-reload fix for large-State components). + rides only when the handler declares `state` in its signature (3.5), + so read-only GET URLs stay pasteable and token-free. The browser sends + the token in the `X-Citry-State-Token` request header, which access + logs do not record the way they record a URL; the server also reads a + `_citry_state_token` query parameter, and refuses a call whose header + and query parameter carry different tokens with 400 + `protocol_mismatch`. A GET answer lists `X-Citry-State-Token` in + `Vary`. The per-handler descriptor carries `usesState: true` only when the handler - declares the State injectable, so the browser can enforce that URL rule. + declares the State injectable, so the browser sends the token only to such + a handler. When a header-only call answers `invalid_state` without + listing the header in `Vary` (a server from before 1.3.0 reads only the + query), the browser sends it once more with the token in the query. + When a call sends the header and a handler's own response sets a cache + policy, the server keeps only the directives a browser cache follows, + adds `private`, and drops CDN-only cache headers, because the URL does + not carry the token and some CDNs ignore `Vary`. The built-in browser transport selects GET for a single call to a GET-declared handler. It serializes scalar string, boolean, and finite number args, and non-empty arrays of those values as repeated query @@ -5353,7 +5369,7 @@ traversal of any object graph; extra arg keys are rejected, not absorbed. `_citry_request_id`, and JSON `_citry_capabilities`, preserving version rejection, response correlation, and morph/action negotiation from the ordinary envelope. `_citry_caller_render_id` and `_citry_send_sequence` preserve call metadata; - `_citry_state_token` appears only for a state-declaring handler. The query codec + the `X-Citry-State-Token` header appears only for a state-declaring handler. The query codec removes those reserved fields before input validation. A GET call never flushes or consumes pending two-way writes: those remain queued for the next mutating call. A mixed or multi-call envelope still uses the POST-only batch endpoint, including when diff --git a/docs/design/trust_boundaries.md b/docs/design/trust_boundaries.md index 5fcaeb05d1..f98547e095 100644 --- a/docs/design/trust_boundaries.md +++ b/docs/design/trust_boundaries.md @@ -247,7 +247,7 @@ template from request data". | `Dependencies` entry with `__html__` (a ready-made tag) | App code | Markup | Inserted raw (`citry/ext/dependencies/emission.py:1114`); refused in fragments, on Vue pages, and with a nonce or Citry SRI. | `docs/advanced/dependency-files.md:266-276` | | `Script(url=, content=, attrs=)`, `Style(...)` in `Dependencies`, `Component.on_dependencies()`, or the `on_dependencies` hook | App code | Runs / CSS | `content` checked by `_check_validity`; `attrs` names by `validate_html_attr_name`, values escaped. A `url` that is a `str` subclass, such as Django's `SafeString`, is stored as a plain `str` when it is set (`Dependency.__setattr__`, `citry/ext/dependencies/types.py:150`): its text, or for a value with `__html__` that text with its character references decoded, as every attribute writer reads it (`_plain_url_text`, `:96`). So the escaping, the `javascript:` URL check that `security_javascript` runs (`_sanitize_structured_attributes`, `citry/_javascript_policy.py:511`), and the serialization check that the written `src` or `href` matches `url` all read the text the page gets; the safe mark is not trusted. With `security_javascript` off there is no scheme check; an `on*` key in `attrs` is allowed. | `docs/advanced/dependency-files.md` ("Customize the tag") and the `Script` / `Style` docstrings | | `serialize(csp_nonce=)`, Events `_csp_nonce` | App code (syntax-checked, so a bad value cannot break out) | Lets scripts run under the CSP | `_validate_csp_nonce` (`citry/serialize.py:1225`, CSP base64 only), then added to every structured tag after the dependency hooks (`citry/_serialization_security.py:497`), the fragment loader, and the Vue data. Tags written in a template never get it. | `docs/security.md:1129-1295` | -| `X-Citry-Page-Nonce` request header, read by `page_nonce_from_headers()` and by an Events `Render` when the app sets no `_csp_nonce` | Request data (any client can send any value) | Becomes the CSP nonce of the answer to that same request | `page_nonce_from_headers` (`citry/_page_nonce.py:48`) returns `None` unless the value is CSP base64 of at most 256 characters, so it cannot break out of an attribute. A forged value only reaches the forger's own answer, where the forger's page refuses the fragment. A cross-origin page cannot set the header without a CORS preflight. A shared cache is the one way an answer reaches another visitor, so every Events answer lists `X-Citry-Page-Nonce` in `Vary`, and an answer to a call that sent the header also gets `Cache-Control: no-store` (`_with_page_nonce_marks`, `citry/ext/events/routes.py:843`; the fallback is `_page_csp_nonce`, `citry/ext/events/dispatcher.py:394`). The docs tell hosts and custom transports to do the same. The browser runtime never puts the nonce on a fragment itself; `Citry.pageNonce()` (`citry/_vue/client.js:6118`) only reads it, and only for code already running. | `docs/security.md`, "Nonces in fragments" | +| `X-Citry-Page-Nonce` request header, read by `page_nonce_from_headers()` and by an Events `Render` when the app sets no `_csp_nonce` | Request data (any client can send any value) | Becomes the CSP nonce of the answer to that same request | `page_nonce_from_headers` (`citry/_page_nonce.py:48`) returns `None` unless the value is CSP base64 of at most 256 characters, so it cannot break out of an attribute. A forged value only reaches the forger's own answer, where the forger's page refuses the fragment. A cross-origin page cannot set the header without a CORS preflight. A shared cache is the one way an answer reaches another visitor, so every Events answer lists `X-Citry-Page-Nonce` in `Vary`, and an answer to a call that sent the header also gets `Cache-Control: no-store` (`_with_page_nonce_marks`, `citry/ext/events/routes.py:950`; the fallback is `_page_csp_nonce`, `citry/ext/events/dispatcher.py:397`). The docs tell hosts and custom transports to do the same. The browser runtime never puts the nonce on a fragment itself; `Citry.pageNonce()` (`citry/_vue/client.js:6118`) only reads it, and only for code already running. | `docs/security.md`, "Nonces in fragments" | ## 7. Vue and translated text @@ -295,11 +295,11 @@ OK are checked by Citry on the server and again in the browser. | Input | Who may supply it | Browser | What Citry does, and where | Docs | |---|---|---|---|---| -| `Redirect(url=)` | Request data OK for the scheme and the header. App code for the destination: the app checks a URL from the request with `local_url_or()` or `is_local_url()` (`citry/ext/events/local_urls.py`), which accept only a relative URL or an `http`/`https` URL on a host the app lists, read as a browser reads it | Navigates | `Redirect.__post_init__` (`citry/ext/events/actions.py:383`) refuses controls and any scheme other than `http`/`https`, read the way the WHATWG URL parser reads it (`redirect_url_scheme`, `:322`, which calls the one scheme reader every server-side check shares: `url_scheme` in `crates/citry_html_transform/src/url_scheme.rs`, through `citry/_urls.py`). The resolver for the no-JavaScript form path reads the scheme through the same reader (`_resolve_redirect_url`, `citry/ext/events/routes.py:666`) and resolves a URL that depends on the page against a same-host `Referer`, as the browser runtime resolves it against the page: a URL with no scheme, or one such as `http:next` that has the page's own scheme and no `/` or `\` after the colon. The browser checks the scheme again (`navigateToRedirect`, `citry/_vue/client.js:172`) and throws on a refused one, so `Citry.events.applyActions` rejects and a sent call fails. Without JavaScript, `_encode_location` (`citry/ext/events/routes.py:816`) leaves only printable ASCII in the `Location` header. | `docs/events/actions.md:391`; `docs/security.md:197` | +| `Redirect(url=)` | Request data OK for the scheme and the header. App code for the destination: the app checks a URL from the request with `local_url_or()` or `is_local_url()` (`citry/ext/events/local_urls.py`), which accept only a relative URL or an `http`/`https` URL on a host the app lists, read as a browser reads it | Navigates | `Redirect.__post_init__` (`citry/ext/events/actions.py:383`) refuses controls and any scheme other than `http`/`https`, read the way the WHATWG URL parser reads it (`redirect_url_scheme`, `:322`, which calls the one scheme reader every server-side check shares: `url_scheme` in `crates/citry_html_transform/src/url_scheme.rs`, through `citry/_urls.py`). The resolver for the no-JavaScript form path reads the scheme through the same reader (`_resolve_redirect_url`, `citry/ext/events/routes.py:773`) and resolves a URL that depends on the page against a same-host `Referer`, as the browser runtime resolves it against the page: a URL with no scheme, or one such as `http:next` that has the page's own scheme and no `/` or `\` after the colon. The browser checks the scheme again (`navigateToRedirect`, `citry/_vue/client.js:172`) and throws on a refused one, so `Citry.events.applyActions` rejects and a sent call fails. Without JavaScript, `_encode_location` (`citry/ext/events/routes.py:923`) leaves only printable ASCII in the `Location` header. | `docs/events/actions.md:391`; `docs/security.md:197` | | `PushUrl(url=)`, `ReplaceUrl(url=)` | Request data OK (the browser refuses another origin). App code for which same-origin path is shown | Changes the address bar | Server checks only a non-empty string (`citry/ext/events/actions.py:416`, `:445`). The browser resolves against the page address (`citry/_vue/client.js:150`) and the History API refuses another origin. Never applied without JavaScript. | `docs/events/actions.md:293-316` | | `Render(element=, target=, swap=)` | `element`: section 1 rules. `target`, `swap`: request data OK | Markup | `Render.__post_init__` (`citry/ext/events/actions.py:171`) checks `target` with `validate_render_id` or `validate_mark_name` and `swap` against a fixed set; the browser checks again, for server results at `citry/_vue/client.js:3789-3794` and for `applyActions` at `:499-512`. | `docs/events/actions.md:27-125` | | `Dispatch(name=, detail=)` | `name`: app code (pick it from your own list; never copy it from a request). `detail`: request data OK as JSON | A `CustomEvent` that cannot be cancelled, fired at the component's first element; it bubbles | `Dispatch.__post_init__` (`citry/ext/events/actions.py`) refuses an empty name, a standard DOM event name such as `click` or `submit` (`DOM_EVENT_NAMES` in `citry/_html_attribute_values.py`), and a name starting with `citry:`, `vue:` or `vnode-`, ignoring ASCII letter case (`reserved_event_name_reason`). The browser refuses the same names before it fires the event, on every path (`refuseReservedEventName` in `citry/_vue/client.js`, called from `applyPublicActionsWithoutApp` and from the Events bridge's `dispatchEvent` and `dispatchEventGlobal`), from a copy of the list the generator writes. Request data that picks among the app's own custom names still picks which of the app's listeners run, so the name stays app code. `detail` is strict JSON. Decided in [#704](https://github.com/citry-dev/citry/issues/704). | `docs/events/actions.md` ("`Dispatch` browser events") and the `Dispatch` docstring | -| `Data(value=)`, a returned `dict` | Request data OK | JSON | Strict JSON (`citry/ext/events/routes.py:467`). | `docs/events/actions.md:166-193` | +| `Data(value=)`, a returned `dict` | Request data OK | JSON | Strict JSON (`_encode_envelope`, `citry/ext/events/routes.py:579`). | `docs/events/actions.md:166-193` | | `Download(content=, filename=, content_type=)` | `content`, `filename`: request data OK. `content_type`: app code | Saved as a file | `Download.__post_init__` (`citry/ext/events/actions.py:510`) refuses paths, controls, and bidi characters in `filename`, and anything outside printable ASCII in `content_type`; `_download_content_disposition` (`:543`) writes an `attachment` header. | `docs/events/actions.md:318-348` | | `RouteResponse` from an `@event(bundle=False)` handler | App code | As its `content_type` says | Sent from the per-event route only (`citry/ext/events/dispatcher.py:1160`); the adapters add `nosniff` and a UTF-8 charset (`citry/util/routing.py:302`, `:318`) but do not check header values for line breaks. | `RouteResponse` docstring (`citry/util/routing.py`); `docs/events/actions.md` ("Send your own response") | | `on_event` hook return (Events extension) | Extension code | As the handler's result | A value other than `None` answers the call in place of the handler (`citry/ext/events/dispatcher.py:1061`) and goes through the same result encoding as a handler return. | Docstrings in `citry/ext/events/extension.py` | @@ -313,12 +313,12 @@ page by Citry itself; it is listed because it decides what a handler sees. | Input | Who may supply it | What Citry does, and where | Docs | |---|---|---|---| -| Handler name and component class id | Request data OK | Citry looks both names up in a dictionary and never calls `getattr` (`_resolve_handler`, `citry/ext/events/routes.py:515`). Every public `def` on the `Events` class, and on any class it inherits from other than Citry's own `Events` and `ViewEvents` bases, becomes a handler that any request can call by name (`collect_event_handlers`, `citry/ext/events/handlers.py:421`; the skipped classes are `_FRAMEWORK_CLASSES`, `:93`, and a base class that Citry ships joins them through `framework_base`, `:391`, as `ViewEvents` does at `citry/ext/events/view_events.py:61`). A handler accepts only `POST` unless it lists other methods, and a request with another method gets 405 (`citry/ext/events/routes.py:376`). | `docs/events/routes.md:14-23`. The rule for inherited classes: Missing | -| Event data, body size, form field count | Request data OK | `decode_request` (`citry/ext/events/codecs.py:293`), schema binding, size and field limits in `_prepare_dispatch` (`citry/ext/events/routes.py:339`). A `Decimal` whose size is 1e309 or more, or that has more than 308 decimal places, is refused (`request_decimal_in_range`, `citry/util/decimals.py:105`). Citry's own coercion checks it in `_coerce` (`citry/ext/events/schemas.py:1465`); the result of a Pydantic model or Pydantic dataclass is walked by `find_oversized_decimal` (`citry/util/decimals.py:139`) in `_without_oversized_decimals` (`citry/ext/events/schemas.py:747`), the finished arguments are walked once more when an earlier walk may have skipped an object that code changed later (`citry/ext/events/schemas.py:356`), and the items of an `Iterable[...]` field are checked in `_read_items_now` (`citry/ext/events/_pydantic_bounded.py:1150`). All answer the 422 `invalid_args` error. A Pydantic validator sees the value before this check runs, and the walk does not read into app classes, so an app type that wraps a `Decimal` is not checked. | `docs/security.md:409-472`, `:542-565` | +| Handler name and component class id | Request data OK | Citry looks both names up in a dictionary and never calls `getattr` (`_resolve_handler`, `citry/ext/events/routes.py:627`). Every public `def` on the `Events` class, and on any class it inherits from other than Citry's own `Events` and `ViewEvents` bases, becomes a handler that any request can call by name (`collect_event_handlers`, `citry/ext/events/handlers.py:471`; the skipped classes are `_FRAMEWORK_CLASSES`, `:93`, and a base class that Citry ships joins them through `framework_base`, `:441`, as `ViewEvents` does at `citry/ext/events/view_events.py:61`). A handler accepts only `POST` unless it lists other methods, and a request with another method gets 405 (`citry/ext/events/routes.py:389`). | `docs/events/routes.md:14-23`. The rule for inherited classes: Missing | +| Event data, body size, form field count | Request data OK | `decode_request` (`citry/ext/events/codecs.py:336`), schema binding, size and field limits in `_prepare_dispatch` (`citry/ext/events/routes.py:352`). A `Decimal` whose size is 1e309 or more, or that has more than 308 decimal places, is refused (`request_decimal_in_range`, `citry/util/decimals.py:105`). Citry's own coercion checks it in `_coerce` (`citry/ext/events/schemas.py:1465`); the result of a Pydantic model or Pydantic dataclass is walked by `find_oversized_decimal` (`citry/util/decimals.py:139`) in `_without_oversized_decimals` (`citry/ext/events/schemas.py:747`), the finished arguments are walked once more when an earlier walk may have skipped an object that code changed later (`citry/ext/events/schemas.py:356`), and the items of an `Iterable[...]` field are checked in `_read_items_now` (`citry/ext/events/_pydantic_bounded.py:1150`). All answer the 422 `invalid_args` error. A Pydantic validator sees the value before this check runs, and the walk does not read into app classes, so an app type that wraps a `Decimal` is not checked. | `docs/security.md:409-472`, `:542-565` | | CSRF | Request data (any site can send one) | `build_csrf_check` (`citry/ext/events/csrf.py:201`). A `GET` call skips every check (`:221`). Every other method, `HEAD` and `OPTIONS` included, gets Citry's own header checks (`enforce_floor`, `:150`: the `X-Citry-Events` header on a JSON body, `Origin`, `Sec-Fetch-Site`) and then the handler's own `csrf` callable, if it has one. A `HEAD` request has no body, so the `X-Citry-Events` check does not apply to it, and on a plain-http site a `HEAD` request that another site's script sends can carry neither `Origin` nor `Sec-Fetch-Site`. Django's token check also skips `HEAD` and `OPTIONS`, as it skips `GET`, so a handler that accepts `HEAD`, including a `ViewEvents` `head` method, must not change anything. The `Origin` check compares the host and port with `Host`, and on a request the adapter reports as https (`RouteRequest.scheme`, from the ASGI scope, `wsgi.url_scheme`, or Django's `request.scheme`) it also refuses an `Origin` that is not `https:` (`:193`), so an `http://` page on the same host cannot call an https app even from a client that sends no `Sec-Fetch-Site`. An http request does not compare schemes, so a proxy that ends TLS keeps working. An `Origin` that `urlsplit` cannot read is refused. Tests: `packages/py/citry/tests/test_events_origin_scheme.py`. | `docs/security.md:263-429`. The `HEAD` rule: Missing | | CSRF cookie and header names (`_csrf_cookie`, `_csrf_header` in `extensions_defaults["events"]`) | App code only | Choose which cookie the browser runtime reads and which header it sends the value in, to Citry's own routes on the page's origin | `_validate_engine_config_value` (`citry/ext/events/extension.py:95`) with `csrf_name_problem` (`citry/ext/events/csrf.py:111`): HTTP tokens only, no header Citry or the browser sets. Written into the configuration block as `csrfNames`; the runtime checks them again in `adoptServerCsrf` (`citry/_vue/client.js:421`), reads them with own-key lookups, takes them only from a block it trusts (a document block, a fragment with the page's nonce, or one page code loads), and keeps the first block's names. An explicit `Citry.configure({csrf})` wins for each name it sets. | `docs/security.md`, "CSRF cookie and header" | -| State token | Request data (opaque, signed) | `verify_state_token` (`citry/ext/events/tokens.py:712`): HMAC-SHA256 with a derived key, constant-time comparison, class binding, expiry. After every restore, `oversized_state_decimals` (`citry/ext/events/tokens.py:1476`) checks each State field for a `Decimal` outside the event-data range, so a token signed by an earlier release that holds one is refused with 422 `invalid_args` before the handler runs (`citry/ext/events/dispatcher.py:1077`) and is never signed again. A cached render verifies and re-signs it (`citry/ext/events/cache.py:124-188`), and builds the render afresh when the restored State holds such a value (`citry/ext/events/cache.py:167`). A verified token past half its lifetime (`state_renewal_due`, `citry/ext/events/tokens.py:801`) gets a new token with a full lifetime in a `state` action even when State did not change (`_renewal_wanted` and `_renew_state`, `citry/ext/events/dispatcher.py:1658`, `:1674`). So whoever holds a valid token, a copy included, can keep it alive by calling at least once per half lifetime, even on a component whose handlers only read State; a token in the URL of a GET handler that declares `state` (a handler uses POST unless it opts into GET with `methods=("GET",)` or `_methods`) can be read from logs and kept alive the same way. | `docs/security.md:24-96`, `:542-565` | -| `stateUpdates` (writes from `$state` and `:c-*`) | Request data OK | `apply_state_updates` (`citry/ext/events/tokens.py:1035`): only `_model` fields, typed. After a write to a Pydantic State, every field gets the same size check as event data in `_check_state_decimals` (`citry/ext/events/tokens.py:1498`) before the State changes, so a `Decimal` that Pydantic builds from a write, or that a validator or `__post_init__` derives from it, is refused, at the write or at the next call's restore, even when it compares equal to the old value. | `docs/events/state.md:167-170`, `docs/security.md:542-565` | +| State token | Request data (opaque, signed) | `verify_state_token` (`citry/ext/events/tokens.py:710`): HMAC-SHA256 with a derived key, constant-time comparison, class binding, expiry. After every restore, `oversized_state_decimals` (`citry/ext/events/tokens.py:1474`) checks each State field for a `Decimal` outside the event-data range, so a token signed by an earlier release that holds one is refused with 422 `invalid_args` before the handler runs (`citry/ext/events/dispatcher.py:1099`) and is never signed again. A cached render verifies and re-signs it (`citry/ext/events/cache.py:124-188`), and builds the render afresh when the restored State holds such a value (`citry/ext/events/cache.py:167`). A verified token past half its lifetime (`state_renewal_due`, `citry/ext/events/tokens.py:799`) gets a new token with a full lifetime in a `state` action even when State did not change (`_renewal_wanted` and `_renew_state`, `citry/ext/events/dispatcher.py:1706`, `:1722`). So whoever holds a valid token, a copy included, can keep it alive by calling at least once per half lifetime, even on a component whose handlers only read State. When a handler opts into GET (a handler uses POST unless it lists `methods=("GET",)` or `_methods`) and declares `state`, Citry's browser code sends its token in the `X-Citry-State-Token` header, not in the URL that access logs record; if a server from before 1.3.0 answers `invalid_state` (an answer whose `Vary` does not list the header, or any such answer the browser cannot read `Vary` on), the browser sends the call once more with the token in the query. The server still reads the `_citry_state_token` query parameter, and refuses a call whose header and query carry different tokens with 400 `protocol_mismatch` (`_merge_header_state_token`, `citry/ext/events/codecs.py:304`), so the URL cannot choose a token other than the header's. A token that a client of the app's own, or a page from before 1.3.0, sends in the query can still be read from logs and kept alive the same way. A GET answer lists `X-Citry-State-Token` in `Vary`, and a handler's own cache policy on a call that sent the header keeps only the directives a browser cache follows, behind `private`, with CDN-only cache headers dropped (`_with_cache_marks`, `citry/ext/events/routes.py:482`). | `docs/security.md:24-96`, `:542-565` | +| `stateUpdates` (writes from `$state` and `:c-*`) | Request data OK | `apply_state_updates` (`citry/ext/events/tokens.py:1033`): only `_model` fields, typed. After a write to a Pydantic State, every field gets the same size check as event data in `_check_state_decimals` (`citry/ext/events/tokens.py:1496`) before the State changes, so a `Decimal` that Pydantic builds from a write, or that a validator or `__post_init__` derives from it, is refused, at the write or at the next call's restore, even when it compares equal to the old value. | `docs/events/state.md:167-170`, `docs/security.md:542-565` | | Sub-path (ASGI `root_path`, WSGI `SCRIPT_NAME`) | App deployment only; it becomes request data when a proxy passes on a client's `X-Forwarded-Prefix` | `normalize_sub_path` (`citry/_sub_path.py:34`) uses the site root for a value that is not a path starting with one `/`, and percent-encodes the rest, so it stays a path on the same site either way. | `docs/advanced/web-frameworks.md:419-439` | | `get_event_url(..., query=, fragment=)` | Query and fragment: request data OK | `format_url` (`citry/util/misc.py:175`) encodes them. | `docs/events/routes.md:25-62` | @@ -327,7 +327,7 @@ page by Citry itself; it is listed because it decides what a handler sees. | Route or response | What it serves | Checks, and where | Docs | |---|---|---|---| | Every adapter | Any response | Adds `X-Content-Type-Options: nosniff` unless the response sets that header itself, and `charset=utf-8` to a `text/*` string body (`citry/util/routing.py:302`, `:318`). A 405 for a method the route does not accept names the accepted methods in an `Allow` header (`route_allowed_methods`, `citry/util/routing.py:860`). | `docs/advanced/extensions.md:400-404` | -| Events response body and errors | JSON, or `text/plain` without JavaScript | Strict JSON; error text that echoes request values is only sent as `text/plain` or JSON with `nosniff`. Exception text appears only when the `citry` logger is at `DEBUG` (`citry/ext/events/dispatcher.py:448`). A `GET` call answers with `Cache-Control: no-store` (`citry/ext/events/routes.py:836`); a `Download` always does (`citry/ext/events/dispatcher.py:1149`). | `docs/security.md:1104-1116` | +| Events response body and errors | JSON, or `text/plain` without JavaScript | Strict JSON; error text that echoes request values is only sent as `text/plain` or JSON with `nosniff`. Exception text appears only when the `citry` logger is at `DEBUG` (`citry/ext/events/dispatcher.py:613`). A `GET` call answers with `Cache-Control: no-store` (`_respond`, `citry/ext/events/routes.py:478`); a `Download` always does (`citry/ext/events/dispatcher.py:1324`). | `docs/security.md:1104-1116` | | Runtime files (`citry..js`, `ext/events/definitions/.js`, `ext/events/assets/.css`, i18n runtime) | Citry's own files | Digest must be 64 hex characters; a shared-cache copy is served only if its hash matches (`citry/_hashed_runtime.py:54`, `:172`; `citry/_vue/events.py:418`). These, and their 404s, carry `Access-Control-Allow-Origin: *` (`citry/_owned_resource.py:19`); hashed files are sent as `immutable`. | `docs/security.md:1707-1745` | | `cache/..{js,css}`, `asset/` | Component files and the `css_data()` stylesheet | Class must be registered; type from a fixed table; a hash must be hex and a file name `<12 hex>.` whose extension holds only ASCII letters, digits and `._~+-`, up to 128 characters, checked before any lookup; content only from Citry's cache (`citry/ext/dependencies/routes.py:121`, `:173`). A `.js` hash that names no class version always misses, because Citry writes `js_data()` only into the page (`get_script`). A `css_data()` stylesheet is built again from its stored values, and its name must be one this engine's key gives those values (`_rebuild_css_data_stylesheet`), so a guessed value cannot be confirmed except with a configured cache and no secret (section 6). With a configured cache, the page writes each stylesheet it links into the cache again when it is serialized, if the cache no longer holds it (`publish_css_data_stylesheets`, `citry/ext/dependencies/emission.py:1256`). The `ext/events/assets/` copy of that stylesheet is served from a shared cache only when this route would serve the same bytes (`check_css_data_stylesheet_copy`). On both routes a refused name makes the same cache calls as a miss, and an entry that an earlier release left is deleted the first time it is refused (`get_script`, `check_css_data_stylesheet_copy`). Until an operator deletes those entries, the first request for one takes slightly longer than a miss, and so does every request for a copy whose component class this engine does not know (kept, because a worker of another deploy may know it). The `asset/` bytes are not re-hashed when served, so the cache operator is trusted. Successful responses carry `Access-Control-Allow-Origin: *` (`citry/_owned_resource.py:157`, `:165`, `:179`), so any site that has the URL can read a `css_data()` stylesheet; `css_data()` must not return secrets. 404s carry no CORS header. | `docs/security.md:1707-1745` | | i18n messages route | Message JSON | 64 KiB, exact fields, allowed locales, known public message ids (`citry/ext/i18n/routes.py:79`). | `docs/i18n/browser.md:227-229` | diff --git a/docs_site/content/events/routes.md b/docs_site/content/events/routes.md index 6d959d23a4..bdd7d9c533 100644 --- a/docs_site/content/events/routes.md +++ b/docs_site/content/events/routes.md @@ -90,6 +90,19 @@ Build the URL while rendering with not change anything on the server. Its arguments arrive in the query string, which holds strings, booleans, numbers, and non-empty lists of those. +A GET handler can also read State, when it declares a `state` parameter +(see [Access State in handlers](/events/state/#access-state-in-handlers)). +Citry's browser code then sends the component's State token in the +`X-Citry-State-Token` request header, so the token stays out of the URL, +which server and proxy logs record. A client you write should do the +same. The `_citry_state_token` query parameter also works, but it puts +the token in those logs. If the header and the query parameter carry +different tokens, the call gets a `400` error and the handler does not +run. When the call sends the header and the handler sets its own +`Cache-Control`, Citry makes that policy `private` and drops `public`, +`s-maxage`, and CDN-only headers such as `CDN-Cache-Control`, because +the URL does not show which visitor's token the call sent. + !!! note "Which HTTP methods a handler accepts" `methods` accepts `GET`, `HEAD`, `POST`, `PUT`, `PATCH`, `DELETE`, and diff --git a/docs_site/content/reference/browser-apis.md b/docs_site/content/reference/browser-apis.md index b80c605aa8..6312f3aa3d 100644 --- a/docs_site/content/reference/browser-apis.md +++ b/docs_site/content/reference/browser-apis.md @@ -606,7 +606,7 @@ envelope only for other methods: | --- | --- | | `url` | The event route, with the query string for a `GET` handler. | | `method` | The HTTP method, usually `POST`. | -| `headers` | A new object with the request headers, including the CSRF token on calls that are not `GET`. | +| `headers` | A new object with the request headers, including the CSRF token on calls that are not `GET`, and the State token in `X-Citry-State-Token` on a `GET` call to a handler that reads State. | | `signal` | An `AbortSignal` that fires when the call times out or Citry cancels it, for example because the component was removed. | Send `request.headers` to the server with the envelope. When a handler @@ -614,7 +614,11 @@ returns a render, the server reads the `X-Citry-Vue-App`, `X-Citry-Vue-Occurrence`, and `X-Citry-Vue-Revision` headers to find the component the browser shows. Without them the call fails with `handler_error`, and the server log says the app, occurrence, or -revision header is missing or invalid. The simplest transport sends the +revision header is missing or invalid. A `GET` call to a handler that +reads State carries its State token in `X-Citry-State-Token`, not in +`url`. When the server answers such a call with `invalid_state`, Citry +calls `send` once more, with a copy of the envelope, the token in `url`, +and without that header. The simplest transport sends the envelope and `request.headers` to `request.url`, Citry's own event route. diff --git a/docs_site/content/security.md b/docs_site/content/security.md index 1f7a90f6c9..f2e3df053b 100644 --- a/docs_site/content/security.md +++ b/docs_site/content/security.md @@ -82,12 +82,24 @@ calling with it. Anyone who sends calls with a copy at least once per half lifetime keeps getting new tokens, as the page does, even when it calls only handlers that read State. -Handlers use POST by default, which keeps the token out of the URL. A -handler that opts into GET with `@event(methods=("GET",))` or -`Events._methods`, and declares `state`, receives the token in its URL, -where it can end up in server and proxy logs. Whoever can read those logs -can keep that token alive the same way. A token grants no permission, so -check permissions in every handler. +Citry's browser code keeps the State token out of the URL, which server +and proxy logs record. Handlers use POST unless they opt into GET with +`@event(methods=("GET",))` or `Events._methods`. A POST call sends the +token in the request body. A GET call to a handler that declares `state` +sends it in the `X-Citry-State-Token` header. + +Four things can still put a token in a log. The server also reads a +token from the `_citry_state_token` query parameter, so a client of your +own that sends it there logs it. Logs written before 1.3.0 hold the +tokens that Citry's browser code sent in the URL. When a GET call +gets an `invalid_state` answer from a server from before 1.3.0, or from +any server when the event URL is on another origin or the call goes +through a custom transport, Citry's browser code sends the call once +more with the token in the URL. A log or tracing tool that records +request headers also records `X-Citry-State-Token`, so +leave that header out of it. Whoever can read a logged token can keep +it alive by calling with it, as described above. A token grants no +permission, so check permissions in every handler. A call with an expired token does not run its handler: it gets a `stale_state` error, and calls from that component keep failing until diff --git a/packages/js/citry-client/src/citry-events-vue.ts b/packages/js/citry-client/src/citry-events-vue.ts index 6a52bc124b..e66d7d05f0 100644 --- a/packages/js/citry-client/src/citry-events-vue.ts +++ b/packages/js/citry-client/src/citry-events-vue.ts @@ -2,6 +2,8 @@ import { assertValidActionList as assertProtocolActionList, + CARRIER_FIELDS, + CARRIER_HEADERS, buildOkResult, buildCall, buildCallEnvelope, @@ -343,6 +345,19 @@ const flatQuery = (args: JsonObject): URLSearchParams => { return query; }; +// Whether a raw per-event answer is the single `invalid_state` error a server gives a call that +// needs State and sent no token it could read. Only the shape is checked here; the full result +// check runs later on whichever answer the bridge keeps. +const answersInvalidState = (raw: unknown): boolean => { + if (raw === null || typeof raw !== "object" || !Array.isArray((raw as { results?: unknown }).results)) return false; + const results = (raw as { results: unknown[] }).results; + if (results.length !== 1) return false; + const [result] = results; + if (result === null || typeof result !== "object") return false; + const error = (result as { error?: unknown }).error; + return error !== null && typeof error === "object" && (error as { code?: unknown }).code === "invalid_state"; +}; + const attachmentFilename = (value: string): string => { const extended = /(?:^|;)\s*filename\*\s*=\s*([^;]+)/i.exec(value)?.[1]?.trim(); if (extended !== undefined) { @@ -878,6 +893,8 @@ export const createVueEventsBridge = (options: VueEventsBridgeOptions) => { const controller = new AbortController(); job.controller = controller; let requestUrl = target.href; + // The URL that carries the token in its query, used only when a server ignores the header. + let queryTokenUrl: string | null = null; if (useGet) { const query = flatQuery(input.args ?? {}); query.append("_citry_protocol", envelope.protocol); @@ -885,16 +902,27 @@ export const createVueEventsBridge = (options: VueEventsBridgeOptions) => { query.append("_citry_capabilities", JSON.stringify(envelope.capabilities)); query.append("_citry_caller_render_id", call.callerRenderId ?? ""); query.append("_citry_send_sequence", String(call.sendSequence)); - if (handlerOptions.usesState === true && call.stateToken !== undefined) - query.append("_citry_state_token", call.stateToken); + // The token goes in a header rather than the query, because servers and proxies write + // the URL to their access logs. It still goes only to a handler that reads State, so a + // read-only GET answer does not depend on it. + if (handlerOptions.usesState === true && call.stateToken !== undefined) { + headers[CARRIER_HEADERS.stateToken] = call.stateToken; + const withToken = new URLSearchParams(query); + withToken.append(CARRIER_FIELDS.stateToken, call.stateToken); + queryTokenUrl = `${requestUrl}?${withToken.toString()}`; + } requestUrl += `?${query.toString()}`; } const requestHeaders = useGet ? Object.fromEntries(Object.entries(headers).filter(([name]) => name !== "Content-Type")) : headers; const requestMethod = isolated ? handlerOptions.httpMethod : "POST"; - const operation = (async (): Promise< - { raw: unknown; transported?: true } | { attachment: Blob; filename: string } + const attempt = async ( + requestUrl: string, + requestHeaders: Record, + sentEnvelope: typeof envelope, + ): Promise< + { raw: unknown; transported?: true; readsTokenHeader?: true } | { attachment: Blob; filename: string } > => { if (selectedTransport) { // The server needs the same app, occurrence and revision headers the @@ -907,7 +935,7 @@ export const createVueEventsBridge = (options: VueEventsBridgeOptions) => { signal: controller.signal, }; try { - return { raw: await selectedTransport.send(envelope, request), transported: true }; + return { raw: await selectedTransport.send(sentEnvelope, request), transported: true }; } catch (error) { if (error !== null && typeof error === "object") reportableFailures.add(error); throw error; @@ -943,11 +971,38 @@ export const createVueEventsBridge = (options: VueEventsBridgeOptions) => { } try { const raw: unknown = await response.json(); - return { raw }; + // A server that reads the token header lists it in Vary on every GET answer, so its + // invalid_state is about the token itself and sending the token again cannot help. The + // header is readable only on the page's own origin; elsewhere the retry rule stays. + const vary = response.headers?.get?.("Vary") ?? ""; + const readsTokenHeader = vary + .split(",") + .map((name) => name.trim().toLowerCase()) + // `*` says the answer depends on every request header, the token header included. + .some((name) => name === "*" || name === CARRIER_HEADERS.stateToken.toLowerCase()); + return readsTokenHeader ? { raw, readsTokenHeader: true } : { raw }; } catch (error) { if (response.ok) throw new Error("A successful raw Event response must be an attachment."); throw error; } + }; + const operation = (async () => { + const first = await attempt(requestUrl, requestHeaders, envelope); + // A server from before Citry 1.3.0, still running during a deploy or after a rollback, + // reads the token only from the query and answers invalid_state without it, and so does + // a custom transport that forwards only the URL. One retry with the token in the query + // keeps such a call working. The first answer refused + // the call before its handler ran, so sending it again is safe. + if ( + queryTokenUrl === null || + controller.signal.aborted || + !("raw" in first) || + first.readsTokenHeader === true || + !answersInvalidState(first.raw) + ) + return first; + const { [CARRIER_HEADERS.stateToken]: _sentToken, ...withoutToken } = requestHeaders; + return attempt(queryTokenUrl, withoutToken, structuredClone(envelope)); })(); let timeoutId = 0; const received = await Promise.race([ diff --git a/packages/js/citry-client/test/vue-events.test.mjs b/packages/js/citry-client/test/vue-events.test.mjs index 3431539db8..d78ff03e35 100644 --- a/packages/js/citry-client/test/vue-events.test.mjs +++ b/packages/js/citry-client/test/vue-events.test.mjs @@ -1552,7 +1552,9 @@ test("GET uses the exact per-event URL and flat metadata without consuming State assert.equal(parsed.pathname, "/prefix/ext/events/e/Board_1/search"); assert.deepEqual(parsed.searchParams.getAll("tags"), ["x", "y"]); assert.equal(parsed.searchParams.get("q"), "a/b"); - assert.equal(parsed.searchParams.get("_citry_state_token"), "state-token"); + // The token rides a header, so the URL that access logs record carries none. + assert.equal(parsed.searchParams.has("_citry_state_token"), false); + assert.equal(request.init.headers["X-Citry-State-Token"], "state-token"); assert.equal(parsed.searchParams.get("_citry_protocol"), "citry-events/1"); assert.deepEqual(JSON.parse(parsed.searchParams.get("_citry_capabilities")), { actions: ["render", "data", "state", "event", "redirect", "url"], @@ -1561,6 +1563,172 @@ test("GET uses the exact per-event URL and flat metadata without consuming State }); }); +test("GET to a handler that does not read State sends no State token", async () => { + const getDescriptor = { componentClassId: "Board_1", eventHandlers: { search: { httpMethod: "GET" } } }; + let request; + const bridge = bridgeModule.createVueEventsBridge({ + endpoint: "/events", + eventBaseUrl: "/events/e/", + host: basicHost(() => ({ ...contextFor(), stateToken: "state-token", descriptor: getDescriptor })), + fetch: async (url, init) => { + request = { url, init }; + const query = new URL(url, "https://example.test").searchParams; + return resultResponse({ + requestId: query.get("_citry_request_id"), + calls: [{ sendSequence: Number(query.get("_citry_send_sequence")) }], + }); + }, + }); + await bridge.send({ source: { stableId: "board", generation: 1 }, handler: "search", args: { q: "a" } }); + assert.equal(new URL(request.url, "https://example.test").searchParams.has("_citry_state_token"), false); + assert.equal(request.init.headers["X-Citry-State-Token"], undefined); +}); + +const statefulGetDescriptor = { + componentClassId: "Board_1", + eventHandlers: { search: { httpMethod: "GET", usesState: true } }, +}; + +const invalidStateError = { status: 403, code: "invalid_state", message: "The state token is invalid." }; + +const queryEnvelope = (url) => { + const query = new URL(url, "https://example.test").searchParams; + return { + requestId: query.get("_citry_request_id"), + calls: [{ sendSequence: Number(query.get("_citry_send_sequence")) }], + }; +}; + +test("GET retries once with the token in the query when a server ignores the header", async () => { + // A server from before the header existed reads the token only from the query. + const requests = []; + const bridge = bridgeModule.createVueEventsBridge({ + endpoint: "/events", + eventBaseUrl: "/events/e/", + host: basicHost(() => ({ ...contextFor(), stateToken: "state-token", descriptor: statefulGetDescriptor })), + fetch: async (url, init) => { + requests.push({ url: new URL(url, "https://example.test"), headers: init.headers }); + const envelope = queryEnvelope(url); + return requests.at(-1).url.searchParams.get("_citry_state_token") === "state-token" + ? resultResponse(envelope, [{ action: "data", value: "found" }]) + : errorResponse(envelope, invalidStateError); + }, + }); + const result = await bridge.send({ source: { stableId: "board", generation: 1 }, handler: "search", args: {} }); + assert.equal(result, "found"); + assert.equal(requests.length, 2); + assert.equal(requests[0].headers["X-Citry-State-Token"], "state-token"); + assert.equal(requests[0].url.searchParams.has("_citry_state_token"), false); + assert.equal(requests[1].headers["X-Citry-State-Token"], undefined); + assert.equal(requests[1].headers["X-Citry-Events"], "1"); + assert.equal( + requests[1].url.searchParams.get("_citry_request_id"), + requests[0].url.searchParams.get("_citry_request_id"), + ); +}); + +test("GET does not retry an answer other than invalid_state, nor a second invalid_state", async () => { + for (const [error, expected] of [ + [staleStateError, 1], + [invalidStateError, 2], + ]) { + let fetched = 0; + const bridge = bridgeModule.createVueEventsBridge({ + endpoint: "/events", + eventBaseUrl: "/events/e/", + host: basicHost(() => ({ ...contextFor(), stateToken: "state-token", descriptor: statefulGetDescriptor })), + fetch: async (url) => { + fetched += 1; + return errorResponse(queryEnvelope(url), error); + }, + }); + await assert.rejects(bridge.send({ source: { stableId: "board", generation: 1 }, handler: "search", args: {} })); + assert.equal(fetched, expected); + } +}); + +test("GET does not retry an invalid_state from a server that reads the token header", async () => { + let fetched = 0; + let vary = ""; + const bridge = bridgeModule.createVueEventsBridge({ + endpoint: "/events", + eventBaseUrl: "/events/e/", + host: basicHost(() => ({ ...contextFor(), stateToken: "state-token", descriptor: statefulGetDescriptor })), + fetch: async (url) => { + fetched += 1; + const response = errorResponse(queryEnvelope(url), invalidStateError); + response.headers.set("Vary", vary); + return response; + }, + }); + for (vary of ["X-Citry-Page-Nonce, X-Citry-State-Token", "*"]) { + fetched = 0; + await assert.rejects(bridge.send({ source: { stableId: "board", generation: 1 }, handler: "search", args: {} })); + assert.equal(fetched, 1, vary); + } +}); + +test("a custom transport that forwards only the URL gets the retry with the token in it", async () => { + const requests = []; + const bridge = bridgeModule.createVueEventsBridge({ + endpoint: "/events", + eventBaseUrl: "/events/e/", + host: basicHost(() => ({ ...contextFor(), stateToken: "state-token", descriptor: statefulGetDescriptor })), + runtimeConfig: () => ({ transport: "memory" }), + transport: () => ({ + send(envelope, request) { + requests.push({ envelope, request }); + const url = new URL(request.url, "https://example.test"); + const ok = url.searchParams.get("_citry_state_token") === "state-token"; + const sendSequence = envelope.calls[0].sendSequence; + return { + protocol: "citry-events/1", + requestId: envelope.requestId, + results: [ + ok + ? { ok: true, sendSequence, actions: [{ action: "data", value: "found" }] } + : { ok: false, sendSequence, error: invalidStateError }, + ], + }; + }, + }), + }); + const result = await bridge.send({ source: { stableId: "board", generation: 1 }, handler: "search", args: {} }); + assert.equal(result, "found"); + assert.equal(requests.length, 2); + assert.equal(requests[1].request.headers["X-Citry-State-Token"], undefined); + // Each send gets its own envelope, so a transport that changes one cannot change the other. + assert.notEqual(requests[0].envelope, requests[1].envelope); + assert.deepEqual(requests[0].envelope, requests[1].envelope); +}); + +test("a custom transport gets the State token of a GET call in its headers", async () => { + const requests = []; + const bridge = bridgeModule.createVueEventsBridge({ + endpoint: "/events", + eventBaseUrl: "/events/e/", + host: basicHost(() => ({ ...contextFor(), stateToken: "state-token", descriptor: statefulGetDescriptor })), + runtimeConfig: () => ({ transport: "memory" }), + transport: () => ({ + send(envelope, request) { + requests.push(request); + return { + protocol: "citry-events/1", + requestId: envelope.requestId, + results: [ + { ok: true, sendSequence: envelope.calls[0].sendSequence, actions: [{ action: "data", value: 1 }] }, + ], + }; + }, + }), + }); + await bridge.send({ source: { stableId: "board", generation: 1 }, handler: "search", args: {} }); + assert.equal(requests.length, 1); + assert.equal(requests[0].method, "GET"); + assert.equal(requests[0].headers["X-Citry-State-Token"], "state-token"); + assert.equal(new URL(requests[0].url, "https://example.test").searchParams.has("_citry_state_token"), false); +}); + test("GET rejects unrepresentable or reserved args before fetch and does not block the next call", async () => { const getDescriptor = { componentClassId: "Board_1", eventHandlers: { search: { httpMethod: "GET" } } }; let fetched = 0; diff --git a/packages/protocol/events/v1/js/src/calls.ts b/packages/protocol/events/v1/js/src/calls.ts index 34d31ed0f8..cf16582d77 100644 --- a/packages/protocol/events/v1/js/src/calls.ts +++ b/packages/protocol/events/v1/js/src/calls.ts @@ -58,6 +58,12 @@ export const CARRIER_FIELDS = { requestId: "_citry_request_id", capabilities: "_citry_capabilities", } as const; +// A GET call sends its State token in this request header, which access logs +// do not record by default, unlike the query string. The server still reads +// CARRIER_FIELDS.stateToken from the query for clients that send it there. +export const CARRIER_HEADERS = { + stateToken: "X-Citry-State-Token", +} as const; const ENVELOPE_FIELDS = new Set([ "protocol", diff --git a/packages/protocol/events/v1/js/test/runtime.test.mjs b/packages/protocol/events/v1/js/test/runtime.test.mjs index 16401def26..dd75e27d42 100644 --- a/packages/protocol/events/v1/js/test/runtime.test.mjs +++ b/packages/protocol/events/v1/js/test/runtime.test.mjs @@ -177,6 +177,12 @@ test("exports the transport carrier field names", () => { }); }); +test("exports the transport carrier header names", () => { + assert.deepEqual(protocol.CARRIER_HEADERS, { + stateToken: "X-Citry-State-Token", + }); +}); + test("strict JSON checks reject browser-only invalid values", () => { const cyclic = {}; cyclic.self = cyclic; diff --git a/packages/protocol/events/v1/python/citry_events/__init__.py b/packages/protocol/events/v1/python/citry_events/__init__.py index d1fd77c635..3b98c13cfe 100644 --- a/packages/protocol/events/v1/python/citry_events/__init__.py +++ b/packages/protocol/events/v1/python/citry_events/__init__.py @@ -34,6 +34,7 @@ REQUEST_ID_FIELD, SEND_SEQUENCE_FIELD, STATE_TOKEN_FIELD, + STATE_TOKEN_HEADER, CarrierFields, add_route_identity, build_partial_call_envelope, @@ -109,6 +110,7 @@ "REQUEST_ID_FIELD", "SEND_SEQUENCE_FIELD", "STATE_TOKEN_FIELD", + "STATE_TOKEN_HEADER", "SWAPS", "CallEnvelopeFailure", "CarrierFields", diff --git a/packages/protocol/events/v1/python/citry_events/carriers.py b/packages/protocol/events/v1/python/citry_events/carriers.py index d499e614bd..206cc48c8d 100644 --- a/packages/protocol/events/v1/python/citry_events/carriers.py +++ b/packages/protocol/events/v1/python/citry_events/carriers.py @@ -18,6 +18,10 @@ PROTOCOL_FIELD = "_citry_protocol" REQUEST_ID_FIELD = "_citry_request_id" CAPABILITIES_FIELD = "_citry_capabilities" +# A GET call sends its State token in this request header, which access logs +# do not record by default, unlike the query string. STATE_TOKEN_FIELD stays +# accepted in the query for clients that send it there. +STATE_TOKEN_HEADER = "X-Citry-State-Token" # noqa: S105 - header name, not a credential FORM_REQUEST_ID = "form" FLAT_REQUEST_ID = "flat" diff --git a/packages/protocol/events/v1/spec.md b/packages/protocol/events/v1/spec.md index f7a5ce8909..cb90a11471 100644 --- a/packages/protocol/events/v1/spec.md +++ b/packages/protocol/events/v1/spec.md @@ -991,7 +991,10 @@ answers the first problem it finds: On a component that declares State, a call needs State when its handler reads State, when it sends `stateUpdates`, or when it sends a token at -all. A component without State ignores a token. +all. A `GET` call is the exception to the last case: its token counts +only when the handler reads State (see +[State tokens on GET](#state-tokens-on-get)). A component without State +ignores a token. Step 1 exists because a later release can change the token format. During a deploy, a page that the new release rendered can send its token @@ -1199,6 +1202,7 @@ Citry's HTTP routes read these request headers: | `X-Citry-Vue-Occurrence` | The ID the browser keeps for the calling component across renders. It is not the component's `renderId`. | | `X-Citry-Vue-Revision` | The revision of the Vue app that the browser has applied, in ASCII digits, at most 2^53 - 1. | | CSRF token header | `X-CSRFToken` unless the app's `_csrf_header` setting or the page names another. Read by a host framework that checks a token, such as Django, or by a component's own `_csrf` check. | +| `X-Citry-State-Token` | Optional. The call's `stateToken`. The server reads it only on a `GET` call to a handler that reads State. Citry's browser code sends it here and not in the URL, because server and proxy access logs record URLs. See [State tokens on GET](#state-tokens-on-get). | | `X-Citry-Page-Nonce` | Optional. The CSP nonce of the page that sends the call, as `Citry.pageNonce()` returns it. When the app sets no `_csp_nonce`, an `html-fragment/1` render carries this nonce if it has the shape of one (CSP base64, at most 256 characters). Experimental. | A `vue-prepared/1` render needs all three `X-Citry-Vue-*` headers; without @@ -1218,15 +1222,30 @@ a proxy that serves the site over https the app sees http while the browser's Whether a call sends `X-Citry-Page-Nonce` changes its answer, so every answer lists `X-Citry-Page-Nonce` in its `Vary` header. The answer to a -call that sends it holds the nonce of one page, so the server also sends -it with `Cache-Control: no-store`, unless a handler's own response sets a -cache policy. Citry's own browser code does +call that sends the nonce holds the nonce of one page, so the server also +sends it with `Cache-Control: no-store`, unless a handler's own response +sets a cache policy. Citry's own browser code does not send the header: its `vue-prepared/1` renders take the nonce from -the page itself. +the page itself. Every answer to a `GET` call also lists +`X-Citry-State-Token` in `Vary`, because the token decides which State +the handler sees. Some shared caches ignore `Vary`, so when a `GET` call +sends `X-Citry-State-Token` and the handler's own response sets a cache +policy, the server limits it to the visitor's browser. It replaces +`Cache-Control` with `private` followed by the directives a browser +cache follows (`max-age`, `no-cache`, `must-revalidate`, +`no-transform`, `immutable`, `stale-while-revalidate`), or with +`no-store` when the policy holds it. It drops every other directive, +such as `public` and `s-maxage`, and the headers that only a CDN reads: +`CDN-Cache-Control` and any `-CDN-Cache-Control`, +`Surrogate-Control`, `Edge-Control`, and `X-Accel-Expires`. A refusal sent before the handler runs also +lists these headers in `Vary`, and on a `GET` call it carries +`Cache-Control: no-store`. Citry's browser code sends `X-Citry-Events` and the three `X-Citry-Vue-*` -headers on every call. It sends the CSRF token header on a call that is -not `GET` when the page has a token and the event URL is on the page's +headers on every call, and `X-Citry-State-Token` on a `GET` call to a +handler that reads State, except on the one retry that +[State tokens on GET](#state-tokens-on-get) describes. It sends the +CSRF token header on a call that is not `GET` when the page has a token and the event URL is on the page's origin. Browser code that sends calls some other way, such as a transport registered with `Citry.events.registerTransport`, must send the headers it is given. Server code that runs calls itself, @@ -1250,6 +1269,64 @@ hand-authored GET URL may omit all of them. The adapter supplies the current protocol, a transport-local request ID, baseline capabilities, and no caller, token, or send sequence. +### State tokens on GET + +A `GET` call to a handler that reads State sends its State token in one +of two places: + +- the `X-Citry-State-Token` request header, which Citry's browser code + uses, because server and proxy access logs record the URL of every + request and, by default, not its headers; +- the `_citry_state_token` query field, which the server also reads, so + clients that send the token there keep working. + +A `GET` call to any other handler has no use for a token, and the server +ignores one wherever it is sent. + +The server treats the header and the query field as one token. An empty +header or query field counts as absent. + +| The call sends | The server uses | +|---|---| +| Only the header | The header | +| Only the query field, once | The query field | +| The same token in both | That token | +| Different tokens in the header and the query field | Neither. It answers `400` with code `protocol_mismatch`, and the handler does not run. | +| The header, and the query field more than once | Neither, as above. | + +Refusing two different tokens keeps a URL that someone else wrote from +choosing which State a call runs with. A query field sent more than once +without the header gives no token, as for any other `GET` call. + +The server then checks the token as [State tokens](#state-tokens) +describes, wherever it came from, so a malformed header answers +`invalid_state` like a malformed query field. + +A server that only reads the query field, such as one running Citry +1.2.0 or earlier, does not see a token sent in the header and answers +`invalid_state`. This happens when a page that a newer release rendered +calls a server that still runs an older one, for example during a +rolling deploy or a rollback. A proxy in front of the server must +forward the header: a server that reads it but does not receive it +answers `invalid_state`, and the browser does not retry. + +A server that reads the header lists `X-Citry-State-Token` in `Vary` on +every `GET` answer, and an older server does not. So when a `GET` call +that sent the token only in the header gets a single `invalid_state` +error without that `Vary` entry, Citry's browser code sends the same +call once more with the token in the query field and without the +header, and uses that answer. A browser can read `Vary` on an answer +from another origin only when the server lists it in +`Access-Control-Expose-Headers`, and a custom transport returns no +headers. In those cases the browser retries on any such +`invalid_state`. A client that sends the header should do +the same while it may reach an older server. + +A header sent more than once reaches the server as one value joined +with commas, which is not a token the server can read, so the call +answers `invalid_state`. A web server may refuse a header longer than +its own limit with its own error before Citry sees the call. + ## Versioning The number after the slash in the `protocol` string is the protocol major, diff --git a/packages/py/citry/citry/_protocol/events/__init__.py b/packages/py/citry/citry/_protocol/events/__init__.py index d1fd77c635..3b98c13cfe 100644 --- a/packages/py/citry/citry/_protocol/events/__init__.py +++ b/packages/py/citry/citry/_protocol/events/__init__.py @@ -34,6 +34,7 @@ REQUEST_ID_FIELD, SEND_SEQUENCE_FIELD, STATE_TOKEN_FIELD, + STATE_TOKEN_HEADER, CarrierFields, add_route_identity, build_partial_call_envelope, @@ -109,6 +110,7 @@ "REQUEST_ID_FIELD", "SEND_SEQUENCE_FIELD", "STATE_TOKEN_FIELD", + "STATE_TOKEN_HEADER", "SWAPS", "CallEnvelopeFailure", "CarrierFields", diff --git a/packages/py/citry/citry/_protocol/events/carriers.py b/packages/py/citry/citry/_protocol/events/carriers.py index d499e614bd..206cc48c8d 100644 --- a/packages/py/citry/citry/_protocol/events/carriers.py +++ b/packages/py/citry/citry/_protocol/events/carriers.py @@ -18,6 +18,10 @@ PROTOCOL_FIELD = "_citry_protocol" REQUEST_ID_FIELD = "_citry_request_id" CAPABILITIES_FIELD = "_citry_capabilities" +# A GET call sends its State token in this request header, which access logs +# do not record by default, unlike the query string. STATE_TOKEN_FIELD stays +# accepted in the query for clients that send it there. +STATE_TOKEN_HEADER = "X-Citry-State-Token" # noqa: S105 - header name, not a credential FORM_REQUEST_ID = "form" FLAT_REQUEST_ID = "flat" diff --git a/packages/py/citry/citry/_vue/events.js b/packages/py/citry/citry/_vue/events.js index 59e728932d..37b37041cc 100644 --- a/packages/py/citry/citry/_vue/events.js +++ b/packages/py/citry/citry/_vue/events.js @@ -1,2 +1,2 @@ /* Citry Vue Events bridge. GENERATED FILE, do not edit: built from packages/js/citry-client/src/citry-events-vue.ts (pnpm run build there). */ -var CitryVueEvents=(()=>{var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:true,configurable:true,writable:true,value}):obj[key]=value;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var __publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!=="symbol"?key+"":key,value);var citry_events_vue_exports={};__export(citry_events_vue_exports,{assertValidActionList:()=>assertValidActionList2,collectFormArgs:()=>collectFormArgs,createVueEventsBridge:()=>createVueEventsBridge});var ProtocolValueError=class extends TypeError{constructor(issue){super(issue.message);__publicField(this,"issue");this.name="ProtocolValueError";this.issue=issue}};var hasOwn=(value,key)=>Object.prototype.hasOwnProperty.call(value,key);var pointer=(parent,member)=>{const escaped=String(member).replace(/~/g,"~0").replace(/\//g,"~1");return parent?`${parent}/${escaped}`:`/${escaped}`};var isPlainObject=value=>{if(value===null||typeof value!=="object"||Array.isArray(value))return false;const prototype=Object.getPrototypeOf(value);return prototype===Object.prototype||prototype===null};var firstUnknown=(value,allowed)=>Object.keys(value).filter(key=>!allowed.has(key)).sort()[0]??null;var containerIssue=(value,path)=>{if(Object.getOwnPropertySymbols(value).length){return{path:path(),category:"strict_json",message:"The value contains a symbol-keyed property."}}for(const name of Object.getOwnPropertyNames(value)){if(Array.isArray(value)&&name==="length")continue;const descriptor=Object.getOwnPropertyDescriptor(value,name);if(!descriptor?.enumerable||!("value"in descriptor)){return{path:pointer(path(),name),category:"strict_json",message:"A JSON property must be an enumerable data property."}}}return null};var validateStrictJson=(value,path="")=>{const pathOf=frame=>{const members=[];for(let cursor=frame;cursor.parent;cursor=cursor.parent)members.push(cursor.member);let result=path;for(let index=members.length-1;index>=0;index-=1)result=pointer(result,members[index]);return result};const stack=[{value,parent:null,member:"",leaving:false}];const ancestors=new Set;while(stack.length){const frame=stack.pop();const current=frame.value;if(frame.leaving){ancestors.delete(current);continue}if(current===null||typeof current==="string"||typeof current==="boolean"){continue}if(typeof current==="number"){if(!Number.isFinite(current)){return{path:pathOf(frame),category:"strict_json",message:"The value contains a non-finite number."}}continue}if(typeof current!=="object"){return{path:pathOf(frame),category:"strict_json",message:"The value contains a non-JSON value."}}if(!Array.isArray(current)&&!isPlainObject(current)){return{path:pathOf(frame),category:"strict_json",message:"The value contains a non-JSON object."}}const ownIssue=containerIssue(current,()=>pathOf(frame));if(ownIssue)return ownIssue;if(ancestors.has(current)){return{path:pathOf(frame),category:"strict_json",message:"The value contains a cycle."}}ancestors.add(current);frame.leaving=true;stack.push(frame);if(Array.isArray(current)){const names=Object.keys(current);if(names.length!==current.length||names.some((name,index)=>name!==String(index))){return{path:pathOf(frame),category:"strict_json",message:"A JSON array must be dense and carry no named properties."}}for(let index=current.length-1;index>=0;index-=1){stack.push({value:current[index],parent:frame,member:index,leaving:false})}continue}const keys=Object.keys(current).sort();for(let index=keys.length-1;index>=0;index-=1){const key=keys[index];stack.push({value:current[key],parent:frame,member:key,leaving:false})}}return null};var copyJson=value=>{const issue=validateStrictJson(value);if(issue)throw new ProtocolValueError(issue);if(value===null||typeof value!=="object")return value;const copied=Array.isArray(value)?new Array(value.length):{};const stack=[{source:value,target:copied}];while(stack.length){const{source,target}=stack.pop();for(const key of Object.keys(source)){const item=source[key];if(item!==null&&typeof item==="object"){const child=Array.isArray(item)?new Array(item.length):{};Object.defineProperty(target,key,{configurable:true,enumerable:true,value:child,writable:true});stack.push({source:item,target:child})}else{Object.defineProperty(target,key,{configurable:true,enumerable:true,value:item,writable:true})}}}return copied};var PROTOCOL="citry-events/1";var CALLS_LIMIT=16;var ACTION_KINDS=["render","data","state","event","redirect","url"];var SWAPS=["morph","replace","inner","append","prepend","remove","none"];var RENDERERS=["html-fragment/1","vue-prepared/1"];var CAPABILITIES_BASELINE_V1={swaps:["replace","inner","append","prepend","remove","none"],actions:ACTION_KINDS,renderers:["html-fragment/1"]};var ARGS_SOURCE_FORM="form";var ENVELOPE_FIELDS=new Set(["protocol","requestId","capabilities","calls"]);var CALL_FIELDS=new Set(["componentClassId","handlerName","callerRenderId","args","argsSource","stateToken","stateUpdates","sendSequence"]);var isSafeRenderId=value=>typeof value==="string"&&/^[a-z0-9_-]+$/.test(value);var nonEmptyStringIssue=(value,path,message)=>{if(typeof value!=="string")return{path,category:"type",message};if(!value)return{path,category:"range",message};return null};var integerIssue=(value,path,message)=>{if(typeof value!=="number"||!Number.isInteger(value)){if(typeof value==="number"&&!Number.isFinite(value)){return{path,category:"strict_json",message}}return{path,category:"type",message}}if(value<0)return{path,category:"range",message};return null};var validateCall=(value,path="")=>{const jsonIssue=validateStrictJson(value,path);if(jsonIssue)return jsonIssue;if(!isPlainObject(value)){return{path,category:"type",message:"Each entry of 'calls' must be a call object."}}for(const required of["componentClassId","handlerName","args"]){if(!hasOwn(value,required)){return{path:pointer(path,required),category:"required",message:`The call is missing required field '${required}'.`}}}const unknown=firstUnknown(value,CALL_FIELDS);if(unknown!==null){return{path:pointer(path,unknown),category:"unknown_field",message:`The call carries unknown field '${unknown}'.`}}for(const field of["componentClassId","handlerName"]){const issue=nonEmptyStringIssue(value[field],pointer(path,field),`The call's '${field}' must be a non-empty string.`);if(issue)return issue}if(hasOwn(value,"callerRenderId")){const issue=nonEmptyStringIssue(value.callerRenderId,pointer(path,"callerRenderId"),"The call's 'callerRenderId' must be a non-empty string.");if(issue)return issue;if(!isSafeRenderId(value.callerRenderId)){return{path:pointer(path,"callerRenderId"),category:"pattern",message:"The call's 'callerRenderId' must use only lowercase ASCII letters, digits, hyphens, and underscores."}}}if(!isPlainObject(value.args)){return{path:pointer(path,"args"),category:"type",message:"The call's 'args' must be an object."}}const argsIssue=validateStrictJson(value.args);if(argsIssue){return{path:pointer(path,"args")+argsIssue.path,category:"strict_json",message:"The call's 'args' must contain only strict JSON values under string keys."}}if(hasOwn(value,"argsSource")&&value.argsSource!==ARGS_SOURCE_FORM){return{path:pointer(path,"argsSource"),category:typeof value.argsSource==="string"?"enum":"type",message:`The call's 'argsSource' must be '${ARGS_SOURCE_FORM}' or omitted.`}}if(hasOwn(value,"stateToken")){const issue=nonEmptyStringIssue(value.stateToken,pointer(path,"stateToken"),"The call's 'stateToken' must be a non-empty string.");if(issue)return issue}if(hasOwn(value,"stateUpdates")){if(!isPlainObject(value.stateUpdates)){return{path:pointer(path,"stateUpdates"),category:"type",message:"The call's 'stateUpdates' must be an object."}}const stateIssue=validateStrictJson(value.stateUpdates);if(stateIssue){return{path:pointer(path,"stateUpdates")+stateIssue.path,category:"strict_json",message:"The call's 'stateUpdates' must contain only strict JSON values under string keys."}}}if(hasOwn(value,"sendSequence")){return integerIssue(value.sendSequence,pointer(path,"sendSequence"),"The call's 'sendSequence' must be an integer of at least 0.")}return null};var validateCapabilities=(value,path="/capabilities")=>{const jsonIssue=validateStrictJson(value,path);if(jsonIssue)return jsonIssue;const message="The envelope's 'capabilities' must contain only 'swaps', 'actions', and 'renderers'; each value must be a duplicate-free array of known v1 names.";if(!isPlainObject(value))return{path,category:"type",message};const unknown=firstUnknown(value,new Set(["swaps","actions","renderers"]));if(unknown!==null){return{path:pointer(path,unknown),category:"unknown_field",message}}for(const[name,known]of[["swaps",SWAPS],["actions",ACTION_KINDS],["renderers",RENDERERS]]){if(!hasOwn(value,name))continue;const items=value[name];const itemPath=pointer(path,name);if(!Array.isArray(items))return{path:itemPath,category:"type",message};for(let index=0;index{const jsonIssue=validateStrictJson(value);if(jsonIssue)return jsonIssue;if(!isPlainObject(value)){return{path:"",category:"type",message:"The request body is not a call envelope object."}}for(const required of["protocol","requestId","calls"]){if(!hasOwn(value,required)){return{path:pointer("",required),category:"required",message:`The envelope requires '${required}'.`}}}const unknown=firstUnknown(value,ENVELOPE_FIELDS);if(unknown!==null){return{path:pointer("",unknown),category:"unknown_field",message:`The envelope carries unknown field '${unknown}'.`}}if(value.protocol!==PROTOCOL){return{path:"/protocol",category:typeof value.protocol==="string"?"enum":"type",message:"The envelope protocol must be citry-events/1."}}const requestIssue=nonEmptyStringIssue(value.requestId,"/requestId","The envelope carries no 'requestId' string.");if(requestIssue)return requestIssue;if(hasOwn(value,"capabilities")){const issue=validateCapabilities(value.capabilities);if(issue)return issue}if(!Array.isArray(value.calls)){return{path:"/calls",category:"type",message:"The envelope calls must be an array."}}if(!value.calls.length||value.calls.length>CALLS_LIMIT){return{path:"/calls",category:"range",message:`The envelope must carry 1 to ${CALLS_LIMIT} calls.`}}for(let index=0;index{const call={componentClassId:input.componentClassId,handlerName:input.handlerName,args:copyJson(input.args)};for(const field of["argsSource","callerRenderId","stateToken","sendSequence"]){if(input[field]!==void 0)call[field]=input[field]}if(input.stateUpdates!==void 0){call.stateUpdates=copyJson(input.stateUpdates)}const issue=validateCall(call);if(issue)throw new ProtocolValueError(issue);return call};var buildCallEnvelope=(requestId,calls,capabilities)=>{const envelope={protocol:PROTOCOL,requestId,calls:copyJson(calls)};if(capabilities!==void 0)envelope.capabilities=copyJson(capabilities);const issue=validateCallEnvelope(envelope);if(issue)throw new ProtocolValueError(issue);return envelope};var HTTP_METHOD=/^[!#$%&'*+.^_`|~0-9A-Z-]+$/;var DESCRIPTOR_FIELDS=new Set(["componentClassId","eventHandlers","writableStateFields"]);var HANDLER_FIELDS=new Set(["httpMethod","usesState","debounceMilliseconds","throttleMilliseconds","latestCallWins","allowBatching","detached"]);var nonNegativeIntegerIssue=(value,path,name)=>{if(typeof value!=="number"||!Number.isInteger(value)){return{path,category:typeof value==="number"&&!Number.isFinite(value)?"strict_json":"type",message:`The ${name} hint must be an integer.`}}if(value<0){return{path,category:"range",message:`The ${name} hint must be at least 0.`}}return null};var validateHandlerDescriptor=(value,path="")=>{const jsonIssue=validateStrictJson(value,path);if(jsonIssue)return jsonIssue;if(!isPlainObject(value)){return{path,category:"type",message:"Event-handler hints must be an object."}}if(!hasOwn(value,"httpMethod")){return{path:pointer(path,"httpMethod"),category:"required",message:"Handler hints require 'httpMethod'."}}const unknown=firstUnknown(value,HANDLER_FIELDS);if(unknown!==null){return{path:pointer(path,unknown),category:"unknown_field",message:"Handler hints have an unknown field."}}if(typeof value.httpMethod!=="string"){return{path:pointer(path,"httpMethod"),category:"type",message:"The HTTP method must be a string."}}if(!HTTP_METHOD.test(value.httpMethod)){return{path:pointer(path,"httpMethod"),category:"pattern",message:"The HTTP method must be an uppercase token."}}if(hasOwn(value,"usesState")&&value.usesState!==true){return{path:pointer(path,"usesState"),category:"enum",message:"The usesState hint has its non-default literal value."}}for(const name of["debounceMilliseconds","throttleMilliseconds"]){if(!hasOwn(value,name))continue;const issue=nonNegativeIntegerIssue(value[name],pointer(path,name),name);if(issue)return issue}if(hasOwn(value,"latestCallWins")&&value.latestCallWins!==true){return{path:pointer(path,"latestCallWins"),category:"enum",message:"The latestCallWins hint has its non-default literal value."}}if(hasOwn(value,"allowBatching")&&value.allowBatching!==false){return{path:pointer(path,"allowBatching"),category:"enum",message:"The allowBatching hint has its non-default literal value."}}if(hasOwn(value,"detached")&&value.detached!==true){return{path:pointer(path,"detached"),category:"enum",message:"The detached hint has its non-default literal value."}}return null};var validateDescriptor=(value,path="")=>{const jsonIssue=validateStrictJson(value,path);if(jsonIssue)return jsonIssue;if(!isPlainObject(value)){return{path,category:"type",message:"A component descriptor must be an object."}}for(const required of["componentClassId","eventHandlers"]){if(!hasOwn(value,required)){return{path:pointer(path,required),category:"required",message:`The descriptor requires '${required}'.`}}}const unknown=firstUnknown(value,DESCRIPTOR_FIELDS);if(unknown!==null){return{path:pointer(path,unknown),category:"unknown_field",message:"The descriptor has an unknown field."}}if(typeof value.componentClassId!=="string"){return{path:pointer(path,"componentClassId"),category:"type",message:"The component class ID must be a string."}}if(!value.componentClassId){return{path:pointer(path,"componentClassId"),category:"range",message:"The component class ID must not be empty."}}if(!isPlainObject(value.eventHandlers)){return{path:pointer(path,"eventHandlers"),category:"type",message:"Event handlers must be an object."}}for(const name of Object.keys(value.eventHandlers).sort()){if(!name){return{path:pointer(path,"eventHandlers"),category:"range",message:"A handler name must not be empty."}}const issue=validateHandlerDescriptor(value.eventHandlers[name],pointer(pointer(path,"eventHandlers"),name));if(issue)return issue}if(hasOwn(value,"writableStateFields")){const fields=value.writableStateFields;const fieldPath=pointer(path,"writableStateFields");if(!Array.isArray(fields)){return{path:fieldPath,category:"type",message:"Writable State fields must be an array."}}const seen=new Set;for(let index=0;index{if(typeof value!=="number"||!Number.isInteger(value)){return{path,category:typeof value==="number"&&!Number.isFinite(value)?"strict_json":"type",message}}if(value<0)return{path,category:"range",message};return null};var validateTiming=(value,path)=>{if(hasOwn(value,"delay")){const delay=value.delay;if(typeof delay!=="number"){return{path:pointer(path,"delay"),category:"type",message:"The action delay must be a finite number."}}if(!Number.isFinite(delay)){return{path:pointer(path,"delay"),category:"strict_json",message:"The action delay must be finite."}}if(delay<0){return{path:pointer(path,"delay"),category:"range",message:"The action delay must be at least 0."}}}if(hasOwn(value,"wait")&&value.wait!==false){return{path:pointer(path,"wait"),category:"enum",message:"The action wait flag, when present, must be false."}}return null};var MARK_NAME=/^[A-Za-z][A-Za-z0-9_-]*$/;var validateTarget=(value,path,allowMarker)=>{if(typeof value!=="string"){return{path,category:"type",message:"An action target must be a non-empty string."}}if(!value){return{path,category:"range",message:"An action target must be a non-empty string."}}if(value.startsWith("render:")){if(isSafeRenderId(value.slice(7)))return null;return{path,category:"pattern",message:"A render: target must contain a valid render ID."}}if(allowMarker&&value.startsWith("mark:")){const rest=value.slice(5);const separator=rest.indexOf(":");const caller=separator<0?"":rest.slice(0,separator);const name=separator<0?"":rest.slice(separator+1);if(isSafeRenderId(caller)&&MARK_NAME.test(name))return null;return{path,category:"pattern",message:"A marker target must be mark:: with a valid ID and name."}}return{path,category:"pattern",message:allowMarker?"A render target must be render: or mark::.":"An event target must be render:."}};var validateActionShape=(value,path="")=>{if(!isPlainObject(value)){return{path,category:"type",message:"An action must be an object."}}if(!hasOwn(value,"action")){return{path:pointer(path,"action"),category:"required",message:"The action kind is required."}}if(typeof value.action!=="string"){return{path:pointer(path,"action"),category:"type",message:"The action kind must be a string."}}if(!ACTION_KINDS.includes(value.action)){return{path:pointer(path,"action"),category:"enum",message:`Unknown action kind '${value.action}'.`}}const kind=value.action;for(const required of ACTION_REQUIRED[kind]){if(!hasOwn(value,required)){return{path:pointer(path,required),category:"required",message:`The ${kind} action requires '${required}'.`}}}const unknown=firstUnknown(value,ACTION_FIELDS[kind]);if(unknown!==null){return{path:pointer(path,unknown),category:"unknown_field",message:`The ${kind} action has an unknown field.`}}if(kind==="render"){const targetIssue=validateTarget(value.target,pointer(path,"target"),true);if(targetIssue)return targetIssue;if(!SWAPS.includes(value.swap)){return{path:pointer(path,"swap"),category:typeof value.swap==="string"?"enum":"type",message:"The render swap is not a v1 swap."}}const renderer=hasOwn(value,"renderer")?value.renderer:"html-fragment/1";if(typeof renderer!=="string"){return{path:pointer(path,"renderer"),category:"type",message:"The render renderer must be a string."}}if(!RENDERERS.includes(renderer)){return{path:pointer(path,"renderer"),category:"enum",message:"The render renderer is not a v1 renderer."}}const content=renderer==="html-fragment/1"?"html":"prepared";const other=content==="html"?"prepared":"html";if(!hasOwn(value,content)){return{path:pointer(path,content),category:"required",message:`The ${renderer} render requires '${content}'.`}}if(hasOwn(value,other)){return{path:pointer(path,other),category:"semantic",message:"A render action must carry exactly one content representation."}}if(content==="html"&&typeof value.html!=="string"){return{path:pointer(path,"html"),category:"type",message:"The render HTML must be a string."}}if(content==="prepared"&&!isPlainObject(value.prepared)){return{path:pointer(path,"prepared"),category:"type",message:"The prepared render content must be a JSON object."}}if(content==="prepared"&&value.swap!=="morph"){return{path:pointer(path,"swap"),category:"enum",message:"A vue-prepared/1 render must use the morph swap."}}}else if(kind==="data"){}else if(kind==="state"){if(typeof value.targetRenderId!=="string"){return{path:pointer(path,"targetRenderId"),category:"type",message:"The state target must be a render ID."}}if(!isSafeRenderId(value.targetRenderId)){return{path:pointer(path,"targetRenderId"),category:"pattern",message:"The state target must be a valid render ID."}}if(typeof value.stateToken!=="string"){return{path:pointer(path,"stateToken"),category:"type",message:"The state token must be a string."}}if(!value.stateToken){return{path:pointer(path,"stateToken"),category:"range",message:"The state token must not be empty."}}if(!isPlainObject(value.publicState)){return{path:pointer(path,"publicState"),category:"type",message:"Public State must be an object."}}}else if(kind==="event"){if(typeof value.eventName!=="string"){return{path:pointer(path,"eventName"),category:"type",message:"The event name must be a string."}}if(!value.eventName){return{path:pointer(path,"eventName"),category:"range",message:"The event name must not be empty."}}if(value.eventName.startsWith("citry:")){return{path:pointer(path,"eventName"),category:"pattern",message:"The event name is reserved."}}if(hasOwn(value,"target")){const issue=validateTarget(value.target,pointer(path,"target"),false);if(issue)return issue}}else if(kind==="redirect"){if(typeof value.url!=="string"){return{path:pointer(path,"url"),category:"type",message:"The redirect URL must be a string."}}if(!value.url){return{path:pointer(path,"url"),category:"range",message:"The redirect URL must not be empty."}}}else{if(typeof value.url!=="string"){return{path:pointer(path,"url"),category:"type",message:"The URL action URL must be a string."}}if(!value.url){return{path:pointer(path,"url"),category:"range",message:"The URL action URL must not be empty."}}if(value.mode!=="push"&&value.mode!=="replace"){return{path:pointer(path,"mode"),category:typeof value.mode==="string"?"enum":"type",message:"The URL action mode must be push or replace."}}}return validateTiming(value,path)};var validateErrorShape=(value,path="")=>{if(!isPlainObject(value)){return{path,category:"type",message:"The result error must be an object."}}for(const required of["status","code","message"]){if(!hasOwn(value,required)){return{path:pointer(path,required),category:"required",message:`The error requires '${required}'.`}}}const unknown=firstUnknown(value,ERROR_FIELDS);if(unknown!==null){return{path:pointer(path,unknown),category:"unknown_field",message:"The result error has an unknown field."}}if(typeof value.status!=="number"||!Number.isInteger(value.status)){return{path:pointer(path,"status"),category:typeof value.status==="number"&&!Number.isFinite(value.status)?"strict_json":"type",message:"The error status must be an integer."}}if(value.status<400||value.status>599){return{path:pointer(path,"status"),category:"range",message:"The error status must be from 400 to 599."}}if(typeof value.code!=="string"){return{path:pointer(path,"code"),category:"type",message:"The error code must be a string."}}if(!hasOwn(ERROR_STATUS_BY_CODE,value.code)){return{path:pointer(path,"code"),category:"enum",message:"The error code is not a v1 code."}}if(typeof value.message!=="string"){return{path:pointer(path,"message"),category:"type",message:"The error message must be a string."}}if(!value.message){return{path:pointer(path,"message"),category:"range",message:"The error message must not be empty."}}if(hasOwn(value,"fieldErrors")){if(!isPlainObject(value.fieldErrors)){return{path:pointer(path,"fieldErrors"),category:"type",message:"Field errors must be an object."}}for(const name of Object.keys(value.fieldErrors).sort()){if(typeof value.fieldErrors[name]!=="string"){return{path:pointer(pointer(path,"fieldErrors"),name),category:"type",message:"Field errors map strings."}}}}const expected=ERROR_STATUS_BY_CODE[value.code];if(expected!==null&&value.status!==expected){return{path:pointer(path,"status"),category:"semantic",message:"The error status does not match its code."}}return null};var validateResultShape=(value,path="")=>{if(!isPlainObject(value)){return{path,category:"type",message:"A result must be an object."}}if(!hasOwn(value,"ok")){return{path:pointer(path,"ok"),category:"required",message:"The result requires 'ok'."}}if(typeof value.ok!=="boolean"){return{path:pointer(path,"ok"),category:"type",message:"The result's 'ok' field must be a boolean."}}const required=value.ok?["ok","actions"]:["ok","error"];for(const field of required){if(!hasOwn(value,field)){return{path:pointer(path,field),category:"required",message:`The result requires '${field}'.`}}}const unknown=firstUnknown(value,value.ok?OK_RESULT_FIELDS:ERROR_RESULT_FIELDS);if(unknown!==null){return{path:pointer(path,unknown),category:"unknown_field",message:"The result has an unknown field."}}if(hasOwn(value,"sendSequence")){const issue=validateNonNegativeInteger(value.sendSequence,pointer(path,"sendSequence"),"The send sequence must be an integer.");if(issue)return issue}if(!value.ok)return validateErrorShape(value.error,pointer(path,"error"));if(!Array.isArray(value.actions)){return{path:pointer(path,"actions"),category:"type",message:"The result actions must be an array."}}for(let index=0;indexisPlainObject(action)&&action.action==="data").length>1){return{path:pointer(path,"actions"),category:"semantic",message:"Each result may carry at most one data action."}}return null};var validateResult=(value,path="")=>{const jsonIssue=validateStrictJson(value,path);return jsonIssue??validateResultShape(value,path)};var validateResultEnvelopeShape=(value,path="")=>{if(!isPlainObject(value)){return{path,category:"type",message:"The result envelope must be an object."}}for(const required of["protocol","requestId","results"]){if(!hasOwn(value,required)){return{path:pointer(path,required),category:"required",message:`The result envelope requires '${required}'.`}}}const unknown=firstUnknown(value,RESULT_ENVELOPE_FIELDS);if(unknown!==null){return{path:pointer(path,unknown),category:"unknown_field",message:"The result envelope has an unknown field."}}if(value.protocol!==PROTOCOL){return{path:pointer(path,"protocol"),category:typeof value.protocol==="string"?"enum":"type",message:"The result protocol must be citry-events/1."}}if(value.requestId!==null&&typeof value.requestId!=="string"){return{path:pointer(path,"requestId"),category:"type",message:"The result request ID must be a string or null."}}if(value.requestId===""){return{path:pointer(path,"requestId"),category:"range",message:"The result request ID must not be empty."}}if(!Array.isArray(value.results)){return{path:pointer(path,"results"),category:"type",message:"The results must be an array."}}if(!value.results.length){return{path:pointer(path,"results"),category:"range",message:"The results array must not be empty."}}for(let index=0;index{const jsonIssue=validateStrictJson(value,path);return jsonIssue??validateResultEnvelopeShape(value,path)};var validateExchangeAfterValidatedEnvelope=(callEnvelope,resultEnvelope)=>{const result=resultEnvelope;if(result.requestId!==callEnvelope.requestId){return{path:"/requestId",category:"correlation",message:"The result request ID does not match the call."}}if(result.results.length!==callEnvelope.calls.length){return{path:"/results",category:"correlation",message:"The result count does not match the call count."}}const advertised=callEnvelope.capabilities??{};const actions=new Set(advertised.actions??CAPABILITIES_BASELINE_V1.actions);const swaps=new Set(advertised.swaps??CAPABILITIES_BASELINE_V1.swaps);const renderers=new Set(advertised.renderers??CAPABILITIES_BASELINE_V1.renderers);for(let index=0;indexvalidateResult({ok:true,actions});var buildOkResult=(actions,sendSequence)=>{const result={ok:true,actions:copyJson(actions)};if(sendSequence!==void 0)result.sendSequence=sendSequence;const issue=validateResult(result);if(issue)throw new ProtocolValueError(issue);return result};var resultIndex=path=>{const match=/^\/results\/(\d+)(?:\/|$)/.exec(path);return match?Number(match[1]):null};var preflightResultEnvelope=(reply,sent)=>{const structural=validateResultEnvelope(reply);if(structural){const edge=isPlainObject(reply)&&reply.requestId===null;const index=resultIndex(structural.path);return{ok:false,issue:structural,reason:edge&&structural.path.startsWith("/results")?"edge":index===null?"header":`result ${index}`}}const envelope=reply;if(envelope.requestId===null){const edge=envelope.results[0];return{ok:true,results:sent.calls.map(()=>edge)}}const relationship=validateExchangeAfterValidatedEnvelope(sent,envelope);if(relationship){const index=resultIndex(relationship.path);return{ok:false,issue:relationship,reason:relationship.path==="/requestId"||relationship.path==="/results"&&relationship.category==="correlation"?"correlation":`result ${index??0}`}}return{ok:true,results:envelope.results}};var assertValidActionList=actions=>{const issue=validateActionList(actions);if(issue)throw new ProtocolValueError(issue);return actions};var isFormSubmitter=(value,form)=>(typeof HTMLButtonElement==="function"&&value instanceof HTMLButtonElement||typeof HTMLInputElement==="function"&&value instanceof HTMLInputElement)&&value.form===form;var collectFormArgs=(form,reservedFields,submitter)=>{const entries=new Map;const button=isFormSubmitter(submitter,form)?submitter:void 0;let data;try{data=new FormData(form,button)}catch{data=new FormData(form)}data.forEach((value,name)=>{if(reservedFields.has(name)||typeof value!=="string")return;const bucket=entries.get(name)??[];bucket.push(value);entries.set(name,bucket)});const output={};entries.forEach((values,name)=>{Object.defineProperty(output,name,{configurable:true,enumerable:true,value:values.length===1?values[0]:values.slice(),writable:true})});return output};var builtInMember=(target,key)=>{const own=Object.getOwnPropertyDescriptor(target,key);if(own!==void 0&&(own.get!==void 0||own.set!==void 0))return own;for(let proto=Object.getPrototypeOf(target);proto!==null;proto=Object.getPrototypeOf(proto)){const descriptor=Object.getOwnPropertyDescriptor(proto,key);if(descriptor!==void 0)return descriptor}return void 0};var documentMembers=currentDocument=>{const bound=new WeakMap;const bind=(method,target)=>{const cached=bound.get(method);if(cached!==void 0&&cached.target===target)return cached.method;const boundMethod=method.bind(target);bound.set(method,{target,method:boundMethod});return boundMethod};return new Proxy({},{get(_shell,key){const target=currentDocument();const descriptor=builtInMember(target,key);let value;if(descriptor===void 0)value=Reflect.get(target,key);else if(descriptor.get!==void 0)return descriptor.get.call(target);else if(descriptor.set!==void 0)return void 0;else value=descriptor.value;return typeof value==="function"?bind(value,target):value},set(_shell,key,value){const target=currentDocument();const descriptor=builtInMember(target,key);if(descriptor?.set!==void 0){descriptor.set.call(target,value);return true}return Reflect.set(target,key,value)}})};var pageDocument=documentMembers(()=>globalThis.document);var pageOrigin=()=>{const scope=globalThis;if(scope.location===void 0)return null;return typeof scope.origin==="string"?scope.origin:String(scope.location.origin)};var onPageOrigin=target=>{const origin=pageOrigin();return origin!==null&&target.origin!=="null"&&target.origin===origin};var resolveOnPage=url=>{const location=globalThis.location;if(location===void 0||typeof location.href!=="string")return null;try{return new URL(url,location.href)}catch{let inherited;try{inherited=new URL(url,pageDocument.baseURI)}catch{throw new Error(`Citry cannot resolve the URL ${JSON.stringify(url.slice(0,80))}.`)}if(!onPageOrigin(inherited))throw new Error("Citry refused a URL that does not resolve to this page's origin.");return inherited}};var assertValidActionList2=actions=>assertValidActionList(actions);var describeValue=value=>typeof value==="string"?JSON.stringify(value):typeof value==="number"?String(value):`a ${typeof value}`;var checkSendOptions=value=>{if(value===void 0)return void 0;if(value===null||typeof value!=="object"||Array.isArray(value))throw new TypeError("Citry Events send options must be an object, such as {timeout: 5000}.");for(const key of Object.keys(value)){if(key!=="timeout"&&key!=="wait")throw new TypeError(`Citry Events send got an unknown option '${key}'; the options are 'timeout' and 'wait'.`)}const{timeout,wait}=value;if(wait!==void 0&&wait!==true&&wait!==false)throw new TypeError(`Citry Events option 'wait' must be true or false; got ${describeValue(wait)}.`);if(timeout!==void 0&&(typeof timeout!=="number"||!Number.isFinite(timeout)||timeout<=0))throw new Error("Citry Events timeout must be a positive finite number.");const checked={};if(timeout!==void 0)checked.timeout=timeout;if(wait===false)checked.wait=false;return checked};var queuedHandlerError=handler=>new TypeError(`Citry Events option 'wait: false' needs a detached handler, and '${handler}' is not one. Calls from one Vue app are sent one at a time, in order, because each render and State change builds on the one before it. Remove 'wait: false', or declare the handler with @event(detached=True) if it never renders or changes State. To replace an older call to the same handler instead, declare it with @event(latest_wins=True).`);var validContext=value=>value!==null&&typeof value==="object"&&Object.keys(value).sort().join("|")==="componentClassId|descriptor|publicState|serverRenderId|stateToken"&&validateStrictJson(value)===null&&typeof value.serverRenderId==="string"&&value.serverRenderId.length>0&&(value.stateToken===null||typeof value.stateToken==="string"&&value.stateToken.length>0)&&typeof value.componentClassId==="string"&&value.componentClassId.length>0&&validateDescriptor(value.descriptor)===null&&value.descriptor.componentClassId===value.componentClassId;var VueEventCancellation=class extends Error{};var VueEventStale=class extends VueEventCancellation{constructor(reason){super(reason==="disposed"?"The Vue Events bridge was disposed; the source is stale or retired.":reason==="superseded"?"The Vue event call was superseded by a newer call.":"The Vue event source is stale or retired.");__publicField(this,"reason");this.reason=reason}};var stale=(reason="retired")=>new VueEventStale(reason);var activityError=error=>{if(error!==null&&typeof error==="object"&&"status"in error&&typeof error.status==="number"&&"code"in error&&typeof error.code==="string"&&"message"in error&&typeof error.message==="string")return error;const message=error instanceof Error?error.message:"The Vue event request failed.";return{status:0,code:message==="The Vue event request timed out."?"timeout":"transport",message}};var eventUrl=(base,context,handler)=>{if(typeof base!=="string"||!base.endsWith("/")||base.includes("?")||base.includes("#")){throw new Error("Vue Events eventBaseUrl must be a path ending in '/'.")}return`${base}${encodeURIComponent(context.componentClassId)}/${encodeURIComponent(handler)}`};var configuredEventRoutes=(url,endpoint,eventBaseUrl)=>{if(typeof url!=="string"||url.length===0)return{endpoint,eventBaseUrl};if(url.includes("?")||url.includes("#"))throw new Error("Citry Events url must not contain a query or fragment.");const normalized=url.endsWith("/")?url:`${url}/`;if(normalized.endsWith("/call/")){return{endpoint:normalized.slice(0,-1),eventBaseUrl:`${normalized.slice(0,-5)}e/`}}if(normalized.endsWith("/e/")){return{endpoint:`${normalized.slice(0,-2)}call`,eventBaseUrl:normalized}}return{endpoint:`${normalized}call`,eventBaseUrl:`${normalized}e/`}};var eventRequestTarget=url=>{const target=resolveOnPage(url);if(target===null)return{href:url,sameOrigin:false};return{href:target.href,sameOrigin:onPageOrigin(target)}};var readCookie=name=>{if(typeof document==="undefined"||typeof pageDocument.cookie!=="string")return"";for(const item of pageDocument.cookie.split(";")){const value=item.trim();if(!value.startsWith(`${name}=`))continue;try{return decodeURIComponent(value.slice(name.length+1))}catch{}}return""};var isWellFormedUtf16=value=>{for(let index=0;index=55296&&unit<=56319){const next=value.charCodeAt(index+1);if(!(next>=56320&&next<=57343))return false;index+=1}else if(unit>=56320&&unit<=57343)return false}return true};var flatQuery=args=>{const query=new URLSearchParams;const append=(key,value)=>{if(typeof value==="string"){if(!isWellFormedUtf16(value))throw new Error(`Event argument '${key}' is not well-formed UTF-16.`);query.append(key,value)}else if(typeof value==="boolean")query.append(key,String(value));else if(typeof value==="number"&&Number.isFinite(value))query.append(key,String(value));else throw new Error(`Event argument '${key}' has no flat GET query representation.`)};for(const[key,value]of Object.entries(args)){if(!isWellFormedUtf16(key))throw new Error("Event argument name is not well-formed UTF-16.");if(key.startsWith("_citry_"))throw new Error(`Event argument '${key}' uses a reserved GET query name.`);if(Array.isArray(value)){if(value.length===0)throw new Error(`Event argument '${key}' has no flat GET query representation.`);for(const item of value)append(key,item)}else append(key,value)}return query};var attachmentFilename=value=>{const extended=/(?:^|;)\s*filename\*\s*=\s*([^;]+)/i.exec(value)?.[1]?.trim();if(extended!==void 0){const encoded=/^UTF-8''(.+)$/i.exec(extended)?.[1];if(!encoded)throw new Error("The attachment response has an unsupported encoded filename.");try{return decodeURIComponent(encoded)}catch{throw new Error("The attachment response has an invalid encoded filename.")}}const quoted=/(?:^|;)\s*filename\s*=\s*"((?:\\.|[^"\\])*)"/i.exec(value)?.[1];if(quoted!==void 0)return quoted.replace(/\\(.)/g,"$1")||"download";const token=/(?:^|;)\s*filename\s*=\s*([!#$%&'*+.^_`|~0-9A-Za-z-]+)/i.exec(value)?.[1];return token||"download"};var saveAttachment=(blob,filename)=>{const url=URL.createObjectURL(blob);const anchor=pageDocument.createElement("a");try{anchor.href=url;anchor.download=filename;anchor.style.display="none";pageDocument.body.append(anchor);anchor.click()}finally{anchor.remove();URL.revokeObjectURL(url)}};var createVueEventsBridge=options=>{const reportableFailures=new WeakSet;const handledFailures=new WeakSet;const fetchImpl=options.fetch??globalThis.fetch.bind(globalThis);let correlation=0;const owners=new Map;const acceptedAtSpot=new Map;const acceptAtSpot=(source,job)=>{const count=(acceptedAtSpot.get(source.stableId)??0)+1;acceptedAtSpot.set(source.stableId,count);job.acceptedAtSpotWhenAccepted=count};const queue=[];let active=null;const externalJobs=new Set;const jobsWithNoWaitActions=new Set;const detachedCalls=new Set;let running=false;let disposed=false;const supersedeEarlier=input=>{const error=stale("superseded");const sameCall=job=>job.input.source.stableId===input.source.stableId&&job.input.source.generation===input.source.generation&&job.input.handler===input.handler;for(const job of jobsWithNoWaitActions)if(sameCall(job))job.cancel(error);for(const job of detachedCalls)if(sameCall(job))job.cancel(error);for(let index=queue.length-1;index>=0;index-=1){const job=queue[index];if(job.input.source.stableId===input.source.stableId&&job.input.source.generation===input.source.generation&&job.input.handler===input.handler){queue.splice(index,1);lifecycle("stale",job.input.source,job.input.handler,{reason:"superseded"});job.cancel(error)}}if(active&&active.input.source.stableId===input.source.stableId&&active.input.source.generation===input.source.generation&&active.input.handler===input.handler)active.cancel(error)};const lifecycle=(kind,source,event,detail)=>{try{return options.host.lifecycle?.(kind,source,event,detail)!==false}catch(error){console.error(`[Citry] citry:events:${kind} listener failed:`,error);return true}};const reportFailure=(source,handler,error)=>{const reported=activityError(error);if(reported.code==="stale_state"){if(error!==null&&typeof error==="object")reportableFailures.add(error);if(lifecycle("stale",source,handler,{reason:"version"}))options.host.reportOutOfDate?.()}lifecycle("error",source,handler,{error:reported})};const ownerState=source=>{const existing=owners.get(source.stableId);if(existing?.generation===source.generation)return existing;const state={generation:source.generation,sendSequence:0,acceptedEpoch:0,retired:false,timers:new Map};owners.set(source.stableId,state);return state};const current=source=>{const context=options.host.resolve(source);if(context===null||!validContext(context))throw stale("retired");return context};const stillCurrent=(source,state,epoch)=>{if(state.retired||owners.get(source.stableId)!==state||state.generation!==source.generation||epoch!==void 0&&epoch!==state.acceptedEpoch){throw stale(state.retired?"retired":"epoch")}current(source)};const remountTimers=new Map;const sourcelessTimers=new Map;const delay=(milliseconds,state,job)=>new Promise((resolve,reject)=>{if(job.cancelError){reject(job.cancelError);return}if(disposed||state.retired&&!job.acceptedRemount){reject(stale(disposed?"disposed":"retired"));return}const timers=job.acceptedRemount?remountTimers:state.timers;const timer=globalThis.setTimeout(()=>{timers.delete(timer);resolve()},milliseconds);timers.set(timer,reject);void job.cancelled.catch(error=>{if(!timers.delete(timer))return;globalThis.clearTimeout(timer);reject(error)})});const continuationCurrent=(source,state,epoch,job,survivesNewerResult=false)=>{if(job.cancelError)throw job.cancelError;if(disposed)throw stale("disposed");if(!survivesNewerResult&&epoch!==state.acceptedEpoch)throw stale("epoch");if(!job.acceptedRemount){stillCurrent(source,state,survivesNewerResult?void 0:epoch);return}if(!survivesNewerResult&&acceptedAtSpot.get(source.stableId)!==job.acceptedAtSpotWhenAccepted){throw stale("epoch")}};const validateTargets=(result,source,serverRenderId)=>{if(!result.ok)return;const componentTarget=`render:${serverRenderId}`;for(const action of result.actions){if(action.action==="render"&&!options.host.preflightResult&&action.target!==componentTarget){throw new Error("Vue Events accepts the current component target; marker targets are not implemented.")}if(action.action==="event"&&action.target!==void 0&&action.target!==componentTarget){throw new Error("Vue Events accepts the current component Event target; marker targets are not implemented.")}}current(source)};const applyOne=async(action,source,state,epoch,onData,job,renderPlan)=>{if(action.action==="data"){if(!job.external)continuationCurrent(source,state,epoch,job);onData(action.value);return}if(action.action==="render"){if(job.cancelError)throw job.cancelError;stillCurrent(source,state,epoch);const context=current(source);if(!renderPlan&&action.target!==`render:${context.serverRenderId}`){throw new Error("The experimental Vue Events bridge accepts only its current root Render target.")}if(!("renderer"in action)||action.renderer!=="vue-prepared/1"){throw new Error("The Vue Events bridge requires a vue-prepared/1 Render action.")}const preparing=options.host.prepareRender(action,source,job.controller?.signal??new AbortController().signal,renderPlan);let prepared;try{prepared=await Promise.race([preparing,job.cancelled]);stillCurrent(source,state,epoch)}catch(error){try{options.host.abortRender(void 0,source)}catch(cleanupError){console.error("[Citry] aborting a prepared Vue render failed:",cleanupError)}void preparing.then(value=>{try{options.host.abortRender(value,source)}catch(cleanupError){console.error("[Citry] aborting a late prepared Vue render failed:",cleanupError)}},()=>void 0);throw error}job.committingTransaction=prepared.transaction;try{await Promise.race([options.host.commitRender(prepared,source),job.cancelled]);lifecycle("swapped",source,job.input.handler,{els:[]})}finally{job.committingTransaction=void 0}}else if(action.action==="state"){continuationCurrent(source,state,epoch,job);options.host.commitState(action.targetRenderId,action.stateToken,action.publicState,source)}else if(action.action==="event"){continuationCurrent(source,state,epoch,job);const followRemount=job.acceptedRemount;const rootTarget=followRemount?void 0:`render:${current(source).serverRenderId}`;const callerTarget=job.callerRenderId===void 0?void 0:`render:${job.callerRenderId}`;if(action.target!==void 0&&action.target!==rootTarget&&action.target!==callerTarget){throw new Error("The experimental Vue Events bridge accepts only its current root Event target.")}if(job.external&&action.target===void 0&&options.host.dispatchEventGlobal)options.host.dispatchEventGlobal(action.eventName,action.detail);else options.host.dispatchEvent(action.eventName,action.detail,source,followRemount)}else if(action.action==="redirect"){if(!job.external)continuationCurrent(source,state,epoch,job,true);options.host.redirect(action.url)}else{if(!job.external)continuationCurrent(source,state,epoch,job);options.host.updateUrl(action.url,action.mode)}};const applyActions=async(result,source,state,epoch,job,renderPlan)=>{if(!result.ok){reportableFailures.add(result.error);throw result.error}let data;const hoisted=new Set;result.actions.forEach((action,index)=>{if(action.action==="state"&&!(typeof action.delay==="number"&&action.delay>0)&&action.wait!==false){if(job.cancelError)throw job.cancelError;stillCurrent(source,state,epoch);options.host.commitState(action.targetRenderId,action.stateToken,action.publicState,source);hoisted.add(index)}});for(const[index,action]of result.actions.entries()){if(hoisted.has(index))continue;const run=async()=>{const seconds=typeof action.delay==="number"?action.delay:0;const delayed=seconds>0;if(delayed)await delay(seconds*1e3,state,job);const actionEpoch=job.detachedHandler&&!delayed?state.acceptedEpoch:epoch;await applyOne(action,source,state,actionEpoch,value=>{data=value},job,action.action==="render"?renderPlan:void 0)};if("wait"in action&&action.wait===false){job.noWaitPending+=1;jobsWithNoWaitActions.add(job);void run().catch(error=>{if(error instanceof VueEventStale){lifecycle("stale",source,job.input.handler,{reason:error.reason});return}if(!(error instanceof VueEventCancellation))reportFailure(source,job.input.handler,error);console.error("[Citry] applying a Vue event action marked wait: false failed:",error)}).finally(()=>{job.noWaitPending-=1;if(job.noWaitPending===0)jobsWithNoWaitActions.delete(job)})}else await run()}return data};const sendNow=async job=>{const input=job.input;if(disposed)throw stale("disposed");const context=current(input.source);const state=ownerState(input.source);job.owner=state;const appId=options.host.appId(input.source);if(typeof appId!=="string"||appId.length===0)throw stale("retired");const committedRevision=options.host.revision(input.source);if(!Number.isInteger(committedRevision)||committedRevision<0)throw stale("retired");if(!Object.prototype.hasOwnProperty.call(context.descriptor.eventHandlers,input.handler))throw new Error(`Unknown event handler '${input.handler}'.`);const handlerOptions=context.descriptor.eventHandlers[input.handler];const detachedHandler=handlerOptions.detached===true;job.detachedHandler=detachedHandler;job.callerRenderId=context.serverRenderId;job.lifecycleStarted=true;if(!lifecycle("before",input.source,input.handler))throw new VueEventCancellation(`Citry Events send '${input.handler}' was cancelled by citry:events:before.`);const useGet=handlerOptions.httpMethod==="GET";const runtimeConfig=options.runtimeConfig?.()??{};const configuredEndpoint=typeof options.endpoint==="function"&&!useGet?options.endpoint(context,input.handler):typeof options.endpoint==="string"?options.endpoint:"";const routes=configuredEventRoutes(runtimeConfig.url??"",configuredEndpoint,options.eventBaseUrl);if(useGet&&input.stateUpdates!==void 0)throw new Error("GET events cannot send pending State updates.");const taken=useGet||detachedHandler?void 0:input.stateUpdates??options.host.takePendingState?.(input.source,input.handler);job.stateUpdates=taken===void 0?void 0:structuredClone(taken);state.sendSequence+=1;correlation+=1;const call=buildCall({componentClassId:context.componentClassId,handlerName:input.handler,callerRenderId:context.serverRenderId,args:input.args??{},argsSource:input.argsSource,stateToken:context.stateToken??void 0,stateUpdates:job.stateUpdates,sendSequence:state.sendSequence});const envelope=buildCallEnvelope(`vue_${correlation}`,[call],{actions:["render","data","state","event","redirect","url"],swaps:["morph"],renderers:["vue-prepared/1"]});const headers={"Content-Type":"application/citry-events+json","X-Citry-Events":"1","X-Citry-Vue-App":appId,"X-Citry-Vue-Occurrence":input.source.stableId,"X-Citry-Vue-Revision":String(committedRevision)};const selectedTransport=options.transport?.()??null;const isolated=useGet||handlerOptions.allowBatching===false;const endpoint=isolated?eventUrl(routes.eventBaseUrl??"",context,input.handler):routes.endpoint;const target=selectedTransport?{href:endpoint,sameOrigin:true}:eventRequestTarget(endpoint);const csrf=runtimeConfig.csrf??options.csrf;if(!useGet&&csrf&&target.sameOrigin){const token=csrf.token?typeof csrf.token==="function"?csrf.token():csrf.token:selectedTransport?void 0:readCookie(csrf.cookie??"csrftoken");if(token)headers[csrf.header??"X-CSRFToken"]=token}const callTimeout=input.options?.timeout;const timeoutMs=callTimeout??runtimeConfig.timeout??options.timeoutMs??3e4;if(!Number.isFinite(timeoutMs)||timeoutMs<=0)throw new Error("Vue Events timeoutMs must be positive.");const controller=new AbortController;job.controller=controller;let requestUrl=target.href;if(useGet){const query=flatQuery(input.args??{});query.append("_citry_protocol",envelope.protocol);query.append("_citry_request_id",envelope.requestId);query.append("_citry_capabilities",JSON.stringify(envelope.capabilities));query.append("_citry_caller_render_id",call.callerRenderId??"");query.append("_citry_send_sequence",String(call.sendSequence));if(handlerOptions.usesState===true&&call.stateToken!==void 0)query.append("_citry_state_token",call.stateToken);requestUrl+=`?${query.toString()}`}const requestHeaders=useGet?Object.fromEntries(Object.entries(headers).filter(([name])=>name!=="Content-Type")):headers;const requestMethod=isolated?handlerOptions.httpMethod:"POST";const operation=(async()=>{if(selectedTransport){const request={url:requestUrl,method:requestMethod,headers:{...requestHeaders},signal:controller.signal};try{return{raw:await selectedTransport.send(envelope,request),transported:true}}catch(error){if(error!==null&&typeof error==="object")reportableFailures.add(error);throw error}}const requestInit={method:requestMethod,credentials:"same-origin",redirect:"manual",headers:requestHeaders,...useGet?{}:{body:JSON.stringify(envelope)},signal:controller.signal};let response;try{response=await fetchImpl(requestUrl,requestInit)}catch(error){if(error!==null&&typeof error==="object")reportableFailures.add(error);throw error}if(response.type==="opaqueredirect"){const error=new Error("The server answered the event call with a redirect, which event calls do not follow.");reportableFailures.add(error);throw error}const disposition=response.headers?.get?.("Content-Disposition")??null;if(response.ok&&disposition&&/^\s*attachment(?:;|$)/i.test(disposition)){return{attachment:await response.blob(),filename:attachmentFilename(disposition)}}try{const raw2=await response.json();return{raw:raw2}}catch(error){if(response.ok)throw new Error("A successful raw Event response must be an attachment.");throw error}})();let timeoutId=0;const received=await Promise.race([operation,job.cancelled,new Promise((_resolve,reject)=>{timeoutId=globalThis.setTimeout(()=>{controller.abort();const error=new Error("The Vue event request timed out.");reportableFailures.add(error);reject(error)},timeoutMs)})]).finally(()=>globalThis.clearTimeout(timeoutId));if("attachment"in received){stillCurrent(input.source,state);if(!detachedHandler){state.acceptedEpoch+=1;acceptAtSpot(input.source,job)}continuationCurrent(input.source,state,state.acceptedEpoch,job);saveAttachment(received.attachment,received.filename);return void 0}const raw=received.raw;const checked=preflightResultEnvelope(raw,envelope);if(!checked.ok)throw new Error(`Invalid Events response: ${checked.issue.message}`);const[result]=received.transported?copyJson(checked.results):checked.results;if(detachedHandler&&result.ok){const forbidden=result.actions.find(action=>action.action==="render"||action.action==="state");if(forbidden)throw new Error(`Invalid Events response: detached handler '${input.handler}' returned a '${forbidden.action}' action.`)}stillCurrent(input.source,state);validateTargets(result,input.source,context.serverRenderId);const preparedResult=options.host.preflightResult?.(result,input.source)??{result};if(job.cancelError)throw job.cancelError;if(!detachedHandler){state.acceptedEpoch+=1;acceptAtSpot(input.source,job)}if(preparedResult.result.ok)job.stateAccepted=true;return applyActions(preparedResult.result,input.source,state,state.acceptedEpoch,job,preparedResult.renderPlan)};const runJob=async job=>{try{job.activity?.start(job.intent);const value=await sendNow(job);if(job.cancelError)throw job.cancelError;job.stateAccepted=true;job.activity?.succeed(job.intent);if(job.lifecycleStarted)lifecycle("after",job.input.source,job.input.handler,{ok:true});job.resolve(value)}catch(error){if(!job.stateAccepted&&job.stateUpdates!==void 0)options.host.restorePendingState?.(job.input.source,job.stateUpdates);if(job.lifecycleStarted){if(error instanceof VueEventStale){lifecycle("stale",job.input.source,job.input.handler,{reason:error.reason})}else if(!(error instanceof VueEventCancellation)){reportFailure(job.input.source,job.input.handler,error)}lifecycle("after",job.input.source,job.input.handler,{ok:false})}if(!(error instanceof VueEventCancellation)){job.activity?.fail(job.intent,activityError(error));if(job.activity&&error!==null&&typeof error==="object"&&reportableFailures.has(error))handledFailures.add(error)}job.reject(error)}finally{if(!job.activityFinished){job.activityFinished=true;job.activity?.finish(job.intent)}}};const runQueue=async()=>{if(running)return;running=true;try{while(queue.length>0){const job=queue.shift();if(!job||job.settled)continue;active=job;try{await runJob(job)}finally{active=null}}}finally{running=false}};const unsupportedBrowserMethods=new Set(["HEAD","OPTIONS","CONNECT","TRACE","TRACK"]);const send=given=>{if(disposed)return Promise.reject(stale("disposed"));let activity;let intent;let input=given;let outsideQueue=false;try{input={...given,options:checkSendOptions(given.options)};const context=current(input.source);if(!Object.prototype.hasOwnProperty.call(context.descriptor.eventHandlers,input.handler))throw new Error(`Unknown event handler '${input.handler}'.`);const method=context.descriptor.eventHandlers[input.handler].httpMethod;if(unsupportedBrowserMethods.has(method))throw new Error(`Event handler '${input.handler}' uses HTTP ${method}, which is server-transport-only and cannot be sent by the browser bridge.`);const handlerOptions=context.descriptor.eventHandlers[input.handler];outsideQueue=input.options?.wait===false;if(outsideQueue&&handlerOptions.detached!==true)throw queuedHandlerError(input.handler);if(handlerOptions.detached===true&&input.stateUpdates!==void 0)throw new TypeError(`Event handler '${input.handler}' is detached, so a call to it cannot send State updates.`);activity=options.activity?.(input.source,context.descriptor);intent=activity?.enqueue(input.handler);if(handlerOptions.latestCallWins===true)supersedeEarlier(input)}catch(error){return Promise.reject(error)}let resolvePromise;let rejectPromise;let cancelPromise;const promise=new Promise((resolve,reject)=>{resolvePromise=resolve;rejectPromise=reject});const cancelled=new Promise((_resolve,reject)=>{cancelPromise=reject});void cancelled.catch(()=>void 0);const job={input,acceptedRemount:false,noWaitPending:0,activity,intent,activityFinished:false,lifecycleStarted:false,external:false,stateAccepted:false,settled:false,cancelled,cancel(error){if(job.cancelError===void 0){job.cancelError=error;cancelPromise(error)}if(job.settled)return;job.controller?.abort();if(!job.activityFinished){job.activityFinished=true;job.activity?.finish(job.intent)}job.reject(error)},resolve(value){if(job.settled)return;job.settled=true;resolvePromise(value)},reject(error){if(job.settled)return;job.settled=true;rejectPromise(error)}};if(outsideQueue){detachedCalls.add(job);void runJob(job).finally(()=>detachedCalls.delete(job))}else{queue.push(job);void runQueue()}return promise};const applyActionsExternally=async(actions,source)=>{const result=buildOkResult(actions);if(!source){let data;for(const action of result.actions){if(disposed)throw stale("disposed");if(typeof action.delay==="number"&&action.delay>0){const milliseconds=action.delay*1e3;await new Promise((resolve,reject)=>{const timer=globalThis.setTimeout(()=>{sourcelessTimers.delete(timer);resolve()},milliseconds);sourcelessTimers.set(timer,reject)});if(disposed)throw stale("disposed")}if(action.action==="data")data=action.value;else if(action.action==="redirect")options.host.redirect(action.url);else if(action.action==="url")options.host.updateUrl(action.url,action.mode);else if(action.action==="event"){if(action.target!==void 0||!options.host.dispatchEventGlobal)throw new Error("Citry.events.applyActions needs a mounted component for targeted Event actions.");options.host.dispatchEventGlobal(action.eventName,action.detail)}else{throw new Error("Citry.events.applyActions needs a mounted component for Render and State actions.")}}return data}const externalContext=current(source);const state=ownerState(source);state.acceptedEpoch+=1;const cancelled=new Promise(()=>void 0);const job={input:{source,handler:"__external__"},acceptedRemount:false,noWaitPending:0,activityFinished:true,lifecycleStarted:true,external:true,callerRenderId:externalContext.serverRenderId,stateAccepted:true,settled:true,cancelled,cancel(){},resolve(){},reject(){}};let prepared;try{prepared=options.host.preflightResult?.(result,source)??{result}}catch(error){if(activityError(error).code==="stale_state"&&lifecycle("before",source,job.input.handler)){reportFailure(source,job.input.handler,error);lifecycle("after",source,job.input.handler,{ok:false})}throw error}if(!lifecycle("before",source,job.input.handler)){const error=new VueEventCancellation("Citry Events applyActions was cancelled by citry:events:before.");lifecycle("after",source,job.input.handler,{ok:false});throw error}acceptAtSpot(source,job);externalJobs.add(job);try{const value=await applyActions(prepared.result,source,state,state.acceptedEpoch,job,prepared.renderPlan);lifecycle("after",source,job.input.handler,{ok:true});return value}catch(error){if(error instanceof VueEventStale){lifecycle("stale",source,job.input.handler,{reason:error.reason})}else if(!(error instanceof VueEventCancellation)){reportFailure(source,job.input.handler,error)}lifecycle("after",source,job.input.handler,{ok:false});throw error}finally{externalJobs.delete(job)}};const retire=(source,acceptedTransaction)=>{const state=owners.get(source.stableId);if(state?.generation===source.generation){state.retired=true;for(const[timer,reject]of state.timers){globalThis.clearTimeout(timer);reject(stale("retired"))}state.timers.clear();owners.delete(source.stableId)}const error=new VueEventStale("retired");for(let index=queue.length-1;index>=0;index-=1){const job=queue[index];if(job.input.source.stableId===source.stableId&&job.input.source.generation===source.generation){queue.splice(index,1);lifecycle("stale",source,job.input.handler,{reason:"retired"});job.cancel(error)}}for(const job of detachedCalls)if(job.input.source.stableId===source.stableId&&job.input.source.generation===source.generation)job.cancel(error);for(const job of externalJobs){if(acceptedTransaction!==void 0&&job.committingTransaction===acceptedTransaction&&job.input.source.stableId===source.stableId&&job.input.source.generation===source.generation)job.acceptedRemount=true}if(active?.input.source.stableId===source.stableId&&active.input.source.generation===source.generation&&acceptedTransaction!==void 0&&active.committingTransaction===acceptedTransaction){active.acceptedRemount=true}else if(active?.input.source.stableId===source.stableId&&active.input.source.generation===source.generation)active.cancel(error)};const dispose=()=>{if(disposed)return;disposed=true;for(const state of owners.values()){state.retired=true;for(const[timer,reject]of state.timers){globalThis.clearTimeout(timer);reject(stale("disposed"))}state.timers.clear()}owners.clear();acceptedAtSpot.clear();for(const timers of[remountTimers,sourcelessTimers]){for(const[timer,reject]of timers){globalThis.clearTimeout(timer);reject(stale("disposed"))}timers.clear()}const error=new VueEventStale("disposed");for(const job of queue.splice(0)){lifecycle("stale",job.input.source,job.input.handler,{reason:"disposed"});job.cancel(error)}active?.cancel(error);for(const job of detachedCalls)job.cancel(error)};const isDeclarativeFailureHandled=error=>error instanceof VueEventCancellation||error!==null&&typeof error==="object"&&handledFailures.has(error);return{send,applyActions:applyActionsExternally,retire,dispose,isDeclarativeFailureHandled}};return __toCommonJS(citry_events_vue_exports);})(); +var CitryVueEvents=(()=>{var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:true,configurable:true,writable:true,value}):obj[key]=value;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var __publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!=="symbol"?key+"":key,value);var citry_events_vue_exports={};__export(citry_events_vue_exports,{assertValidActionList:()=>assertValidActionList2,collectFormArgs:()=>collectFormArgs,createVueEventsBridge:()=>createVueEventsBridge});var ProtocolValueError=class extends TypeError{constructor(issue){super(issue.message);__publicField(this,"issue");this.name="ProtocolValueError";this.issue=issue}};var hasOwn=(value,key)=>Object.prototype.hasOwnProperty.call(value,key);var pointer=(parent,member)=>{const escaped=String(member).replace(/~/g,"~0").replace(/\//g,"~1");return parent?`${parent}/${escaped}`:`/${escaped}`};var isPlainObject=value=>{if(value===null||typeof value!=="object"||Array.isArray(value))return false;const prototype=Object.getPrototypeOf(value);return prototype===Object.prototype||prototype===null};var firstUnknown=(value,allowed)=>Object.keys(value).filter(key=>!allowed.has(key)).sort()[0]??null;var containerIssue=(value,path)=>{if(Object.getOwnPropertySymbols(value).length){return{path:path(),category:"strict_json",message:"The value contains a symbol-keyed property."}}for(const name of Object.getOwnPropertyNames(value)){if(Array.isArray(value)&&name==="length")continue;const descriptor=Object.getOwnPropertyDescriptor(value,name);if(!descriptor?.enumerable||!("value"in descriptor)){return{path:pointer(path(),name),category:"strict_json",message:"A JSON property must be an enumerable data property."}}}return null};var validateStrictJson=(value,path="")=>{const pathOf=frame=>{const members=[];for(let cursor=frame;cursor.parent;cursor=cursor.parent)members.push(cursor.member);let result=path;for(let index=members.length-1;index>=0;index-=1)result=pointer(result,members[index]);return result};const stack=[{value,parent:null,member:"",leaving:false}];const ancestors=new Set;while(stack.length){const frame=stack.pop();const current=frame.value;if(frame.leaving){ancestors.delete(current);continue}if(current===null||typeof current==="string"||typeof current==="boolean"){continue}if(typeof current==="number"){if(!Number.isFinite(current)){return{path:pathOf(frame),category:"strict_json",message:"The value contains a non-finite number."}}continue}if(typeof current!=="object"){return{path:pathOf(frame),category:"strict_json",message:"The value contains a non-JSON value."}}if(!Array.isArray(current)&&!isPlainObject(current)){return{path:pathOf(frame),category:"strict_json",message:"The value contains a non-JSON object."}}const ownIssue=containerIssue(current,()=>pathOf(frame));if(ownIssue)return ownIssue;if(ancestors.has(current)){return{path:pathOf(frame),category:"strict_json",message:"The value contains a cycle."}}ancestors.add(current);frame.leaving=true;stack.push(frame);if(Array.isArray(current)){const names=Object.keys(current);if(names.length!==current.length||names.some((name,index)=>name!==String(index))){return{path:pathOf(frame),category:"strict_json",message:"A JSON array must be dense and carry no named properties."}}for(let index=current.length-1;index>=0;index-=1){stack.push({value:current[index],parent:frame,member:index,leaving:false})}continue}const keys=Object.keys(current).sort();for(let index=keys.length-1;index>=0;index-=1){const key=keys[index];stack.push({value:current[key],parent:frame,member:key,leaving:false})}}return null};var copyJson=value=>{const issue=validateStrictJson(value);if(issue)throw new ProtocolValueError(issue);if(value===null||typeof value!=="object")return value;const copied=Array.isArray(value)?new Array(value.length):{};const stack=[{source:value,target:copied}];while(stack.length){const{source,target}=stack.pop();for(const key of Object.keys(source)){const item=source[key];if(item!==null&&typeof item==="object"){const child=Array.isArray(item)?new Array(item.length):{};Object.defineProperty(target,key,{configurable:true,enumerable:true,value:child,writable:true});stack.push({source:item,target:child})}else{Object.defineProperty(target,key,{configurable:true,enumerable:true,value:item,writable:true})}}}return copied};var PROTOCOL="citry-events/1";var CALLS_LIMIT=16;var ACTION_KINDS=["render","data","state","event","redirect","url"];var SWAPS=["morph","replace","inner","append","prepend","remove","none"];var RENDERERS=["html-fragment/1","vue-prepared/1"];var CAPABILITIES_BASELINE_V1={swaps:["replace","inner","append","prepend","remove","none"],actions:ACTION_KINDS,renderers:["html-fragment/1"]};var ARGS_SOURCE_FORM="form";var CARRIER_FIELDS={callerRenderId:"_citry_caller_render_id",stateToken:"_citry_state_token",sendSequence:"_citry_send_sequence",protocol:"_citry_protocol",requestId:"_citry_request_id",capabilities:"_citry_capabilities"};var CARRIER_HEADERS={stateToken:"X-Citry-State-Token"};var ENVELOPE_FIELDS=new Set(["protocol","requestId","capabilities","calls"]);var CALL_FIELDS=new Set(["componentClassId","handlerName","callerRenderId","args","argsSource","stateToken","stateUpdates","sendSequence"]);var isSafeRenderId=value=>typeof value==="string"&&/^[a-z0-9_-]+$/.test(value);var nonEmptyStringIssue=(value,path,message)=>{if(typeof value!=="string")return{path,category:"type",message};if(!value)return{path,category:"range",message};return null};var integerIssue=(value,path,message)=>{if(typeof value!=="number"||!Number.isInteger(value)){if(typeof value==="number"&&!Number.isFinite(value)){return{path,category:"strict_json",message}}return{path,category:"type",message}}if(value<0)return{path,category:"range",message};return null};var validateCall=(value,path="")=>{const jsonIssue=validateStrictJson(value,path);if(jsonIssue)return jsonIssue;if(!isPlainObject(value)){return{path,category:"type",message:"Each entry of 'calls' must be a call object."}}for(const required of["componentClassId","handlerName","args"]){if(!hasOwn(value,required)){return{path:pointer(path,required),category:"required",message:`The call is missing required field '${required}'.`}}}const unknown=firstUnknown(value,CALL_FIELDS);if(unknown!==null){return{path:pointer(path,unknown),category:"unknown_field",message:`The call carries unknown field '${unknown}'.`}}for(const field of["componentClassId","handlerName"]){const issue=nonEmptyStringIssue(value[field],pointer(path,field),`The call's '${field}' must be a non-empty string.`);if(issue)return issue}if(hasOwn(value,"callerRenderId")){const issue=nonEmptyStringIssue(value.callerRenderId,pointer(path,"callerRenderId"),"The call's 'callerRenderId' must be a non-empty string.");if(issue)return issue;if(!isSafeRenderId(value.callerRenderId)){return{path:pointer(path,"callerRenderId"),category:"pattern",message:"The call's 'callerRenderId' must use only lowercase ASCII letters, digits, hyphens, and underscores."}}}if(!isPlainObject(value.args)){return{path:pointer(path,"args"),category:"type",message:"The call's 'args' must be an object."}}const argsIssue=validateStrictJson(value.args);if(argsIssue){return{path:pointer(path,"args")+argsIssue.path,category:"strict_json",message:"The call's 'args' must contain only strict JSON values under string keys."}}if(hasOwn(value,"argsSource")&&value.argsSource!==ARGS_SOURCE_FORM){return{path:pointer(path,"argsSource"),category:typeof value.argsSource==="string"?"enum":"type",message:`The call's 'argsSource' must be '${ARGS_SOURCE_FORM}' or omitted.`}}if(hasOwn(value,"stateToken")){const issue=nonEmptyStringIssue(value.stateToken,pointer(path,"stateToken"),"The call's 'stateToken' must be a non-empty string.");if(issue)return issue}if(hasOwn(value,"stateUpdates")){if(!isPlainObject(value.stateUpdates)){return{path:pointer(path,"stateUpdates"),category:"type",message:"The call's 'stateUpdates' must be an object."}}const stateIssue=validateStrictJson(value.stateUpdates);if(stateIssue){return{path:pointer(path,"stateUpdates")+stateIssue.path,category:"strict_json",message:"The call's 'stateUpdates' must contain only strict JSON values under string keys."}}}if(hasOwn(value,"sendSequence")){return integerIssue(value.sendSequence,pointer(path,"sendSequence"),"The call's 'sendSequence' must be an integer of at least 0.")}return null};var validateCapabilities=(value,path="/capabilities")=>{const jsonIssue=validateStrictJson(value,path);if(jsonIssue)return jsonIssue;const message="The envelope's 'capabilities' must contain only 'swaps', 'actions', and 'renderers'; each value must be a duplicate-free array of known v1 names.";if(!isPlainObject(value))return{path,category:"type",message};const unknown=firstUnknown(value,new Set(["swaps","actions","renderers"]));if(unknown!==null){return{path:pointer(path,unknown),category:"unknown_field",message}}for(const[name,known]of[["swaps",SWAPS],["actions",ACTION_KINDS],["renderers",RENDERERS]]){if(!hasOwn(value,name))continue;const items=value[name];const itemPath=pointer(path,name);if(!Array.isArray(items))return{path:itemPath,category:"type",message};for(let index=0;index{const jsonIssue=validateStrictJson(value);if(jsonIssue)return jsonIssue;if(!isPlainObject(value)){return{path:"",category:"type",message:"The request body is not a call envelope object."}}for(const required of["protocol","requestId","calls"]){if(!hasOwn(value,required)){return{path:pointer("",required),category:"required",message:`The envelope requires '${required}'.`}}}const unknown=firstUnknown(value,ENVELOPE_FIELDS);if(unknown!==null){return{path:pointer("",unknown),category:"unknown_field",message:`The envelope carries unknown field '${unknown}'.`}}if(value.protocol!==PROTOCOL){return{path:"/protocol",category:typeof value.protocol==="string"?"enum":"type",message:"The envelope protocol must be citry-events/1."}}const requestIssue=nonEmptyStringIssue(value.requestId,"/requestId","The envelope carries no 'requestId' string.");if(requestIssue)return requestIssue;if(hasOwn(value,"capabilities")){const issue=validateCapabilities(value.capabilities);if(issue)return issue}if(!Array.isArray(value.calls)){return{path:"/calls",category:"type",message:"The envelope calls must be an array."}}if(!value.calls.length||value.calls.length>CALLS_LIMIT){return{path:"/calls",category:"range",message:`The envelope must carry 1 to ${CALLS_LIMIT} calls.`}}for(let index=0;index{const call={componentClassId:input.componentClassId,handlerName:input.handlerName,args:copyJson(input.args)};for(const field of["argsSource","callerRenderId","stateToken","sendSequence"]){if(input[field]!==void 0)call[field]=input[field]}if(input.stateUpdates!==void 0){call.stateUpdates=copyJson(input.stateUpdates)}const issue=validateCall(call);if(issue)throw new ProtocolValueError(issue);return call};var buildCallEnvelope=(requestId,calls,capabilities)=>{const envelope={protocol:PROTOCOL,requestId,calls:copyJson(calls)};if(capabilities!==void 0)envelope.capabilities=copyJson(capabilities);const issue=validateCallEnvelope(envelope);if(issue)throw new ProtocolValueError(issue);return envelope};var HTTP_METHOD=/^[!#$%&'*+.^_`|~0-9A-Z-]+$/;var DESCRIPTOR_FIELDS=new Set(["componentClassId","eventHandlers","writableStateFields"]);var HANDLER_FIELDS=new Set(["httpMethod","usesState","debounceMilliseconds","throttleMilliseconds","latestCallWins","allowBatching","detached"]);var nonNegativeIntegerIssue=(value,path,name)=>{if(typeof value!=="number"||!Number.isInteger(value)){return{path,category:typeof value==="number"&&!Number.isFinite(value)?"strict_json":"type",message:`The ${name} hint must be an integer.`}}if(value<0){return{path,category:"range",message:`The ${name} hint must be at least 0.`}}return null};var validateHandlerDescriptor=(value,path="")=>{const jsonIssue=validateStrictJson(value,path);if(jsonIssue)return jsonIssue;if(!isPlainObject(value)){return{path,category:"type",message:"Event-handler hints must be an object."}}if(!hasOwn(value,"httpMethod")){return{path:pointer(path,"httpMethod"),category:"required",message:"Handler hints require 'httpMethod'."}}const unknown=firstUnknown(value,HANDLER_FIELDS);if(unknown!==null){return{path:pointer(path,unknown),category:"unknown_field",message:"Handler hints have an unknown field."}}if(typeof value.httpMethod!=="string"){return{path:pointer(path,"httpMethod"),category:"type",message:"The HTTP method must be a string."}}if(!HTTP_METHOD.test(value.httpMethod)){return{path:pointer(path,"httpMethod"),category:"pattern",message:"The HTTP method must be an uppercase token."}}if(hasOwn(value,"usesState")&&value.usesState!==true){return{path:pointer(path,"usesState"),category:"enum",message:"The usesState hint has its non-default literal value."}}for(const name of["debounceMilliseconds","throttleMilliseconds"]){if(!hasOwn(value,name))continue;const issue=nonNegativeIntegerIssue(value[name],pointer(path,name),name);if(issue)return issue}if(hasOwn(value,"latestCallWins")&&value.latestCallWins!==true){return{path:pointer(path,"latestCallWins"),category:"enum",message:"The latestCallWins hint has its non-default literal value."}}if(hasOwn(value,"allowBatching")&&value.allowBatching!==false){return{path:pointer(path,"allowBatching"),category:"enum",message:"The allowBatching hint has its non-default literal value."}}if(hasOwn(value,"detached")&&value.detached!==true){return{path:pointer(path,"detached"),category:"enum",message:"The detached hint has its non-default literal value."}}return null};var validateDescriptor=(value,path="")=>{const jsonIssue=validateStrictJson(value,path);if(jsonIssue)return jsonIssue;if(!isPlainObject(value)){return{path,category:"type",message:"A component descriptor must be an object."}}for(const required of["componentClassId","eventHandlers"]){if(!hasOwn(value,required)){return{path:pointer(path,required),category:"required",message:`The descriptor requires '${required}'.`}}}const unknown=firstUnknown(value,DESCRIPTOR_FIELDS);if(unknown!==null){return{path:pointer(path,unknown),category:"unknown_field",message:"The descriptor has an unknown field."}}if(typeof value.componentClassId!=="string"){return{path:pointer(path,"componentClassId"),category:"type",message:"The component class ID must be a string."}}if(!value.componentClassId){return{path:pointer(path,"componentClassId"),category:"range",message:"The component class ID must not be empty."}}if(!isPlainObject(value.eventHandlers)){return{path:pointer(path,"eventHandlers"),category:"type",message:"Event handlers must be an object."}}for(const name of Object.keys(value.eventHandlers).sort()){if(!name){return{path:pointer(path,"eventHandlers"),category:"range",message:"A handler name must not be empty."}}const issue=validateHandlerDescriptor(value.eventHandlers[name],pointer(pointer(path,"eventHandlers"),name));if(issue)return issue}if(hasOwn(value,"writableStateFields")){const fields=value.writableStateFields;const fieldPath=pointer(path,"writableStateFields");if(!Array.isArray(fields)){return{path:fieldPath,category:"type",message:"Writable State fields must be an array."}}const seen=new Set;for(let index=0;index{if(typeof value!=="number"||!Number.isInteger(value)){return{path,category:typeof value==="number"&&!Number.isFinite(value)?"strict_json":"type",message}}if(value<0)return{path,category:"range",message};return null};var validateTiming=(value,path)=>{if(hasOwn(value,"delay")){const delay=value.delay;if(typeof delay!=="number"){return{path:pointer(path,"delay"),category:"type",message:"The action delay must be a finite number."}}if(!Number.isFinite(delay)){return{path:pointer(path,"delay"),category:"strict_json",message:"The action delay must be finite."}}if(delay<0){return{path:pointer(path,"delay"),category:"range",message:"The action delay must be at least 0."}}}if(hasOwn(value,"wait")&&value.wait!==false){return{path:pointer(path,"wait"),category:"enum",message:"The action wait flag, when present, must be false."}}return null};var MARK_NAME=/^[A-Za-z][A-Za-z0-9_-]*$/;var validateTarget=(value,path,allowMarker)=>{if(typeof value!=="string"){return{path,category:"type",message:"An action target must be a non-empty string."}}if(!value){return{path,category:"range",message:"An action target must be a non-empty string."}}if(value.startsWith("render:")){if(isSafeRenderId(value.slice(7)))return null;return{path,category:"pattern",message:"A render: target must contain a valid render ID."}}if(allowMarker&&value.startsWith("mark:")){const rest=value.slice(5);const separator=rest.indexOf(":");const caller=separator<0?"":rest.slice(0,separator);const name=separator<0?"":rest.slice(separator+1);if(isSafeRenderId(caller)&&MARK_NAME.test(name))return null;return{path,category:"pattern",message:"A marker target must be mark:: with a valid ID and name."}}return{path,category:"pattern",message:allowMarker?"A render target must be render: or mark::.":"An event target must be render:."}};var validateActionShape=(value,path="")=>{if(!isPlainObject(value)){return{path,category:"type",message:"An action must be an object."}}if(!hasOwn(value,"action")){return{path:pointer(path,"action"),category:"required",message:"The action kind is required."}}if(typeof value.action!=="string"){return{path:pointer(path,"action"),category:"type",message:"The action kind must be a string."}}if(!ACTION_KINDS.includes(value.action)){return{path:pointer(path,"action"),category:"enum",message:`Unknown action kind '${value.action}'.`}}const kind=value.action;for(const required of ACTION_REQUIRED[kind]){if(!hasOwn(value,required)){return{path:pointer(path,required),category:"required",message:`The ${kind} action requires '${required}'.`}}}const unknown=firstUnknown(value,ACTION_FIELDS[kind]);if(unknown!==null){return{path:pointer(path,unknown),category:"unknown_field",message:`The ${kind} action has an unknown field.`}}if(kind==="render"){const targetIssue=validateTarget(value.target,pointer(path,"target"),true);if(targetIssue)return targetIssue;if(!SWAPS.includes(value.swap)){return{path:pointer(path,"swap"),category:typeof value.swap==="string"?"enum":"type",message:"The render swap is not a v1 swap."}}const renderer=hasOwn(value,"renderer")?value.renderer:"html-fragment/1";if(typeof renderer!=="string"){return{path:pointer(path,"renderer"),category:"type",message:"The render renderer must be a string."}}if(!RENDERERS.includes(renderer)){return{path:pointer(path,"renderer"),category:"enum",message:"The render renderer is not a v1 renderer."}}const content=renderer==="html-fragment/1"?"html":"prepared";const other=content==="html"?"prepared":"html";if(!hasOwn(value,content)){return{path:pointer(path,content),category:"required",message:`The ${renderer} render requires '${content}'.`}}if(hasOwn(value,other)){return{path:pointer(path,other),category:"semantic",message:"A render action must carry exactly one content representation."}}if(content==="html"&&typeof value.html!=="string"){return{path:pointer(path,"html"),category:"type",message:"The render HTML must be a string."}}if(content==="prepared"&&!isPlainObject(value.prepared)){return{path:pointer(path,"prepared"),category:"type",message:"The prepared render content must be a JSON object."}}if(content==="prepared"&&value.swap!=="morph"){return{path:pointer(path,"swap"),category:"enum",message:"A vue-prepared/1 render must use the morph swap."}}}else if(kind==="data"){}else if(kind==="state"){if(typeof value.targetRenderId!=="string"){return{path:pointer(path,"targetRenderId"),category:"type",message:"The state target must be a render ID."}}if(!isSafeRenderId(value.targetRenderId)){return{path:pointer(path,"targetRenderId"),category:"pattern",message:"The state target must be a valid render ID."}}if(typeof value.stateToken!=="string"){return{path:pointer(path,"stateToken"),category:"type",message:"The state token must be a string."}}if(!value.stateToken){return{path:pointer(path,"stateToken"),category:"range",message:"The state token must not be empty."}}if(!isPlainObject(value.publicState)){return{path:pointer(path,"publicState"),category:"type",message:"Public State must be an object."}}}else if(kind==="event"){if(typeof value.eventName!=="string"){return{path:pointer(path,"eventName"),category:"type",message:"The event name must be a string."}}if(!value.eventName){return{path:pointer(path,"eventName"),category:"range",message:"The event name must not be empty."}}if(value.eventName.startsWith("citry:")){return{path:pointer(path,"eventName"),category:"pattern",message:"The event name is reserved."}}if(hasOwn(value,"target")){const issue=validateTarget(value.target,pointer(path,"target"),false);if(issue)return issue}}else if(kind==="redirect"){if(typeof value.url!=="string"){return{path:pointer(path,"url"),category:"type",message:"The redirect URL must be a string."}}if(!value.url){return{path:pointer(path,"url"),category:"range",message:"The redirect URL must not be empty."}}}else{if(typeof value.url!=="string"){return{path:pointer(path,"url"),category:"type",message:"The URL action URL must be a string."}}if(!value.url){return{path:pointer(path,"url"),category:"range",message:"The URL action URL must not be empty."}}if(value.mode!=="push"&&value.mode!=="replace"){return{path:pointer(path,"mode"),category:typeof value.mode==="string"?"enum":"type",message:"The URL action mode must be push or replace."}}}return validateTiming(value,path)};var validateErrorShape=(value,path="")=>{if(!isPlainObject(value)){return{path,category:"type",message:"The result error must be an object."}}for(const required of["status","code","message"]){if(!hasOwn(value,required)){return{path:pointer(path,required),category:"required",message:`The error requires '${required}'.`}}}const unknown=firstUnknown(value,ERROR_FIELDS);if(unknown!==null){return{path:pointer(path,unknown),category:"unknown_field",message:"The result error has an unknown field."}}if(typeof value.status!=="number"||!Number.isInteger(value.status)){return{path:pointer(path,"status"),category:typeof value.status==="number"&&!Number.isFinite(value.status)?"strict_json":"type",message:"The error status must be an integer."}}if(value.status<400||value.status>599){return{path:pointer(path,"status"),category:"range",message:"The error status must be from 400 to 599."}}if(typeof value.code!=="string"){return{path:pointer(path,"code"),category:"type",message:"The error code must be a string."}}if(!hasOwn(ERROR_STATUS_BY_CODE,value.code)){return{path:pointer(path,"code"),category:"enum",message:"The error code is not a v1 code."}}if(typeof value.message!=="string"){return{path:pointer(path,"message"),category:"type",message:"The error message must be a string."}}if(!value.message){return{path:pointer(path,"message"),category:"range",message:"The error message must not be empty."}}if(hasOwn(value,"fieldErrors")){if(!isPlainObject(value.fieldErrors)){return{path:pointer(path,"fieldErrors"),category:"type",message:"Field errors must be an object."}}for(const name of Object.keys(value.fieldErrors).sort()){if(typeof value.fieldErrors[name]!=="string"){return{path:pointer(pointer(path,"fieldErrors"),name),category:"type",message:"Field errors map strings."}}}}const expected=ERROR_STATUS_BY_CODE[value.code];if(expected!==null&&value.status!==expected){return{path:pointer(path,"status"),category:"semantic",message:"The error status does not match its code."}}return null};var validateResultShape=(value,path="")=>{if(!isPlainObject(value)){return{path,category:"type",message:"A result must be an object."}}if(!hasOwn(value,"ok")){return{path:pointer(path,"ok"),category:"required",message:"The result requires 'ok'."}}if(typeof value.ok!=="boolean"){return{path:pointer(path,"ok"),category:"type",message:"The result's 'ok' field must be a boolean."}}const required=value.ok?["ok","actions"]:["ok","error"];for(const field of required){if(!hasOwn(value,field)){return{path:pointer(path,field),category:"required",message:`The result requires '${field}'.`}}}const unknown=firstUnknown(value,value.ok?OK_RESULT_FIELDS:ERROR_RESULT_FIELDS);if(unknown!==null){return{path:pointer(path,unknown),category:"unknown_field",message:"The result has an unknown field."}}if(hasOwn(value,"sendSequence")){const issue=validateNonNegativeInteger(value.sendSequence,pointer(path,"sendSequence"),"The send sequence must be an integer.");if(issue)return issue}if(!value.ok)return validateErrorShape(value.error,pointer(path,"error"));if(!Array.isArray(value.actions)){return{path:pointer(path,"actions"),category:"type",message:"The result actions must be an array."}}for(let index=0;indexisPlainObject(action)&&action.action==="data").length>1){return{path:pointer(path,"actions"),category:"semantic",message:"Each result may carry at most one data action."}}return null};var validateResult=(value,path="")=>{const jsonIssue=validateStrictJson(value,path);return jsonIssue??validateResultShape(value,path)};var validateResultEnvelopeShape=(value,path="")=>{if(!isPlainObject(value)){return{path,category:"type",message:"The result envelope must be an object."}}for(const required of["protocol","requestId","results"]){if(!hasOwn(value,required)){return{path:pointer(path,required),category:"required",message:`The result envelope requires '${required}'.`}}}const unknown=firstUnknown(value,RESULT_ENVELOPE_FIELDS);if(unknown!==null){return{path:pointer(path,unknown),category:"unknown_field",message:"The result envelope has an unknown field."}}if(value.protocol!==PROTOCOL){return{path:pointer(path,"protocol"),category:typeof value.protocol==="string"?"enum":"type",message:"The result protocol must be citry-events/1."}}if(value.requestId!==null&&typeof value.requestId!=="string"){return{path:pointer(path,"requestId"),category:"type",message:"The result request ID must be a string or null."}}if(value.requestId===""){return{path:pointer(path,"requestId"),category:"range",message:"The result request ID must not be empty."}}if(!Array.isArray(value.results)){return{path:pointer(path,"results"),category:"type",message:"The results must be an array."}}if(!value.results.length){return{path:pointer(path,"results"),category:"range",message:"The results array must not be empty."}}for(let index=0;index{const jsonIssue=validateStrictJson(value,path);return jsonIssue??validateResultEnvelopeShape(value,path)};var validateExchangeAfterValidatedEnvelope=(callEnvelope,resultEnvelope)=>{const result=resultEnvelope;if(result.requestId!==callEnvelope.requestId){return{path:"/requestId",category:"correlation",message:"The result request ID does not match the call."}}if(result.results.length!==callEnvelope.calls.length){return{path:"/results",category:"correlation",message:"The result count does not match the call count."}}const advertised=callEnvelope.capabilities??{};const actions=new Set(advertised.actions??CAPABILITIES_BASELINE_V1.actions);const swaps=new Set(advertised.swaps??CAPABILITIES_BASELINE_V1.swaps);const renderers=new Set(advertised.renderers??CAPABILITIES_BASELINE_V1.renderers);for(let index=0;indexvalidateResult({ok:true,actions});var buildOkResult=(actions,sendSequence)=>{const result={ok:true,actions:copyJson(actions)};if(sendSequence!==void 0)result.sendSequence=sendSequence;const issue=validateResult(result);if(issue)throw new ProtocolValueError(issue);return result};var resultIndex=path=>{const match=/^\/results\/(\d+)(?:\/|$)/.exec(path);return match?Number(match[1]):null};var preflightResultEnvelope=(reply,sent)=>{const structural=validateResultEnvelope(reply);if(structural){const edge=isPlainObject(reply)&&reply.requestId===null;const index=resultIndex(structural.path);return{ok:false,issue:structural,reason:edge&&structural.path.startsWith("/results")?"edge":index===null?"header":`result ${index}`}}const envelope=reply;if(envelope.requestId===null){const edge=envelope.results[0];return{ok:true,results:sent.calls.map(()=>edge)}}const relationship=validateExchangeAfterValidatedEnvelope(sent,envelope);if(relationship){const index=resultIndex(relationship.path);return{ok:false,issue:relationship,reason:relationship.path==="/requestId"||relationship.path==="/results"&&relationship.category==="correlation"?"correlation":`result ${index??0}`}}return{ok:true,results:envelope.results}};var assertValidActionList=actions=>{const issue=validateActionList(actions);if(issue)throw new ProtocolValueError(issue);return actions};var isFormSubmitter=(value,form)=>(typeof HTMLButtonElement==="function"&&value instanceof HTMLButtonElement||typeof HTMLInputElement==="function"&&value instanceof HTMLInputElement)&&value.form===form;var collectFormArgs=(form,reservedFields,submitter)=>{const entries=new Map;const button=isFormSubmitter(submitter,form)?submitter:void 0;let data;try{data=new FormData(form,button)}catch{data=new FormData(form)}data.forEach((value,name)=>{if(reservedFields.has(name)||typeof value!=="string")return;const bucket=entries.get(name)??[];bucket.push(value);entries.set(name,bucket)});const output={};entries.forEach((values,name)=>{Object.defineProperty(output,name,{configurable:true,enumerable:true,value:values.length===1?values[0]:values.slice(),writable:true})});return output};var builtInMember=(target,key)=>{const own=Object.getOwnPropertyDescriptor(target,key);if(own!==void 0&&(own.get!==void 0||own.set!==void 0))return own;for(let proto=Object.getPrototypeOf(target);proto!==null;proto=Object.getPrototypeOf(proto)){const descriptor=Object.getOwnPropertyDescriptor(proto,key);if(descriptor!==void 0)return descriptor}return void 0};var documentMembers=currentDocument=>{const bound=new WeakMap;const bind=(method,target)=>{const cached=bound.get(method);if(cached!==void 0&&cached.target===target)return cached.method;const boundMethod=method.bind(target);bound.set(method,{target,method:boundMethod});return boundMethod};return new Proxy({},{get(_shell,key){const target=currentDocument();const descriptor=builtInMember(target,key);let value;if(descriptor===void 0)value=Reflect.get(target,key);else if(descriptor.get!==void 0)return descriptor.get.call(target);else if(descriptor.set!==void 0)return void 0;else value=descriptor.value;return typeof value==="function"?bind(value,target):value},set(_shell,key,value){const target=currentDocument();const descriptor=builtInMember(target,key);if(descriptor?.set!==void 0){descriptor.set.call(target,value);return true}return Reflect.set(target,key,value)}})};var pageDocument=documentMembers(()=>globalThis.document);var pageOrigin=()=>{const scope=globalThis;if(scope.location===void 0)return null;return typeof scope.origin==="string"?scope.origin:String(scope.location.origin)};var onPageOrigin=target=>{const origin=pageOrigin();return origin!==null&&target.origin!=="null"&&target.origin===origin};var resolveOnPage=url=>{const location=globalThis.location;if(location===void 0||typeof location.href!=="string")return null;try{return new URL(url,location.href)}catch{let inherited;try{inherited=new URL(url,pageDocument.baseURI)}catch{throw new Error(`Citry cannot resolve the URL ${JSON.stringify(url.slice(0,80))}.`)}if(!onPageOrigin(inherited))throw new Error("Citry refused a URL that does not resolve to this page's origin.");return inherited}};var assertValidActionList2=actions=>assertValidActionList(actions);var describeValue=value=>typeof value==="string"?JSON.stringify(value):typeof value==="number"?String(value):`a ${typeof value}`;var checkSendOptions=value=>{if(value===void 0)return void 0;if(value===null||typeof value!=="object"||Array.isArray(value))throw new TypeError("Citry Events send options must be an object, such as {timeout: 5000}.");for(const key of Object.keys(value)){if(key!=="timeout"&&key!=="wait")throw new TypeError(`Citry Events send got an unknown option '${key}'; the options are 'timeout' and 'wait'.`)}const{timeout,wait}=value;if(wait!==void 0&&wait!==true&&wait!==false)throw new TypeError(`Citry Events option 'wait' must be true or false; got ${describeValue(wait)}.`);if(timeout!==void 0&&(typeof timeout!=="number"||!Number.isFinite(timeout)||timeout<=0))throw new Error("Citry Events timeout must be a positive finite number.");const checked={};if(timeout!==void 0)checked.timeout=timeout;if(wait===false)checked.wait=false;return checked};var queuedHandlerError=handler=>new TypeError(`Citry Events option 'wait: false' needs a detached handler, and '${handler}' is not one. Calls from one Vue app are sent one at a time, in order, because each render and State change builds on the one before it. Remove 'wait: false', or declare the handler with @event(detached=True) if it never renders or changes State. To replace an older call to the same handler instead, declare it with @event(latest_wins=True).`);var validContext=value=>value!==null&&typeof value==="object"&&Object.keys(value).sort().join("|")==="componentClassId|descriptor|publicState|serverRenderId|stateToken"&&validateStrictJson(value)===null&&typeof value.serverRenderId==="string"&&value.serverRenderId.length>0&&(value.stateToken===null||typeof value.stateToken==="string"&&value.stateToken.length>0)&&typeof value.componentClassId==="string"&&value.componentClassId.length>0&&validateDescriptor(value.descriptor)===null&&value.descriptor.componentClassId===value.componentClassId;var VueEventCancellation=class extends Error{};var VueEventStale=class extends VueEventCancellation{constructor(reason){super(reason==="disposed"?"The Vue Events bridge was disposed; the source is stale or retired.":reason==="superseded"?"The Vue event call was superseded by a newer call.":"The Vue event source is stale or retired.");__publicField(this,"reason");this.reason=reason}};var stale=(reason="retired")=>new VueEventStale(reason);var activityError=error=>{if(error!==null&&typeof error==="object"&&"status"in error&&typeof error.status==="number"&&"code"in error&&typeof error.code==="string"&&"message"in error&&typeof error.message==="string")return error;const message=error instanceof Error?error.message:"The Vue event request failed.";return{status:0,code:message==="The Vue event request timed out."?"timeout":"transport",message}};var eventUrl=(base,context,handler)=>{if(typeof base!=="string"||!base.endsWith("/")||base.includes("?")||base.includes("#")){throw new Error("Vue Events eventBaseUrl must be a path ending in '/'.")}return`${base}${encodeURIComponent(context.componentClassId)}/${encodeURIComponent(handler)}`};var configuredEventRoutes=(url,endpoint,eventBaseUrl)=>{if(typeof url!=="string"||url.length===0)return{endpoint,eventBaseUrl};if(url.includes("?")||url.includes("#"))throw new Error("Citry Events url must not contain a query or fragment.");const normalized=url.endsWith("/")?url:`${url}/`;if(normalized.endsWith("/call/")){return{endpoint:normalized.slice(0,-1),eventBaseUrl:`${normalized.slice(0,-5)}e/`}}if(normalized.endsWith("/e/")){return{endpoint:`${normalized.slice(0,-2)}call`,eventBaseUrl:normalized}}return{endpoint:`${normalized}call`,eventBaseUrl:`${normalized}e/`}};var eventRequestTarget=url=>{const target=resolveOnPage(url);if(target===null)return{href:url,sameOrigin:false};return{href:target.href,sameOrigin:onPageOrigin(target)}};var readCookie=name=>{if(typeof document==="undefined"||typeof pageDocument.cookie!=="string")return"";for(const item of pageDocument.cookie.split(";")){const value=item.trim();if(!value.startsWith(`${name}=`))continue;try{return decodeURIComponent(value.slice(name.length+1))}catch{}}return""};var isWellFormedUtf16=value=>{for(let index=0;index=55296&&unit<=56319){const next=value.charCodeAt(index+1);if(!(next>=56320&&next<=57343))return false;index+=1}else if(unit>=56320&&unit<=57343)return false}return true};var flatQuery=args=>{const query=new URLSearchParams;const append=(key,value)=>{if(typeof value==="string"){if(!isWellFormedUtf16(value))throw new Error(`Event argument '${key}' is not well-formed UTF-16.`);query.append(key,value)}else if(typeof value==="boolean")query.append(key,String(value));else if(typeof value==="number"&&Number.isFinite(value))query.append(key,String(value));else throw new Error(`Event argument '${key}' has no flat GET query representation.`)};for(const[key,value]of Object.entries(args)){if(!isWellFormedUtf16(key))throw new Error("Event argument name is not well-formed UTF-16.");if(key.startsWith("_citry_"))throw new Error(`Event argument '${key}' uses a reserved GET query name.`);if(Array.isArray(value)){if(value.length===0)throw new Error(`Event argument '${key}' has no flat GET query representation.`);for(const item of value)append(key,item)}else append(key,value)}return query};var answersInvalidState=raw=>{if(raw===null||typeof raw!=="object"||!Array.isArray(raw.results))return false;const results=raw.results;if(results.length!==1)return false;const[result]=results;if(result===null||typeof result!=="object")return false;const error=result.error;return error!==null&&typeof error==="object"&&error.code==="invalid_state"};var attachmentFilename=value=>{const extended=/(?:^|;)\s*filename\*\s*=\s*([^;]+)/i.exec(value)?.[1]?.trim();if(extended!==void 0){const encoded=/^UTF-8''(.+)$/i.exec(extended)?.[1];if(!encoded)throw new Error("The attachment response has an unsupported encoded filename.");try{return decodeURIComponent(encoded)}catch{throw new Error("The attachment response has an invalid encoded filename.")}}const quoted=/(?:^|;)\s*filename\s*=\s*"((?:\\.|[^"\\])*)"/i.exec(value)?.[1];if(quoted!==void 0)return quoted.replace(/\\(.)/g,"$1")||"download";const token=/(?:^|;)\s*filename\s*=\s*([!#$%&'*+.^_`|~0-9A-Za-z-]+)/i.exec(value)?.[1];return token||"download"};var saveAttachment=(blob,filename)=>{const url=URL.createObjectURL(blob);const anchor=pageDocument.createElement("a");try{anchor.href=url;anchor.download=filename;anchor.style.display="none";pageDocument.body.append(anchor);anchor.click()}finally{anchor.remove();URL.revokeObjectURL(url)}};var createVueEventsBridge=options=>{const reportableFailures=new WeakSet;const handledFailures=new WeakSet;const fetchImpl=options.fetch??globalThis.fetch.bind(globalThis);let correlation=0;const owners=new Map;const acceptedAtSpot=new Map;const acceptAtSpot=(source,job)=>{const count=(acceptedAtSpot.get(source.stableId)??0)+1;acceptedAtSpot.set(source.stableId,count);job.acceptedAtSpotWhenAccepted=count};const queue=[];let active=null;const externalJobs=new Set;const jobsWithNoWaitActions=new Set;const detachedCalls=new Set;let running=false;let disposed=false;const supersedeEarlier=input=>{const error=stale("superseded");const sameCall=job=>job.input.source.stableId===input.source.stableId&&job.input.source.generation===input.source.generation&&job.input.handler===input.handler;for(const job of jobsWithNoWaitActions)if(sameCall(job))job.cancel(error);for(const job of detachedCalls)if(sameCall(job))job.cancel(error);for(let index=queue.length-1;index>=0;index-=1){const job=queue[index];if(job.input.source.stableId===input.source.stableId&&job.input.source.generation===input.source.generation&&job.input.handler===input.handler){queue.splice(index,1);lifecycle("stale",job.input.source,job.input.handler,{reason:"superseded"});job.cancel(error)}}if(active&&active.input.source.stableId===input.source.stableId&&active.input.source.generation===input.source.generation&&active.input.handler===input.handler)active.cancel(error)};const lifecycle=(kind,source,event,detail)=>{try{return options.host.lifecycle?.(kind,source,event,detail)!==false}catch(error){console.error(`[Citry] citry:events:${kind} listener failed:`,error);return true}};const reportFailure=(source,handler,error)=>{const reported=activityError(error);if(reported.code==="stale_state"){if(error!==null&&typeof error==="object")reportableFailures.add(error);if(lifecycle("stale",source,handler,{reason:"version"}))options.host.reportOutOfDate?.()}lifecycle("error",source,handler,{error:reported})};const ownerState=source=>{const existing=owners.get(source.stableId);if(existing?.generation===source.generation)return existing;const state={generation:source.generation,sendSequence:0,acceptedEpoch:0,retired:false,timers:new Map};owners.set(source.stableId,state);return state};const current=source=>{const context=options.host.resolve(source);if(context===null||!validContext(context))throw stale("retired");return context};const stillCurrent=(source,state,epoch)=>{if(state.retired||owners.get(source.stableId)!==state||state.generation!==source.generation||epoch!==void 0&&epoch!==state.acceptedEpoch){throw stale(state.retired?"retired":"epoch")}current(source)};const remountTimers=new Map;const sourcelessTimers=new Map;const delay=(milliseconds,state,job)=>new Promise((resolve,reject)=>{if(job.cancelError){reject(job.cancelError);return}if(disposed||state.retired&&!job.acceptedRemount){reject(stale(disposed?"disposed":"retired"));return}const timers=job.acceptedRemount?remountTimers:state.timers;const timer=globalThis.setTimeout(()=>{timers.delete(timer);resolve()},milliseconds);timers.set(timer,reject);void job.cancelled.catch(error=>{if(!timers.delete(timer))return;globalThis.clearTimeout(timer);reject(error)})});const continuationCurrent=(source,state,epoch,job,survivesNewerResult=false)=>{if(job.cancelError)throw job.cancelError;if(disposed)throw stale("disposed");if(!survivesNewerResult&&epoch!==state.acceptedEpoch)throw stale("epoch");if(!job.acceptedRemount){stillCurrent(source,state,survivesNewerResult?void 0:epoch);return}if(!survivesNewerResult&&acceptedAtSpot.get(source.stableId)!==job.acceptedAtSpotWhenAccepted){throw stale("epoch")}};const validateTargets=(result,source,serverRenderId)=>{if(!result.ok)return;const componentTarget=`render:${serverRenderId}`;for(const action of result.actions){if(action.action==="render"&&!options.host.preflightResult&&action.target!==componentTarget){throw new Error("Vue Events accepts the current component target; marker targets are not implemented.")}if(action.action==="event"&&action.target!==void 0&&action.target!==componentTarget){throw new Error("Vue Events accepts the current component Event target; marker targets are not implemented.")}}current(source)};const applyOne=async(action,source,state,epoch,onData,job,renderPlan)=>{if(action.action==="data"){if(!job.external)continuationCurrent(source,state,epoch,job);onData(action.value);return}if(action.action==="render"){if(job.cancelError)throw job.cancelError;stillCurrent(source,state,epoch);const context=current(source);if(!renderPlan&&action.target!==`render:${context.serverRenderId}`){throw new Error("The experimental Vue Events bridge accepts only its current root Render target.")}if(!("renderer"in action)||action.renderer!=="vue-prepared/1"){throw new Error("The Vue Events bridge requires a vue-prepared/1 Render action.")}const preparing=options.host.prepareRender(action,source,job.controller?.signal??new AbortController().signal,renderPlan);let prepared;try{prepared=await Promise.race([preparing,job.cancelled]);stillCurrent(source,state,epoch)}catch(error){try{options.host.abortRender(void 0,source)}catch(cleanupError){console.error("[Citry] aborting a prepared Vue render failed:",cleanupError)}void preparing.then(value=>{try{options.host.abortRender(value,source)}catch(cleanupError){console.error("[Citry] aborting a late prepared Vue render failed:",cleanupError)}},()=>void 0);throw error}job.committingTransaction=prepared.transaction;try{await Promise.race([options.host.commitRender(prepared,source),job.cancelled]);lifecycle("swapped",source,job.input.handler,{els:[]})}finally{job.committingTransaction=void 0}}else if(action.action==="state"){continuationCurrent(source,state,epoch,job);options.host.commitState(action.targetRenderId,action.stateToken,action.publicState,source)}else if(action.action==="event"){continuationCurrent(source,state,epoch,job);const followRemount=job.acceptedRemount;const rootTarget=followRemount?void 0:`render:${current(source).serverRenderId}`;const callerTarget=job.callerRenderId===void 0?void 0:`render:${job.callerRenderId}`;if(action.target!==void 0&&action.target!==rootTarget&&action.target!==callerTarget){throw new Error("The experimental Vue Events bridge accepts only its current root Event target.")}if(job.external&&action.target===void 0&&options.host.dispatchEventGlobal)options.host.dispatchEventGlobal(action.eventName,action.detail);else options.host.dispatchEvent(action.eventName,action.detail,source,followRemount)}else if(action.action==="redirect"){if(!job.external)continuationCurrent(source,state,epoch,job,true);options.host.redirect(action.url)}else{if(!job.external)continuationCurrent(source,state,epoch,job);options.host.updateUrl(action.url,action.mode)}};const applyActions=async(result,source,state,epoch,job,renderPlan)=>{if(!result.ok){reportableFailures.add(result.error);throw result.error}let data;const hoisted=new Set;result.actions.forEach((action,index)=>{if(action.action==="state"&&!(typeof action.delay==="number"&&action.delay>0)&&action.wait!==false){if(job.cancelError)throw job.cancelError;stillCurrent(source,state,epoch);options.host.commitState(action.targetRenderId,action.stateToken,action.publicState,source);hoisted.add(index)}});for(const[index,action]of result.actions.entries()){if(hoisted.has(index))continue;const run=async()=>{const seconds=typeof action.delay==="number"?action.delay:0;const delayed=seconds>0;if(delayed)await delay(seconds*1e3,state,job);const actionEpoch=job.detachedHandler&&!delayed?state.acceptedEpoch:epoch;await applyOne(action,source,state,actionEpoch,value=>{data=value},job,action.action==="render"?renderPlan:void 0)};if("wait"in action&&action.wait===false){job.noWaitPending+=1;jobsWithNoWaitActions.add(job);void run().catch(error=>{if(error instanceof VueEventStale){lifecycle("stale",source,job.input.handler,{reason:error.reason});return}if(!(error instanceof VueEventCancellation))reportFailure(source,job.input.handler,error);console.error("[Citry] applying a Vue event action marked wait: false failed:",error)}).finally(()=>{job.noWaitPending-=1;if(job.noWaitPending===0)jobsWithNoWaitActions.delete(job)})}else await run()}return data};const sendNow=async job=>{const input=job.input;if(disposed)throw stale("disposed");const context=current(input.source);const state=ownerState(input.source);job.owner=state;const appId=options.host.appId(input.source);if(typeof appId!=="string"||appId.length===0)throw stale("retired");const committedRevision=options.host.revision(input.source);if(!Number.isInteger(committedRevision)||committedRevision<0)throw stale("retired");if(!Object.prototype.hasOwnProperty.call(context.descriptor.eventHandlers,input.handler))throw new Error(`Unknown event handler '${input.handler}'.`);const handlerOptions=context.descriptor.eventHandlers[input.handler];const detachedHandler=handlerOptions.detached===true;job.detachedHandler=detachedHandler;job.callerRenderId=context.serverRenderId;job.lifecycleStarted=true;if(!lifecycle("before",input.source,input.handler))throw new VueEventCancellation(`Citry Events send '${input.handler}' was cancelled by citry:events:before.`);const useGet=handlerOptions.httpMethod==="GET";const runtimeConfig=options.runtimeConfig?.()??{};const configuredEndpoint=typeof options.endpoint==="function"&&!useGet?options.endpoint(context,input.handler):typeof options.endpoint==="string"?options.endpoint:"";const routes=configuredEventRoutes(runtimeConfig.url??"",configuredEndpoint,options.eventBaseUrl);if(useGet&&input.stateUpdates!==void 0)throw new Error("GET events cannot send pending State updates.");const taken=useGet||detachedHandler?void 0:input.stateUpdates??options.host.takePendingState?.(input.source,input.handler);job.stateUpdates=taken===void 0?void 0:structuredClone(taken);state.sendSequence+=1;correlation+=1;const call=buildCall({componentClassId:context.componentClassId,handlerName:input.handler,callerRenderId:context.serverRenderId,args:input.args??{},argsSource:input.argsSource,stateToken:context.stateToken??void 0,stateUpdates:job.stateUpdates,sendSequence:state.sendSequence});const envelope=buildCallEnvelope(`vue_${correlation}`,[call],{actions:["render","data","state","event","redirect","url"],swaps:["morph"],renderers:["vue-prepared/1"]});const headers={"Content-Type":"application/citry-events+json","X-Citry-Events":"1","X-Citry-Vue-App":appId,"X-Citry-Vue-Occurrence":input.source.stableId,"X-Citry-Vue-Revision":String(committedRevision)};const selectedTransport=options.transport?.()??null;const isolated=useGet||handlerOptions.allowBatching===false;const endpoint=isolated?eventUrl(routes.eventBaseUrl??"",context,input.handler):routes.endpoint;const target=selectedTransport?{href:endpoint,sameOrigin:true}:eventRequestTarget(endpoint);const csrf=runtimeConfig.csrf??options.csrf;if(!useGet&&csrf&&target.sameOrigin){const token=csrf.token?typeof csrf.token==="function"?csrf.token():csrf.token:selectedTransport?void 0:readCookie(csrf.cookie??"csrftoken");if(token)headers[csrf.header??"X-CSRFToken"]=token}const callTimeout=input.options?.timeout;const timeoutMs=callTimeout??runtimeConfig.timeout??options.timeoutMs??3e4;if(!Number.isFinite(timeoutMs)||timeoutMs<=0)throw new Error("Vue Events timeoutMs must be positive.");const controller=new AbortController;job.controller=controller;let requestUrl=target.href;let queryTokenUrl=null;if(useGet){const query=flatQuery(input.args??{});query.append("_citry_protocol",envelope.protocol);query.append("_citry_request_id",envelope.requestId);query.append("_citry_capabilities",JSON.stringify(envelope.capabilities));query.append("_citry_caller_render_id",call.callerRenderId??"");query.append("_citry_send_sequence",String(call.sendSequence));if(handlerOptions.usesState===true&&call.stateToken!==void 0){headers[CARRIER_HEADERS.stateToken]=call.stateToken;const withToken=new URLSearchParams(query);withToken.append(CARRIER_FIELDS.stateToken,call.stateToken);queryTokenUrl=`${requestUrl}?${withToken.toString()}`}requestUrl+=`?${query.toString()}`}const requestHeaders=useGet?Object.fromEntries(Object.entries(headers).filter(([name])=>name!=="Content-Type")):headers;const requestMethod=isolated?handlerOptions.httpMethod:"POST";const attempt=async(requestUrl2,requestHeaders2,sentEnvelope)=>{if(selectedTransport){const request={url:requestUrl2,method:requestMethod,headers:{...requestHeaders2},signal:controller.signal};try{return{raw:await selectedTransport.send(sentEnvelope,request),transported:true}}catch(error){if(error!==null&&typeof error==="object")reportableFailures.add(error);throw error}}const requestInit={method:requestMethod,credentials:"same-origin",redirect:"manual",headers:requestHeaders2,...useGet?{}:{body:JSON.stringify(envelope)},signal:controller.signal};let response;try{response=await fetchImpl(requestUrl2,requestInit)}catch(error){if(error!==null&&typeof error==="object")reportableFailures.add(error);throw error}if(response.type==="opaqueredirect"){const error=new Error("The server answered the event call with a redirect, which event calls do not follow.");reportableFailures.add(error);throw error}const disposition=response.headers?.get?.("Content-Disposition")??null;if(response.ok&&disposition&&/^\s*attachment(?:;|$)/i.test(disposition)){return{attachment:await response.blob(),filename:attachmentFilename(disposition)}}try{const raw2=await response.json();const vary=response.headers?.get?.("Vary")??"";const readsTokenHeader=vary.split(",").map(name=>name.trim().toLowerCase()).some(name=>name==="*"||name===CARRIER_HEADERS.stateToken.toLowerCase());return readsTokenHeader?{raw:raw2,readsTokenHeader:true}:{raw:raw2}}catch(error){if(response.ok)throw new Error("A successful raw Event response must be an attachment.");throw error}};const operation=(async()=>{const first=await attempt(requestUrl,requestHeaders,envelope);if(queryTokenUrl===null||controller.signal.aborted||!("raw"in first)||first.readsTokenHeader===true||!answersInvalidState(first.raw))return first;const{[CARRIER_HEADERS.stateToken]:_sentToken,...withoutToken}=requestHeaders;return attempt(queryTokenUrl,withoutToken,structuredClone(envelope))})();let timeoutId=0;const received=await Promise.race([operation,job.cancelled,new Promise((_resolve,reject)=>{timeoutId=globalThis.setTimeout(()=>{controller.abort();const error=new Error("The Vue event request timed out.");reportableFailures.add(error);reject(error)},timeoutMs)})]).finally(()=>globalThis.clearTimeout(timeoutId));if("attachment"in received){stillCurrent(input.source,state);if(!detachedHandler){state.acceptedEpoch+=1;acceptAtSpot(input.source,job)}continuationCurrent(input.source,state,state.acceptedEpoch,job);saveAttachment(received.attachment,received.filename);return void 0}const raw=received.raw;const checked=preflightResultEnvelope(raw,envelope);if(!checked.ok)throw new Error(`Invalid Events response: ${checked.issue.message}`);const[result]=received.transported?copyJson(checked.results):checked.results;if(detachedHandler&&result.ok){const forbidden=result.actions.find(action=>action.action==="render"||action.action==="state");if(forbidden)throw new Error(`Invalid Events response: detached handler '${input.handler}' returned a '${forbidden.action}' action.`)}stillCurrent(input.source,state);validateTargets(result,input.source,context.serverRenderId);const preparedResult=options.host.preflightResult?.(result,input.source)??{result};if(job.cancelError)throw job.cancelError;if(!detachedHandler){state.acceptedEpoch+=1;acceptAtSpot(input.source,job)}if(preparedResult.result.ok)job.stateAccepted=true;return applyActions(preparedResult.result,input.source,state,state.acceptedEpoch,job,preparedResult.renderPlan)};const runJob=async job=>{try{job.activity?.start(job.intent);const value=await sendNow(job);if(job.cancelError)throw job.cancelError;job.stateAccepted=true;job.activity?.succeed(job.intent);if(job.lifecycleStarted)lifecycle("after",job.input.source,job.input.handler,{ok:true});job.resolve(value)}catch(error){if(!job.stateAccepted&&job.stateUpdates!==void 0)options.host.restorePendingState?.(job.input.source,job.stateUpdates);if(job.lifecycleStarted){if(error instanceof VueEventStale){lifecycle("stale",job.input.source,job.input.handler,{reason:error.reason})}else if(!(error instanceof VueEventCancellation)){reportFailure(job.input.source,job.input.handler,error)}lifecycle("after",job.input.source,job.input.handler,{ok:false})}if(!(error instanceof VueEventCancellation)){job.activity?.fail(job.intent,activityError(error));if(job.activity&&error!==null&&typeof error==="object"&&reportableFailures.has(error))handledFailures.add(error)}job.reject(error)}finally{if(!job.activityFinished){job.activityFinished=true;job.activity?.finish(job.intent)}}};const runQueue=async()=>{if(running)return;running=true;try{while(queue.length>0){const job=queue.shift();if(!job||job.settled)continue;active=job;try{await runJob(job)}finally{active=null}}}finally{running=false}};const unsupportedBrowserMethods=new Set(["HEAD","OPTIONS","CONNECT","TRACE","TRACK"]);const send=given=>{if(disposed)return Promise.reject(stale("disposed"));let activity;let intent;let input=given;let outsideQueue=false;try{input={...given,options:checkSendOptions(given.options)};const context=current(input.source);if(!Object.prototype.hasOwnProperty.call(context.descriptor.eventHandlers,input.handler))throw new Error(`Unknown event handler '${input.handler}'.`);const method=context.descriptor.eventHandlers[input.handler].httpMethod;if(unsupportedBrowserMethods.has(method))throw new Error(`Event handler '${input.handler}' uses HTTP ${method}, which is server-transport-only and cannot be sent by the browser bridge.`);const handlerOptions=context.descriptor.eventHandlers[input.handler];outsideQueue=input.options?.wait===false;if(outsideQueue&&handlerOptions.detached!==true)throw queuedHandlerError(input.handler);if(handlerOptions.detached===true&&input.stateUpdates!==void 0)throw new TypeError(`Event handler '${input.handler}' is detached, so a call to it cannot send State updates.`);activity=options.activity?.(input.source,context.descriptor);intent=activity?.enqueue(input.handler);if(handlerOptions.latestCallWins===true)supersedeEarlier(input)}catch(error){return Promise.reject(error)}let resolvePromise;let rejectPromise;let cancelPromise;const promise=new Promise((resolve,reject)=>{resolvePromise=resolve;rejectPromise=reject});const cancelled=new Promise((_resolve,reject)=>{cancelPromise=reject});void cancelled.catch(()=>void 0);const job={input,acceptedRemount:false,noWaitPending:0,activity,intent,activityFinished:false,lifecycleStarted:false,external:false,stateAccepted:false,settled:false,cancelled,cancel(error){if(job.cancelError===void 0){job.cancelError=error;cancelPromise(error)}if(job.settled)return;job.controller?.abort();if(!job.activityFinished){job.activityFinished=true;job.activity?.finish(job.intent)}job.reject(error)},resolve(value){if(job.settled)return;job.settled=true;resolvePromise(value)},reject(error){if(job.settled)return;job.settled=true;rejectPromise(error)}};if(outsideQueue){detachedCalls.add(job);void runJob(job).finally(()=>detachedCalls.delete(job))}else{queue.push(job);void runQueue()}return promise};const applyActionsExternally=async(actions,source)=>{const result=buildOkResult(actions);if(!source){let data;for(const action of result.actions){if(disposed)throw stale("disposed");if(typeof action.delay==="number"&&action.delay>0){const milliseconds=action.delay*1e3;await new Promise((resolve,reject)=>{const timer=globalThis.setTimeout(()=>{sourcelessTimers.delete(timer);resolve()},milliseconds);sourcelessTimers.set(timer,reject)});if(disposed)throw stale("disposed")}if(action.action==="data")data=action.value;else if(action.action==="redirect")options.host.redirect(action.url);else if(action.action==="url")options.host.updateUrl(action.url,action.mode);else if(action.action==="event"){if(action.target!==void 0||!options.host.dispatchEventGlobal)throw new Error("Citry.events.applyActions needs a mounted component for targeted Event actions.");options.host.dispatchEventGlobal(action.eventName,action.detail)}else{throw new Error("Citry.events.applyActions needs a mounted component for Render and State actions.")}}return data}const externalContext=current(source);const state=ownerState(source);state.acceptedEpoch+=1;const cancelled=new Promise(()=>void 0);const job={input:{source,handler:"__external__"},acceptedRemount:false,noWaitPending:0,activityFinished:true,lifecycleStarted:true,external:true,callerRenderId:externalContext.serverRenderId,stateAccepted:true,settled:true,cancelled,cancel(){},resolve(){},reject(){}};let prepared;try{prepared=options.host.preflightResult?.(result,source)??{result}}catch(error){if(activityError(error).code==="stale_state"&&lifecycle("before",source,job.input.handler)){reportFailure(source,job.input.handler,error);lifecycle("after",source,job.input.handler,{ok:false})}throw error}if(!lifecycle("before",source,job.input.handler)){const error=new VueEventCancellation("Citry Events applyActions was cancelled by citry:events:before.");lifecycle("after",source,job.input.handler,{ok:false});throw error}acceptAtSpot(source,job);externalJobs.add(job);try{const value=await applyActions(prepared.result,source,state,state.acceptedEpoch,job,prepared.renderPlan);lifecycle("after",source,job.input.handler,{ok:true});return value}catch(error){if(error instanceof VueEventStale){lifecycle("stale",source,job.input.handler,{reason:error.reason})}else if(!(error instanceof VueEventCancellation)){reportFailure(source,job.input.handler,error)}lifecycle("after",source,job.input.handler,{ok:false});throw error}finally{externalJobs.delete(job)}};const retire=(source,acceptedTransaction)=>{const state=owners.get(source.stableId);if(state?.generation===source.generation){state.retired=true;for(const[timer,reject]of state.timers){globalThis.clearTimeout(timer);reject(stale("retired"))}state.timers.clear();owners.delete(source.stableId)}const error=new VueEventStale("retired");for(let index=queue.length-1;index>=0;index-=1){const job=queue[index];if(job.input.source.stableId===source.stableId&&job.input.source.generation===source.generation){queue.splice(index,1);lifecycle("stale",source,job.input.handler,{reason:"retired"});job.cancel(error)}}for(const job of detachedCalls)if(job.input.source.stableId===source.stableId&&job.input.source.generation===source.generation)job.cancel(error);for(const job of externalJobs){if(acceptedTransaction!==void 0&&job.committingTransaction===acceptedTransaction&&job.input.source.stableId===source.stableId&&job.input.source.generation===source.generation)job.acceptedRemount=true}if(active?.input.source.stableId===source.stableId&&active.input.source.generation===source.generation&&acceptedTransaction!==void 0&&active.committingTransaction===acceptedTransaction){active.acceptedRemount=true}else if(active?.input.source.stableId===source.stableId&&active.input.source.generation===source.generation)active.cancel(error)};const dispose=()=>{if(disposed)return;disposed=true;for(const state of owners.values()){state.retired=true;for(const[timer,reject]of state.timers){globalThis.clearTimeout(timer);reject(stale("disposed"))}state.timers.clear()}owners.clear();acceptedAtSpot.clear();for(const timers of[remountTimers,sourcelessTimers]){for(const[timer,reject]of timers){globalThis.clearTimeout(timer);reject(stale("disposed"))}timers.clear()}const error=new VueEventStale("disposed");for(const job of queue.splice(0)){lifecycle("stale",job.input.source,job.input.handler,{reason:"disposed"});job.cancel(error)}active?.cancel(error);for(const job of detachedCalls)job.cancel(error)};const isDeclarativeFailureHandled=error=>error instanceof VueEventCancellation||error!==null&&typeof error==="object"&&handledFailures.has(error);return{send,applyActions:applyActionsExternally,retire,dispose,isDeclarativeFailureHandled}};return __toCommonJS(citry_events_vue_exports);})(); diff --git a/packages/py/citry/citry/_vue/runtime.js b/packages/py/citry/citry/_vue/runtime.js index 4302391d8f..6ddb474107 100644 --- a/packages/py/citry/citry/_vue/runtime.js +++ b/packages/py/citry/citry/_vue/runtime.js @@ -44,7 +44,7 @@ global.CitryVueFragments = CitryVueFragments; } if (!ownGlobal("CitryVueEvents")) { /* Citry Vue Events bridge. GENERATED FILE, do not edit: built from packages/js/citry-client/src/citry-events-vue.ts (pnpm run build there). */ -var CitryVueEvents=(()=>{var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:true,configurable:true,writable:true,value}):obj[key]=value;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var __publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!=="symbol"?key+"":key,value);var citry_events_vue_exports={};__export(citry_events_vue_exports,{assertValidActionList:()=>assertValidActionList2,collectFormArgs:()=>collectFormArgs,createVueEventsBridge:()=>createVueEventsBridge});var ProtocolValueError=class extends TypeError{constructor(issue){super(issue.message);__publicField(this,"issue");this.name="ProtocolValueError";this.issue=issue}};var hasOwn=(value,key)=>Object.prototype.hasOwnProperty.call(value,key);var pointer=(parent,member)=>{const escaped=String(member).replace(/~/g,"~0").replace(/\//g,"~1");return parent?`${parent}/${escaped}`:`/${escaped}`};var isPlainObject=value=>{if(value===null||typeof value!=="object"||Array.isArray(value))return false;const prototype=Object.getPrototypeOf(value);return prototype===Object.prototype||prototype===null};var firstUnknown=(value,allowed)=>Object.keys(value).filter(key=>!allowed.has(key)).sort()[0]??null;var containerIssue=(value,path)=>{if(Object.getOwnPropertySymbols(value).length){return{path:path(),category:"strict_json",message:"The value contains a symbol-keyed property."}}for(const name of Object.getOwnPropertyNames(value)){if(Array.isArray(value)&&name==="length")continue;const descriptor=Object.getOwnPropertyDescriptor(value,name);if(!descriptor?.enumerable||!("value"in descriptor)){return{path:pointer(path(),name),category:"strict_json",message:"A JSON property must be an enumerable data property."}}}return null};var validateStrictJson=(value,path="")=>{const pathOf=frame=>{const members=[];for(let cursor=frame;cursor.parent;cursor=cursor.parent)members.push(cursor.member);let result=path;for(let index=members.length-1;index>=0;index-=1)result=pointer(result,members[index]);return result};const stack=[{value,parent:null,member:"",leaving:false}];const ancestors=new Set;while(stack.length){const frame=stack.pop();const current=frame.value;if(frame.leaving){ancestors.delete(current);continue}if(current===null||typeof current==="string"||typeof current==="boolean"){continue}if(typeof current==="number"){if(!Number.isFinite(current)){return{path:pathOf(frame),category:"strict_json",message:"The value contains a non-finite number."}}continue}if(typeof current!=="object"){return{path:pathOf(frame),category:"strict_json",message:"The value contains a non-JSON value."}}if(!Array.isArray(current)&&!isPlainObject(current)){return{path:pathOf(frame),category:"strict_json",message:"The value contains a non-JSON object."}}const ownIssue=containerIssue(current,()=>pathOf(frame));if(ownIssue)return ownIssue;if(ancestors.has(current)){return{path:pathOf(frame),category:"strict_json",message:"The value contains a cycle."}}ancestors.add(current);frame.leaving=true;stack.push(frame);if(Array.isArray(current)){const names=Object.keys(current);if(names.length!==current.length||names.some((name,index)=>name!==String(index))){return{path:pathOf(frame),category:"strict_json",message:"A JSON array must be dense and carry no named properties."}}for(let index=current.length-1;index>=0;index-=1){stack.push({value:current[index],parent:frame,member:index,leaving:false})}continue}const keys=Object.keys(current).sort();for(let index=keys.length-1;index>=0;index-=1){const key=keys[index];stack.push({value:current[key],parent:frame,member:key,leaving:false})}}return null};var copyJson=value=>{const issue=validateStrictJson(value);if(issue)throw new ProtocolValueError(issue);if(value===null||typeof value!=="object")return value;const copied=Array.isArray(value)?new Array(value.length):{};const stack=[{source:value,target:copied}];while(stack.length){const{source,target}=stack.pop();for(const key of Object.keys(source)){const item=source[key];if(item!==null&&typeof item==="object"){const child=Array.isArray(item)?new Array(item.length):{};Object.defineProperty(target,key,{configurable:true,enumerable:true,value:child,writable:true});stack.push({source:item,target:child})}else{Object.defineProperty(target,key,{configurable:true,enumerable:true,value:item,writable:true})}}}return copied};var PROTOCOL="citry-events/1";var CALLS_LIMIT=16;var ACTION_KINDS=["render","data","state","event","redirect","url"];var SWAPS=["morph","replace","inner","append","prepend","remove","none"];var RENDERERS=["html-fragment/1","vue-prepared/1"];var CAPABILITIES_BASELINE_V1={swaps:["replace","inner","append","prepend","remove","none"],actions:ACTION_KINDS,renderers:["html-fragment/1"]};var ARGS_SOURCE_FORM="form";var ENVELOPE_FIELDS=new Set(["protocol","requestId","capabilities","calls"]);var CALL_FIELDS=new Set(["componentClassId","handlerName","callerRenderId","args","argsSource","stateToken","stateUpdates","sendSequence"]);var isSafeRenderId=value=>typeof value==="string"&&/^[a-z0-9_-]+$/.test(value);var nonEmptyStringIssue=(value,path,message)=>{if(typeof value!=="string")return{path,category:"type",message};if(!value)return{path,category:"range",message};return null};var integerIssue=(value,path,message)=>{if(typeof value!=="number"||!Number.isInteger(value)){if(typeof value==="number"&&!Number.isFinite(value)){return{path,category:"strict_json",message}}return{path,category:"type",message}}if(value<0)return{path,category:"range",message};return null};var validateCall=(value,path="")=>{const jsonIssue=validateStrictJson(value,path);if(jsonIssue)return jsonIssue;if(!isPlainObject(value)){return{path,category:"type",message:"Each entry of 'calls' must be a call object."}}for(const required of["componentClassId","handlerName","args"]){if(!hasOwn(value,required)){return{path:pointer(path,required),category:"required",message:`The call is missing required field '${required}'.`}}}const unknown=firstUnknown(value,CALL_FIELDS);if(unknown!==null){return{path:pointer(path,unknown),category:"unknown_field",message:`The call carries unknown field '${unknown}'.`}}for(const field of["componentClassId","handlerName"]){const issue=nonEmptyStringIssue(value[field],pointer(path,field),`The call's '${field}' must be a non-empty string.`);if(issue)return issue}if(hasOwn(value,"callerRenderId")){const issue=nonEmptyStringIssue(value.callerRenderId,pointer(path,"callerRenderId"),"The call's 'callerRenderId' must be a non-empty string.");if(issue)return issue;if(!isSafeRenderId(value.callerRenderId)){return{path:pointer(path,"callerRenderId"),category:"pattern",message:"The call's 'callerRenderId' must use only lowercase ASCII letters, digits, hyphens, and underscores."}}}if(!isPlainObject(value.args)){return{path:pointer(path,"args"),category:"type",message:"The call's 'args' must be an object."}}const argsIssue=validateStrictJson(value.args);if(argsIssue){return{path:pointer(path,"args")+argsIssue.path,category:"strict_json",message:"The call's 'args' must contain only strict JSON values under string keys."}}if(hasOwn(value,"argsSource")&&value.argsSource!==ARGS_SOURCE_FORM){return{path:pointer(path,"argsSource"),category:typeof value.argsSource==="string"?"enum":"type",message:`The call's 'argsSource' must be '${ARGS_SOURCE_FORM}' or omitted.`}}if(hasOwn(value,"stateToken")){const issue=nonEmptyStringIssue(value.stateToken,pointer(path,"stateToken"),"The call's 'stateToken' must be a non-empty string.");if(issue)return issue}if(hasOwn(value,"stateUpdates")){if(!isPlainObject(value.stateUpdates)){return{path:pointer(path,"stateUpdates"),category:"type",message:"The call's 'stateUpdates' must be an object."}}const stateIssue=validateStrictJson(value.stateUpdates);if(stateIssue){return{path:pointer(path,"stateUpdates")+stateIssue.path,category:"strict_json",message:"The call's 'stateUpdates' must contain only strict JSON values under string keys."}}}if(hasOwn(value,"sendSequence")){return integerIssue(value.sendSequence,pointer(path,"sendSequence"),"The call's 'sendSequence' must be an integer of at least 0.")}return null};var validateCapabilities=(value,path="/capabilities")=>{const jsonIssue=validateStrictJson(value,path);if(jsonIssue)return jsonIssue;const message="The envelope's 'capabilities' must contain only 'swaps', 'actions', and 'renderers'; each value must be a duplicate-free array of known v1 names.";if(!isPlainObject(value))return{path,category:"type",message};const unknown=firstUnknown(value,new Set(["swaps","actions","renderers"]));if(unknown!==null){return{path:pointer(path,unknown),category:"unknown_field",message}}for(const[name,known]of[["swaps",SWAPS],["actions",ACTION_KINDS],["renderers",RENDERERS]]){if(!hasOwn(value,name))continue;const items=value[name];const itemPath=pointer(path,name);if(!Array.isArray(items))return{path:itemPath,category:"type",message};for(let index=0;index{const jsonIssue=validateStrictJson(value);if(jsonIssue)return jsonIssue;if(!isPlainObject(value)){return{path:"",category:"type",message:"The request body is not a call envelope object."}}for(const required of["protocol","requestId","calls"]){if(!hasOwn(value,required)){return{path:pointer("",required),category:"required",message:`The envelope requires '${required}'.`}}}const unknown=firstUnknown(value,ENVELOPE_FIELDS);if(unknown!==null){return{path:pointer("",unknown),category:"unknown_field",message:`The envelope carries unknown field '${unknown}'.`}}if(value.protocol!==PROTOCOL){return{path:"/protocol",category:typeof value.protocol==="string"?"enum":"type",message:"The envelope protocol must be citry-events/1."}}const requestIssue=nonEmptyStringIssue(value.requestId,"/requestId","The envelope carries no 'requestId' string.");if(requestIssue)return requestIssue;if(hasOwn(value,"capabilities")){const issue=validateCapabilities(value.capabilities);if(issue)return issue}if(!Array.isArray(value.calls)){return{path:"/calls",category:"type",message:"The envelope calls must be an array."}}if(!value.calls.length||value.calls.length>CALLS_LIMIT){return{path:"/calls",category:"range",message:`The envelope must carry 1 to ${CALLS_LIMIT} calls.`}}for(let index=0;index{const call={componentClassId:input.componentClassId,handlerName:input.handlerName,args:copyJson(input.args)};for(const field of["argsSource","callerRenderId","stateToken","sendSequence"]){if(input[field]!==void 0)call[field]=input[field]}if(input.stateUpdates!==void 0){call.stateUpdates=copyJson(input.stateUpdates)}const issue=validateCall(call);if(issue)throw new ProtocolValueError(issue);return call};var buildCallEnvelope=(requestId,calls,capabilities)=>{const envelope={protocol:PROTOCOL,requestId,calls:copyJson(calls)};if(capabilities!==void 0)envelope.capabilities=copyJson(capabilities);const issue=validateCallEnvelope(envelope);if(issue)throw new ProtocolValueError(issue);return envelope};var HTTP_METHOD=/^[!#$%&'*+.^_`|~0-9A-Z-]+$/;var DESCRIPTOR_FIELDS=new Set(["componentClassId","eventHandlers","writableStateFields"]);var HANDLER_FIELDS=new Set(["httpMethod","usesState","debounceMilliseconds","throttleMilliseconds","latestCallWins","allowBatching","detached"]);var nonNegativeIntegerIssue=(value,path,name)=>{if(typeof value!=="number"||!Number.isInteger(value)){return{path,category:typeof value==="number"&&!Number.isFinite(value)?"strict_json":"type",message:`The ${name} hint must be an integer.`}}if(value<0){return{path,category:"range",message:`The ${name} hint must be at least 0.`}}return null};var validateHandlerDescriptor=(value,path="")=>{const jsonIssue=validateStrictJson(value,path);if(jsonIssue)return jsonIssue;if(!isPlainObject(value)){return{path,category:"type",message:"Event-handler hints must be an object."}}if(!hasOwn(value,"httpMethod")){return{path:pointer(path,"httpMethod"),category:"required",message:"Handler hints require 'httpMethod'."}}const unknown=firstUnknown(value,HANDLER_FIELDS);if(unknown!==null){return{path:pointer(path,unknown),category:"unknown_field",message:"Handler hints have an unknown field."}}if(typeof value.httpMethod!=="string"){return{path:pointer(path,"httpMethod"),category:"type",message:"The HTTP method must be a string."}}if(!HTTP_METHOD.test(value.httpMethod)){return{path:pointer(path,"httpMethod"),category:"pattern",message:"The HTTP method must be an uppercase token."}}if(hasOwn(value,"usesState")&&value.usesState!==true){return{path:pointer(path,"usesState"),category:"enum",message:"The usesState hint has its non-default literal value."}}for(const name of["debounceMilliseconds","throttleMilliseconds"]){if(!hasOwn(value,name))continue;const issue=nonNegativeIntegerIssue(value[name],pointer(path,name),name);if(issue)return issue}if(hasOwn(value,"latestCallWins")&&value.latestCallWins!==true){return{path:pointer(path,"latestCallWins"),category:"enum",message:"The latestCallWins hint has its non-default literal value."}}if(hasOwn(value,"allowBatching")&&value.allowBatching!==false){return{path:pointer(path,"allowBatching"),category:"enum",message:"The allowBatching hint has its non-default literal value."}}if(hasOwn(value,"detached")&&value.detached!==true){return{path:pointer(path,"detached"),category:"enum",message:"The detached hint has its non-default literal value."}}return null};var validateDescriptor=(value,path="")=>{const jsonIssue=validateStrictJson(value,path);if(jsonIssue)return jsonIssue;if(!isPlainObject(value)){return{path,category:"type",message:"A component descriptor must be an object."}}for(const required of["componentClassId","eventHandlers"]){if(!hasOwn(value,required)){return{path:pointer(path,required),category:"required",message:`The descriptor requires '${required}'.`}}}const unknown=firstUnknown(value,DESCRIPTOR_FIELDS);if(unknown!==null){return{path:pointer(path,unknown),category:"unknown_field",message:"The descriptor has an unknown field."}}if(typeof value.componentClassId!=="string"){return{path:pointer(path,"componentClassId"),category:"type",message:"The component class ID must be a string."}}if(!value.componentClassId){return{path:pointer(path,"componentClassId"),category:"range",message:"The component class ID must not be empty."}}if(!isPlainObject(value.eventHandlers)){return{path:pointer(path,"eventHandlers"),category:"type",message:"Event handlers must be an object."}}for(const name of Object.keys(value.eventHandlers).sort()){if(!name){return{path:pointer(path,"eventHandlers"),category:"range",message:"A handler name must not be empty."}}const issue=validateHandlerDescriptor(value.eventHandlers[name],pointer(pointer(path,"eventHandlers"),name));if(issue)return issue}if(hasOwn(value,"writableStateFields")){const fields=value.writableStateFields;const fieldPath=pointer(path,"writableStateFields");if(!Array.isArray(fields)){return{path:fieldPath,category:"type",message:"Writable State fields must be an array."}}const seen=new Set;for(let index=0;index{if(typeof value!=="number"||!Number.isInteger(value)){return{path,category:typeof value==="number"&&!Number.isFinite(value)?"strict_json":"type",message}}if(value<0)return{path,category:"range",message};return null};var validateTiming=(value,path)=>{if(hasOwn(value,"delay")){const delay=value.delay;if(typeof delay!=="number"){return{path:pointer(path,"delay"),category:"type",message:"The action delay must be a finite number."}}if(!Number.isFinite(delay)){return{path:pointer(path,"delay"),category:"strict_json",message:"The action delay must be finite."}}if(delay<0){return{path:pointer(path,"delay"),category:"range",message:"The action delay must be at least 0."}}}if(hasOwn(value,"wait")&&value.wait!==false){return{path:pointer(path,"wait"),category:"enum",message:"The action wait flag, when present, must be false."}}return null};var MARK_NAME=/^[A-Za-z][A-Za-z0-9_-]*$/;var validateTarget=(value,path,allowMarker)=>{if(typeof value!=="string"){return{path,category:"type",message:"An action target must be a non-empty string."}}if(!value){return{path,category:"range",message:"An action target must be a non-empty string."}}if(value.startsWith("render:")){if(isSafeRenderId(value.slice(7)))return null;return{path,category:"pattern",message:"A render: target must contain a valid render ID."}}if(allowMarker&&value.startsWith("mark:")){const rest=value.slice(5);const separator=rest.indexOf(":");const caller=separator<0?"":rest.slice(0,separator);const name=separator<0?"":rest.slice(separator+1);if(isSafeRenderId(caller)&&MARK_NAME.test(name))return null;return{path,category:"pattern",message:"A marker target must be mark:: with a valid ID and name."}}return{path,category:"pattern",message:allowMarker?"A render target must be render: or mark::.":"An event target must be render:."}};var validateActionShape=(value,path="")=>{if(!isPlainObject(value)){return{path,category:"type",message:"An action must be an object."}}if(!hasOwn(value,"action")){return{path:pointer(path,"action"),category:"required",message:"The action kind is required."}}if(typeof value.action!=="string"){return{path:pointer(path,"action"),category:"type",message:"The action kind must be a string."}}if(!ACTION_KINDS.includes(value.action)){return{path:pointer(path,"action"),category:"enum",message:`Unknown action kind '${value.action}'.`}}const kind=value.action;for(const required of ACTION_REQUIRED[kind]){if(!hasOwn(value,required)){return{path:pointer(path,required),category:"required",message:`The ${kind} action requires '${required}'.`}}}const unknown=firstUnknown(value,ACTION_FIELDS[kind]);if(unknown!==null){return{path:pointer(path,unknown),category:"unknown_field",message:`The ${kind} action has an unknown field.`}}if(kind==="render"){const targetIssue=validateTarget(value.target,pointer(path,"target"),true);if(targetIssue)return targetIssue;if(!SWAPS.includes(value.swap)){return{path:pointer(path,"swap"),category:typeof value.swap==="string"?"enum":"type",message:"The render swap is not a v1 swap."}}const renderer=hasOwn(value,"renderer")?value.renderer:"html-fragment/1";if(typeof renderer!=="string"){return{path:pointer(path,"renderer"),category:"type",message:"The render renderer must be a string."}}if(!RENDERERS.includes(renderer)){return{path:pointer(path,"renderer"),category:"enum",message:"The render renderer is not a v1 renderer."}}const content=renderer==="html-fragment/1"?"html":"prepared";const other=content==="html"?"prepared":"html";if(!hasOwn(value,content)){return{path:pointer(path,content),category:"required",message:`The ${renderer} render requires '${content}'.`}}if(hasOwn(value,other)){return{path:pointer(path,other),category:"semantic",message:"A render action must carry exactly one content representation."}}if(content==="html"&&typeof value.html!=="string"){return{path:pointer(path,"html"),category:"type",message:"The render HTML must be a string."}}if(content==="prepared"&&!isPlainObject(value.prepared)){return{path:pointer(path,"prepared"),category:"type",message:"The prepared render content must be a JSON object."}}if(content==="prepared"&&value.swap!=="morph"){return{path:pointer(path,"swap"),category:"enum",message:"A vue-prepared/1 render must use the morph swap."}}}else if(kind==="data"){}else if(kind==="state"){if(typeof value.targetRenderId!=="string"){return{path:pointer(path,"targetRenderId"),category:"type",message:"The state target must be a render ID."}}if(!isSafeRenderId(value.targetRenderId)){return{path:pointer(path,"targetRenderId"),category:"pattern",message:"The state target must be a valid render ID."}}if(typeof value.stateToken!=="string"){return{path:pointer(path,"stateToken"),category:"type",message:"The state token must be a string."}}if(!value.stateToken){return{path:pointer(path,"stateToken"),category:"range",message:"The state token must not be empty."}}if(!isPlainObject(value.publicState)){return{path:pointer(path,"publicState"),category:"type",message:"Public State must be an object."}}}else if(kind==="event"){if(typeof value.eventName!=="string"){return{path:pointer(path,"eventName"),category:"type",message:"The event name must be a string."}}if(!value.eventName){return{path:pointer(path,"eventName"),category:"range",message:"The event name must not be empty."}}if(value.eventName.startsWith("citry:")){return{path:pointer(path,"eventName"),category:"pattern",message:"The event name is reserved."}}if(hasOwn(value,"target")){const issue=validateTarget(value.target,pointer(path,"target"),false);if(issue)return issue}}else if(kind==="redirect"){if(typeof value.url!=="string"){return{path:pointer(path,"url"),category:"type",message:"The redirect URL must be a string."}}if(!value.url){return{path:pointer(path,"url"),category:"range",message:"The redirect URL must not be empty."}}}else{if(typeof value.url!=="string"){return{path:pointer(path,"url"),category:"type",message:"The URL action URL must be a string."}}if(!value.url){return{path:pointer(path,"url"),category:"range",message:"The URL action URL must not be empty."}}if(value.mode!=="push"&&value.mode!=="replace"){return{path:pointer(path,"mode"),category:typeof value.mode==="string"?"enum":"type",message:"The URL action mode must be push or replace."}}}return validateTiming(value,path)};var validateErrorShape=(value,path="")=>{if(!isPlainObject(value)){return{path,category:"type",message:"The result error must be an object."}}for(const required of["status","code","message"]){if(!hasOwn(value,required)){return{path:pointer(path,required),category:"required",message:`The error requires '${required}'.`}}}const unknown=firstUnknown(value,ERROR_FIELDS);if(unknown!==null){return{path:pointer(path,unknown),category:"unknown_field",message:"The result error has an unknown field."}}if(typeof value.status!=="number"||!Number.isInteger(value.status)){return{path:pointer(path,"status"),category:typeof value.status==="number"&&!Number.isFinite(value.status)?"strict_json":"type",message:"The error status must be an integer."}}if(value.status<400||value.status>599){return{path:pointer(path,"status"),category:"range",message:"The error status must be from 400 to 599."}}if(typeof value.code!=="string"){return{path:pointer(path,"code"),category:"type",message:"The error code must be a string."}}if(!hasOwn(ERROR_STATUS_BY_CODE,value.code)){return{path:pointer(path,"code"),category:"enum",message:"The error code is not a v1 code."}}if(typeof value.message!=="string"){return{path:pointer(path,"message"),category:"type",message:"The error message must be a string."}}if(!value.message){return{path:pointer(path,"message"),category:"range",message:"The error message must not be empty."}}if(hasOwn(value,"fieldErrors")){if(!isPlainObject(value.fieldErrors)){return{path:pointer(path,"fieldErrors"),category:"type",message:"Field errors must be an object."}}for(const name of Object.keys(value.fieldErrors).sort()){if(typeof value.fieldErrors[name]!=="string"){return{path:pointer(pointer(path,"fieldErrors"),name),category:"type",message:"Field errors map strings."}}}}const expected=ERROR_STATUS_BY_CODE[value.code];if(expected!==null&&value.status!==expected){return{path:pointer(path,"status"),category:"semantic",message:"The error status does not match its code."}}return null};var validateResultShape=(value,path="")=>{if(!isPlainObject(value)){return{path,category:"type",message:"A result must be an object."}}if(!hasOwn(value,"ok")){return{path:pointer(path,"ok"),category:"required",message:"The result requires 'ok'."}}if(typeof value.ok!=="boolean"){return{path:pointer(path,"ok"),category:"type",message:"The result's 'ok' field must be a boolean."}}const required=value.ok?["ok","actions"]:["ok","error"];for(const field of required){if(!hasOwn(value,field)){return{path:pointer(path,field),category:"required",message:`The result requires '${field}'.`}}}const unknown=firstUnknown(value,value.ok?OK_RESULT_FIELDS:ERROR_RESULT_FIELDS);if(unknown!==null){return{path:pointer(path,unknown),category:"unknown_field",message:"The result has an unknown field."}}if(hasOwn(value,"sendSequence")){const issue=validateNonNegativeInteger(value.sendSequence,pointer(path,"sendSequence"),"The send sequence must be an integer.");if(issue)return issue}if(!value.ok)return validateErrorShape(value.error,pointer(path,"error"));if(!Array.isArray(value.actions)){return{path:pointer(path,"actions"),category:"type",message:"The result actions must be an array."}}for(let index=0;indexisPlainObject(action)&&action.action==="data").length>1){return{path:pointer(path,"actions"),category:"semantic",message:"Each result may carry at most one data action."}}return null};var validateResult=(value,path="")=>{const jsonIssue=validateStrictJson(value,path);return jsonIssue??validateResultShape(value,path)};var validateResultEnvelopeShape=(value,path="")=>{if(!isPlainObject(value)){return{path,category:"type",message:"The result envelope must be an object."}}for(const required of["protocol","requestId","results"]){if(!hasOwn(value,required)){return{path:pointer(path,required),category:"required",message:`The result envelope requires '${required}'.`}}}const unknown=firstUnknown(value,RESULT_ENVELOPE_FIELDS);if(unknown!==null){return{path:pointer(path,unknown),category:"unknown_field",message:"The result envelope has an unknown field."}}if(value.protocol!==PROTOCOL){return{path:pointer(path,"protocol"),category:typeof value.protocol==="string"?"enum":"type",message:"The result protocol must be citry-events/1."}}if(value.requestId!==null&&typeof value.requestId!=="string"){return{path:pointer(path,"requestId"),category:"type",message:"The result request ID must be a string or null."}}if(value.requestId===""){return{path:pointer(path,"requestId"),category:"range",message:"The result request ID must not be empty."}}if(!Array.isArray(value.results)){return{path:pointer(path,"results"),category:"type",message:"The results must be an array."}}if(!value.results.length){return{path:pointer(path,"results"),category:"range",message:"The results array must not be empty."}}for(let index=0;index{const jsonIssue=validateStrictJson(value,path);return jsonIssue??validateResultEnvelopeShape(value,path)};var validateExchangeAfterValidatedEnvelope=(callEnvelope,resultEnvelope)=>{const result=resultEnvelope;if(result.requestId!==callEnvelope.requestId){return{path:"/requestId",category:"correlation",message:"The result request ID does not match the call."}}if(result.results.length!==callEnvelope.calls.length){return{path:"/results",category:"correlation",message:"The result count does not match the call count."}}const advertised=callEnvelope.capabilities??{};const actions=new Set(advertised.actions??CAPABILITIES_BASELINE_V1.actions);const swaps=new Set(advertised.swaps??CAPABILITIES_BASELINE_V1.swaps);const renderers=new Set(advertised.renderers??CAPABILITIES_BASELINE_V1.renderers);for(let index=0;indexvalidateResult({ok:true,actions});var buildOkResult=(actions,sendSequence)=>{const result={ok:true,actions:copyJson(actions)};if(sendSequence!==void 0)result.sendSequence=sendSequence;const issue=validateResult(result);if(issue)throw new ProtocolValueError(issue);return result};var resultIndex=path=>{const match=/^\/results\/(\d+)(?:\/|$)/.exec(path);return match?Number(match[1]):null};var preflightResultEnvelope=(reply,sent)=>{const structural=validateResultEnvelope(reply);if(structural){const edge=isPlainObject(reply)&&reply.requestId===null;const index=resultIndex(structural.path);return{ok:false,issue:structural,reason:edge&&structural.path.startsWith("/results")?"edge":index===null?"header":`result ${index}`}}const envelope=reply;if(envelope.requestId===null){const edge=envelope.results[0];return{ok:true,results:sent.calls.map(()=>edge)}}const relationship=validateExchangeAfterValidatedEnvelope(sent,envelope);if(relationship){const index=resultIndex(relationship.path);return{ok:false,issue:relationship,reason:relationship.path==="/requestId"||relationship.path==="/results"&&relationship.category==="correlation"?"correlation":`result ${index??0}`}}return{ok:true,results:envelope.results}};var assertValidActionList=actions=>{const issue=validateActionList(actions);if(issue)throw new ProtocolValueError(issue);return actions};var isFormSubmitter=(value,form)=>(typeof HTMLButtonElement==="function"&&value instanceof HTMLButtonElement||typeof HTMLInputElement==="function"&&value instanceof HTMLInputElement)&&value.form===form;var collectFormArgs=(form,reservedFields,submitter)=>{const entries=new Map;const button=isFormSubmitter(submitter,form)?submitter:void 0;let data;try{data=new FormData(form,button)}catch{data=new FormData(form)}data.forEach((value,name)=>{if(reservedFields.has(name)||typeof value!=="string")return;const bucket=entries.get(name)??[];bucket.push(value);entries.set(name,bucket)});const output={};entries.forEach((values,name)=>{Object.defineProperty(output,name,{configurable:true,enumerable:true,value:values.length===1?values[0]:values.slice(),writable:true})});return output};var builtInMember=(target,key)=>{const own=Object.getOwnPropertyDescriptor(target,key);if(own!==void 0&&(own.get!==void 0||own.set!==void 0))return own;for(let proto=Object.getPrototypeOf(target);proto!==null;proto=Object.getPrototypeOf(proto)){const descriptor=Object.getOwnPropertyDescriptor(proto,key);if(descriptor!==void 0)return descriptor}return void 0};var documentMembers=currentDocument=>{const bound=new WeakMap;const bind=(method,target)=>{const cached=bound.get(method);if(cached!==void 0&&cached.target===target)return cached.method;const boundMethod=method.bind(target);bound.set(method,{target,method:boundMethod});return boundMethod};return new Proxy({},{get(_shell,key){const target=currentDocument();const descriptor=builtInMember(target,key);let value;if(descriptor===void 0)value=Reflect.get(target,key);else if(descriptor.get!==void 0)return descriptor.get.call(target);else if(descriptor.set!==void 0)return void 0;else value=descriptor.value;return typeof value==="function"?bind(value,target):value},set(_shell,key,value){const target=currentDocument();const descriptor=builtInMember(target,key);if(descriptor?.set!==void 0){descriptor.set.call(target,value);return true}return Reflect.set(target,key,value)}})};var pageDocument=documentMembers(()=>globalThis.document);var pageOrigin=()=>{const scope=globalThis;if(scope.location===void 0)return null;return typeof scope.origin==="string"?scope.origin:String(scope.location.origin)};var onPageOrigin=target=>{const origin=pageOrigin();return origin!==null&&target.origin!=="null"&&target.origin===origin};var resolveOnPage=url=>{const location=globalThis.location;if(location===void 0||typeof location.href!=="string")return null;try{return new URL(url,location.href)}catch{let inherited;try{inherited=new URL(url,pageDocument.baseURI)}catch{throw new Error(`Citry cannot resolve the URL ${JSON.stringify(url.slice(0,80))}.`)}if(!onPageOrigin(inherited))throw new Error("Citry refused a URL that does not resolve to this page's origin.");return inherited}};var assertValidActionList2=actions=>assertValidActionList(actions);var describeValue=value=>typeof value==="string"?JSON.stringify(value):typeof value==="number"?String(value):`a ${typeof value}`;var checkSendOptions=value=>{if(value===void 0)return void 0;if(value===null||typeof value!=="object"||Array.isArray(value))throw new TypeError("Citry Events send options must be an object, such as {timeout: 5000}.");for(const key of Object.keys(value)){if(key!=="timeout"&&key!=="wait")throw new TypeError(`Citry Events send got an unknown option '${key}'; the options are 'timeout' and 'wait'.`)}const{timeout,wait}=value;if(wait!==void 0&&wait!==true&&wait!==false)throw new TypeError(`Citry Events option 'wait' must be true or false; got ${describeValue(wait)}.`);if(timeout!==void 0&&(typeof timeout!=="number"||!Number.isFinite(timeout)||timeout<=0))throw new Error("Citry Events timeout must be a positive finite number.");const checked={};if(timeout!==void 0)checked.timeout=timeout;if(wait===false)checked.wait=false;return checked};var queuedHandlerError=handler=>new TypeError(`Citry Events option 'wait: false' needs a detached handler, and '${handler}' is not one. Calls from one Vue app are sent one at a time, in order, because each render and State change builds on the one before it. Remove 'wait: false', or declare the handler with @event(detached=True) if it never renders or changes State. To replace an older call to the same handler instead, declare it with @event(latest_wins=True).`);var validContext=value=>value!==null&&typeof value==="object"&&Object.keys(value).sort().join("|")==="componentClassId|descriptor|publicState|serverRenderId|stateToken"&&validateStrictJson(value)===null&&typeof value.serverRenderId==="string"&&value.serverRenderId.length>0&&(value.stateToken===null||typeof value.stateToken==="string"&&value.stateToken.length>0)&&typeof value.componentClassId==="string"&&value.componentClassId.length>0&&validateDescriptor(value.descriptor)===null&&value.descriptor.componentClassId===value.componentClassId;var VueEventCancellation=class extends Error{};var VueEventStale=class extends VueEventCancellation{constructor(reason){super(reason==="disposed"?"The Vue Events bridge was disposed; the source is stale or retired.":reason==="superseded"?"The Vue event call was superseded by a newer call.":"The Vue event source is stale or retired.");__publicField(this,"reason");this.reason=reason}};var stale=(reason="retired")=>new VueEventStale(reason);var activityError=error=>{if(error!==null&&typeof error==="object"&&"status"in error&&typeof error.status==="number"&&"code"in error&&typeof error.code==="string"&&"message"in error&&typeof error.message==="string")return error;const message=error instanceof Error?error.message:"The Vue event request failed.";return{status:0,code:message==="The Vue event request timed out."?"timeout":"transport",message}};var eventUrl=(base,context,handler)=>{if(typeof base!=="string"||!base.endsWith("/")||base.includes("?")||base.includes("#")){throw new Error("Vue Events eventBaseUrl must be a path ending in '/'.")}return`${base}${encodeURIComponent(context.componentClassId)}/${encodeURIComponent(handler)}`};var configuredEventRoutes=(url,endpoint,eventBaseUrl)=>{if(typeof url!=="string"||url.length===0)return{endpoint,eventBaseUrl};if(url.includes("?")||url.includes("#"))throw new Error("Citry Events url must not contain a query or fragment.");const normalized=url.endsWith("/")?url:`${url}/`;if(normalized.endsWith("/call/")){return{endpoint:normalized.slice(0,-1),eventBaseUrl:`${normalized.slice(0,-5)}e/`}}if(normalized.endsWith("/e/")){return{endpoint:`${normalized.slice(0,-2)}call`,eventBaseUrl:normalized}}return{endpoint:`${normalized}call`,eventBaseUrl:`${normalized}e/`}};var eventRequestTarget=url=>{const target=resolveOnPage(url);if(target===null)return{href:url,sameOrigin:false};return{href:target.href,sameOrigin:onPageOrigin(target)}};var readCookie=name=>{if(typeof document==="undefined"||typeof pageDocument.cookie!=="string")return"";for(const item of pageDocument.cookie.split(";")){const value=item.trim();if(!value.startsWith(`${name}=`))continue;try{return decodeURIComponent(value.slice(name.length+1))}catch{}}return""};var isWellFormedUtf16=value=>{for(let index=0;index=55296&&unit<=56319){const next=value.charCodeAt(index+1);if(!(next>=56320&&next<=57343))return false;index+=1}else if(unit>=56320&&unit<=57343)return false}return true};var flatQuery=args=>{const query=new URLSearchParams;const append=(key,value)=>{if(typeof value==="string"){if(!isWellFormedUtf16(value))throw new Error(`Event argument '${key}' is not well-formed UTF-16.`);query.append(key,value)}else if(typeof value==="boolean")query.append(key,String(value));else if(typeof value==="number"&&Number.isFinite(value))query.append(key,String(value));else throw new Error(`Event argument '${key}' has no flat GET query representation.`)};for(const[key,value]of Object.entries(args)){if(!isWellFormedUtf16(key))throw new Error("Event argument name is not well-formed UTF-16.");if(key.startsWith("_citry_"))throw new Error(`Event argument '${key}' uses a reserved GET query name.`);if(Array.isArray(value)){if(value.length===0)throw new Error(`Event argument '${key}' has no flat GET query representation.`);for(const item of value)append(key,item)}else append(key,value)}return query};var attachmentFilename=value=>{const extended=/(?:^|;)\s*filename\*\s*=\s*([^;]+)/i.exec(value)?.[1]?.trim();if(extended!==void 0){const encoded=/^UTF-8''(.+)$/i.exec(extended)?.[1];if(!encoded)throw new Error("The attachment response has an unsupported encoded filename.");try{return decodeURIComponent(encoded)}catch{throw new Error("The attachment response has an invalid encoded filename.")}}const quoted=/(?:^|;)\s*filename\s*=\s*"((?:\\.|[^"\\])*)"/i.exec(value)?.[1];if(quoted!==void 0)return quoted.replace(/\\(.)/g,"$1")||"download";const token=/(?:^|;)\s*filename\s*=\s*([!#$%&'*+.^_`|~0-9A-Za-z-]+)/i.exec(value)?.[1];return token||"download"};var saveAttachment=(blob,filename)=>{const url=URL.createObjectURL(blob);const anchor=pageDocument.createElement("a");try{anchor.href=url;anchor.download=filename;anchor.style.display="none";pageDocument.body.append(anchor);anchor.click()}finally{anchor.remove();URL.revokeObjectURL(url)}};var createVueEventsBridge=options=>{const reportableFailures=new WeakSet;const handledFailures=new WeakSet;const fetchImpl=options.fetch??globalThis.fetch.bind(globalThis);let correlation=0;const owners=new Map;const acceptedAtSpot=new Map;const acceptAtSpot=(source,job)=>{const count=(acceptedAtSpot.get(source.stableId)??0)+1;acceptedAtSpot.set(source.stableId,count);job.acceptedAtSpotWhenAccepted=count};const queue=[];let active=null;const externalJobs=new Set;const jobsWithNoWaitActions=new Set;const detachedCalls=new Set;let running=false;let disposed=false;const supersedeEarlier=input=>{const error=stale("superseded");const sameCall=job=>job.input.source.stableId===input.source.stableId&&job.input.source.generation===input.source.generation&&job.input.handler===input.handler;for(const job of jobsWithNoWaitActions)if(sameCall(job))job.cancel(error);for(const job of detachedCalls)if(sameCall(job))job.cancel(error);for(let index=queue.length-1;index>=0;index-=1){const job=queue[index];if(job.input.source.stableId===input.source.stableId&&job.input.source.generation===input.source.generation&&job.input.handler===input.handler){queue.splice(index,1);lifecycle("stale",job.input.source,job.input.handler,{reason:"superseded"});job.cancel(error)}}if(active&&active.input.source.stableId===input.source.stableId&&active.input.source.generation===input.source.generation&&active.input.handler===input.handler)active.cancel(error)};const lifecycle=(kind,source,event,detail)=>{try{return options.host.lifecycle?.(kind,source,event,detail)!==false}catch(error){console.error(`[Citry] citry:events:${kind} listener failed:`,error);return true}};const reportFailure=(source,handler,error)=>{const reported=activityError(error);if(reported.code==="stale_state"){if(error!==null&&typeof error==="object")reportableFailures.add(error);if(lifecycle("stale",source,handler,{reason:"version"}))options.host.reportOutOfDate?.()}lifecycle("error",source,handler,{error:reported})};const ownerState=source=>{const existing=owners.get(source.stableId);if(existing?.generation===source.generation)return existing;const state={generation:source.generation,sendSequence:0,acceptedEpoch:0,retired:false,timers:new Map};owners.set(source.stableId,state);return state};const current=source=>{const context=options.host.resolve(source);if(context===null||!validContext(context))throw stale("retired");return context};const stillCurrent=(source,state,epoch)=>{if(state.retired||owners.get(source.stableId)!==state||state.generation!==source.generation||epoch!==void 0&&epoch!==state.acceptedEpoch){throw stale(state.retired?"retired":"epoch")}current(source)};const remountTimers=new Map;const sourcelessTimers=new Map;const delay=(milliseconds,state,job)=>new Promise((resolve,reject)=>{if(job.cancelError){reject(job.cancelError);return}if(disposed||state.retired&&!job.acceptedRemount){reject(stale(disposed?"disposed":"retired"));return}const timers=job.acceptedRemount?remountTimers:state.timers;const timer=globalThis.setTimeout(()=>{timers.delete(timer);resolve()},milliseconds);timers.set(timer,reject);void job.cancelled.catch(error=>{if(!timers.delete(timer))return;globalThis.clearTimeout(timer);reject(error)})});const continuationCurrent=(source,state,epoch,job,survivesNewerResult=false)=>{if(job.cancelError)throw job.cancelError;if(disposed)throw stale("disposed");if(!survivesNewerResult&&epoch!==state.acceptedEpoch)throw stale("epoch");if(!job.acceptedRemount){stillCurrent(source,state,survivesNewerResult?void 0:epoch);return}if(!survivesNewerResult&&acceptedAtSpot.get(source.stableId)!==job.acceptedAtSpotWhenAccepted){throw stale("epoch")}};const validateTargets=(result,source,serverRenderId)=>{if(!result.ok)return;const componentTarget=`render:${serverRenderId}`;for(const action of result.actions){if(action.action==="render"&&!options.host.preflightResult&&action.target!==componentTarget){throw new Error("Vue Events accepts the current component target; marker targets are not implemented.")}if(action.action==="event"&&action.target!==void 0&&action.target!==componentTarget){throw new Error("Vue Events accepts the current component Event target; marker targets are not implemented.")}}current(source)};const applyOne=async(action,source,state,epoch,onData,job,renderPlan)=>{if(action.action==="data"){if(!job.external)continuationCurrent(source,state,epoch,job);onData(action.value);return}if(action.action==="render"){if(job.cancelError)throw job.cancelError;stillCurrent(source,state,epoch);const context=current(source);if(!renderPlan&&action.target!==`render:${context.serverRenderId}`){throw new Error("The experimental Vue Events bridge accepts only its current root Render target.")}if(!("renderer"in action)||action.renderer!=="vue-prepared/1"){throw new Error("The Vue Events bridge requires a vue-prepared/1 Render action.")}const preparing=options.host.prepareRender(action,source,job.controller?.signal??new AbortController().signal,renderPlan);let prepared;try{prepared=await Promise.race([preparing,job.cancelled]);stillCurrent(source,state,epoch)}catch(error){try{options.host.abortRender(void 0,source)}catch(cleanupError){console.error("[Citry] aborting a prepared Vue render failed:",cleanupError)}void preparing.then(value=>{try{options.host.abortRender(value,source)}catch(cleanupError){console.error("[Citry] aborting a late prepared Vue render failed:",cleanupError)}},()=>void 0);throw error}job.committingTransaction=prepared.transaction;try{await Promise.race([options.host.commitRender(prepared,source),job.cancelled]);lifecycle("swapped",source,job.input.handler,{els:[]})}finally{job.committingTransaction=void 0}}else if(action.action==="state"){continuationCurrent(source,state,epoch,job);options.host.commitState(action.targetRenderId,action.stateToken,action.publicState,source)}else if(action.action==="event"){continuationCurrent(source,state,epoch,job);const followRemount=job.acceptedRemount;const rootTarget=followRemount?void 0:`render:${current(source).serverRenderId}`;const callerTarget=job.callerRenderId===void 0?void 0:`render:${job.callerRenderId}`;if(action.target!==void 0&&action.target!==rootTarget&&action.target!==callerTarget){throw new Error("The experimental Vue Events bridge accepts only its current root Event target.")}if(job.external&&action.target===void 0&&options.host.dispatchEventGlobal)options.host.dispatchEventGlobal(action.eventName,action.detail);else options.host.dispatchEvent(action.eventName,action.detail,source,followRemount)}else if(action.action==="redirect"){if(!job.external)continuationCurrent(source,state,epoch,job,true);options.host.redirect(action.url)}else{if(!job.external)continuationCurrent(source,state,epoch,job);options.host.updateUrl(action.url,action.mode)}};const applyActions=async(result,source,state,epoch,job,renderPlan)=>{if(!result.ok){reportableFailures.add(result.error);throw result.error}let data;const hoisted=new Set;result.actions.forEach((action,index)=>{if(action.action==="state"&&!(typeof action.delay==="number"&&action.delay>0)&&action.wait!==false){if(job.cancelError)throw job.cancelError;stillCurrent(source,state,epoch);options.host.commitState(action.targetRenderId,action.stateToken,action.publicState,source);hoisted.add(index)}});for(const[index,action]of result.actions.entries()){if(hoisted.has(index))continue;const run=async()=>{const seconds=typeof action.delay==="number"?action.delay:0;const delayed=seconds>0;if(delayed)await delay(seconds*1e3,state,job);const actionEpoch=job.detachedHandler&&!delayed?state.acceptedEpoch:epoch;await applyOne(action,source,state,actionEpoch,value=>{data=value},job,action.action==="render"?renderPlan:void 0)};if("wait"in action&&action.wait===false){job.noWaitPending+=1;jobsWithNoWaitActions.add(job);void run().catch(error=>{if(error instanceof VueEventStale){lifecycle("stale",source,job.input.handler,{reason:error.reason});return}if(!(error instanceof VueEventCancellation))reportFailure(source,job.input.handler,error);console.error("[Citry] applying a Vue event action marked wait: false failed:",error)}).finally(()=>{job.noWaitPending-=1;if(job.noWaitPending===0)jobsWithNoWaitActions.delete(job)})}else await run()}return data};const sendNow=async job=>{const input=job.input;if(disposed)throw stale("disposed");const context=current(input.source);const state=ownerState(input.source);job.owner=state;const appId=options.host.appId(input.source);if(typeof appId!=="string"||appId.length===0)throw stale("retired");const committedRevision=options.host.revision(input.source);if(!Number.isInteger(committedRevision)||committedRevision<0)throw stale("retired");if(!Object.prototype.hasOwnProperty.call(context.descriptor.eventHandlers,input.handler))throw new Error(`Unknown event handler '${input.handler}'.`);const handlerOptions=context.descriptor.eventHandlers[input.handler];const detachedHandler=handlerOptions.detached===true;job.detachedHandler=detachedHandler;job.callerRenderId=context.serverRenderId;job.lifecycleStarted=true;if(!lifecycle("before",input.source,input.handler))throw new VueEventCancellation(`Citry Events send '${input.handler}' was cancelled by citry:events:before.`);const useGet=handlerOptions.httpMethod==="GET";const runtimeConfig=options.runtimeConfig?.()??{};const configuredEndpoint=typeof options.endpoint==="function"&&!useGet?options.endpoint(context,input.handler):typeof options.endpoint==="string"?options.endpoint:"";const routes=configuredEventRoutes(runtimeConfig.url??"",configuredEndpoint,options.eventBaseUrl);if(useGet&&input.stateUpdates!==void 0)throw new Error("GET events cannot send pending State updates.");const taken=useGet||detachedHandler?void 0:input.stateUpdates??options.host.takePendingState?.(input.source,input.handler);job.stateUpdates=taken===void 0?void 0:structuredClone(taken);state.sendSequence+=1;correlation+=1;const call=buildCall({componentClassId:context.componentClassId,handlerName:input.handler,callerRenderId:context.serverRenderId,args:input.args??{},argsSource:input.argsSource,stateToken:context.stateToken??void 0,stateUpdates:job.stateUpdates,sendSequence:state.sendSequence});const envelope=buildCallEnvelope(`vue_${correlation}`,[call],{actions:["render","data","state","event","redirect","url"],swaps:["morph"],renderers:["vue-prepared/1"]});const headers={"Content-Type":"application/citry-events+json","X-Citry-Events":"1","X-Citry-Vue-App":appId,"X-Citry-Vue-Occurrence":input.source.stableId,"X-Citry-Vue-Revision":String(committedRevision)};const selectedTransport=options.transport?.()??null;const isolated=useGet||handlerOptions.allowBatching===false;const endpoint=isolated?eventUrl(routes.eventBaseUrl??"",context,input.handler):routes.endpoint;const target=selectedTransport?{href:endpoint,sameOrigin:true}:eventRequestTarget(endpoint);const csrf=runtimeConfig.csrf??options.csrf;if(!useGet&&csrf&&target.sameOrigin){const token=csrf.token?typeof csrf.token==="function"?csrf.token():csrf.token:selectedTransport?void 0:readCookie(csrf.cookie??"csrftoken");if(token)headers[csrf.header??"X-CSRFToken"]=token}const callTimeout=input.options?.timeout;const timeoutMs=callTimeout??runtimeConfig.timeout??options.timeoutMs??3e4;if(!Number.isFinite(timeoutMs)||timeoutMs<=0)throw new Error("Vue Events timeoutMs must be positive.");const controller=new AbortController;job.controller=controller;let requestUrl=target.href;if(useGet){const query=flatQuery(input.args??{});query.append("_citry_protocol",envelope.protocol);query.append("_citry_request_id",envelope.requestId);query.append("_citry_capabilities",JSON.stringify(envelope.capabilities));query.append("_citry_caller_render_id",call.callerRenderId??"");query.append("_citry_send_sequence",String(call.sendSequence));if(handlerOptions.usesState===true&&call.stateToken!==void 0)query.append("_citry_state_token",call.stateToken);requestUrl+=`?${query.toString()}`}const requestHeaders=useGet?Object.fromEntries(Object.entries(headers).filter(([name])=>name!=="Content-Type")):headers;const requestMethod=isolated?handlerOptions.httpMethod:"POST";const operation=(async()=>{if(selectedTransport){const request={url:requestUrl,method:requestMethod,headers:{...requestHeaders},signal:controller.signal};try{return{raw:await selectedTransport.send(envelope,request),transported:true}}catch(error){if(error!==null&&typeof error==="object")reportableFailures.add(error);throw error}}const requestInit={method:requestMethod,credentials:"same-origin",redirect:"manual",headers:requestHeaders,...useGet?{}:{body:JSON.stringify(envelope)},signal:controller.signal};let response;try{response=await fetchImpl(requestUrl,requestInit)}catch(error){if(error!==null&&typeof error==="object")reportableFailures.add(error);throw error}if(response.type==="opaqueredirect"){const error=new Error("The server answered the event call with a redirect, which event calls do not follow.");reportableFailures.add(error);throw error}const disposition=response.headers?.get?.("Content-Disposition")??null;if(response.ok&&disposition&&/^\s*attachment(?:;|$)/i.test(disposition)){return{attachment:await response.blob(),filename:attachmentFilename(disposition)}}try{const raw2=await response.json();return{raw:raw2}}catch(error){if(response.ok)throw new Error("A successful raw Event response must be an attachment.");throw error}})();let timeoutId=0;const received=await Promise.race([operation,job.cancelled,new Promise((_resolve,reject)=>{timeoutId=globalThis.setTimeout(()=>{controller.abort();const error=new Error("The Vue event request timed out.");reportableFailures.add(error);reject(error)},timeoutMs)})]).finally(()=>globalThis.clearTimeout(timeoutId));if("attachment"in received){stillCurrent(input.source,state);if(!detachedHandler){state.acceptedEpoch+=1;acceptAtSpot(input.source,job)}continuationCurrent(input.source,state,state.acceptedEpoch,job);saveAttachment(received.attachment,received.filename);return void 0}const raw=received.raw;const checked=preflightResultEnvelope(raw,envelope);if(!checked.ok)throw new Error(`Invalid Events response: ${checked.issue.message}`);const[result]=received.transported?copyJson(checked.results):checked.results;if(detachedHandler&&result.ok){const forbidden=result.actions.find(action=>action.action==="render"||action.action==="state");if(forbidden)throw new Error(`Invalid Events response: detached handler '${input.handler}' returned a '${forbidden.action}' action.`)}stillCurrent(input.source,state);validateTargets(result,input.source,context.serverRenderId);const preparedResult=options.host.preflightResult?.(result,input.source)??{result};if(job.cancelError)throw job.cancelError;if(!detachedHandler){state.acceptedEpoch+=1;acceptAtSpot(input.source,job)}if(preparedResult.result.ok)job.stateAccepted=true;return applyActions(preparedResult.result,input.source,state,state.acceptedEpoch,job,preparedResult.renderPlan)};const runJob=async job=>{try{job.activity?.start(job.intent);const value=await sendNow(job);if(job.cancelError)throw job.cancelError;job.stateAccepted=true;job.activity?.succeed(job.intent);if(job.lifecycleStarted)lifecycle("after",job.input.source,job.input.handler,{ok:true});job.resolve(value)}catch(error){if(!job.stateAccepted&&job.stateUpdates!==void 0)options.host.restorePendingState?.(job.input.source,job.stateUpdates);if(job.lifecycleStarted){if(error instanceof VueEventStale){lifecycle("stale",job.input.source,job.input.handler,{reason:error.reason})}else if(!(error instanceof VueEventCancellation)){reportFailure(job.input.source,job.input.handler,error)}lifecycle("after",job.input.source,job.input.handler,{ok:false})}if(!(error instanceof VueEventCancellation)){job.activity?.fail(job.intent,activityError(error));if(job.activity&&error!==null&&typeof error==="object"&&reportableFailures.has(error))handledFailures.add(error)}job.reject(error)}finally{if(!job.activityFinished){job.activityFinished=true;job.activity?.finish(job.intent)}}};const runQueue=async()=>{if(running)return;running=true;try{while(queue.length>0){const job=queue.shift();if(!job||job.settled)continue;active=job;try{await runJob(job)}finally{active=null}}}finally{running=false}};const unsupportedBrowserMethods=new Set(["HEAD","OPTIONS","CONNECT","TRACE","TRACK"]);const send=given=>{if(disposed)return Promise.reject(stale("disposed"));let activity;let intent;let input=given;let outsideQueue=false;try{input={...given,options:checkSendOptions(given.options)};const context=current(input.source);if(!Object.prototype.hasOwnProperty.call(context.descriptor.eventHandlers,input.handler))throw new Error(`Unknown event handler '${input.handler}'.`);const method=context.descriptor.eventHandlers[input.handler].httpMethod;if(unsupportedBrowserMethods.has(method))throw new Error(`Event handler '${input.handler}' uses HTTP ${method}, which is server-transport-only and cannot be sent by the browser bridge.`);const handlerOptions=context.descriptor.eventHandlers[input.handler];outsideQueue=input.options?.wait===false;if(outsideQueue&&handlerOptions.detached!==true)throw queuedHandlerError(input.handler);if(handlerOptions.detached===true&&input.stateUpdates!==void 0)throw new TypeError(`Event handler '${input.handler}' is detached, so a call to it cannot send State updates.`);activity=options.activity?.(input.source,context.descriptor);intent=activity?.enqueue(input.handler);if(handlerOptions.latestCallWins===true)supersedeEarlier(input)}catch(error){return Promise.reject(error)}let resolvePromise;let rejectPromise;let cancelPromise;const promise=new Promise((resolve,reject)=>{resolvePromise=resolve;rejectPromise=reject});const cancelled=new Promise((_resolve,reject)=>{cancelPromise=reject});void cancelled.catch(()=>void 0);const job={input,acceptedRemount:false,noWaitPending:0,activity,intent,activityFinished:false,lifecycleStarted:false,external:false,stateAccepted:false,settled:false,cancelled,cancel(error){if(job.cancelError===void 0){job.cancelError=error;cancelPromise(error)}if(job.settled)return;job.controller?.abort();if(!job.activityFinished){job.activityFinished=true;job.activity?.finish(job.intent)}job.reject(error)},resolve(value){if(job.settled)return;job.settled=true;resolvePromise(value)},reject(error){if(job.settled)return;job.settled=true;rejectPromise(error)}};if(outsideQueue){detachedCalls.add(job);void runJob(job).finally(()=>detachedCalls.delete(job))}else{queue.push(job);void runQueue()}return promise};const applyActionsExternally=async(actions,source)=>{const result=buildOkResult(actions);if(!source){let data;for(const action of result.actions){if(disposed)throw stale("disposed");if(typeof action.delay==="number"&&action.delay>0){const milliseconds=action.delay*1e3;await new Promise((resolve,reject)=>{const timer=globalThis.setTimeout(()=>{sourcelessTimers.delete(timer);resolve()},milliseconds);sourcelessTimers.set(timer,reject)});if(disposed)throw stale("disposed")}if(action.action==="data")data=action.value;else if(action.action==="redirect")options.host.redirect(action.url);else if(action.action==="url")options.host.updateUrl(action.url,action.mode);else if(action.action==="event"){if(action.target!==void 0||!options.host.dispatchEventGlobal)throw new Error("Citry.events.applyActions needs a mounted component for targeted Event actions.");options.host.dispatchEventGlobal(action.eventName,action.detail)}else{throw new Error("Citry.events.applyActions needs a mounted component for Render and State actions.")}}return data}const externalContext=current(source);const state=ownerState(source);state.acceptedEpoch+=1;const cancelled=new Promise(()=>void 0);const job={input:{source,handler:"__external__"},acceptedRemount:false,noWaitPending:0,activityFinished:true,lifecycleStarted:true,external:true,callerRenderId:externalContext.serverRenderId,stateAccepted:true,settled:true,cancelled,cancel(){},resolve(){},reject(){}};let prepared;try{prepared=options.host.preflightResult?.(result,source)??{result}}catch(error){if(activityError(error).code==="stale_state"&&lifecycle("before",source,job.input.handler)){reportFailure(source,job.input.handler,error);lifecycle("after",source,job.input.handler,{ok:false})}throw error}if(!lifecycle("before",source,job.input.handler)){const error=new VueEventCancellation("Citry Events applyActions was cancelled by citry:events:before.");lifecycle("after",source,job.input.handler,{ok:false});throw error}acceptAtSpot(source,job);externalJobs.add(job);try{const value=await applyActions(prepared.result,source,state,state.acceptedEpoch,job,prepared.renderPlan);lifecycle("after",source,job.input.handler,{ok:true});return value}catch(error){if(error instanceof VueEventStale){lifecycle("stale",source,job.input.handler,{reason:error.reason})}else if(!(error instanceof VueEventCancellation)){reportFailure(source,job.input.handler,error)}lifecycle("after",source,job.input.handler,{ok:false});throw error}finally{externalJobs.delete(job)}};const retire=(source,acceptedTransaction)=>{const state=owners.get(source.stableId);if(state?.generation===source.generation){state.retired=true;for(const[timer,reject]of state.timers){globalThis.clearTimeout(timer);reject(stale("retired"))}state.timers.clear();owners.delete(source.stableId)}const error=new VueEventStale("retired");for(let index=queue.length-1;index>=0;index-=1){const job=queue[index];if(job.input.source.stableId===source.stableId&&job.input.source.generation===source.generation){queue.splice(index,1);lifecycle("stale",source,job.input.handler,{reason:"retired"});job.cancel(error)}}for(const job of detachedCalls)if(job.input.source.stableId===source.stableId&&job.input.source.generation===source.generation)job.cancel(error);for(const job of externalJobs){if(acceptedTransaction!==void 0&&job.committingTransaction===acceptedTransaction&&job.input.source.stableId===source.stableId&&job.input.source.generation===source.generation)job.acceptedRemount=true}if(active?.input.source.stableId===source.stableId&&active.input.source.generation===source.generation&&acceptedTransaction!==void 0&&active.committingTransaction===acceptedTransaction){active.acceptedRemount=true}else if(active?.input.source.stableId===source.stableId&&active.input.source.generation===source.generation)active.cancel(error)};const dispose=()=>{if(disposed)return;disposed=true;for(const state of owners.values()){state.retired=true;for(const[timer,reject]of state.timers){globalThis.clearTimeout(timer);reject(stale("disposed"))}state.timers.clear()}owners.clear();acceptedAtSpot.clear();for(const timers of[remountTimers,sourcelessTimers]){for(const[timer,reject]of timers){globalThis.clearTimeout(timer);reject(stale("disposed"))}timers.clear()}const error=new VueEventStale("disposed");for(const job of queue.splice(0)){lifecycle("stale",job.input.source,job.input.handler,{reason:"disposed"});job.cancel(error)}active?.cancel(error);for(const job of detachedCalls)job.cancel(error)};const isDeclarativeFailureHandled=error=>error instanceof VueEventCancellation||error!==null&&typeof error==="object"&&handledFailures.has(error);return{send,applyActions:applyActionsExternally,retire,dispose,isDeclarativeFailureHandled}};return __toCommonJS(citry_events_vue_exports);})(); +var CitryVueEvents=(()=>{var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:true,configurable:true,writable:true,value}):obj[key]=value;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};var __copyProps=(to,from,except,desc)=>{if(from&&typeof from==="object"||typeof from==="function"){for(let key of __getOwnPropNames(from))if(!__hasOwnProp.call(to,key)&&key!==except)__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return to};var __toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:true}),mod);var __publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!=="symbol"?key+"":key,value);var citry_events_vue_exports={};__export(citry_events_vue_exports,{assertValidActionList:()=>assertValidActionList2,collectFormArgs:()=>collectFormArgs,createVueEventsBridge:()=>createVueEventsBridge});var ProtocolValueError=class extends TypeError{constructor(issue){super(issue.message);__publicField(this,"issue");this.name="ProtocolValueError";this.issue=issue}};var hasOwn=(value,key)=>Object.prototype.hasOwnProperty.call(value,key);var pointer=(parent,member)=>{const escaped=String(member).replace(/~/g,"~0").replace(/\//g,"~1");return parent?`${parent}/${escaped}`:`/${escaped}`};var isPlainObject=value=>{if(value===null||typeof value!=="object"||Array.isArray(value))return false;const prototype=Object.getPrototypeOf(value);return prototype===Object.prototype||prototype===null};var firstUnknown=(value,allowed)=>Object.keys(value).filter(key=>!allowed.has(key)).sort()[0]??null;var containerIssue=(value,path)=>{if(Object.getOwnPropertySymbols(value).length){return{path:path(),category:"strict_json",message:"The value contains a symbol-keyed property."}}for(const name of Object.getOwnPropertyNames(value)){if(Array.isArray(value)&&name==="length")continue;const descriptor=Object.getOwnPropertyDescriptor(value,name);if(!descriptor?.enumerable||!("value"in descriptor)){return{path:pointer(path(),name),category:"strict_json",message:"A JSON property must be an enumerable data property."}}}return null};var validateStrictJson=(value,path="")=>{const pathOf=frame=>{const members=[];for(let cursor=frame;cursor.parent;cursor=cursor.parent)members.push(cursor.member);let result=path;for(let index=members.length-1;index>=0;index-=1)result=pointer(result,members[index]);return result};const stack=[{value,parent:null,member:"",leaving:false}];const ancestors=new Set;while(stack.length){const frame=stack.pop();const current=frame.value;if(frame.leaving){ancestors.delete(current);continue}if(current===null||typeof current==="string"||typeof current==="boolean"){continue}if(typeof current==="number"){if(!Number.isFinite(current)){return{path:pathOf(frame),category:"strict_json",message:"The value contains a non-finite number."}}continue}if(typeof current!=="object"){return{path:pathOf(frame),category:"strict_json",message:"The value contains a non-JSON value."}}if(!Array.isArray(current)&&!isPlainObject(current)){return{path:pathOf(frame),category:"strict_json",message:"The value contains a non-JSON object."}}const ownIssue=containerIssue(current,()=>pathOf(frame));if(ownIssue)return ownIssue;if(ancestors.has(current)){return{path:pathOf(frame),category:"strict_json",message:"The value contains a cycle."}}ancestors.add(current);frame.leaving=true;stack.push(frame);if(Array.isArray(current)){const names=Object.keys(current);if(names.length!==current.length||names.some((name,index)=>name!==String(index))){return{path:pathOf(frame),category:"strict_json",message:"A JSON array must be dense and carry no named properties."}}for(let index=current.length-1;index>=0;index-=1){stack.push({value:current[index],parent:frame,member:index,leaving:false})}continue}const keys=Object.keys(current).sort();for(let index=keys.length-1;index>=0;index-=1){const key=keys[index];stack.push({value:current[key],parent:frame,member:key,leaving:false})}}return null};var copyJson=value=>{const issue=validateStrictJson(value);if(issue)throw new ProtocolValueError(issue);if(value===null||typeof value!=="object")return value;const copied=Array.isArray(value)?new Array(value.length):{};const stack=[{source:value,target:copied}];while(stack.length){const{source,target}=stack.pop();for(const key of Object.keys(source)){const item=source[key];if(item!==null&&typeof item==="object"){const child=Array.isArray(item)?new Array(item.length):{};Object.defineProperty(target,key,{configurable:true,enumerable:true,value:child,writable:true});stack.push({source:item,target:child})}else{Object.defineProperty(target,key,{configurable:true,enumerable:true,value:item,writable:true})}}}return copied};var PROTOCOL="citry-events/1";var CALLS_LIMIT=16;var ACTION_KINDS=["render","data","state","event","redirect","url"];var SWAPS=["morph","replace","inner","append","prepend","remove","none"];var RENDERERS=["html-fragment/1","vue-prepared/1"];var CAPABILITIES_BASELINE_V1={swaps:["replace","inner","append","prepend","remove","none"],actions:ACTION_KINDS,renderers:["html-fragment/1"]};var ARGS_SOURCE_FORM="form";var CARRIER_FIELDS={callerRenderId:"_citry_caller_render_id",stateToken:"_citry_state_token",sendSequence:"_citry_send_sequence",protocol:"_citry_protocol",requestId:"_citry_request_id",capabilities:"_citry_capabilities"};var CARRIER_HEADERS={stateToken:"X-Citry-State-Token"};var ENVELOPE_FIELDS=new Set(["protocol","requestId","capabilities","calls"]);var CALL_FIELDS=new Set(["componentClassId","handlerName","callerRenderId","args","argsSource","stateToken","stateUpdates","sendSequence"]);var isSafeRenderId=value=>typeof value==="string"&&/^[a-z0-9_-]+$/.test(value);var nonEmptyStringIssue=(value,path,message)=>{if(typeof value!=="string")return{path,category:"type",message};if(!value)return{path,category:"range",message};return null};var integerIssue=(value,path,message)=>{if(typeof value!=="number"||!Number.isInteger(value)){if(typeof value==="number"&&!Number.isFinite(value)){return{path,category:"strict_json",message}}return{path,category:"type",message}}if(value<0)return{path,category:"range",message};return null};var validateCall=(value,path="")=>{const jsonIssue=validateStrictJson(value,path);if(jsonIssue)return jsonIssue;if(!isPlainObject(value)){return{path,category:"type",message:"Each entry of 'calls' must be a call object."}}for(const required of["componentClassId","handlerName","args"]){if(!hasOwn(value,required)){return{path:pointer(path,required),category:"required",message:`The call is missing required field '${required}'.`}}}const unknown=firstUnknown(value,CALL_FIELDS);if(unknown!==null){return{path:pointer(path,unknown),category:"unknown_field",message:`The call carries unknown field '${unknown}'.`}}for(const field of["componentClassId","handlerName"]){const issue=nonEmptyStringIssue(value[field],pointer(path,field),`The call's '${field}' must be a non-empty string.`);if(issue)return issue}if(hasOwn(value,"callerRenderId")){const issue=nonEmptyStringIssue(value.callerRenderId,pointer(path,"callerRenderId"),"The call's 'callerRenderId' must be a non-empty string.");if(issue)return issue;if(!isSafeRenderId(value.callerRenderId)){return{path:pointer(path,"callerRenderId"),category:"pattern",message:"The call's 'callerRenderId' must use only lowercase ASCII letters, digits, hyphens, and underscores."}}}if(!isPlainObject(value.args)){return{path:pointer(path,"args"),category:"type",message:"The call's 'args' must be an object."}}const argsIssue=validateStrictJson(value.args);if(argsIssue){return{path:pointer(path,"args")+argsIssue.path,category:"strict_json",message:"The call's 'args' must contain only strict JSON values under string keys."}}if(hasOwn(value,"argsSource")&&value.argsSource!==ARGS_SOURCE_FORM){return{path:pointer(path,"argsSource"),category:typeof value.argsSource==="string"?"enum":"type",message:`The call's 'argsSource' must be '${ARGS_SOURCE_FORM}' or omitted.`}}if(hasOwn(value,"stateToken")){const issue=nonEmptyStringIssue(value.stateToken,pointer(path,"stateToken"),"The call's 'stateToken' must be a non-empty string.");if(issue)return issue}if(hasOwn(value,"stateUpdates")){if(!isPlainObject(value.stateUpdates)){return{path:pointer(path,"stateUpdates"),category:"type",message:"The call's 'stateUpdates' must be an object."}}const stateIssue=validateStrictJson(value.stateUpdates);if(stateIssue){return{path:pointer(path,"stateUpdates")+stateIssue.path,category:"strict_json",message:"The call's 'stateUpdates' must contain only strict JSON values under string keys."}}}if(hasOwn(value,"sendSequence")){return integerIssue(value.sendSequence,pointer(path,"sendSequence"),"The call's 'sendSequence' must be an integer of at least 0.")}return null};var validateCapabilities=(value,path="/capabilities")=>{const jsonIssue=validateStrictJson(value,path);if(jsonIssue)return jsonIssue;const message="The envelope's 'capabilities' must contain only 'swaps', 'actions', and 'renderers'; each value must be a duplicate-free array of known v1 names.";if(!isPlainObject(value))return{path,category:"type",message};const unknown=firstUnknown(value,new Set(["swaps","actions","renderers"]));if(unknown!==null){return{path:pointer(path,unknown),category:"unknown_field",message}}for(const[name,known]of[["swaps",SWAPS],["actions",ACTION_KINDS],["renderers",RENDERERS]]){if(!hasOwn(value,name))continue;const items=value[name];const itemPath=pointer(path,name);if(!Array.isArray(items))return{path:itemPath,category:"type",message};for(let index=0;index{const jsonIssue=validateStrictJson(value);if(jsonIssue)return jsonIssue;if(!isPlainObject(value)){return{path:"",category:"type",message:"The request body is not a call envelope object."}}for(const required of["protocol","requestId","calls"]){if(!hasOwn(value,required)){return{path:pointer("",required),category:"required",message:`The envelope requires '${required}'.`}}}const unknown=firstUnknown(value,ENVELOPE_FIELDS);if(unknown!==null){return{path:pointer("",unknown),category:"unknown_field",message:`The envelope carries unknown field '${unknown}'.`}}if(value.protocol!==PROTOCOL){return{path:"/protocol",category:typeof value.protocol==="string"?"enum":"type",message:"The envelope protocol must be citry-events/1."}}const requestIssue=nonEmptyStringIssue(value.requestId,"/requestId","The envelope carries no 'requestId' string.");if(requestIssue)return requestIssue;if(hasOwn(value,"capabilities")){const issue=validateCapabilities(value.capabilities);if(issue)return issue}if(!Array.isArray(value.calls)){return{path:"/calls",category:"type",message:"The envelope calls must be an array."}}if(!value.calls.length||value.calls.length>CALLS_LIMIT){return{path:"/calls",category:"range",message:`The envelope must carry 1 to ${CALLS_LIMIT} calls.`}}for(let index=0;index{const call={componentClassId:input.componentClassId,handlerName:input.handlerName,args:copyJson(input.args)};for(const field of["argsSource","callerRenderId","stateToken","sendSequence"]){if(input[field]!==void 0)call[field]=input[field]}if(input.stateUpdates!==void 0){call.stateUpdates=copyJson(input.stateUpdates)}const issue=validateCall(call);if(issue)throw new ProtocolValueError(issue);return call};var buildCallEnvelope=(requestId,calls,capabilities)=>{const envelope={protocol:PROTOCOL,requestId,calls:copyJson(calls)};if(capabilities!==void 0)envelope.capabilities=copyJson(capabilities);const issue=validateCallEnvelope(envelope);if(issue)throw new ProtocolValueError(issue);return envelope};var HTTP_METHOD=/^[!#$%&'*+.^_`|~0-9A-Z-]+$/;var DESCRIPTOR_FIELDS=new Set(["componentClassId","eventHandlers","writableStateFields"]);var HANDLER_FIELDS=new Set(["httpMethod","usesState","debounceMilliseconds","throttleMilliseconds","latestCallWins","allowBatching","detached"]);var nonNegativeIntegerIssue=(value,path,name)=>{if(typeof value!=="number"||!Number.isInteger(value)){return{path,category:typeof value==="number"&&!Number.isFinite(value)?"strict_json":"type",message:`The ${name} hint must be an integer.`}}if(value<0){return{path,category:"range",message:`The ${name} hint must be at least 0.`}}return null};var validateHandlerDescriptor=(value,path="")=>{const jsonIssue=validateStrictJson(value,path);if(jsonIssue)return jsonIssue;if(!isPlainObject(value)){return{path,category:"type",message:"Event-handler hints must be an object."}}if(!hasOwn(value,"httpMethod")){return{path:pointer(path,"httpMethod"),category:"required",message:"Handler hints require 'httpMethod'."}}const unknown=firstUnknown(value,HANDLER_FIELDS);if(unknown!==null){return{path:pointer(path,unknown),category:"unknown_field",message:"Handler hints have an unknown field."}}if(typeof value.httpMethod!=="string"){return{path:pointer(path,"httpMethod"),category:"type",message:"The HTTP method must be a string."}}if(!HTTP_METHOD.test(value.httpMethod)){return{path:pointer(path,"httpMethod"),category:"pattern",message:"The HTTP method must be an uppercase token."}}if(hasOwn(value,"usesState")&&value.usesState!==true){return{path:pointer(path,"usesState"),category:"enum",message:"The usesState hint has its non-default literal value."}}for(const name of["debounceMilliseconds","throttleMilliseconds"]){if(!hasOwn(value,name))continue;const issue=nonNegativeIntegerIssue(value[name],pointer(path,name),name);if(issue)return issue}if(hasOwn(value,"latestCallWins")&&value.latestCallWins!==true){return{path:pointer(path,"latestCallWins"),category:"enum",message:"The latestCallWins hint has its non-default literal value."}}if(hasOwn(value,"allowBatching")&&value.allowBatching!==false){return{path:pointer(path,"allowBatching"),category:"enum",message:"The allowBatching hint has its non-default literal value."}}if(hasOwn(value,"detached")&&value.detached!==true){return{path:pointer(path,"detached"),category:"enum",message:"The detached hint has its non-default literal value."}}return null};var validateDescriptor=(value,path="")=>{const jsonIssue=validateStrictJson(value,path);if(jsonIssue)return jsonIssue;if(!isPlainObject(value)){return{path,category:"type",message:"A component descriptor must be an object."}}for(const required of["componentClassId","eventHandlers"]){if(!hasOwn(value,required)){return{path:pointer(path,required),category:"required",message:`The descriptor requires '${required}'.`}}}const unknown=firstUnknown(value,DESCRIPTOR_FIELDS);if(unknown!==null){return{path:pointer(path,unknown),category:"unknown_field",message:"The descriptor has an unknown field."}}if(typeof value.componentClassId!=="string"){return{path:pointer(path,"componentClassId"),category:"type",message:"The component class ID must be a string."}}if(!value.componentClassId){return{path:pointer(path,"componentClassId"),category:"range",message:"The component class ID must not be empty."}}if(!isPlainObject(value.eventHandlers)){return{path:pointer(path,"eventHandlers"),category:"type",message:"Event handlers must be an object."}}for(const name of Object.keys(value.eventHandlers).sort()){if(!name){return{path:pointer(path,"eventHandlers"),category:"range",message:"A handler name must not be empty."}}const issue=validateHandlerDescriptor(value.eventHandlers[name],pointer(pointer(path,"eventHandlers"),name));if(issue)return issue}if(hasOwn(value,"writableStateFields")){const fields=value.writableStateFields;const fieldPath=pointer(path,"writableStateFields");if(!Array.isArray(fields)){return{path:fieldPath,category:"type",message:"Writable State fields must be an array."}}const seen=new Set;for(let index=0;index{if(typeof value!=="number"||!Number.isInteger(value)){return{path,category:typeof value==="number"&&!Number.isFinite(value)?"strict_json":"type",message}}if(value<0)return{path,category:"range",message};return null};var validateTiming=(value,path)=>{if(hasOwn(value,"delay")){const delay=value.delay;if(typeof delay!=="number"){return{path:pointer(path,"delay"),category:"type",message:"The action delay must be a finite number."}}if(!Number.isFinite(delay)){return{path:pointer(path,"delay"),category:"strict_json",message:"The action delay must be finite."}}if(delay<0){return{path:pointer(path,"delay"),category:"range",message:"The action delay must be at least 0."}}}if(hasOwn(value,"wait")&&value.wait!==false){return{path:pointer(path,"wait"),category:"enum",message:"The action wait flag, when present, must be false."}}return null};var MARK_NAME=/^[A-Za-z][A-Za-z0-9_-]*$/;var validateTarget=(value,path,allowMarker)=>{if(typeof value!=="string"){return{path,category:"type",message:"An action target must be a non-empty string."}}if(!value){return{path,category:"range",message:"An action target must be a non-empty string."}}if(value.startsWith("render:")){if(isSafeRenderId(value.slice(7)))return null;return{path,category:"pattern",message:"A render: target must contain a valid render ID."}}if(allowMarker&&value.startsWith("mark:")){const rest=value.slice(5);const separator=rest.indexOf(":");const caller=separator<0?"":rest.slice(0,separator);const name=separator<0?"":rest.slice(separator+1);if(isSafeRenderId(caller)&&MARK_NAME.test(name))return null;return{path,category:"pattern",message:"A marker target must be mark:: with a valid ID and name."}}return{path,category:"pattern",message:allowMarker?"A render target must be render: or mark::.":"An event target must be render:."}};var validateActionShape=(value,path="")=>{if(!isPlainObject(value)){return{path,category:"type",message:"An action must be an object."}}if(!hasOwn(value,"action")){return{path:pointer(path,"action"),category:"required",message:"The action kind is required."}}if(typeof value.action!=="string"){return{path:pointer(path,"action"),category:"type",message:"The action kind must be a string."}}if(!ACTION_KINDS.includes(value.action)){return{path:pointer(path,"action"),category:"enum",message:`Unknown action kind '${value.action}'.`}}const kind=value.action;for(const required of ACTION_REQUIRED[kind]){if(!hasOwn(value,required)){return{path:pointer(path,required),category:"required",message:`The ${kind} action requires '${required}'.`}}}const unknown=firstUnknown(value,ACTION_FIELDS[kind]);if(unknown!==null){return{path:pointer(path,unknown),category:"unknown_field",message:`The ${kind} action has an unknown field.`}}if(kind==="render"){const targetIssue=validateTarget(value.target,pointer(path,"target"),true);if(targetIssue)return targetIssue;if(!SWAPS.includes(value.swap)){return{path:pointer(path,"swap"),category:typeof value.swap==="string"?"enum":"type",message:"The render swap is not a v1 swap."}}const renderer=hasOwn(value,"renderer")?value.renderer:"html-fragment/1";if(typeof renderer!=="string"){return{path:pointer(path,"renderer"),category:"type",message:"The render renderer must be a string."}}if(!RENDERERS.includes(renderer)){return{path:pointer(path,"renderer"),category:"enum",message:"The render renderer is not a v1 renderer."}}const content=renderer==="html-fragment/1"?"html":"prepared";const other=content==="html"?"prepared":"html";if(!hasOwn(value,content)){return{path:pointer(path,content),category:"required",message:`The ${renderer} render requires '${content}'.`}}if(hasOwn(value,other)){return{path:pointer(path,other),category:"semantic",message:"A render action must carry exactly one content representation."}}if(content==="html"&&typeof value.html!=="string"){return{path:pointer(path,"html"),category:"type",message:"The render HTML must be a string."}}if(content==="prepared"&&!isPlainObject(value.prepared)){return{path:pointer(path,"prepared"),category:"type",message:"The prepared render content must be a JSON object."}}if(content==="prepared"&&value.swap!=="morph"){return{path:pointer(path,"swap"),category:"enum",message:"A vue-prepared/1 render must use the morph swap."}}}else if(kind==="data"){}else if(kind==="state"){if(typeof value.targetRenderId!=="string"){return{path:pointer(path,"targetRenderId"),category:"type",message:"The state target must be a render ID."}}if(!isSafeRenderId(value.targetRenderId)){return{path:pointer(path,"targetRenderId"),category:"pattern",message:"The state target must be a valid render ID."}}if(typeof value.stateToken!=="string"){return{path:pointer(path,"stateToken"),category:"type",message:"The state token must be a string."}}if(!value.stateToken){return{path:pointer(path,"stateToken"),category:"range",message:"The state token must not be empty."}}if(!isPlainObject(value.publicState)){return{path:pointer(path,"publicState"),category:"type",message:"Public State must be an object."}}}else if(kind==="event"){if(typeof value.eventName!=="string"){return{path:pointer(path,"eventName"),category:"type",message:"The event name must be a string."}}if(!value.eventName){return{path:pointer(path,"eventName"),category:"range",message:"The event name must not be empty."}}if(value.eventName.startsWith("citry:")){return{path:pointer(path,"eventName"),category:"pattern",message:"The event name is reserved."}}if(hasOwn(value,"target")){const issue=validateTarget(value.target,pointer(path,"target"),false);if(issue)return issue}}else if(kind==="redirect"){if(typeof value.url!=="string"){return{path:pointer(path,"url"),category:"type",message:"The redirect URL must be a string."}}if(!value.url){return{path:pointer(path,"url"),category:"range",message:"The redirect URL must not be empty."}}}else{if(typeof value.url!=="string"){return{path:pointer(path,"url"),category:"type",message:"The URL action URL must be a string."}}if(!value.url){return{path:pointer(path,"url"),category:"range",message:"The URL action URL must not be empty."}}if(value.mode!=="push"&&value.mode!=="replace"){return{path:pointer(path,"mode"),category:typeof value.mode==="string"?"enum":"type",message:"The URL action mode must be push or replace."}}}return validateTiming(value,path)};var validateErrorShape=(value,path="")=>{if(!isPlainObject(value)){return{path,category:"type",message:"The result error must be an object."}}for(const required of["status","code","message"]){if(!hasOwn(value,required)){return{path:pointer(path,required),category:"required",message:`The error requires '${required}'.`}}}const unknown=firstUnknown(value,ERROR_FIELDS);if(unknown!==null){return{path:pointer(path,unknown),category:"unknown_field",message:"The result error has an unknown field."}}if(typeof value.status!=="number"||!Number.isInteger(value.status)){return{path:pointer(path,"status"),category:typeof value.status==="number"&&!Number.isFinite(value.status)?"strict_json":"type",message:"The error status must be an integer."}}if(value.status<400||value.status>599){return{path:pointer(path,"status"),category:"range",message:"The error status must be from 400 to 599."}}if(typeof value.code!=="string"){return{path:pointer(path,"code"),category:"type",message:"The error code must be a string."}}if(!hasOwn(ERROR_STATUS_BY_CODE,value.code)){return{path:pointer(path,"code"),category:"enum",message:"The error code is not a v1 code."}}if(typeof value.message!=="string"){return{path:pointer(path,"message"),category:"type",message:"The error message must be a string."}}if(!value.message){return{path:pointer(path,"message"),category:"range",message:"The error message must not be empty."}}if(hasOwn(value,"fieldErrors")){if(!isPlainObject(value.fieldErrors)){return{path:pointer(path,"fieldErrors"),category:"type",message:"Field errors must be an object."}}for(const name of Object.keys(value.fieldErrors).sort()){if(typeof value.fieldErrors[name]!=="string"){return{path:pointer(pointer(path,"fieldErrors"),name),category:"type",message:"Field errors map strings."}}}}const expected=ERROR_STATUS_BY_CODE[value.code];if(expected!==null&&value.status!==expected){return{path:pointer(path,"status"),category:"semantic",message:"The error status does not match its code."}}return null};var validateResultShape=(value,path="")=>{if(!isPlainObject(value)){return{path,category:"type",message:"A result must be an object."}}if(!hasOwn(value,"ok")){return{path:pointer(path,"ok"),category:"required",message:"The result requires 'ok'."}}if(typeof value.ok!=="boolean"){return{path:pointer(path,"ok"),category:"type",message:"The result's 'ok' field must be a boolean."}}const required=value.ok?["ok","actions"]:["ok","error"];for(const field of required){if(!hasOwn(value,field)){return{path:pointer(path,field),category:"required",message:`The result requires '${field}'.`}}}const unknown=firstUnknown(value,value.ok?OK_RESULT_FIELDS:ERROR_RESULT_FIELDS);if(unknown!==null){return{path:pointer(path,unknown),category:"unknown_field",message:"The result has an unknown field."}}if(hasOwn(value,"sendSequence")){const issue=validateNonNegativeInteger(value.sendSequence,pointer(path,"sendSequence"),"The send sequence must be an integer.");if(issue)return issue}if(!value.ok)return validateErrorShape(value.error,pointer(path,"error"));if(!Array.isArray(value.actions)){return{path:pointer(path,"actions"),category:"type",message:"The result actions must be an array."}}for(let index=0;indexisPlainObject(action)&&action.action==="data").length>1){return{path:pointer(path,"actions"),category:"semantic",message:"Each result may carry at most one data action."}}return null};var validateResult=(value,path="")=>{const jsonIssue=validateStrictJson(value,path);return jsonIssue??validateResultShape(value,path)};var validateResultEnvelopeShape=(value,path="")=>{if(!isPlainObject(value)){return{path,category:"type",message:"The result envelope must be an object."}}for(const required of["protocol","requestId","results"]){if(!hasOwn(value,required)){return{path:pointer(path,required),category:"required",message:`The result envelope requires '${required}'.`}}}const unknown=firstUnknown(value,RESULT_ENVELOPE_FIELDS);if(unknown!==null){return{path:pointer(path,unknown),category:"unknown_field",message:"The result envelope has an unknown field."}}if(value.protocol!==PROTOCOL){return{path:pointer(path,"protocol"),category:typeof value.protocol==="string"?"enum":"type",message:"The result protocol must be citry-events/1."}}if(value.requestId!==null&&typeof value.requestId!=="string"){return{path:pointer(path,"requestId"),category:"type",message:"The result request ID must be a string or null."}}if(value.requestId===""){return{path:pointer(path,"requestId"),category:"range",message:"The result request ID must not be empty."}}if(!Array.isArray(value.results)){return{path:pointer(path,"results"),category:"type",message:"The results must be an array."}}if(!value.results.length){return{path:pointer(path,"results"),category:"range",message:"The results array must not be empty."}}for(let index=0;index{const jsonIssue=validateStrictJson(value,path);return jsonIssue??validateResultEnvelopeShape(value,path)};var validateExchangeAfterValidatedEnvelope=(callEnvelope,resultEnvelope)=>{const result=resultEnvelope;if(result.requestId!==callEnvelope.requestId){return{path:"/requestId",category:"correlation",message:"The result request ID does not match the call."}}if(result.results.length!==callEnvelope.calls.length){return{path:"/results",category:"correlation",message:"The result count does not match the call count."}}const advertised=callEnvelope.capabilities??{};const actions=new Set(advertised.actions??CAPABILITIES_BASELINE_V1.actions);const swaps=new Set(advertised.swaps??CAPABILITIES_BASELINE_V1.swaps);const renderers=new Set(advertised.renderers??CAPABILITIES_BASELINE_V1.renderers);for(let index=0;indexvalidateResult({ok:true,actions});var buildOkResult=(actions,sendSequence)=>{const result={ok:true,actions:copyJson(actions)};if(sendSequence!==void 0)result.sendSequence=sendSequence;const issue=validateResult(result);if(issue)throw new ProtocolValueError(issue);return result};var resultIndex=path=>{const match=/^\/results\/(\d+)(?:\/|$)/.exec(path);return match?Number(match[1]):null};var preflightResultEnvelope=(reply,sent)=>{const structural=validateResultEnvelope(reply);if(structural){const edge=isPlainObject(reply)&&reply.requestId===null;const index=resultIndex(structural.path);return{ok:false,issue:structural,reason:edge&&structural.path.startsWith("/results")?"edge":index===null?"header":`result ${index}`}}const envelope=reply;if(envelope.requestId===null){const edge=envelope.results[0];return{ok:true,results:sent.calls.map(()=>edge)}}const relationship=validateExchangeAfterValidatedEnvelope(sent,envelope);if(relationship){const index=resultIndex(relationship.path);return{ok:false,issue:relationship,reason:relationship.path==="/requestId"||relationship.path==="/results"&&relationship.category==="correlation"?"correlation":`result ${index??0}`}}return{ok:true,results:envelope.results}};var assertValidActionList=actions=>{const issue=validateActionList(actions);if(issue)throw new ProtocolValueError(issue);return actions};var isFormSubmitter=(value,form)=>(typeof HTMLButtonElement==="function"&&value instanceof HTMLButtonElement||typeof HTMLInputElement==="function"&&value instanceof HTMLInputElement)&&value.form===form;var collectFormArgs=(form,reservedFields,submitter)=>{const entries=new Map;const button=isFormSubmitter(submitter,form)?submitter:void 0;let data;try{data=new FormData(form,button)}catch{data=new FormData(form)}data.forEach((value,name)=>{if(reservedFields.has(name)||typeof value!=="string")return;const bucket=entries.get(name)??[];bucket.push(value);entries.set(name,bucket)});const output={};entries.forEach((values,name)=>{Object.defineProperty(output,name,{configurable:true,enumerable:true,value:values.length===1?values[0]:values.slice(),writable:true})});return output};var builtInMember=(target,key)=>{const own=Object.getOwnPropertyDescriptor(target,key);if(own!==void 0&&(own.get!==void 0||own.set!==void 0))return own;for(let proto=Object.getPrototypeOf(target);proto!==null;proto=Object.getPrototypeOf(proto)){const descriptor=Object.getOwnPropertyDescriptor(proto,key);if(descriptor!==void 0)return descriptor}return void 0};var documentMembers=currentDocument=>{const bound=new WeakMap;const bind=(method,target)=>{const cached=bound.get(method);if(cached!==void 0&&cached.target===target)return cached.method;const boundMethod=method.bind(target);bound.set(method,{target,method:boundMethod});return boundMethod};return new Proxy({},{get(_shell,key){const target=currentDocument();const descriptor=builtInMember(target,key);let value;if(descriptor===void 0)value=Reflect.get(target,key);else if(descriptor.get!==void 0)return descriptor.get.call(target);else if(descriptor.set!==void 0)return void 0;else value=descriptor.value;return typeof value==="function"?bind(value,target):value},set(_shell,key,value){const target=currentDocument();const descriptor=builtInMember(target,key);if(descriptor?.set!==void 0){descriptor.set.call(target,value);return true}return Reflect.set(target,key,value)}})};var pageDocument=documentMembers(()=>globalThis.document);var pageOrigin=()=>{const scope=globalThis;if(scope.location===void 0)return null;return typeof scope.origin==="string"?scope.origin:String(scope.location.origin)};var onPageOrigin=target=>{const origin=pageOrigin();return origin!==null&&target.origin!=="null"&&target.origin===origin};var resolveOnPage=url=>{const location=globalThis.location;if(location===void 0||typeof location.href!=="string")return null;try{return new URL(url,location.href)}catch{let inherited;try{inherited=new URL(url,pageDocument.baseURI)}catch{throw new Error(`Citry cannot resolve the URL ${JSON.stringify(url.slice(0,80))}.`)}if(!onPageOrigin(inherited))throw new Error("Citry refused a URL that does not resolve to this page's origin.");return inherited}};var assertValidActionList2=actions=>assertValidActionList(actions);var describeValue=value=>typeof value==="string"?JSON.stringify(value):typeof value==="number"?String(value):`a ${typeof value}`;var checkSendOptions=value=>{if(value===void 0)return void 0;if(value===null||typeof value!=="object"||Array.isArray(value))throw new TypeError("Citry Events send options must be an object, such as {timeout: 5000}.");for(const key of Object.keys(value)){if(key!=="timeout"&&key!=="wait")throw new TypeError(`Citry Events send got an unknown option '${key}'; the options are 'timeout' and 'wait'.`)}const{timeout,wait}=value;if(wait!==void 0&&wait!==true&&wait!==false)throw new TypeError(`Citry Events option 'wait' must be true or false; got ${describeValue(wait)}.`);if(timeout!==void 0&&(typeof timeout!=="number"||!Number.isFinite(timeout)||timeout<=0))throw new Error("Citry Events timeout must be a positive finite number.");const checked={};if(timeout!==void 0)checked.timeout=timeout;if(wait===false)checked.wait=false;return checked};var queuedHandlerError=handler=>new TypeError(`Citry Events option 'wait: false' needs a detached handler, and '${handler}' is not one. Calls from one Vue app are sent one at a time, in order, because each render and State change builds on the one before it. Remove 'wait: false', or declare the handler with @event(detached=True) if it never renders or changes State. To replace an older call to the same handler instead, declare it with @event(latest_wins=True).`);var validContext=value=>value!==null&&typeof value==="object"&&Object.keys(value).sort().join("|")==="componentClassId|descriptor|publicState|serverRenderId|stateToken"&&validateStrictJson(value)===null&&typeof value.serverRenderId==="string"&&value.serverRenderId.length>0&&(value.stateToken===null||typeof value.stateToken==="string"&&value.stateToken.length>0)&&typeof value.componentClassId==="string"&&value.componentClassId.length>0&&validateDescriptor(value.descriptor)===null&&value.descriptor.componentClassId===value.componentClassId;var VueEventCancellation=class extends Error{};var VueEventStale=class extends VueEventCancellation{constructor(reason){super(reason==="disposed"?"The Vue Events bridge was disposed; the source is stale or retired.":reason==="superseded"?"The Vue event call was superseded by a newer call.":"The Vue event source is stale or retired.");__publicField(this,"reason");this.reason=reason}};var stale=(reason="retired")=>new VueEventStale(reason);var activityError=error=>{if(error!==null&&typeof error==="object"&&"status"in error&&typeof error.status==="number"&&"code"in error&&typeof error.code==="string"&&"message"in error&&typeof error.message==="string")return error;const message=error instanceof Error?error.message:"The Vue event request failed.";return{status:0,code:message==="The Vue event request timed out."?"timeout":"transport",message}};var eventUrl=(base,context,handler)=>{if(typeof base!=="string"||!base.endsWith("/")||base.includes("?")||base.includes("#")){throw new Error("Vue Events eventBaseUrl must be a path ending in '/'.")}return`${base}${encodeURIComponent(context.componentClassId)}/${encodeURIComponent(handler)}`};var configuredEventRoutes=(url,endpoint,eventBaseUrl)=>{if(typeof url!=="string"||url.length===0)return{endpoint,eventBaseUrl};if(url.includes("?")||url.includes("#"))throw new Error("Citry Events url must not contain a query or fragment.");const normalized=url.endsWith("/")?url:`${url}/`;if(normalized.endsWith("/call/")){return{endpoint:normalized.slice(0,-1),eventBaseUrl:`${normalized.slice(0,-5)}e/`}}if(normalized.endsWith("/e/")){return{endpoint:`${normalized.slice(0,-2)}call`,eventBaseUrl:normalized}}return{endpoint:`${normalized}call`,eventBaseUrl:`${normalized}e/`}};var eventRequestTarget=url=>{const target=resolveOnPage(url);if(target===null)return{href:url,sameOrigin:false};return{href:target.href,sameOrigin:onPageOrigin(target)}};var readCookie=name=>{if(typeof document==="undefined"||typeof pageDocument.cookie!=="string")return"";for(const item of pageDocument.cookie.split(";")){const value=item.trim();if(!value.startsWith(`${name}=`))continue;try{return decodeURIComponent(value.slice(name.length+1))}catch{}}return""};var isWellFormedUtf16=value=>{for(let index=0;index=55296&&unit<=56319){const next=value.charCodeAt(index+1);if(!(next>=56320&&next<=57343))return false;index+=1}else if(unit>=56320&&unit<=57343)return false}return true};var flatQuery=args=>{const query=new URLSearchParams;const append=(key,value)=>{if(typeof value==="string"){if(!isWellFormedUtf16(value))throw new Error(`Event argument '${key}' is not well-formed UTF-16.`);query.append(key,value)}else if(typeof value==="boolean")query.append(key,String(value));else if(typeof value==="number"&&Number.isFinite(value))query.append(key,String(value));else throw new Error(`Event argument '${key}' has no flat GET query representation.`)};for(const[key,value]of Object.entries(args)){if(!isWellFormedUtf16(key))throw new Error("Event argument name is not well-formed UTF-16.");if(key.startsWith("_citry_"))throw new Error(`Event argument '${key}' uses a reserved GET query name.`);if(Array.isArray(value)){if(value.length===0)throw new Error(`Event argument '${key}' has no flat GET query representation.`);for(const item of value)append(key,item)}else append(key,value)}return query};var answersInvalidState=raw=>{if(raw===null||typeof raw!=="object"||!Array.isArray(raw.results))return false;const results=raw.results;if(results.length!==1)return false;const[result]=results;if(result===null||typeof result!=="object")return false;const error=result.error;return error!==null&&typeof error==="object"&&error.code==="invalid_state"};var attachmentFilename=value=>{const extended=/(?:^|;)\s*filename\*\s*=\s*([^;]+)/i.exec(value)?.[1]?.trim();if(extended!==void 0){const encoded=/^UTF-8''(.+)$/i.exec(extended)?.[1];if(!encoded)throw new Error("The attachment response has an unsupported encoded filename.");try{return decodeURIComponent(encoded)}catch{throw new Error("The attachment response has an invalid encoded filename.")}}const quoted=/(?:^|;)\s*filename\s*=\s*"((?:\\.|[^"\\])*)"/i.exec(value)?.[1];if(quoted!==void 0)return quoted.replace(/\\(.)/g,"$1")||"download";const token=/(?:^|;)\s*filename\s*=\s*([!#$%&'*+.^_`|~0-9A-Za-z-]+)/i.exec(value)?.[1];return token||"download"};var saveAttachment=(blob,filename)=>{const url=URL.createObjectURL(blob);const anchor=pageDocument.createElement("a");try{anchor.href=url;anchor.download=filename;anchor.style.display="none";pageDocument.body.append(anchor);anchor.click()}finally{anchor.remove();URL.revokeObjectURL(url)}};var createVueEventsBridge=options=>{const reportableFailures=new WeakSet;const handledFailures=new WeakSet;const fetchImpl=options.fetch??globalThis.fetch.bind(globalThis);let correlation=0;const owners=new Map;const acceptedAtSpot=new Map;const acceptAtSpot=(source,job)=>{const count=(acceptedAtSpot.get(source.stableId)??0)+1;acceptedAtSpot.set(source.stableId,count);job.acceptedAtSpotWhenAccepted=count};const queue=[];let active=null;const externalJobs=new Set;const jobsWithNoWaitActions=new Set;const detachedCalls=new Set;let running=false;let disposed=false;const supersedeEarlier=input=>{const error=stale("superseded");const sameCall=job=>job.input.source.stableId===input.source.stableId&&job.input.source.generation===input.source.generation&&job.input.handler===input.handler;for(const job of jobsWithNoWaitActions)if(sameCall(job))job.cancel(error);for(const job of detachedCalls)if(sameCall(job))job.cancel(error);for(let index=queue.length-1;index>=0;index-=1){const job=queue[index];if(job.input.source.stableId===input.source.stableId&&job.input.source.generation===input.source.generation&&job.input.handler===input.handler){queue.splice(index,1);lifecycle("stale",job.input.source,job.input.handler,{reason:"superseded"});job.cancel(error)}}if(active&&active.input.source.stableId===input.source.stableId&&active.input.source.generation===input.source.generation&&active.input.handler===input.handler)active.cancel(error)};const lifecycle=(kind,source,event,detail)=>{try{return options.host.lifecycle?.(kind,source,event,detail)!==false}catch(error){console.error(`[Citry] citry:events:${kind} listener failed:`,error);return true}};const reportFailure=(source,handler,error)=>{const reported=activityError(error);if(reported.code==="stale_state"){if(error!==null&&typeof error==="object")reportableFailures.add(error);if(lifecycle("stale",source,handler,{reason:"version"}))options.host.reportOutOfDate?.()}lifecycle("error",source,handler,{error:reported})};const ownerState=source=>{const existing=owners.get(source.stableId);if(existing?.generation===source.generation)return existing;const state={generation:source.generation,sendSequence:0,acceptedEpoch:0,retired:false,timers:new Map};owners.set(source.stableId,state);return state};const current=source=>{const context=options.host.resolve(source);if(context===null||!validContext(context))throw stale("retired");return context};const stillCurrent=(source,state,epoch)=>{if(state.retired||owners.get(source.stableId)!==state||state.generation!==source.generation||epoch!==void 0&&epoch!==state.acceptedEpoch){throw stale(state.retired?"retired":"epoch")}current(source)};const remountTimers=new Map;const sourcelessTimers=new Map;const delay=(milliseconds,state,job)=>new Promise((resolve,reject)=>{if(job.cancelError){reject(job.cancelError);return}if(disposed||state.retired&&!job.acceptedRemount){reject(stale(disposed?"disposed":"retired"));return}const timers=job.acceptedRemount?remountTimers:state.timers;const timer=globalThis.setTimeout(()=>{timers.delete(timer);resolve()},milliseconds);timers.set(timer,reject);void job.cancelled.catch(error=>{if(!timers.delete(timer))return;globalThis.clearTimeout(timer);reject(error)})});const continuationCurrent=(source,state,epoch,job,survivesNewerResult=false)=>{if(job.cancelError)throw job.cancelError;if(disposed)throw stale("disposed");if(!survivesNewerResult&&epoch!==state.acceptedEpoch)throw stale("epoch");if(!job.acceptedRemount){stillCurrent(source,state,survivesNewerResult?void 0:epoch);return}if(!survivesNewerResult&&acceptedAtSpot.get(source.stableId)!==job.acceptedAtSpotWhenAccepted){throw stale("epoch")}};const validateTargets=(result,source,serverRenderId)=>{if(!result.ok)return;const componentTarget=`render:${serverRenderId}`;for(const action of result.actions){if(action.action==="render"&&!options.host.preflightResult&&action.target!==componentTarget){throw new Error("Vue Events accepts the current component target; marker targets are not implemented.")}if(action.action==="event"&&action.target!==void 0&&action.target!==componentTarget){throw new Error("Vue Events accepts the current component Event target; marker targets are not implemented.")}}current(source)};const applyOne=async(action,source,state,epoch,onData,job,renderPlan)=>{if(action.action==="data"){if(!job.external)continuationCurrent(source,state,epoch,job);onData(action.value);return}if(action.action==="render"){if(job.cancelError)throw job.cancelError;stillCurrent(source,state,epoch);const context=current(source);if(!renderPlan&&action.target!==`render:${context.serverRenderId}`){throw new Error("The experimental Vue Events bridge accepts only its current root Render target.")}if(!("renderer"in action)||action.renderer!=="vue-prepared/1"){throw new Error("The Vue Events bridge requires a vue-prepared/1 Render action.")}const preparing=options.host.prepareRender(action,source,job.controller?.signal??new AbortController().signal,renderPlan);let prepared;try{prepared=await Promise.race([preparing,job.cancelled]);stillCurrent(source,state,epoch)}catch(error){try{options.host.abortRender(void 0,source)}catch(cleanupError){console.error("[Citry] aborting a prepared Vue render failed:",cleanupError)}void preparing.then(value=>{try{options.host.abortRender(value,source)}catch(cleanupError){console.error("[Citry] aborting a late prepared Vue render failed:",cleanupError)}},()=>void 0);throw error}job.committingTransaction=prepared.transaction;try{await Promise.race([options.host.commitRender(prepared,source),job.cancelled]);lifecycle("swapped",source,job.input.handler,{els:[]})}finally{job.committingTransaction=void 0}}else if(action.action==="state"){continuationCurrent(source,state,epoch,job);options.host.commitState(action.targetRenderId,action.stateToken,action.publicState,source)}else if(action.action==="event"){continuationCurrent(source,state,epoch,job);const followRemount=job.acceptedRemount;const rootTarget=followRemount?void 0:`render:${current(source).serverRenderId}`;const callerTarget=job.callerRenderId===void 0?void 0:`render:${job.callerRenderId}`;if(action.target!==void 0&&action.target!==rootTarget&&action.target!==callerTarget){throw new Error("The experimental Vue Events bridge accepts only its current root Event target.")}if(job.external&&action.target===void 0&&options.host.dispatchEventGlobal)options.host.dispatchEventGlobal(action.eventName,action.detail);else options.host.dispatchEvent(action.eventName,action.detail,source,followRemount)}else if(action.action==="redirect"){if(!job.external)continuationCurrent(source,state,epoch,job,true);options.host.redirect(action.url)}else{if(!job.external)continuationCurrent(source,state,epoch,job);options.host.updateUrl(action.url,action.mode)}};const applyActions=async(result,source,state,epoch,job,renderPlan)=>{if(!result.ok){reportableFailures.add(result.error);throw result.error}let data;const hoisted=new Set;result.actions.forEach((action,index)=>{if(action.action==="state"&&!(typeof action.delay==="number"&&action.delay>0)&&action.wait!==false){if(job.cancelError)throw job.cancelError;stillCurrent(source,state,epoch);options.host.commitState(action.targetRenderId,action.stateToken,action.publicState,source);hoisted.add(index)}});for(const[index,action]of result.actions.entries()){if(hoisted.has(index))continue;const run=async()=>{const seconds=typeof action.delay==="number"?action.delay:0;const delayed=seconds>0;if(delayed)await delay(seconds*1e3,state,job);const actionEpoch=job.detachedHandler&&!delayed?state.acceptedEpoch:epoch;await applyOne(action,source,state,actionEpoch,value=>{data=value},job,action.action==="render"?renderPlan:void 0)};if("wait"in action&&action.wait===false){job.noWaitPending+=1;jobsWithNoWaitActions.add(job);void run().catch(error=>{if(error instanceof VueEventStale){lifecycle("stale",source,job.input.handler,{reason:error.reason});return}if(!(error instanceof VueEventCancellation))reportFailure(source,job.input.handler,error);console.error("[Citry] applying a Vue event action marked wait: false failed:",error)}).finally(()=>{job.noWaitPending-=1;if(job.noWaitPending===0)jobsWithNoWaitActions.delete(job)})}else await run()}return data};const sendNow=async job=>{const input=job.input;if(disposed)throw stale("disposed");const context=current(input.source);const state=ownerState(input.source);job.owner=state;const appId=options.host.appId(input.source);if(typeof appId!=="string"||appId.length===0)throw stale("retired");const committedRevision=options.host.revision(input.source);if(!Number.isInteger(committedRevision)||committedRevision<0)throw stale("retired");if(!Object.prototype.hasOwnProperty.call(context.descriptor.eventHandlers,input.handler))throw new Error(`Unknown event handler '${input.handler}'.`);const handlerOptions=context.descriptor.eventHandlers[input.handler];const detachedHandler=handlerOptions.detached===true;job.detachedHandler=detachedHandler;job.callerRenderId=context.serverRenderId;job.lifecycleStarted=true;if(!lifecycle("before",input.source,input.handler))throw new VueEventCancellation(`Citry Events send '${input.handler}' was cancelled by citry:events:before.`);const useGet=handlerOptions.httpMethod==="GET";const runtimeConfig=options.runtimeConfig?.()??{};const configuredEndpoint=typeof options.endpoint==="function"&&!useGet?options.endpoint(context,input.handler):typeof options.endpoint==="string"?options.endpoint:"";const routes=configuredEventRoutes(runtimeConfig.url??"",configuredEndpoint,options.eventBaseUrl);if(useGet&&input.stateUpdates!==void 0)throw new Error("GET events cannot send pending State updates.");const taken=useGet||detachedHandler?void 0:input.stateUpdates??options.host.takePendingState?.(input.source,input.handler);job.stateUpdates=taken===void 0?void 0:structuredClone(taken);state.sendSequence+=1;correlation+=1;const call=buildCall({componentClassId:context.componentClassId,handlerName:input.handler,callerRenderId:context.serverRenderId,args:input.args??{},argsSource:input.argsSource,stateToken:context.stateToken??void 0,stateUpdates:job.stateUpdates,sendSequence:state.sendSequence});const envelope=buildCallEnvelope(`vue_${correlation}`,[call],{actions:["render","data","state","event","redirect","url"],swaps:["morph"],renderers:["vue-prepared/1"]});const headers={"Content-Type":"application/citry-events+json","X-Citry-Events":"1","X-Citry-Vue-App":appId,"X-Citry-Vue-Occurrence":input.source.stableId,"X-Citry-Vue-Revision":String(committedRevision)};const selectedTransport=options.transport?.()??null;const isolated=useGet||handlerOptions.allowBatching===false;const endpoint=isolated?eventUrl(routes.eventBaseUrl??"",context,input.handler):routes.endpoint;const target=selectedTransport?{href:endpoint,sameOrigin:true}:eventRequestTarget(endpoint);const csrf=runtimeConfig.csrf??options.csrf;if(!useGet&&csrf&&target.sameOrigin){const token=csrf.token?typeof csrf.token==="function"?csrf.token():csrf.token:selectedTransport?void 0:readCookie(csrf.cookie??"csrftoken");if(token)headers[csrf.header??"X-CSRFToken"]=token}const callTimeout=input.options?.timeout;const timeoutMs=callTimeout??runtimeConfig.timeout??options.timeoutMs??3e4;if(!Number.isFinite(timeoutMs)||timeoutMs<=0)throw new Error("Vue Events timeoutMs must be positive.");const controller=new AbortController;job.controller=controller;let requestUrl=target.href;let queryTokenUrl=null;if(useGet){const query=flatQuery(input.args??{});query.append("_citry_protocol",envelope.protocol);query.append("_citry_request_id",envelope.requestId);query.append("_citry_capabilities",JSON.stringify(envelope.capabilities));query.append("_citry_caller_render_id",call.callerRenderId??"");query.append("_citry_send_sequence",String(call.sendSequence));if(handlerOptions.usesState===true&&call.stateToken!==void 0){headers[CARRIER_HEADERS.stateToken]=call.stateToken;const withToken=new URLSearchParams(query);withToken.append(CARRIER_FIELDS.stateToken,call.stateToken);queryTokenUrl=`${requestUrl}?${withToken.toString()}`}requestUrl+=`?${query.toString()}`}const requestHeaders=useGet?Object.fromEntries(Object.entries(headers).filter(([name])=>name!=="Content-Type")):headers;const requestMethod=isolated?handlerOptions.httpMethod:"POST";const attempt=async(requestUrl2,requestHeaders2,sentEnvelope)=>{if(selectedTransport){const request={url:requestUrl2,method:requestMethod,headers:{...requestHeaders2},signal:controller.signal};try{return{raw:await selectedTransport.send(sentEnvelope,request),transported:true}}catch(error){if(error!==null&&typeof error==="object")reportableFailures.add(error);throw error}}const requestInit={method:requestMethod,credentials:"same-origin",redirect:"manual",headers:requestHeaders2,...useGet?{}:{body:JSON.stringify(envelope)},signal:controller.signal};let response;try{response=await fetchImpl(requestUrl2,requestInit)}catch(error){if(error!==null&&typeof error==="object")reportableFailures.add(error);throw error}if(response.type==="opaqueredirect"){const error=new Error("The server answered the event call with a redirect, which event calls do not follow.");reportableFailures.add(error);throw error}const disposition=response.headers?.get?.("Content-Disposition")??null;if(response.ok&&disposition&&/^\s*attachment(?:;|$)/i.test(disposition)){return{attachment:await response.blob(),filename:attachmentFilename(disposition)}}try{const raw2=await response.json();const vary=response.headers?.get?.("Vary")??"";const readsTokenHeader=vary.split(",").map(name=>name.trim().toLowerCase()).some(name=>name==="*"||name===CARRIER_HEADERS.stateToken.toLowerCase());return readsTokenHeader?{raw:raw2,readsTokenHeader:true}:{raw:raw2}}catch(error){if(response.ok)throw new Error("A successful raw Event response must be an attachment.");throw error}};const operation=(async()=>{const first=await attempt(requestUrl,requestHeaders,envelope);if(queryTokenUrl===null||controller.signal.aborted||!("raw"in first)||first.readsTokenHeader===true||!answersInvalidState(first.raw))return first;const{[CARRIER_HEADERS.stateToken]:_sentToken,...withoutToken}=requestHeaders;return attempt(queryTokenUrl,withoutToken,structuredClone(envelope))})();let timeoutId=0;const received=await Promise.race([operation,job.cancelled,new Promise((_resolve,reject)=>{timeoutId=globalThis.setTimeout(()=>{controller.abort();const error=new Error("The Vue event request timed out.");reportableFailures.add(error);reject(error)},timeoutMs)})]).finally(()=>globalThis.clearTimeout(timeoutId));if("attachment"in received){stillCurrent(input.source,state);if(!detachedHandler){state.acceptedEpoch+=1;acceptAtSpot(input.source,job)}continuationCurrent(input.source,state,state.acceptedEpoch,job);saveAttachment(received.attachment,received.filename);return void 0}const raw=received.raw;const checked=preflightResultEnvelope(raw,envelope);if(!checked.ok)throw new Error(`Invalid Events response: ${checked.issue.message}`);const[result]=received.transported?copyJson(checked.results):checked.results;if(detachedHandler&&result.ok){const forbidden=result.actions.find(action=>action.action==="render"||action.action==="state");if(forbidden)throw new Error(`Invalid Events response: detached handler '${input.handler}' returned a '${forbidden.action}' action.`)}stillCurrent(input.source,state);validateTargets(result,input.source,context.serverRenderId);const preparedResult=options.host.preflightResult?.(result,input.source)??{result};if(job.cancelError)throw job.cancelError;if(!detachedHandler){state.acceptedEpoch+=1;acceptAtSpot(input.source,job)}if(preparedResult.result.ok)job.stateAccepted=true;return applyActions(preparedResult.result,input.source,state,state.acceptedEpoch,job,preparedResult.renderPlan)};const runJob=async job=>{try{job.activity?.start(job.intent);const value=await sendNow(job);if(job.cancelError)throw job.cancelError;job.stateAccepted=true;job.activity?.succeed(job.intent);if(job.lifecycleStarted)lifecycle("after",job.input.source,job.input.handler,{ok:true});job.resolve(value)}catch(error){if(!job.stateAccepted&&job.stateUpdates!==void 0)options.host.restorePendingState?.(job.input.source,job.stateUpdates);if(job.lifecycleStarted){if(error instanceof VueEventStale){lifecycle("stale",job.input.source,job.input.handler,{reason:error.reason})}else if(!(error instanceof VueEventCancellation)){reportFailure(job.input.source,job.input.handler,error)}lifecycle("after",job.input.source,job.input.handler,{ok:false})}if(!(error instanceof VueEventCancellation)){job.activity?.fail(job.intent,activityError(error));if(job.activity&&error!==null&&typeof error==="object"&&reportableFailures.has(error))handledFailures.add(error)}job.reject(error)}finally{if(!job.activityFinished){job.activityFinished=true;job.activity?.finish(job.intent)}}};const runQueue=async()=>{if(running)return;running=true;try{while(queue.length>0){const job=queue.shift();if(!job||job.settled)continue;active=job;try{await runJob(job)}finally{active=null}}}finally{running=false}};const unsupportedBrowserMethods=new Set(["HEAD","OPTIONS","CONNECT","TRACE","TRACK"]);const send=given=>{if(disposed)return Promise.reject(stale("disposed"));let activity;let intent;let input=given;let outsideQueue=false;try{input={...given,options:checkSendOptions(given.options)};const context=current(input.source);if(!Object.prototype.hasOwnProperty.call(context.descriptor.eventHandlers,input.handler))throw new Error(`Unknown event handler '${input.handler}'.`);const method=context.descriptor.eventHandlers[input.handler].httpMethod;if(unsupportedBrowserMethods.has(method))throw new Error(`Event handler '${input.handler}' uses HTTP ${method}, which is server-transport-only and cannot be sent by the browser bridge.`);const handlerOptions=context.descriptor.eventHandlers[input.handler];outsideQueue=input.options?.wait===false;if(outsideQueue&&handlerOptions.detached!==true)throw queuedHandlerError(input.handler);if(handlerOptions.detached===true&&input.stateUpdates!==void 0)throw new TypeError(`Event handler '${input.handler}' is detached, so a call to it cannot send State updates.`);activity=options.activity?.(input.source,context.descriptor);intent=activity?.enqueue(input.handler);if(handlerOptions.latestCallWins===true)supersedeEarlier(input)}catch(error){return Promise.reject(error)}let resolvePromise;let rejectPromise;let cancelPromise;const promise=new Promise((resolve,reject)=>{resolvePromise=resolve;rejectPromise=reject});const cancelled=new Promise((_resolve,reject)=>{cancelPromise=reject});void cancelled.catch(()=>void 0);const job={input,acceptedRemount:false,noWaitPending:0,activity,intent,activityFinished:false,lifecycleStarted:false,external:false,stateAccepted:false,settled:false,cancelled,cancel(error){if(job.cancelError===void 0){job.cancelError=error;cancelPromise(error)}if(job.settled)return;job.controller?.abort();if(!job.activityFinished){job.activityFinished=true;job.activity?.finish(job.intent)}job.reject(error)},resolve(value){if(job.settled)return;job.settled=true;resolvePromise(value)},reject(error){if(job.settled)return;job.settled=true;rejectPromise(error)}};if(outsideQueue){detachedCalls.add(job);void runJob(job).finally(()=>detachedCalls.delete(job))}else{queue.push(job);void runQueue()}return promise};const applyActionsExternally=async(actions,source)=>{const result=buildOkResult(actions);if(!source){let data;for(const action of result.actions){if(disposed)throw stale("disposed");if(typeof action.delay==="number"&&action.delay>0){const milliseconds=action.delay*1e3;await new Promise((resolve,reject)=>{const timer=globalThis.setTimeout(()=>{sourcelessTimers.delete(timer);resolve()},milliseconds);sourcelessTimers.set(timer,reject)});if(disposed)throw stale("disposed")}if(action.action==="data")data=action.value;else if(action.action==="redirect")options.host.redirect(action.url);else if(action.action==="url")options.host.updateUrl(action.url,action.mode);else if(action.action==="event"){if(action.target!==void 0||!options.host.dispatchEventGlobal)throw new Error("Citry.events.applyActions needs a mounted component for targeted Event actions.");options.host.dispatchEventGlobal(action.eventName,action.detail)}else{throw new Error("Citry.events.applyActions needs a mounted component for Render and State actions.")}}return data}const externalContext=current(source);const state=ownerState(source);state.acceptedEpoch+=1;const cancelled=new Promise(()=>void 0);const job={input:{source,handler:"__external__"},acceptedRemount:false,noWaitPending:0,activityFinished:true,lifecycleStarted:true,external:true,callerRenderId:externalContext.serverRenderId,stateAccepted:true,settled:true,cancelled,cancel(){},resolve(){},reject(){}};let prepared;try{prepared=options.host.preflightResult?.(result,source)??{result}}catch(error){if(activityError(error).code==="stale_state"&&lifecycle("before",source,job.input.handler)){reportFailure(source,job.input.handler,error);lifecycle("after",source,job.input.handler,{ok:false})}throw error}if(!lifecycle("before",source,job.input.handler)){const error=new VueEventCancellation("Citry Events applyActions was cancelled by citry:events:before.");lifecycle("after",source,job.input.handler,{ok:false});throw error}acceptAtSpot(source,job);externalJobs.add(job);try{const value=await applyActions(prepared.result,source,state,state.acceptedEpoch,job,prepared.renderPlan);lifecycle("after",source,job.input.handler,{ok:true});return value}catch(error){if(error instanceof VueEventStale){lifecycle("stale",source,job.input.handler,{reason:error.reason})}else if(!(error instanceof VueEventCancellation)){reportFailure(source,job.input.handler,error)}lifecycle("after",source,job.input.handler,{ok:false});throw error}finally{externalJobs.delete(job)}};const retire=(source,acceptedTransaction)=>{const state=owners.get(source.stableId);if(state?.generation===source.generation){state.retired=true;for(const[timer,reject]of state.timers){globalThis.clearTimeout(timer);reject(stale("retired"))}state.timers.clear();owners.delete(source.stableId)}const error=new VueEventStale("retired");for(let index=queue.length-1;index>=0;index-=1){const job=queue[index];if(job.input.source.stableId===source.stableId&&job.input.source.generation===source.generation){queue.splice(index,1);lifecycle("stale",source,job.input.handler,{reason:"retired"});job.cancel(error)}}for(const job of detachedCalls)if(job.input.source.stableId===source.stableId&&job.input.source.generation===source.generation)job.cancel(error);for(const job of externalJobs){if(acceptedTransaction!==void 0&&job.committingTransaction===acceptedTransaction&&job.input.source.stableId===source.stableId&&job.input.source.generation===source.generation)job.acceptedRemount=true}if(active?.input.source.stableId===source.stableId&&active.input.source.generation===source.generation&&acceptedTransaction!==void 0&&active.committingTransaction===acceptedTransaction){active.acceptedRemount=true}else if(active?.input.source.stableId===source.stableId&&active.input.source.generation===source.generation)active.cancel(error)};const dispose=()=>{if(disposed)return;disposed=true;for(const state of owners.values()){state.retired=true;for(const[timer,reject]of state.timers){globalThis.clearTimeout(timer);reject(stale("disposed"))}state.timers.clear()}owners.clear();acceptedAtSpot.clear();for(const timers of[remountTimers,sourcelessTimers]){for(const[timer,reject]of timers){globalThis.clearTimeout(timer);reject(stale("disposed"))}timers.clear()}const error=new VueEventStale("disposed");for(const job of queue.splice(0)){lifecycle("stale",job.input.source,job.input.handler,{reason:"disposed"});job.cancel(error)}active?.cancel(error);for(const job of detachedCalls)job.cancel(error)};const isDeclarativeFailureHandled=error=>error instanceof VueEventCancellation||error!==null&&typeof error==="object"&&handledFailures.has(error);return{send,applyActions:applyActionsExternally,retire,dispose,isDeclarativeFailureHandled}};return __toCommonJS(citry_events_vue_exports);})(); global.CitryVueEvents = CitryVueEvents; } diff --git a/packages/py/citry/citry/ext/events/codecs.py b/packages/py/citry/citry/ext/events/codecs.py index 30c37fca13..ead4263d57 100644 --- a/packages/py/citry/citry/ext/events/codecs.py +++ b/packages/py/citry/citry/ext/events/codecs.py @@ -62,6 +62,7 @@ REQUEST_ID_FIELD, SEND_SEQUENCE_FIELD, STATE_TOKEN_FIELD, + STATE_TOKEN_HEADER, JsonNestingError, build_partial_call_envelope, build_query_envelope, @@ -85,6 +86,7 @@ "REQUEST_ID_FIELD", "SEND_SEQUENCE_FIELD", "STATE_TOKEN_FIELD", + "STATE_TOKEN_HEADER", "DecodedPayload", "EnvelopeCodec", "FlatJsonCodec", @@ -262,10 +264,13 @@ def decode_query_request(request: RouteRequest, *, state_declared: bool) -> dict """ The GET codec: args ride as query parameters (design 6.2). - The state token rides the ``_citry_state_token`` parameter only when the - handler declares ``state`` in its signature; a read-only GET URL stays - pasteable and token-free, and a stray token parameter on a stateless - handler is simply not part of the call. ``_citry_caller_render_id`` maps + The State token counts only when the handler declares ``state`` in its + signature; a read-only GET URL stays pasteable and token-free, and a + stray token on a stateless handler is simply not part of the call. + Citry's browser code sends the token in the ``X-Citry-State-Token`` + header, which access logs do not record by default; the ``_citry_state_token`` + query parameter is still read for clients that send it there. A call + that sends both with different values is refused. ``_citry_caller_render_id`` maps onto the call's ``callerRenderId`` either way. Browser sends also carry their integer out-of-order guard as ``_citry_send_sequence``. Browser calls preserve the flattened envelope's protocol, request ID, and JSON capabilities @@ -281,15 +286,53 @@ def decode_query_request(request: RouteRequest, *, state_declared: bool) -> dict Returns: The single-call envelope the query string means. + Raises: + EventError: With status 400 when the header and the query parameter + carry different tokens. + """ args: dict[str, Any] = StringArgs( {key: values[0] if len(values) == 1 else list(values) for key, values in request.query.items()} ) + if state_declared: + args = _merge_header_state_token(args, request) fields = split_query_fields(args, state_declared=state_declared) fields.call["args"] = StringArgs(fields.call["args"]) return build_query_envelope(fields) +def _merge_header_state_token(args: dict[str, Any], request: RouteRequest) -> dict[str, Any]: + """ + Put the ``X-Citry-State-Token`` header's token where the query codec reads it. + + The header and the query parameter are two ways to send one token, so + the rest of the codec reads a single place. An empty header counts as + absent, matching an empty query parameter. + + Raises: + EventError: With status 400 when both carry a token and they differ. + Picking one would let a URL someone else wrote decide which + State a call runs with, so the call is refused instead. + + """ + header = request.headers.get(STATE_TOKEN_HEADER) or "" + if not header: + return args + query = args.get(STATE_TOKEN_FIELD) + # A repeated query parameter arrives as a list, which never equals the + # header's string, so it is refused like any other mismatch. + if query not in (None, "", header): + msg = ( + f"The call sends a State token in both the {STATE_TOKEN_HEADER} header and the" + f" {STATE_TOKEN_FIELD} query parameter, and they differ. Send it in one place." + ) + raise EventError(msg, status=400) + # StringArgs marks the args as text for binding; keep that type. + merged = StringArgs(args) + merged[STATE_TOKEN_FIELD] = header + return merged + + def decode_request( request: RouteRequest, user_codecs: Sequence[Any] = (), diff --git a/packages/py/citry/citry/ext/events/routes.py b/packages/py/citry/citry/ext/events/routes.py index f734748a54..bed573d346 100644 --- a/packages/py/citry/citry/ext/events/routes.py +++ b/packages/py/citry/citry/ext/events/routes.py @@ -58,7 +58,7 @@ ) from citry._urls import url_scheme_and_rest from citry.ext.dependencies.routes import SHARED_RUNTIME -from citry.ext.events.codecs import decode_request +from citry.ext.events.codecs import STATE_TOKEN_HEADER, decode_request from citry.ext.events.csrf import build_csrf_check from citry.ext.events.dispatcher import EventRequest, EventsDispatcher, TransportContext from citry.ext.events.errors import EventError, wire_error @@ -296,7 +296,7 @@ def _serve_call( """One events HTTP request through the sync dispatcher: decode, dispatch, translate back to HTTP.""" prepared = _prepare_dispatch(request, citry, url_component=url_component, url_event=url_event) if isinstance(prepared, RouteResponse): - return prepared + return _early_refusal(prepared, request) outcome = dispatcher.dispatch( prepared.envelope, prepared.ctx, @@ -325,7 +325,7 @@ async def _serve_call_async( """ prepared = _prepare_dispatch(request, citry, url_component=url_component, url_event=url_event) if isinstance(prepared, RouteResponse): - return prepared + return _early_refusal(prepared, request) outcome = await dispatcher.dispatch_async( prepared.envelope, prepared.ctx, @@ -337,6 +337,18 @@ async def _serve_call_async( return _respond(request, outcome, batch=prepared.batch, compat=prepared.compat) +def _early_refusal(response: RouteResponse, request: RouteRequest) -> RouteResponse: + """ + Mark a refusal sent before dispatch like any other answer. + + It can depend on the request headers, such as a State token header that + differs from the query parameter, and a GET answer is kept out of + caches, as a dispatched one is. + """ + refused = _with_no_store(response) if request.method == "GET" else response + return _with_cache_marks(refused, request) + + def _prepare_dispatch( request: RouteRequest, citry: Citry, @@ -449,7 +461,7 @@ def _respond( if isinstance(outcome, RouteResponse): # The RouteResponse escape hatch (per-event route only). response = _with_no_store(outcome) if request.method == "GET" else outcome - return _with_page_nonce_marks(response, sent=PAGE_NONCE_HEADER in request.headers) + return _with_cache_marks(response, request) if compat: response = _compat_response(outcome, request) @@ -464,9 +476,104 @@ def _respond( # GET handlers are cacheable in principle but served no-store until GET # caching lands (design 3.5 and section 16). response = _with_no_store(response) if request.method == "GET" else response - # A Render in this answer may carry the nonce the call sent, which belongs - # to one tab of one visitor, so no cache may keep the answer for another. - return _with_page_nonce_marks(response, sent=PAGE_NONCE_HEADER in request.headers) + return _with_cache_marks(response, request) + + +def _with_cache_marks(response: RouteResponse, request: RouteRequest) -> RouteResponse: + """ + Keep caches from giving one visitor's answer to another. + + ``Vary`` lists the request headers that carry one visitor's values into + the answer: the page nonce, which a Render may carry and which belongs + to one tab, and on a GET call the State token. Citry's own GET URLs hold + a fresh request ID, so no cache shares their answers; a client of the + app's own may send a stable URL, though, and some CDNs ignore ``Vary``. + So when such a call sends its token in the ``X-Citry-State-Token`` + header and the handler lets caches keep the answer, only the visitor's + own browser may. + """ + is_get = request.method == "GET" + if is_get and request.headers.get(STATE_TOKEN_HEADER): + response = _private_cache_policy(response) + varied = (PAGE_NONCE_HEADER, STATE_TOKEN_HEADER) if is_get else (PAGE_NONCE_HEADER,) + return _with_page_nonce_marks(response, sent=PAGE_NONCE_HEADER in request.headers, varied=varied) + + +# Cache-Control directives a browser's own cache may follow, without and with +# a number of seconds. Everything else is dropped: `public`, `s-maxage`, and a +# `private` that names fields, which still lets a shared cache keep the rest. +_BROWSER_CACHE_FLAGS = frozenset({"must-revalidate", "no-transform", "immutable"}) +_BROWSER_CACHE_SECONDS = frozenset({"max-age", "stale-while-revalidate"}) +# Headers that set the policy of a CDN alone; a CDN that reads one ignores +# Cache-Control. RFC 9213 also lets a CDN name its own `-CDN-Cache-Control`. +_CDN_CACHE_HEADERS = frozenset({"surrogate-control", "edge-control", "x-accel-expires"}) + + +def _private_cache_policy(response: RouteResponse) -> RouteResponse: + """Turn a handler's cache policy into one that only the visitor's browser may follow.""" + headers: list[tuple[str, str]] = [] + for name, value in response.headers: + lowered = name.lower() + if lowered in _CDN_CACHE_HEADERS or lowered.endswith("cdn-cache-control"): + continue + if lowered == "cache-control": + headers.append((name, _private_cache_control(value))) + else: + headers.append((name, value)) + return RouteResponse( + content=response.content, + content_type=response.content_type, + status=response.status, + headers=tuple(headers), + ) + + +def _private_cache_control(value: str) -> str: + """The ``Cache-Control`` value ``private`` plus the handler's directives a browser cache may follow.""" + kept: list[str] = [] + for item in _split_cache_directives(value): + name, has_argument, argument = item.partition("=") + directive = name.strip().lower() + argument = argument.strip() + if directive == "no-store": + return "no-store" + if directive == "no-cache": + # A `no-cache` that names fields binds every cache, and browsers + # often read it as the bare form; the bare form is never looser. + if "no-cache" not in kept: + kept.append("no-cache") + elif directive in _BROWSER_CACHE_FLAGS and not has_argument: + kept.append(directive) + elif directive in _BROWSER_CACHE_SECONDS and argument.isascii() and argument.isdigit(): + kept.append(f"{directive}={argument}") + return ", ".join(["private", *kept]) + + +def _split_cache_directives(value: str) -> list[str]: + """ + Split a ``Cache-Control`` value at the commas outside quoted strings. + + One pass over the characters, so a long value a handler built costs + time in step with its length. + """ + items: list[str] = [] + current: list[str] = [] + quoted = False + escaped = False + for char in value: + if escaped: + escaped = False + elif quoted and char == "\\": + escaped = True + elif char == '"': + quoted = not quoted + elif char == "," and not quoted: + items.append("".join(current)) + current = [] + continue + current.append(char) + items.append("".join(current)) + return [item for item in items if item.strip()] def _encode_envelope(envelope: Mapping[str, Any]) -> tuple[str, Mapping[str, Any]]: @@ -840,9 +947,11 @@ def _encode_location(url: str) -> str: return quote(url, safe=_LOCATION_SAFE) -def _with_page_nonce_marks(response: RouteResponse, *, sent: bool) -> RouteResponse: +def _with_page_nonce_marks( + response: RouteResponse, *, sent: bool, varied: tuple[str, ...] = (PAGE_NONCE_HEADER,) +) -> RouteResponse: """ - Mark an answer so that no cache gives the nonce of one page to another. + List ``varied`` in ``Vary``, and keep a nonce answer out of every cache. Every answer lists ``X-Citry-Page-Nonce`` in ``Vary``: whether the call sent the header changes the answer, so a cache must not give an answer @@ -850,21 +959,23 @@ def _with_page_nonce_marks(response: RouteResponse, *, sent: bool) -> RouteRespo call ``sent`` the header, ``no-store`` also keeps every cache from storing the answer, unless the handler set its own cache policy. Any ``Vary`` the handler set is extended rather than repeated, because the Django adapter - refuses a repeated header name. + refuses a repeated header name. ``varied`` names the request headers to + list, ``X-Citry-Page-Nonce`` first. """ with_no_store = _with_no_store(response) if sent else response headers: list[tuple[str, str]] = [] - varied = False + has_vary = False for name, value in with_no_store.headers: merged = value if name.lower() == "vary": - varied = True + has_vary = True listed = {item.strip().lower() for item in value.split(",")} - if "*" not in listed and PAGE_NONCE_HEADER.lower() not in listed: - merged = f"{value}, {PAGE_NONCE_HEADER}" + if "*" not in listed: + missing = [header for header in varied if header.lower() not in listed] + merged = ", ".join([value, *missing]) headers.append((name, merged)) - if not varied: - headers.append(("Vary", PAGE_NONCE_HEADER)) + if not has_vary: + headers.append(("Vary", ", ".join(varied))) return RouteResponse( content=with_no_store.content, content_type=with_no_store.content_type, diff --git a/packages/py/citry/tests/e2e/test_vue_events_default_e2e.py b/packages/py/citry/tests/e2e/test_vue_events_default_e2e.py index 15c0b3b396..da5f06779f 100644 --- a/packages/py/citry/tests/e2e/test_vue_events_default_e2e.py +++ b/packages/py/citry/tests/e2e/test_vue_events_default_e2e.py @@ -2285,6 +2285,55 @@ def download(self): assert faults == [] +@pytest.mark.e2e +def test_a_get_call_that_reads_state_sends_its_token_in_a_header( + page: Any, serve_live: Any, open_citry_page: Any +) -> None: + # The URL of a GET call lands in access logs, so the browser must send + # the State token in a header and the server must read it from there. + engine = Citry(secret="vue-get-token-header-secret", autodiscover=False) # noqa: S106 + engine.set_mounted_prefix("/citry") + + class PeekState: + label: str = "kept" + + class Peeker(Component): + citry = engine + template = """ +
+ + +
+ """ + js = """$component({ + data(){return {result:''}}, + methods:{peek(){this.$sendEvent('peek').then(value=>{this.result=value.label})}} + });""" + + State = PeekState + + class Events: + @event(methods=("GET",)) + def peek(self, state: PeekState): + return {"label": state.label} + + dispatcher_for(engine) + html = Peeker().render().serialize() + requests: list[Any] = [] + faults: list[str] = [] + page.on("request", lambda request: requests.append(request) if "/ext/events/e/" in request.url else None) + page.on("pageerror", lambda error: faults.append(str(error))) + base = serve_live(engine, html, "") + open_citry_page(base + "/") + page.locator("#peek").click() + page.wait_for_function("document.querySelector('#peek-result')?.textContent === 'kept'") + [peek_request] = requests + assert peek_request.method == "GET" + assert "_citry_state_token" not in peek_request.url + assert peek_request.headers.get("x-citry-state-token") + assert faults == [] + + @pytest.mark.e2e def test_two_serialized_vue_apps_share_runtime_without_reset( page: Any, serve_document: Any, open_citry_page: Any diff --git a/packages/py/citry/tests/test_events_host_parity.py b/packages/py/citry/tests/test_events_host_parity.py index c6b92b14b7..d67fee0248 100644 --- a/packages/py/citry/tests/test_events_host_parity.py +++ b/packages/py/citry/tests/test_events_host_parity.py @@ -49,6 +49,7 @@ from citry.contrib.wsgi import wsgi_app # noqa: E402 from citry.ext.events import event # noqa: E402 from citry.ext.events.tokens import mint_state_token # noqa: E402 +from citry.util.routing import RouteResponse # noqa: E402 SIGNING_KEY = "wp18-host-parity-secret" FIXED_NOW = 1_700_000_000.0 @@ -103,6 +104,18 @@ def quiet(self, state: ParityState) -> None: def echo(self, data: _TextIn) -> dict[str, str]: return {"echo": data.text} + @event(methods=("GET",)) + def peek(self, state: ParityState) -> dict[str, str]: + return {"text": state.text} + + @event(methods=("GET",), bundle=False) + def localized(self, state: ParityState) -> RouteResponse: + return RouteResponse( + content=state.text, + content_type="text/plain", + headers=(("Vary", "Accept-Language"), ("Cache-Control", "public, s-maxage=60, max-age=10")), + ) + @event(methods=("PUT", "DELETE")) def replace(self, data: _TextIn) -> dict[str, str]: method_calls.append(data.text) @@ -208,10 +221,10 @@ def post_raw_body(self, url: str, body: bytes, content_type: str) -> _Response: return self.client.post(url, data=body, content_type=content_type, headers=RUNTIME_HEADERS) return self.client.post(url, content=body, headers={"Content-Type": content_type, **RUNTIME_HEADERS}) - def get(self, event_name: str, query: dict[str, str]) -> _Response: + def get(self, event_name: str, query: dict[str, str], headers: dict[str, str] | None = None) -> _Response: if self.name == "django": - return self.client.get(self.event_url(event_name), data=query) - return self.client.get(self.event_url(event_name), params=query) + return self.client.get(self.event_url(event_name), data=query, headers=headers) + return self.client.get(self.event_url(event_name), params=query, headers=headers) def post_form(self, event_name: str, fields: dict[str, str]) -> _Response: if self.name == "django": @@ -342,6 +355,37 @@ def _stateless_get(host: _MountedHost) -> _Snapshot: return snapshot +def _stateful_get_token_header(host: _MountedHost) -> tuple[Any, ...]: + # The browser sends a GET call's State token in a header, which every + # host must hand to Citry, and the answer must vary on it. + token = _token(host.component, text="from header") + response = host.get("peek", {}, headers={"X-Citry-State-Token": token}) + snapshot = _json_snapshot(response) + assert snapshot.body["results"][0]["actions"] == [{"action": "data", "value": {"text": "from header"}}] + vary = tuple(_header_values(response, "vary")) + assert vary == ("X-Citry-Page-Nonce, X-Citry-State-Token",) + conflict = _json_snapshot( + host.get("peek", {"_citry_state_token": "other"}, headers={"X-Citry-State-Token": token}) + ) + assert conflict.status == 400 + assert conflict.body["results"][0]["error"]["code"] == "protocol_mismatch" + assert conflict.cache_control == "no-store" + # A handler's own Vary is extended in place, since Django refuses a + # repeated header, and its shared-cache policy is narrowed to the + # visitor's browser because the URL does not carry the token. + own = host.get("localized", {}, headers={"X-Citry-State-Token": token}) + assert own.status_code == 200 + own_marks = ( + tuple(_header_values(own, "vary")), + tuple(_header_values(own, "cache-control")), + ) + assert own_marks == ( + ("Accept-Language, X-Citry-Page-Nonce, X-Citry-State-Token",), + ("private, max-age=10",), + ) + return snapshot, conflict, vary, own_marks + + def _validation_and_unknown_errors(host: _MountedHost) -> tuple[_Snapshot, _Snapshot]: invalid = _json_snapshot(host.post_envelope("add", {"args": {"count": "three"}})) unknown = _json_snapshot(host.post_envelope("missing", {"args": {}})) @@ -540,6 +584,7 @@ def _nosniff_on_every_kind_of_response(host: _MountedHost) -> tuple[tuple[int, s SCENARIOS: tuple[Any, ...] = ( pytest.param(_happy_stateful_render, id="happy-stateful-render"), pytest.param(_stateless_get, id="stateless-get"), + pytest.param(_stateful_get_token_header, id="stateful-get-token-header"), pytest.param(_validation_and_unknown_errors, id="validation-and-unknown-errors"), pytest.param(_unknown_component, id="unknown-component"), pytest.param(_mixed_batch, id="mixed-batch-always-200"), @@ -607,7 +652,14 @@ def test_django_and_fastapi_have_the_same_events_http_contract(scenario: _Scenar def _wsgi_call( - citry: Citry, method: str, path: str, *, body: bytes = b"", content_type: str = "", query: str = "" + citry: Citry, + method: str, + path: str, + *, + body: bytes = b"", + content_type: str = "", + query: str = "", + headers: dict[str, str] | None = None, ) -> tuple[str, list[tuple[str, str]], bytes]: """Run one request through the WSGI adapter, returning the status line, the headers, and the body.""" environ: dict[str, Any] = { @@ -620,6 +672,8 @@ def _wsgi_call( } if content_type: environ["CONTENT_TYPE"] = content_type + for name, value in (headers or {}).items(): + environ[f"HTTP_{name.upper().replace('-', '_')}"] = value sent: dict[str, Any] = {} def start_response(status: str, headers: list[tuple[str, str]]) -> None: @@ -653,6 +707,21 @@ def test_wsgi_sends_nosniff_with_every_kind_of_events_response() -> None: assert dict(by_name)["content-type"].startswith(expected_type) +def test_wsgi_reads_the_state_token_header_on_a_get_call() -> None: + citry = Citry(secret=SIGNING_KEY) + citry.set_mounted_prefix("/citry") + component = _fixture_component(citry) + token = _token(component, text="from header") + + status, headers, payload = _wsgi_call( + citry, "GET", f"/ext/events/e/{component.class_id}/peek", headers={"X-Citry-State-Token": token} + ) + + assert status.startswith("200") + assert json.loads(payload)["results"][0]["actions"] == [{"action": "data", "value": {"text": "from header"}}] + assert {name.lower(): value for name, value in headers}["vary"] == "X-Citry-Page-Nonce, X-Citry-State-Token" + + def test_wsgi_answers_a_too_deep_json_body_with_a_400() -> None: citry = Citry(secret=SIGNING_KEY) citry.set_mounted_prefix("/citry") diff --git a/packages/py/citry/tests/test_events_routes.py b/packages/py/citry/tests/test_events_routes.py index 21bfab3458..7453dacf78 100644 --- a/packages/py/citry/tests/test_events_routes.py +++ b/packages/py/citry/tests/test_events_routes.py @@ -1434,6 +1434,201 @@ def test_a_get_with_an_old_token_gets_a_new_one(self, monkeypatch): assert state_action["targetRenderId"] == "i1" assert state_action["stateToken"] != token + def test_state_declaring_get_reads_the_token_header(self): + # Citry's browser code sends the token in a header, so it stays out + # of the URL that access logs record. + c = _citry() + greeter = _greeter(c) + client = _mounted(c) + token = _token(greeter, text="stored") + response = client.get(_event_url(greeter, "peek"), headers={"X-Citry-State-Token": token}) + assert response.status_code == 200 + assert response.json()["results"][0]["actions"][0]["value"] == {"text": "stored"} + + def test_the_same_token_in_header_and_query_is_accepted(self): + c = _citry() + greeter = _greeter(c) + client = _mounted(c) + token = _token(greeter, text="stored") + response = client.get( + _event_url(greeter, "peek"), + params={"_citry_state_token": token}, + headers={"X-Citry-State-Token": token}, + ) + assert response.status_code == 200 + assert response.json()["results"][0]["actions"][0]["value"] == {"text": "stored"} + + @pytest.mark.parametrize( + "query", + [ + pytest.param({"_citry_state_token": "other"}, id="different"), + pytest.param([("_citry_state_token", "a"), ("_citry_state_token", "b")], id="repeated"), + ], + ) + def test_different_tokens_in_header_and_query_are_refused(self, query): + # Choosing one would let whoever wrote the URL pick the State the + # call runs with, so the call is refused before any handler runs. + c = _citry() + greeter = _greeter(c) + client = _mounted(c) + response = client.get( + _event_url(greeter, "peek"), params=query, headers={"X-Citry-State-Token": _token(greeter)} + ) + assert response.status_code == 400 + error = response.json()["results"][0]["error"] + assert error["code"] == "protocol_mismatch" + assert "X-Citry-State-Token" in error["message"] + # The refusal depends on the header too, so a cache must not reuse it. + assert response.headers["vary"] == "X-Citry-Page-Nonce, X-Citry-State-Token" + + def test_an_empty_token_header_falls_back_to_the_query(self): + c = _citry() + greeter = _greeter(c) + client = _mounted(c) + token = _token(greeter, text="stored") + response = client.get( + _event_url(greeter, "peek"), + params={"_citry_state_token": token}, + headers={"X-Citry-State-Token": ""}, + ) + assert response.status_code == 200 + assert response.json()["results"][0]["actions"][0]["value"] == {"text": "stored"} + + def test_a_malformed_token_header_answers_invalid_state(self): + c = _citry() + greeter = _greeter(c) + client = _mounted(c) + response = client.get(_event_url(greeter, "peek"), headers={"X-Citry-State-Token": "not-a-token"}) + assert response.status_code == 403 + assert response.json()["results"][0]["error"]["code"] == "invalid_state" + + def test_a_repeated_token_header_answers_invalid_state(self): + # The host joins a repeated header with commas, which no token reads as. + c = _citry() + greeter = _greeter(c) + client = _mounted(c) + token = _token(greeter) + response = client.get( + _event_url(greeter, "peek"), + headers=[("X-Citry-State-Token", token), ("X-Citry-State-Token", token)], + ) + assert response.status_code == 403 + assert response.json()["results"][0]["error"]["code"] == "invalid_state" + + def test_a_stateless_get_ignores_the_token_header(self): + # As with the query parameter, a token on a handler that does not + # read State is not part of the call, even a conflicting one. + c = _citry() + greeter = _greeter(c) + client = _mounted(c) + response = client.get( + _event_url(greeter, "echo"), + params={"text": "hi", "_citry_state_token": "a"}, + headers={"X-Citry-State-Token": "b"}, + ) + assert response.status_code == 200 + assert response.json()["results"][0]["actions"] == [{"action": "data", "value": {"echo": "hi"}}] + + def test_a_get_with_an_old_header_token_gets_a_new_one(self, monkeypatch): + c = _citry() + greeter = _greeter(c) + client = _mounted(c) + token = _token(greeter, text="stored") + monkeypatch.setattr("citry.ext.events.tokens._now", lambda: FIXED_NOW + 12 * 60 * 60) + response = client.get( + _event_url(greeter, "peek"), + params={"_citry_caller_render_id": "i1"}, + headers={"X-Citry-State-Token": token}, + ) + state_action, data_action = response.json()["results"][0]["actions"] + assert data_action["value"] == {"text": "stored"} + assert state_action["action"] == "state" + assert state_action["targetRenderId"] == "i1" + assert state_action["stateToken"] != token + + def test_get_answers_vary_on_the_token_header_and_post_answers_do_not(self): + # A cache that keys a GET answer only on its URL must not hand one + # visitor's State answer to a call that sent another token. + c = _citry() + greeter = _greeter(c) + client = _mounted(c) + response = client.get(_event_url(greeter, "peek"), headers={"X-Citry-State-Token": _token(greeter)}) + assert response.headers["vary"] == "X-Citry-Page-Nonce, X-Citry-State-Token" + # A GET handler that sets its own public cache policy is the case + # where a shared cache would otherwise keep the answer. + response = client.get(_event_url(greeter, "cached")) + assert response.headers["cache-control"] == "public, max-age=60" + assert response.headers["vary"] == "X-Citry-Page-Nonce, X-Citry-State-Token" + response = client.post(_event_url(greeter, "quiet"), data={"_citry_state_token": _token(greeter)}) + assert response.headers["vary"] == "X-Citry-Page-Nonce" + + def test_a_handler_cache_policy_turns_private_when_the_token_rides_a_header(self): + # The URL does not carry the token, and a CDN that ignores Vary + # would share the answer, so only the visitor's own browser may + # keep it. + c = _citry() + greeter = _greeter(c) + client = _mounted(c) + response = client.get(_event_url(greeter, "cached"), headers={"X-Citry-State-Token": "t"}) + assert response.headers["cache-control"] == "private, max-age=60" + response = client.get(_event_url(greeter, "cached")) + assert response.headers["cache-control"] == "public, max-age=60" + + @pytest.mark.parametrize( + ("policy", "expected"), + [ + ("public, max-age=60", "private, max-age=60"), + ("public, s-maxage=600, max-age=10, must-revalidate", "private, max-age=10, must-revalidate"), + # A field-qualified private still lets a shared cache keep the rest. + ('private="Set-Cookie", max-age=60', "private, max-age=60"), + # A comma inside quotes does not make a bare `private`, and a + # `no-cache` that names fields becomes the stricter bare form. + ('public, max-age=60, no-cache="X, private, Y"', "private, max-age=60, no-cache"), + ("max-age=0, NO-CACHE", "private, max-age=0, no-cache"), + ("no-store", "no-store"), + ("max-age=60, no-store=1", "no-store"), + # Malformed directives are dropped rather than passed on. + ("max-age=, immutable=1, public max-age=60", "private"), + ("", "private"), + ], + ) + def test_a_handler_cache_policy_keeps_only_what_a_browser_cache_follows(self, policy, expected): + assert events_routes._private_cache_control(policy) == expected + + def test_a_split_of_a_long_cache_policy_takes_time_in_step_with_its_length(self): + # A handler may build the value from request data. + started = time.perf_counter() + events_routes._private_cache_control("a" * 200_000 + " b, " + '"' * 200_000) + assert time.perf_counter() - started < 1.0 + + def test_a_cdn_only_cache_policy_is_dropped_when_the_token_rides_a_header(self): + response = RouteResponse( + content="x", + headers=( + ("CDN-Cache-Control", "max-age=600"), + ("Cloudflare-CDN-Cache-Control", "max-age=600"), + ("Surrogate-Control", "max-age=600"), + ("Edge-Control", "max-age=600"), + ("X-Accel-Expires", "600"), + ), + ) + request = RouteRequest(method="GET", path="/", headers=RouteHeaders([("X-Citry-State-Token", "t")])) + marked = events_routes._with_cache_marks(response, request) + assert {name.lower() for name, _ in marked.headers} == {"vary"} + + def test_a_refused_get_is_kept_out_of_caches(self): + # A 405 is cacheable by default, and the refusal may depend on headers. + c = _citry() + greeter = _greeter(c) + client = _mounted(c) + response = client.request("PUT", _event_url(greeter, "peek")) + assert response.status_code == 405 + assert response.headers["vary"] == "X-Citry-Page-Nonce" + response = client.get(_event_url(greeter, "save")) + assert response.status_code == 405 + assert response.headers["cache-control"] == "no-store" + assert response.headers["vary"] == "X-Citry-Page-Nonce, X-Citry-State-Token" + def test_a_get_without_a_token_gets_no_new_token(self, monkeypatch): # A GET to a handler that does not read State sends no token, so # there is nothing to renew.