# FKN API Reference (@fkn/lib) > Generated TypeDoc reference for every public entry point and namespace of `@fkn/lib`. --- # @fkn/lib URL: https://docs.fkn.dev/api/ ## Namespaces - [network](/api/namespaces/network/) - [shell](/api/namespaces/shell/) ## Type Aliases ### RelayUnavailableError ```ts type RelayUnavailableError = Error & object; ``` What a call carrying a `RelayChoice` rejects with when no relay can serve the choice: none matches it, the ones that match cannot be reached, or the FKN page is too old to choose. Nothing was sent. #### Type Declaration ##### name ```ts name: typeof RELAY_UNAVAILABLE; ``` ## Variables ### attachFrame ```ts const attachFrame: AttachFrameFunction; ``` Attaches FKN to an iframe the app mounted, or with `{ window }` opens the attachment in a window of its own. `cookies` picks the jar and with it the backend (`AttachCookies`): `'persistent'`, the default, and `'ephemeral'` run on the cloud render proxy whatever is installed, and never wait for the extension; `'native'` runs on the extension, waiting up to 2000 ms from the call for it to announce itself, however long after the page's load that is (`waitForExtensionExposure`), and showing the install prompt when it does not. A `blank` attach is the cloud render proxy's alone, so beside `'native'` it is a TypeError. `frame.backend()` says which backend serves an attachment. A window opens before the first await, so call this directly in the click or key handler whose activation opens it. On `'persistent'` or `'ephemeral'` it opens on the cloud, extension or not. On `'native'` it opens as a real browser window on the extension, with no exposure wait; an extension that does not announce `attachWindow`, or none at all, is refused at once with `ExtensionOperationUnsupportedError` (operation `'attachWindow'`), before anything opens or is waited for, so the same click can still open one on another value. A window on `'persistent'` or `'ephemeral'` goes on answering, and on reporting its page's messages and documents, after this page replaces its document with `document.open()`. ## Functions ### connect() ```ts function connect(): Promise; ``` #### Returns `Promise`\<`boolean`\> *** ### fetch() ```ts function fetch(input, init?): Promise; ``` #### Parameters ##### input `URL` \| `RequestInfo` ##### init? `RequestInit` & `object` #### Returns `Promise`\<`Response`\> *** ### isRelayUnavailable() ```ts function isRelayUnavailable(error): error is RelayUnavailableError; ``` Whether `error` is a `RelayUnavailableError`, matched on `name` so it holds across a worker hop. #### Parameters ##### error `unknown` #### Returns `error is RelayUnavailableError` *** ### promptRelay() ```ts function promptRelay(): Promise; ``` #### Returns `Promise`\<`string` \| `null`\> *** ### relayOf() ```ts function relayOf(served): string | undefined; ``` The relay that served a cloud answer, socket, server, UDP socket or frame, as an id to pass back in a `RelayChoice`. Undefined when no relay did (the extension, the desktop, a `'native'` frame), before a socket is connected or bound, and on an FKN page too old to say, so a loop that retries on another relay stops there. A frame attached without a choice answers the default relay of its attach once the broker has named it, normally before the attach resolves. #### Parameters ##### served \| `Socket` \| `Server` \| [`Socket`](/api/dgram/#socket) \| `Response` \| [`Frame`](/api/extension/#frame) \| `Socket` #### Returns `string` \| `undefined` *** ### relayWorker() ```ts function relayWorker(worker, options?): Promise; ``` Bridges a worker into the FKN API: once called, the worker can import `@fkn/lib` and use `net` / `dgram` exactly like the main thread. Main thread only. `originA` and `originB` are kept for compatibility and change nothing: the page reaches fkn.app's broker frame on fkn.app's origin both ways, and a page nested under fkn.app reaches it over a port. The page hands its `fkn-api` channel to the worker for good, and its own calls move to `fkn-api-window`. Against a cached FKN page from before that channel, the page's own calls refuse with `OwnChannelUnavailableError` and FKN's UI and account changes stay off here until a reload. A socket the page opened through FKN before its first `relayWorker` rides the channel it hands over, so it closes then. The bridge ends when `unregisterSignal` aborts or the worker is gone (`terminate()`, a crash), the latter seen only for a worker running this version of `@fkn/lib` or a later one. Every socket the worker opened through FKN's relay is then closed there, one still opening included, and a worker that lives on has its FKN calls refused. A page relays one worker at a time: with two bridges open, every answer goes to both workers, and one carrying a stream, a promise or a port reaches only the worker relayed first. #### Parameters ##### worker `Worker` ##### options? ###### originA? `string` ###### originB? `string` ###### unregisterSignal? `AbortSignal` #### Returns `Promise`\<`void`\> ## References ### account Re-exports [account](/api/account/) *** ### AddScriptTagOptions Re-exports [AddScriptTagOptions](/api/extension/#addscripttagoptions) *** ### assertAttachableFrameUrl Re-exports [assertAttachableFrameUrl](/api/extension/#assertattachableframeurl) *** ### assertFetchableUrl Re-exports [assertFetchableUrl](/api/extension/#assertfetchableurl) *** ### AttachCookies Re-exports [AttachCookies](/api/extension/#attachcookies) *** ### AttachFrameOptions Re-exports [AttachFrameOptions](/api/extension/#attachframeoptions) *** ### AttachWindowOptions Re-exports [AttachWindowOptions](/api/extension/#attachwindowoptions) *** ### BACKGROUND\_STOPPED Re-exports [BACKGROUND_STOPPED](/api/extension/#background_stopped) *** ### BackgroundStoppedError Re-exports [BackgroundStoppedError](/api/extension/#backgroundstoppederror) *** ### BlankPage Re-exports [BlankPage](/api/extension/#blankpage) *** ### BrokerUnreachableError Re-exports [BrokerUnreachableError](/api/api/#brokerunreachableerror) *** ### ClearCookiesOptions Re-exports [ClearCookiesOptions](/api/extension/#clearcookiesoptions) *** ### cloud Re-exports [cloud](/api/cloud/) *** ### CloudPermissionRequest Re-exports [CloudPermissionRequest](/api/cloud/#cloudpermissionrequest) *** ### connectButtonUrl Re-exports [connectButtonUrl](/api/react/#connectbuttonurl) *** ### CookieDetails Re-exports [CookieDetails](/api/extension/#cookiedetails) *** ### cookies Re-exports [cookies](/api/extension/#cookies-3) *** ### desktop Re-exports [desktop](/api/desktop/) *** ### dgram Re-exports [dgram](/api/dgram/) *** ### dns Re-exports [dns](/api/dns/) *** ### extension Re-exports [extension](/api/extension/) *** ### EXTENSION\_ABI Re-exports [EXTENSION_ABI](/api/extension/#extension_abi) *** ### ExtensionHandshake Re-exports [ExtensionHandshake](/api/extension/#extensionhandshake) *** ### ExtensionOperationUnsupportedError Re-exports [ExtensionOperationUnsupportedError](/api/extension/#extensionoperationunsupportederror) *** ### ExtensionOutdatedError Re-exports [ExtensionOutdatedError](/api/extension/#extensionoutdatederror) *** ### FetchInit Re-exports [FetchInit](/api/extension/#fetchinit) *** ### FORGEABLE\_HEADERS Re-exports [FORGEABLE_HEADERS](/api/extension/#forgeable_headers) *** ### Frame Re-exports [Frame](/api/extension/#frame) *** ### FrameLocator Re-exports [FrameLocator](/api/extension/#framelocator) *** ### FrameWindowBlockedError Re-exports [FrameWindowBlockedError](/api/extension/#framewindowblockederror) *** ### FrameWindowOptions Re-exports [FrameWindowOptions](/api/extension/#framewindowoptions) *** ### FrameWindowRefusal Re-exports [FrameWindowRefusal](/api/extension/#framewindowrefusal) *** ### FrameWindowRefusedError Re-exports [FrameWindowRefusedError](/api/extension/#framewindowrefusederror) *** ### fs Re-exports [fs](/api/fs/) *** ### GotoOptions Re-exports [GotoOptions](/api/extension/#gotooptions) *** ### HeaderOperation Re-exports [HeaderOperation](/api/extension/#headeroperation) *** ### http Re-exports [http](/api/http/) *** ### isBackgroundStopped Re-exports [isBackgroundStopped](/api/extension/#isbackgroundstopped) *** ### isExtensionExposed Re-exports [isExtensionExposed](/api/extension/#isextensionexposed) *** ### isLocalNetworkUrl Re-exports [isLocalNetworkUrl](/api/extension/#islocalnetworkurl) *** ### isLocatorInvalid Re-exports [isLocatorInvalid](/api/extension/#islocatorinvalid) *** ### LOCATOR\_INVALID Re-exports [LOCATOR_INVALID](/api/extension/#locator_invalid) *** ### net Re-exports [net](/api/net/) *** ### opfs Re-exports [opfs](/api/opfs/) *** ### packages Re-exports [packages](/api/packages/) *** ### PermissionGrant Re-exports [PermissionGrant](/api/extension/#permissiongrant) *** ### PermissionRequest Re-exports [PermissionRequest](/api/extension/#permissionrequest) *** ### permissions Re-exports [permissions](/api/extension/#permissions-2) *** ### promptInstall Re-exports [promptInstall](/api/extension/#promptinstall) *** ### readExtensionHandshake Re-exports [readExtensionHandshake](/api/extension/#readextensionhandshake) *** ### RELAY\_UNAVAILABLE Re-exports [RELAY_UNAVAILABLE](/api/contract/#relay_unavailable) *** ### RemoteVideoElement Re-exports [RemoteVideoElement](/api/extension/#remotevideoelement) *** ### removeRequestHeaderRule Re-exports [removeRequestHeaderRule](/api/extension/#removerequestheaderrule) *** ### RequestHeaderRule Re-exports [RequestHeaderRule](/api/extension/#requestheaderrule) *** ### REQUIRED\_EXTENSION\_ABI Re-exports [REQUIRED_EXTENSION_ABI](/api/extension/#required_extension_abi) *** ### rooms Re-exports [rooms](/api/rooms/) *** ### setMissingExtensionHandler Re-exports [setMissingExtensionHandler](/api/extension/#setmissingextensionhandler) *** ### setRequestHeaderRule Re-exports [setRequestHeaderRule](/api/extension/#setrequestheaderrule) *** ### SiteCookie Re-exports [SiteCookie](/api/extension/#sitecookie) *** ### storage Re-exports [storage](/api/storage/) *** ### StorageState Re-exports [StorageState](/api/extension/#storagestate-2) *** ### StorageStateCookie Re-exports [StorageStateCookie](/api/extension/#storagestatecookie) *** ### supportsOperation Re-exports [supportsOperation](/api/extension/#supportsoperation) *** ### TimeoutError Re-exports [TimeoutError](/api/extension/#timeouterror) *** ### waitForExtensionExposure Re-exports [waitForExtensionExposure](/api/extension/#waitforextensionexposure) *** ### WindowFrame Re-exports [WindowFrame](/api/extension/#windowframe) --- # network (namespace of @fkn/lib) URL: https://docs.fkn.dev/api/namespaces/network/ ## Functions ### request() ```ts function request(hosts): Promise; ``` Asks the person, with one card from fkn.app, to let this app reach `hosts`: host names, `*.name`, or `""` for any site. True once every one is allowed, and from a broker that applies no network rule; false on Not now, for a list off the grammar, or where fkn.app cannot show a card. A `fetch()` or asynchronous `XMLHttpRequest` uses the answer at once; images, styles, frames and sockets from the app's next load. #### Parameters ##### hosts `string`[] #### Returns `Promise`\<`boolean`\> --- # shell (namespace of @fkn/lib) URL: https://docs.fkn.dev/api/namespaces/shell/ ## Functions ### applyUpdate() ```ts function applyUpdate(): Promise; ``` Apply a ready update by reloading the FKN frame this page mounted. Resolves true when the reload was taken, false when there is nothing to apply or this caller does not own the frame. Nothing calls this on the app's behalf. The broker's own header offers the same action to the user; this is the app's way to offer it on its own terms, or to take it at a moment it knows is safe. Check `busyReasons()` first if the app has no better signal of its own. #### Returns `Promise`\<`boolean`\> *** ### busyReasons() ```ts function busyReasons(): string[]; ``` What a shell reload would sever right now, as human-readable reasons, empty when nothing is bound to the broker connection: open sockets and listening servers, a streaming proxy response, a mounted package, a live frame attachment, unflushed write-behind. Empty is not a promise that a reload is free, only that this realm holds nothing the lib knows about. It is per REALM: a worker that imports `@fkn/lib/net` keeps its own tally, which the window cannot see. An app whose transfers live in a worker should ask the worker, not the page. #### Returns `string`[] *** ### isAppTab() ```ts function isAppTab(): Promise; ``` Whether this page is the app fkn.app shows as its tab's own page: the frame fkn.app's `/app/` page mounted for this app, still holding a document of the origin it mounted there, with that `/app` page the tab's top page. So no other app placed this page. A link to `fkn.app/app/` opened in a tab or a window reaches it, and so do a reload and the app's own navigations. False everywhere else: on the app's own site, in a window of its own, in a frame another app or site placed (a package another app connects, shows or mounts, or a frame sent to this app's address), in this app's own child frames, under an `/app` page that is itself framed, when fkn.app does not answer within the lib's broker deadline, and on an fkn.app that predates this answer. It never rejects. It says which window this is, never who chose its address: whatever navigates the whole tab chooses the app it shows. Nor does it say nothing is drawn over the page: a package this app's own plugins connect can be shown over it, as on the app's own site. The answer does not change while the document lives. #### Returns `Promise`\<`boolean`\> *** ### onUpdate() ```ts function onUpdate(callback): Promise<() => void>; ``` Subscribe to "a newer FKN shell is ready". Fires immediately when an update is already waiting at subscribe time, so a late subscriber misses nothing. Returns an unsubscribe that stays valid across broker replacements. #### Parameters ##### callback () => `void` #### Returns `Promise`\<() => `void`\> *** ### onUpdateTaken() ```ts function onUpdateTaken(handler): () => void; ``` Handle "the FKN shell was just updated", which arrives in EVERY open page, not only the one where the person pressed the button. Activating a new shell claims every client on the origin, so each page's broker frame learns about it and tells its app. The default, with no handler registered, is to RELOAD THIS PAGE. That is deliberate: after an update every tab is running the new worker against a document from the old build, and the only way out of that mix is a reload. Doing it for the whole browser at once is what a person means when they press update. Registering a handler REPLACES that default, and then reloading is entirely the app's business. That is the escape hatch for an app that cannot be interrupted: ```ts shell.onUpdateTaken(() => { if (downloads.idle()) location.reload() else banner.show('FKN updated. Reload when you are ready.') }) ``` Unsubscribing restores the default. Note the difference from `onUpdate`, which fires when an update is merely READY and nothing has happened yet. #### Parameters ##### handler () => `void` #### Returns () => `void` *** ### showHeader() ```ts function showHeader(): Promise; ``` Reveal the FKN header bar on this page, as hovering the top edge does. Resolves true when a header is shown for this page, false when this realm has no FKN header (a worker, a nested package frame, a page whose broker is unreachable or predates this call, or while an FKN card is open). It never rejects. #### Returns `Promise`\<`boolean`\> *** ### updateReady() ```ts function updateReady(): Promise; ``` Whether a newer FKN shell is downloaded and ready to apply. #### Returns `Promise`\<`boolean`\> --- # @fkn/lib/account URL: https://docs.fkn.dev/api/account/ ## Type Aliases ### AccountInfo ```ts type AccountInfo = object; ``` #### Properties ##### image ```ts image: string | null; ``` profile image URL, or null if none is set ##### name ```ts name: string; ``` the account's display name (a username, not necessarily a real name) ##### premium ```ts premium: boolean; ``` the account has an active paid subscription ##### premiumUntil ```ts premiumUntil: number | null; ``` when the current subscription lapses, as a ms epoch, or null when not subscribed ## Functions ### info() ```ts function info(): Promise; ``` #### Returns `Promise`\<[`AccountInfo`](#accountinfo) \| `null`\> *** ### login() ```ts function login(): Promise; ``` #### Returns `Promise`\<`boolean`\> *** ### logout() ```ts function logout(): Promise; ``` #### Returns `Promise`\<`void`\> *** ### onChange() ```ts function onChange(callback): Promise<() => void>; ``` Calls `callback` whenever the account this page acts as may have changed (a switch, a sign-in or a sign-out, in this tab or another), and when the connection is renewed without one. Works in a window and in a worker bridged with `relayWorker`; resolves to a no-op where there is no FKN transport at all. `change.switched` says which. True: this page may now act as another account, or as none, so drop what the old account put in memory (its lists, any open work) and read again; a storage call made before this callback never lands in the new account (it is refused with `StorageAccountChangedError`). It is also true when fkn.app is too old to tell (before 2026-10-02) and when the library moved on its own after a refusal, so treating true as a switch is always safe. False: fkn.app saw the same account. Its connect token was renewed, or an app in this browser signed in or out of FKN on its own, this one included, so read `info()` again to learn whether this page is still signed in. Calls made before it still land. A switch fkn.app could not see, because its document was replaced in between, reaches you as true once a storage call is refused for it. Storage moves to the new account BEFORE any callback runs. Work the app started before a switch and resumes after it is the app's to check: keep a counter this callback bumps when `switched` is true, and compare it synchronously right before the storage call, which captures the account in the same synchronous step, so the check and the call are atomic. #### Parameters ##### callback (`change`) => `void` #### Returns `Promise`\<() => `void`\> ## References ### AccountChange Re-exports [AccountChange](/api/contract/#accountchange) --- # @fkn/lib/extension URL: https://docs.fkn.dev/api/extension/ ## Classes ### ExtensionOperationUnsupportedError Thrown when the extension is current but does not serve the operation being asked for. `message` replaces the default advice where updating the extension cannot help. #### Extends - `Error` #### Constructors ##### Constructor ```ts new ExtensionOperationUnsupportedError( operation, abi, message?): ExtensionOperationUnsupportedError; ``` ###### Parameters ###### operation `string` ###### abi `number` ###### message? `string` ###### Returns [`ExtensionOperationUnsupportedError`](#extensionoperationunsupportederror) ###### Overrides ```ts Error.constructor ``` #### Properties ##### abi ```ts readonly abi: number; ``` ##### name ```ts readonly name: "ExtensionOperationUnsupportedError" = "ExtensionOperationUnsupportedError"; ``` ###### Overrides ```ts Error.name ``` ##### operation ```ts readonly operation: string; ``` *** ### ExtensionOutdatedError Thrown instead of the generic "not installed" message when the extension is installed but too old. Carries both numbers so an app can say which and link its listing. Match it by `name`, which survives a structured-clone hop. #### Extends - `Error` #### Constructors ##### Constructor ```ts new ExtensionOutdatedError(abi, required): ExtensionOutdatedError; ``` ###### Parameters ###### abi `number` ###### required `number` ###### Returns [`ExtensionOutdatedError`](#extensionoutdatederror) ###### Overrides ```ts Error.constructor ``` #### Properties ##### abi ```ts readonly abi: number; ``` ##### name ```ts readonly name: "ExtensionOutdatedError" = "ExtensionOutdatedError"; ``` ###### Overrides ```ts Error.name ``` ##### required ```ts readonly required: number; ``` *** ### FrameWindowBlockedError `window.open` returned null, so nothing was opened: the call ran without user activation, the popup blocker refused it, or the calling frame is sandboxed without `allow-popups`. #### Extends - `Error` #### Constructors ##### Constructor ```ts new FrameWindowBlockedError(): FrameWindowBlockedError; ``` ###### Returns [`FrameWindowBlockedError`](#framewindowblockederror) ###### Overrides ```ts Error.constructor ``` #### Properties ##### name ```ts readonly name: "FrameWindowBlockedError" = "FrameWindowBlockedError"; ``` ###### Overrides ```ts Error.name ``` *** ### FrameWindowRefusedError The window refused to attach, by `reason`, after loading nothing. #### Extends - `Error` #### Constructors ##### Constructor ```ts new FrameWindowRefusedError(reason): FrameWindowRefusedError; ``` `reason` is what the window said; anything this library does not know becomes `'unknown'`. ###### Parameters ###### reason `unknown` ###### Returns [`FrameWindowRefusedError`](#framewindowrefusederror) ###### Overrides ```ts Error.constructor ``` #### Properties ##### name ```ts readonly name: "FrameWindowRefusedError" = "FrameWindowRefusedError"; ``` ###### Overrides ```ts Error.name ``` ##### reason ```ts readonly reason: FrameWindowRefusal; ``` *** ### TimeoutError A call that ran out of time: its deadline passed before it settled. One class for every call that has a deadline, as Playwright's `TimeoutError`, named `'TimeoutError'` so a check by name works as well as `instanceof`. It is minted where the call was made, never in the realm that ran it, so it is an instance of this class in the caller's realm. `message` is what the call reported at its deadline, unchanged from the error it replaces. `cause` is the last retryable error an attempt met before the deadline, so a locator call that never found its element says why; it is absent when no attempt failed (one never settled, or the call is not retried). Not terminal: nothing retries a call past its own deadline. #### Extends - `Error` #### Constructors ##### Constructor ```ts new TimeoutError(message, options?): TimeoutError; ``` ###### Parameters ###### message `string` ###### options? ###### cause? `unknown` ###### Returns [`TimeoutError`](#timeouterror) ###### Overrides ```ts Error.constructor ``` #### Properties ##### name ```ts readonly name: "TimeoutError" = "TimeoutError"; ``` ###### Overrides ```ts Error.name ``` ## Type Aliases ### AddScriptTagOptions ```ts type AddScriptTagOptions = object; ``` `frame.addScriptTag`'s options, Playwright's `content` and FKN's `sourceUrl`. #### Properties ##### content ```ts content: string; ``` The script's source text. ##### sourceUrl? ```ts optional sourceUrl?: string; ``` Names the script in stack traces through `//# sourceURL`. Absent, its frames name the document. *** ### AttachCookies ```ts type AttachCookies = "persistent" | "ephemeral" | "native"; ``` Which cookie jar an attachment runs on, and with it which backend serves it. One attachment, one jar: no value unions two jars, so which cookie a request carries always has one answer. HttpOnly values never reach app code on any value. - `'persistent'`, the default: the cloud render proxy's jar of the app's top-level site (https://fkn.app for every fkn.app app), which every app of that site shares, the same jar its inline frames and its windows use, kept across visits on this device, signed in to FKN or not. It is written sealed under a key the render proxy generates for that site's jar and keeps beside it on the device, so no cookie of it is on disk in the clear, while a copy of the device's files holds what opens it. Where an earlier build kept that jar in the clear, Chrome can keep the old text in its files for a time after the seal. Always the cloud backend, whatever is installed, so `frame.backend()` answers `'cloud'`. Its requests leave through WebVPN, which keeps the cookies their answers set. - `'ephemeral'`: a fresh jar of the attachment's own, with site storage under a namespace of its own, both gone with it, seeded from `storageState` when one is given. Always the cloud backend: the browser keeps a partition's cookies after its frame goes, so no extension jar ends with the attachment. Its requests leave through WebVPN. - `'native'`: the person's own browser cookies for `domains` and every goto's host, copied into the browser's partition for the app's top-level site on the attach and on every goto. Extension backend only, so `frame.backend()` answers `'extension'`. Without the extension the top-level `attachFrame` shows the install prompt, as every extension-only call does; `cloud.attachFrame` refuses it. Refused by name before anything is attached, opened, waited for or dispatched, in this order: - any `syncCookies` key, true and false alike: TypeError `attachFrame: syncCookies was replaced by cookies. true is cookies: 'persistent', or 'native' for the person's own browser cookies on the extension; false is cookies: 'ephemeral'` - an unknown value: TypeError `attachFrame: cookies must be 'persistent', 'ephemeral' or 'native', not ""` - a `storageState` beside anything but `'ephemeral'`, the default included: TypeError `attachFrame: storageState seeds a fresh jar, so it needs cookies: 'ephemeral'` - a malformed `storageState`: TypeError `attachFrame: storageState. `, for the first field of another shape in the order the state lists them (`StorageState`) - a cookie whose `expires` is above 0 and below 100000000000: TypeError `attachFrame: storageState.cookies[].expires is milliseconds since the epoch, and reads as a date before 1974; a Playwright storageState gives seconds, so multiply it by 1000` - then the shape of the attachment: `iframe` and `window` at once, and `lockdown` or `blank` with a window, each a TypeError - `lockdown` with anything but `'native'`: TypeError `attachFrame: lockdown runs on the extension, which serves only cookies: 'native'` - a `permissions` entry whose `reason` is over `MAX_REASON_LENGTH` characters: TypeError `attachFrame: reason must be at most 100 characters, not ` - `cloud.attachFrame` with `'native'`: TypeError `cloud.attachFrame: cookies: 'native' needs the FKN browser extension; the cloud render proxy has no browser cookies` - `extension.attachFrame` with `'persistent'` or `'ephemeral'`, so also with no `cookies` at all: `ExtensionOperationUnsupportedError` (operation `'cookies'`) `attachFrame: cookies: '' runs on the cloud render proxy; call cloud.attachFrame or the top-level attachFrame` - a window on `'native'`, through the top-level `attachFrame` or `extension.attachFrame`, when the extension does not announce `attachWindow` (one before ABI 5): `ExtensionOperationUnsupportedError` (operation `'attachWindow'`) with the advice to update it, and with no extension on the page at all `attachFrame: a window on cookies: 'native' needs the FKN WebExtension, which is not on this page`. Neither waits or shows the install prompt, so the click's activation is left for the app's fallback. *** ### AttachFrameOptions ```ts type AttachFrameOptions = object; ``` #### Properties ##### blank? ```ts optional blank?: BlankPage; ``` Starts the frame on an empty page presented at `blank.url`, with nothing requested from that site for it. For running the app's own code (an attestation VM, a session client) in the origin it needs, without loading or running the site's page. The document is exactly ``, served 200 with `content-type: text/html; charset=utf-8` and `cache-control: no-store`: no content security policy, no Set-Cookie. Its `location`, `origin`, `document.URL`, `document.domain` and `baseURI` read `blank.url`, and `document.referrer` reads `''` on the first load (after a reload it reads the page's own url, as on any proxied page). `url()` returns it. `evaluate`, `postMessage` and the `message` and `document` events work as on any page. Requests the page's code makes later go out as that page's would, through WebVPN, on the attachment's jar: with `cookies: 'persistent'`, the default, the cloud jar of the app's top-level site, which every app of that site shares (HttpOnly values are never readable in the page); with `'ephemeral'` a jar of the attachment's own, and site storage under a namespace of its own, both gone with it. With `cookies: 'ephemeral'` nothing of the user's is reachable, so calls the Evaluation grant covers ask no card while the frame shows the empty page: until the attachment's first `goto`, or until code in the page moves it to another url, even on the same host, after which they ask as on any page. With `'persistent'` the Evaluation card names the url's host, as for any page. The empty page answers its url until the first `goto`: a reload of the page, or a replacement of the render proxy's own document, brings it back and fires `document`, so an installer must be idempotent. After the first `goto` the url loads from the site like any other. Always the cloud render proxy, with or without the extension: only it can present an origin without loading it. `frame.backend()` then answers `'cloud'`, and the jar is the cloud's, never the browser's. Refused, in this order, before anything is attached, and after the refusals of `cookies` (`AttachCookies`), so through `cloud.attachFrame` lockdown and `'native'` meet those first: - TypeError `attachFrame: blank must be an object { url }` (null, a string) - TypeError `attachFrame: blank takes { url }, not ""` (an unknown key) - TypeError `attachFrame: blank.url must be an absolute http or https url, not ""` - TypeError `attachFrame: blank needs an iframe with no src; this one has ""` - TypeError `attachFrame: blank does not combine with lockdown` - TypeError `attachFrame: blank runs on the cloud render proxy, which has no browser cookies; pass cookies: 'persistent' or 'ephemeral'` (with `cookies: 'native'`) - Error `attachFrame: refusing to target the extension's own pages or an FKN platform origin`, the scope check every attach url meets - Error `attachFrame: a blank page is served by the cloud render proxy, which this build does not configure` After the handshake, with the iframe put back on about:blank and nothing requested from the site: the terminal `LocatorUnsupportedError` `cloud.attachFrame: this FKN page predates blank pages; reload the app to load the current one`. The handshake and ready limits are every cloud attach's, 20000 ms and 65000 ms. Also refused, before anything opens or is dispatched: with `window`, the TypeError `attachFrame: blank does not apply to a window`, since a window opened with no `url` is already called blank there; and through `extension.attachFrame` with `cookies: 'native'`, `ExtensionOperationUnsupportedError` (operation `'blank'`) `attachFrame: a blank page is served by the cloud render proxy only; call cloud.attachFrame`. ##### cookies? ```ts optional cookies?: AttachCookies; ``` Which jar, and with it which backend: `'persistent'` when absent. See `AttachCookies`. ##### domains? ```ts optional domains?: string[]; ``` ##### iframe ```ts iframe: HTMLIFrameElement; ``` ##### lockdown? ```ts optional lockdown?: boolean; ``` Replace the embedded site's CSP with a lockdown policy: the frame cannot fetch, connect, or load any resource. Extension backend only, so it takes `cookies: 'native'`; beside any other value it is a TypeError (see `AttachCookies`). It needs an extension that announces an ABI: an older one may not serve it, so the attach is refused with `ExtensionOperationUnsupportedError` (operation `'lockdown'`) before anything is attached. ##### onClose? ```ts optional onClose?: () => void; ``` Called once when the attachment ended because FKN's own frame in this page was replaced, as an FKN update does: the page inside reaches the network through that frame, so it can load nothing more, and every later call on the `Frame` is refused with an error starting `FKN: the broker was replaced`. Attach again from here. Passing it also tells FKN the app does so by itself, which lets FKN replace its frame while the attachment is up; without it FKN waits for the page to reload. Cloud render proxy only: on the extension, which does not go through that frame, it is never called. ###### Returns `void` ##### permissions? ```ts optional permissions?: CategoryRequest[]; ``` Whole categories to ask for on one sheet or card right after the attach, before it resolves. A refusal does not reject the attach: it surfaces on the first refused operation. A `reason` over `MAX_REASON_LENGTH` characters is a TypeError before anything is attached (`AttachCookies`). ##### relay? ```ts optional relay?: RelayChoice; ``` The relays the attachment may go through on the cloud render proxy (`RelayChoice`), resolved to one at attach and kept for the attachment's life; `relayOf(frame)` names it. Without it the frame follows the app's default relay. Ignored on the extension, as `cookies: 'native'` has no relay. ##### storageState? ```ts optional storageState?: StorageState; ``` Seeds an `'ephemeral'` jar before the attachment's first document; with any other value a TypeError. See `StorageState`. *** ### AttachWindowOptions ```ts type AttachWindowOptions = object; ``` `attachFrame`'s options when the attachment is a new window rather than an iframe. Call `attachFrame` directly in the click or key handler: the window opens before the first await, with the activation of that event, and the browser's popup rules apply to it as to any page's own `window.open`. `iframe` and `lockdown` do not apply to a window, and passing either is a TypeError. #### Properties ##### cookies? ```ts optional cookies?: AttachCookies; ``` The window's jar, with an iframe's values (`AttachCookies`). `'persistent'`, the default: the jar of the app that opened it, the same as that app's inline frames; a window whose app is on another site shares cookies only with those frames, and its site storage stays its own. `'ephemeral'`: a jar of the window's own that ends with it, seeded from `storageState`. Both run on the cloud backend whatever is installed. `'native'`: a real browser window on the extension, on the person's own browser session for every site it shows, as a window they opened themselves would be (`WindowFrame` says what differs there). ##### domains? ```ts optional domains?: string[]; ``` ##### permissions? ```ts optional permissions?: CategoryRequest[]; ``` Whole categories asked for once the window has connected: the card is drawn in the window on the cloud backend, and the sheet on the app's page on the extension, as every extension sheet is. A `reason` over `MAX_REASON_LENGTH` characters is a TypeError before the window opens. ##### relay? ```ts optional relay?: RelayChoice; ``` The relays the attachment may go through on the cloud render proxy (`RelayChoice`), resolved to one at attach and kept for the attachment's life; `relayOf(frame)` names it. Without it the frame follows the app's default relay. Ignored on the extension, as `cookies: 'native'` has no relay. ##### storageState? ```ts optional storageState?: StorageState; ``` As for an iframe: only with `'ephemeral'`. The window opens at once, with the click's activation, and goes to `window.url` once the seed is in place. ##### window ```ts window: FrameWindowOptions; ``` *** ### BackgroundStoppedError ```ts type BackgroundStoppedError = Error & object; ``` What a call into the extension rejects with when Chrome stopped the extension's worker before it finished answering: before the call resolved, or, for a `fetch`, while its response body was still arriving. The call may or may not have run, so it is never resent; a retry by the app reaches the restarted worker. #### Type Declaration ##### name ```ts name: typeof BACKGROUND_STOPPED; ``` *** ### BlankPage ```ts type BlankPage = object; ``` Where `attachFrame`'s `blank` option presents its empty page. #### Properties ##### url ```ts url: string; ``` Absolute http or https url the empty page is presented at. The fragment is ignored for matching. *** ### ClearCookiesOptions ```ts type ClearCookiesOptions = object; ``` `frame.clearCookies`' options, Playwright's `browserContext.clearCookies` names with its string semantics: each matches exactly. A cookie is removed when it matches every option given; an option left out, or `undefined`, matches every cookie. Playwright also takes a RegExp for each, which FKN refuses for now (`Frame.clearCookies` says why). #### Properties ##### domain? ```ts optional domain?: string; ``` Only cookies with this domain, in the form Playwright reports it: `.youtube.com` for a cookie its subdomains also receive, `www.youtube.com` for a host-only one, so `'youtube.com'` matches neither of those. It must be on a site this attachment reaches. ##### name? ```ts optional name?: string; ``` Only cookies with this name. ##### path? ```ts optional path?: string; ``` Only cookies with this path, exactly as the cookie carries it. *** ### CookieDetails ```ts type CookieDetails = object; ``` #### Properties ##### name ```ts name: string; ``` ##### url ```ts url: string; ``` *** ### Executor ```ts type Executor = object; ``` #### Properties ##### execute ```ts execute: (parts, operation, args, context?) => Promise; ``` Runs `operation` on what `parts` resolve to, in whichever realm the chain lands in. `context` is an opaque per-call value for the host: frame-locator never reads it, and carries it unchanged through every pivot and across the window bridge, so each executor the call passes through hands it to its own `assertRealm` (see `ExecutorOptions`). It crosses a window by structured clone, so it must be cloneable. A chain built with `createFrameLocator` never sends one; only a caller holding the executor itself can. ###### Parameters ###### parts [`SelectorPart`](#selectorpart)[] ###### operation `string` ###### args `unknown`[] ###### context? `unknown` ###### Returns `Promise`\<`unknown`\> ##### highlight ```ts highlight: (parts, on) => Promise; ``` ###### Parameters ###### parts [`SelectorPart`](#selectorpart)[] ###### on `boolean` ###### Returns `Promise`\<`void`\> ##### stale? ```ts optional stale?: Promise; ``` *** ### ExtensionHandshake ```ts type ExtensionHandshake = | { status: "absent"; } | { abi: number; operations: readonly string[] | null; status: "ok"; } | { abi: number; operations: readonly string[] | null; required: number; status: "outdated"; }; ``` `operations` is `null` when the extension announced no list, which is not the same as an empty one: a pre-versioning extension supports the whole original surface and cannot say so, so `null` reads as "assume the original set", never "supports nothing". *** ### FetchInit ```ts type FetchInit = RequestInit & object; ``` #### Type Declaration ##### reason? ```ts optional reason?: string; ``` The app's sentence for the prompt a credentialed or local network fetch raises, at most `MAX_REASON_LENGTH` (100) characters. *** ### Frame ```ts type Frame = Omit & object; ``` An attached frame. What it promises across navigations is the same on both backends. A Frame follows its FRAME, not a document. The page in it may move itself (a link, a form, a redirect, a script), and every call runs against the document the frame holds when the call arrives. A call made while the next document commits waits for it, within the call's own timeout. It reads a document only while that document's host is inside the attachment: the attach url's host, each `goto` target's host, and `domains`, each matched exactly. A document on any other host is refused with a `LocatorDeniedError` ("frame: this frame no longer holds the document the app attached it to"), which names nothing about where the frame went. The Frame stays attached, and answers again once the frame is back inside, by the page's own move or by a `goto`. What belongs to a document ends with it. A style `addStyleTag` added is gone after a navigation. A `videoElement` handle from a document that left rejects every call that answers (`play`, the picture-in-picture calls), and its fire-and-forget ones (`pause`, `load`, the setters) do nothing. On the cloud backend an `evaluate` whose document leaves before it settles rejects, and is not run again. Not followed: a navigation the page aims out of its frame (a link or a form targeting the top window or a new one, a popup). A document with nothing of the page's own to run it in, such as an error page or a file that is not HTML, cannot be read, and a call on it waits to its deadline. #### Type Declaration ##### addScriptTag() ```ts addScriptTag(options): Promise; ``` Runs `content` as a classic inline script of the attached document, as one of that page's own scripts would run: its top-level declarations stay on the page's global for later scripts and `evaluate` calls, `document.currentScript` is the script while it runs, and the page's own error listeners see its top-level error. Mirage rewrites it as it rewrites the page's scripts, and the page's eval refusal and Trusted Types requirement do not refuse it, as for `evaluate`. Playwright's name and its `content` option; its `url`, `path` and `type` are not served, and FKN's `sourceUrl` names the script rather than loading one. Resolves `undefined` once the script ran; what it installed lives as long as the document, and the `document` event says when that is gone. Same grant, limit and timing as `evaluate`: the Evaluation grant (one card covers both), 30000 ms counted after any consent card, the attached frame only, and after a `goto` the document that goto brought, waited for as `evaluate` waits. It runs once: it never rides the locator retry loop, and a call whose document left before it answered rejects and is not run again. Cloud only for now: the extension refuses it by name. Refused: - TypeError, before anything is sent, in this order: `frame.addScriptTag: options must be an object { content }`; for Playwright's `url`, `path` and `type`, `frame.addScriptTag: "" is not served; it runs content as a classic inline script`; `frame.addScriptTag: unknown option ""`; `frame.addScriptTag: content must be a string`; `frame.addScriptTag: sourceUrl must be a non-empty string with no line break`. - an `Error` carrying the page's own name and message: the script's top-level throw, after it ran. - `LocatorDeniedError`: no Evaluation grant, the frame holds no page, or its document is outside the attachment. Against an FKN page that predates `addScriptTag` the call arrives with no proof of a grant and the render proxy refuses it: `frame.addScriptTag: the call arrived without an Evaluation grant, so it was not run`. - cloud, `LocatorUnsupportedError` `frame.addScriptTag: this render proxy predates addScriptTag; reload the app`. - cloud, `LocatorError`: the document of the goto before it had not come by that goto's deadline, or the app started another goto first, so the script was not run. - extension, `ExtensionOperationUnsupportedError` (operation `'addScriptTag'`) `frame.addScriptTag: an extension frame does not run scripts through mirage yet; attach with cloud.attachFrame`, before anything is dispatched. - `TimeoutError` `frame.addScriptTag: no answer within 30000ms; the script may or may not have run`. - the terminal detach error once the attachment ended. ###### Parameters ###### options [`AddScriptTagOptions`](#addscripttagoptions) ###### Returns `Promise`\<`void`\> ##### backend() ```ts backend(): "cloud" | "extension" | undefined; ``` Which backend serves this attachment, fixed for its life. The same call can draw a card on one backend and not the other, and spends a different identity on each, so an app must be able to tell. Undefined only for a Frame an app built itself with `createFrame` from a backend that names none. ###### Returns `"cloud"` \| `"extension"` \| `undefined` ##### clearCookies() ```ts clearCookies(options?): Promise; ``` Removes cookies from this attachment's cookie jar, as Playwright's `browserContext.clearCookies` removes them from a context. With no options it removes every cookie of the sites this attachment reaches; with options, only the ones that match every option given (`ClearCookiesOptions`). Each option is a string for now: a RegExp is refused. For signing out of a site the user signed in to inside an FKN frame: that session lives in FKN's jar, never in the app, so the app cannot remove it any other way. Which jar: with `cookies: 'persistent'`, the default, the cloud jar of the app's top-level site, which every app of that site shares (every fkn.app app shares one), so a removal there signs every one of those apps out of that site. With `'ephemeral'` the attachment's own jar. Which cookies: only those of a site this attachment reaches, a site being a host's registered domain under the Public Suffix List, private section included: the attach url's host (the empty page's, for `blank`), each goto target's host from the goto's send, and `domains`. `www.youtube.com` reaches every `*.youtube.com` cookie and no `google.com` one, the rule browsers follow for `Clear-Site-Data: "cookies"`. A host under the same name is still another site when a suffix lies between: `amazonaws.com` reaches no `mybucket.s3.amazonaws.com` cookie, since `s3.amazonaws.com` is a suffix. A host that is itself a public suffix (`com`, `co.uk`, `github.io`) is no site, and reaches only the cookies set for exactly that host. A Partitioned cookie matches in every partition. Once it resolves: no request a document of this attachment starts carries a removed cookie, its documents' `document.cookie` lists none, and the removal is committed to the jar, so an attachment created afterwards never sees one. Another live attachment on the same jar (another tab, another app's frame) drops them when it hears the commit, normally within milliseconds; a request it started before then may still carry one. A request already in flight keeps what it was sent with, and a later response may set cookies again, as in any browser. It resolves `undefined` and never says what or how much it removed, so it cannot tell an app whether the user had a session on a site. It takes the same steps and the same store write whether or not a cookie matched, so neither how long it takes nor which refusal it meets says so either. That is why a RegExp is refused before anything is sent: it would be tested in the render proxy against cookies the app cannot read, and a pattern slow on some of them would make the call's duration, or a `TimeoutError`, say whether the jar holds one. Calling it again is harmless. It does not tell the site: the session stays valid there until it lapses, and FKN no longer holds it. No consent card on either jar, and a frame holding no page is served. Cloud only. It runs once, never inside the locator retry loop, and waits at most 30000 ms. Refused: - TypeError, before anything is sent, in this order: `frame.clearCookies: options must be an object`; `frame.clearCookies: unknown option ""`; `frame.clearCookies: is a RegExp, and clearCookies takes strings for name, domain and path for now`; `frame.clearCookies: must be a string`; `frame.clearCookies: must not be empty; leave it out to match every `. - `LocatorDeniedError` `frame.clearCookies: this attachment reaches no site yet; attach a url, goto one, or declare it in domains`. - `LocatorDeniedError` `frame.clearCookies: is not on a site this attachment reaches; goto it or declare it in domains`, for a string `domain`. - cloud, `LocatorUnsupportedError` `frame.clearCookies: this FKN page predates clearCookies; reload the app to load the current one`, with nothing sent. - cloud, `LocatorUnsupportedError` `frame.clearCookies: this render proxy predates clearCookies; reload the app`. - cloud, `Error` `frame.clearCookies: the cookies are gone from this attachment, but its jar did not take the removal, so other attachments may still send them; call it again`. - cloud, `TimeoutError` `frame.clearCookies: the render proxy did not answer within 30000ms; the cookies may or may not be gone, and calling it again is safe`. - extension, `ExtensionOperationUnsupportedError` (operation `'clearCookies'`) `frame.clearCookies: an extension frame runs on the browser's own cookies (cookies: 'native'), which FKN does not clear; attach with cookies: 'persistent' to clear the app's jar`, before anything is dispatched. - the terminal detach error once the attachment ended. ###### Parameters ###### options? [`ClearCookiesOptions`](#clearcookiesoptions) ###### Returns `Promise`\<`void`\> ##### evaluate() ```ts evaluate(pageFunction, arg?): Promise>; ``` Runs `pageFunction` inside the attached site's OWN page realm, as a script of that page would: it sees the site's `window`, its globals and its DOM. The function is sent as source (`Function.prototype.toString`), so it captures NOTHING from the caller's scope; everything it needs must come through `arg`. A plain source string is run as an expression, the way Playwright does, and is not called. A promise, returned by the function or produced by the expression, is awaited. `arg` is structured-cloned at the call, in the app's realm, on both backends, and the result comes back by structured clone, so an `ArrayBuffer` or a typed array of bytes survives the round trip. A value structured clone refuses in `arg` (a function, a DOM node, an untransferred port) rejects with the platform's `DataCloneError` before anything is sent; a port goes to the page with `postMessage`. A thrown error or a rejected promise comes back as an `Error` carrying the page's own name and message. A result that cannot be cloned (a function, a DOM node) is a `LocatorInvalidError`, never a silent `undefined` and never a live handle into the page. Every limit is refused by name, never a call left pending: - time, both backends: the code has 30 seconds to settle, counted after any consent card, and then the call rejects with `TimeoutError`. Only the wait ends there; code that never settles keeps running in the page. - size, extension only, a `LocatorInvalidError`: the source with its `arg`, and the result, each carry at most 32 MiB (binary data by its bytes, text by its UTF-8 size), the most its message relay carries. - `Blob`, extension only, a `LocatorInvalidError`: the relay cannot carry one, so pass or return `await blob.arrayBuffer()`. The cloud backend has neither limit, and returns a `Blob` as a `Blob`. Needs the Evaluation grant on both backends; an app without it is refused by name. It runs on the attached frame only: a nested `FrameLocator` does not offer it, and a call there anyway is refused. Called after `goto` resolved, whichever `waitUntil`, it runs once on the document that goto brought, never on the one it replaced. On the cloud backend the call waits for that document when it has not committed yet, and the wait counts toward the 30 seconds; if it has not come by the goto's own deadline (the goto failed, or loaded something that is not a page), or the app started another goto first, the call rejects with a `LocatorError` saying the code was not run. On the extension it also needs an extension new enough to run code (ABI 3, older ones are refused with `ExtensionOperationUnsupportedError`), and it runs where the page's content security policy allows it: a frame whose host the app declared has its CSP replaced, so code runs; an undeclared frame, and every attached window, keeps its CSP, and a page that forbids `eval` refuses with a named error. On the cloud backend the code runs in the proxied document's realm, which mirage virtualizes: the page's own eval refusal and Trusted Types requirement do not refuse the source `evaluate` compiles, and every string that code compiles itself (`eval`, `Function`, a string timer) is held to them, as the page's own are. ###### Type Parameters ###### R `R` = `unknown` ###### A `A` = `undefined` ###### Parameters ###### pageFunction `string` \| ((`arg`) => `R` \| `Promise`\<`R`\>) ###### arg? `A` ###### Returns `Promise`\<`Awaited`\<`R`\>\> ##### flushCookies() ```ts flushCookies(): Promise; ``` Resolves once every cookie change made in this attachment so far is committed to its jar, so an inline frame torn down right after leaves nothing unsaved. Never gated: asks for no grant, draws no card, and works even before any document is loaded. On the extension (`cookies: 'native'`) browser cookies are written synchronously/eagerly, so this resolves at once (or rejects with the terminal closed error on a closed extension window). Refuses: - cloud, `LocatorUnsupportedError` `frame.flushCookies: this FKN page predates flushCookies; reload the app to load the current one`, when the middle page predates it. - cloud, `LocatorUnsupportedError` `frame.flushCookies: this render proxy predates flushCookies; reload the app`, when the shell predates it. - cloud, `TimeoutError` `frame.flushCookies: the render proxy did not answer within 10000ms; the cookies may not be committed yet`. - cloud, the terminal detach error once the attachment ended; extension window, the terminal closed error once the window closed. ###### Returns `Promise`\<`void`\> ##### goto() ```ts goto(url, options?): Promise; ``` Navigates the frame to `url`, which must pass the rules an iframe src does, and adds its host to the attachment. Resolves at `options.waitUntil`, and rejects with `TimeoutError` past `options.timeout` (`GotoOptions`). ###### Parameters ###### url `string` ###### options? [`GotoOptions`](#gotooptions) ###### Returns `Promise`\<`void`\> ##### off() ```ts off(type, listener): void; ``` Removes a listener `on` added; one that is not on the Frame is ignored. An unknown `type` is a `TypeError`. ###### Type Parameters ###### K `K` *extends* keyof `FrameEventMap` ###### Parameters ###### type `K` ###### listener `FrameEventListener`\<`K`\> ###### Returns `void` ##### on() ```ts on( type, listener, options?): void; ``` `message`: what the page posted to the app, with its `origin` and `ports`, and this Frame as `source`. The page reaches the app with `parent.postMessage(x, appOrigin)`, `top.postMessage(x, appOrigin)`, or `event.source.postMessage(x, event.origin)` on a message the app sent it; in an extension window, with `opener.postMessage(x, appOrigin)`. A document outside the attachment is dropped, never masked. On the cloud backend a post to `'*'` does not reach the app: there the page is its own parent, so it cannot be told apart from the page messaging itself, and it stays with the page. The extension delivers it, as a real parent would receive it. `document`: a new document arrived in the frame. What `evaluate` installed in the one before is gone, with every port it held, and nothing is reinstalled for the app: this is the signal to install again. It can fire twice for one document (a return from the back/forward cache), so an install should be idempotent. Cloud: fires for a document inside the attachment, with its origin, and not for the document the frame already held when the first listener was added. Extension: fires on every load of an iframe and every new document of a window, with `origin` `''`. Listeners stay on the Frame across navigations and end with the attachment, or when `signal` aborts, FKN's addition to Playwright's `on`. A listener added twice is called once, and one whose signal already aborted is not added. A listener that throws is reported and does not stop the others. An unknown `type`, or a listener that is not a function, is a `TypeError`. On the cloud backend, against an FKN page that predates messaging, nothing arrives and the console says so once. ###### Type Parameters ###### K `K` *extends* keyof `FrameEventMap` ###### Parameters ###### type `K` ###### listener `FrameEventListener`\<`K`\> ###### options? ###### signal? `AbortSignal` ###### Returns `void` ##### postMessage() ###### Call Signature ```ts postMessage( message, targetOrigin, transfer?): Promise; ``` Delivers `message` to the page in the frame as a real `message` event, the way `iframe.contentWindow.postMessage` would. The page sees a trusted event: `data` is the message, `ports` are the MessagePorts `transfer` moved, `source` is the page's own `parent`, and `origin` is this app's origin. So a page script that `evaluate` installed can take `event.ports[0]` and run any port protocol (osra included) over it, and no FKN code sits on that port afterwards. `targetOrigin` is the page's origin as the site knows it (`https://anilist.co`), parsed as the platform parses it, so a trailing slash or a path is fine. The message is delivered only if the frame's document is on that origin, and otherwise dropped silently, as `Window.postMessage` does. `'*'`, the default, means whatever document the frame holds; the extension refuses it for now. It resolves once the message was handed to the browser for the document the frame holds, in the order the calls were made. That says nothing about whether the page listened, and a message dropped for its origin resolves the same way. Sent after `goto` resolved, it goes to the document that goto brought, as `evaluate` runs there. Refused, and never sent again. On the cloud backend a refusal that depends on the grant or on the frame's document comes after `transfer` was detached, and loses what it moved with the message; every other refusal comes before anything is detached. - `TypeError`, before anything is sent or detached: a `targetOrigin` that is not `'*'` or an origin (`'/'` included), or a `transfer` that is not an array. A message that cannot be cloned is the platform's own `DataCloneError`. - `LocatorDeniedError` naming nothing: `targetOrigin` names a host outside the attachment, or the frame's document is outside it. - `LocatorDeniedError` "frame: navigate the frame before postMessage": the frame holds no page. - cloud, `LocatorDeniedError`: the app has no Evaluation grant, which is asked for on first use as `evaluate` asks. Messaging sits under Evaluation because the message arrives as the page's own traffic and a port handed over is a live channel into the page. - cloud, `LocatorUnsupportedError`: an FKN page or render proxy that predates messaging. - cloud, `LocatorError`: the document changed during the call, so the message may or may not have reached it and is not sent to the next one; or the document of the goto before it had not come by that goto's deadline (the goto failed, or loaded something that is not a page) or before the app started another goto, so nothing was sent. - extension, `LocatorUnsupportedError`: `'*'`, which needs an extension release that reports the frame's origin. Pass the origin. - extension, `LocatorDeniedError`: a window whose page cut its link to the app's page (`WindowFrame`). - the terminal detach error once the attachment ended. ###### Parameters ###### message `unknown` ###### targetOrigin `string` ###### transfer? `Transferable`[] ###### Returns `Promise`\<`void`\> ###### Call Signature ```ts postMessage(message, options?): Promise; ``` ###### Parameters ###### message `unknown` ###### options? `FramePostMessageOptions` ###### Returns `Promise`\<`void`\> ##### requestPermissions() ```ts requestPermissions(requests): Promise; ``` Asks for whole categories on this attachment's hosts, before any call. Resolves per request, in the order they were asked; a refusal is `allow: false`, never a rejection. An ask naming a category or key the registry cannot place on a row is a `TypeError`, thrown before it is sent, and so is a `reason` over `MAX_REASON_LENGTH` characters: `frame.requestPermissions: reason must be at most 100 characters, not `. Not Playwright's `page.request`, which is an HTTP client; the app asks here and the user grants. ###### Parameters ###### requests `CategoryRequest`[] ###### Returns `Promise`\<`CategoryAnswer`[]\> ##### url() ```ts url(): string; ``` The url last given to `attachFrame` or `goto`, never the frame's live location: a page that moves itself does not change it. ###### Returns `string` *** ### FrameLocator ```ts type FrameLocator = FrameLocatorChain; ``` A frame inside an attached frame, entered with `frameLocator(selector)`. Its document is read as the attached frame's is. `owner()` is Playwright's: a `Locator` on the iframe it entered, whose `contentFrame()` comes back here. `getByTestId` searches from its document root. `evaluate` and `addScriptTag` run on the attached frame only, so neither is offered here. *** ### FrameWindowOptions ```ts type FrameWindowOptions = object; ``` Where an attachment's window opens and how big it asks to be. #### Properties ##### height? ```ts optional height?: number; ``` Inner height in CSS pixels, 700 by default. The browser may clamp it. ##### url? ```ts optional url?: string; ``` Where the window opens: an http or https address, which must also pass the rules an iframe src does. Omitted, the window opens blank and the app navigates it with `goto`, which is how an app keeps the click's activation when the url needs an await first. ##### width? ```ts optional width?: number; ``` Inner width in CSS pixels, 500 by default. The browser may clamp it. *** ### FrameWindowRefusal ```ts type FrameWindowRefusal = "jar-unreachable" | "bad-url" | "opaque-opener" | "unknown"; ``` Why a window refused to attach. `'jar-unreachable'`: the cookie jar of the app that opened it could not be reached. `'bad-url'`: the window would not open that address. `'opaque-opener'`: this page's origin is opaque (a sandboxed frame without `allow-same-origin`, or a `file:` page). A window can never address such a page, so none is opened. `'unknown'`: a reason this library does not know, sent by a newer window. *** ### Gate ```ts type Gate = (request, tools) => void | Promise; ``` #### Parameters ##### request [`OperationRequest`](#operationrequest) ##### tools [`GateTools`](#gatetools) #### Returns `void` \| `Promise`\<`void`\> *** ### GateTools ```ts type GateTools = object; ``` #### Properties ##### highlight ```ts highlight: (on) => Promise; ``` ###### Parameters ###### on `boolean` ###### Returns `Promise`\<`void`\> *** ### GotoOptions ```ts type GotoOptions = object; ``` `frame.goto`'s options. Refused with a TypeError before anything is sent: a `waitUntil` other than `'load'` or `'commit'` (Playwright's `'domcontentloaded'` and `'networkidle'` are not served, and `'documentstart'` is now `'commit'`), a `timeout` of 0 or below or not finite, and `timeoutMs`. #### Properties ##### domains? ```ts optional domains?: string[]; ``` ##### timeout? ```ts optional timeout?: number; ``` How long the goto may take, in milliseconds: 30000 when absent. Past it the goto rejects with `TimeoutError`. A positive number: 0 is a TypeError, since every call ends by its deadline and so does not take Playwright's "0 disables the timeout". ##### waitUntil? ```ts optional waitUntil?: "commit" | "load"; ``` When `goto` resolves: `'load'`, the default, once the document it brings fired load; `'commit'`, Playwright's, once that document holds the frame, possibly before the page's own scripts ran and whether or not it ever fires load. Either way a call made after it runs on the document the goto brought, never on the one it replaced, and the goto rejects with `TimeoutError` when that document has not come by its deadline. A goto that changes only the fragment of the url the page is at keeps its document. On the cloud backend it resolves, either way, once the page reports the new fragment. Two pages are the exception there, where such a goto brings a new document like any other: one reached through a redirect, and one that followed a link onto another origin. On the extension (measured on Chromium) one awaited to `'load'` resolves, since the frame fires load for it, and one awaited to `'commit'` runs out at its timeout, since no new document starts. *** ### HeaderOperation ```ts type HeaderOperation = object; ``` #### Properties ##### header ```ts header: string; ``` ##### operation ```ts operation: "set" | "remove"; ``` ##### value? ```ts optional value?: string; ``` *** ### OperationRequest ```ts type OperationRequest = object; ``` #### Properties ##### args ```ts args: unknown[]; ``` ##### operation ```ts operation: string; ``` ##### parts ```ts parts: SelectorPart[]; ``` ##### phase ```ts phase: "execute" | "ensure"; ``` *** ### PermissionGrant ```ts type PermissionGrant = | CategoryGrant | { allow: boolean; key: PermissionScope; scope: string; site: string; }; ``` `key` and `scope` are set only for a legacy answer, `category` and `hosts` only for a category one. A legacy answer also carries `site`, the host its scope named, empty where the scope names none (a locator selector), which is the case that is always refused. *** ### PermissionRequest ```ts type PermissionRequest = CategoryRequest & object | LegacyPermissionRequest; ``` `hosts` is what makes an item a category ask; without it the item is the legacy per-key one. *** ### RemoteVideoElement ```ts type RemoteVideoElement = EventTarget & object; ``` #### Type Declaration ##### autoplay ```ts autoplay: boolean; ``` ##### buffered ```ts readonly buffered: TimeRanges; ``` ##### currentSrc ```ts readonly currentSrc: string; ``` ##### currentTime ```ts currentTime: number; ``` ##### disableRemotePlayback ```ts disableRemotePlayback: boolean; ``` ##### duration ```ts readonly duration: number; ``` ##### ended ```ts readonly ended: boolean; ``` ##### error ```ts readonly error: MediaError | null; ``` ##### HAVE\_ENOUGH\_DATA ```ts readonly HAVE_ENOUGH_DATA: 4; ``` ##### HAVE\_FUTURE\_DATA ```ts readonly HAVE_FUTURE_DATA: 3; ``` ##### loop ```ts loop: boolean; ``` ##### muted ```ts muted: boolean; ``` ##### paused ```ts readonly paused: boolean; ``` ##### playbackRate ```ts playbackRate: number; ``` ##### poster ```ts poster: string; ``` ##### preload ```ts preload: string; ``` ##### readyState ```ts readonly readyState: number; ``` ##### seekable ```ts readonly seekable: TimeRanges; ``` ##### seeking ```ts readonly seeking: boolean; ``` ##### src ```ts src: string; ``` ##### volume ```ts volume: number; ``` ##### exitPictureInPicture() ```ts exitPictureInPicture(): Promise; ``` ###### Returns `Promise`\<`void`\> ##### load() ```ts load(): void; ``` ###### Returns `void` ##### pause() ```ts pause(): void; ``` ###### Returns `void` ##### play() ```ts play(): Promise; ``` ###### Returns `Promise`\<`void`\> ##### requestPictureInPicture() ```ts requestPictureInPicture(): Promise; ``` ###### Returns `Promise`\<`void`\> *** ### RequestHeaderRule ```ts type RequestHeaderRule = object; ``` #### Properties ##### domains ```ts domains: string[]; ``` ##### reason? ```ts optional reason?: string; ``` The app's sentence for the prompt, at most `MAX_REASON_LENGTH` (100) characters. ##### requestHeaders ```ts requestHeaders: HeaderOperation[]; ``` *** ### SelectorPart ```ts type SelectorPart = object; ``` #### Properties ##### args ```ts args: unknown[]; ``` ##### kind ```ts kind: ChainKind; ``` ##### name ```ts name: string; ``` *** ### SiteCookie ```ts type SiteCookie = object; ``` #### Properties ##### name ```ts name: string; ``` ##### value ```ts value: string; ``` *** ### StorageState ```ts type StorageState = object; ``` A jar's starting state, in the shape Playwright's `browser.newContext({ storageState })` takes, except that a cookie's `expires` is milliseconds here where Playwright's is seconds. Seeded into an `'ephemeral'` attachment's fresh jar and its storage namespace before the attachment's first document is requested, so that request already carries its cookies and the page's first script already reads its localStorage. With `blank`, whose empty page requests nothing and runs no code, it is seeded right after that page is in place, before the attach resolves. Accepted only with `cookies: 'ephemeral'`: with `'persistent'` an app-written cookie would land in the jar every app of the top-level site shares, and with `'native'` in the person's own session. The seed travels on FKN's own channels, never in a url the app page could read. A seeded HttpOnly cookie is sent to its site and never readable in the page, as any HttpOnly cookie, and it never comes back to app code. Refused by name, before anything is attached (`AttachCookies` has the order): a field of another shape; a name or value with `;` or a control character, or a name with `=`; a cookie a browser does not store (SameSite=None or `__Secure-` without `secure`, `__Host-` without `secure`, a host-only domain and path '/'); an origin that is not an absolute http or https origin; and an `expires` that reads as seconds. Against an FKN page or render proxy that predates it, after the iframe is put back on about:blank (or the window closed) and before anything is requested from the site: the terminal `LocatorUnsupportedError` `attachFrame: this FKN page predates storageState; reload the app to load the current one`. #### Properties ##### cookies? ```ts optional cookies?: StorageStateCookie[]; ``` ##### origins? ```ts optional origins?: object[]; ``` Each origin's localStorage items, read by every page of that origin in the attachment. ###### localStorage ```ts localStorage: object[]; ``` ###### origin ```ts origin: string; ``` *** ### StorageStateCookie ```ts type StorageStateCookie = object; ``` One cookie of a `StorageState`. #### Properties ##### domain ```ts domain: string; ``` `.youtube.com` for a cookie its subdomains also receive, `www.youtube.com` for a host-only one, as Playwright writes it. ##### expires? ```ts optional expires?: number; ``` Milliseconds since the epoch, where Playwright's is seconds; -1 or absent for a session cookie. ##### httpOnly? ```ts optional httpOnly?: boolean; ``` ##### name ```ts name: string; ``` Non-empty, with no `=`, `;` or control character. ##### path? ```ts optional path?: string; ``` `/` when absent. ##### sameSite? ```ts optional sameSite?: "Strict" | "Lax" | "None"; ``` `'Lax'` when absent, as a browser defaults it. ##### secure? ```ts optional secure?: boolean; ``` ##### value ```ts value: string; ``` With no `;` or control character. *** ### WindowFrame ```ts type WindowFrame = Frame & object; ``` The Frame of an attachment that lives in its own window. On the extension (`cookies: 'native'`) the window is a real browser popup the app's page opens with `window.open`, whose page is the site itself: there is no FKN page in it. Where that differs: - The Frame follows the window's page wherever it goes, as it follows an iframe's, and its reads answer only inside the attachment. A page that goes to an FKN host ends the attachment (`closed`). - `postMessage` and the `message` event need the window to keep its link to the app's page. A page served with Cross-Origin-Opener-Policy (`same-origin`, `same-origin-allow-popups`) cuts it as it loads, and `postMessage` is then the `LocatorDeniedError` `frame.postMessage: this window's page no longer keeps a link to the app's page, so a message cannot reach it`. Everything else still answers: the extension knows the window by its tab, never by that link. The page reaches the app with `opener.postMessage(x, appOrigin)` while the link holds. - Its consent sheets are drawn on the app's page, not in the window. - `evaluate` keeps the window page's content security policy (an attached iframe on a declared host has it replaced), so a page that forbids `eval` refuses with a named error. - Calls after `closed` reject with the terminal `LocatorUnsupportedError` `extension.attachFrame: the attached window closed; attach a fresh window`. - The extension never throws `FrameWindowRefusedError`, which is the cloud's. #### Type Declaration ##### closed ```ts closed: Promise; ``` Resolves once the attachment has ended, and never rejects. Calls made after it resolved reject with the terminal detach error. On the cloud backend: the window was closed by anyone, reloaded, or left the page FKN attached; it stopped answering (a crash, a frozen page); it lost the app's cookie jar mid-session; or the app page went away. On the extension: the window was closed by anyone, `close()` ran, its page went to an FKN host (a `goto` redirected there rejects with the detach error), or the app page went away; the last two leave the window open for the person. Any other reload or navigation in the window does not end it, since the Frame follows the window's page. ##### close() ```ts close(): Promise; ``` Ends the attachment and closes the window. On the cloud backend it first waits, at most 2 seconds, for the window's cookie changes to be committed to its jar, so a `goto` on the app's inline frame right after sees the session. On the extension the window ran on the person's own browser cookies, which are already written, so an inline `'native'` frame sees a sign-in on its next `goto`. Idempotent, and never rejects. ###### Returns `Promise`\<`void`\> ## Variables ### assertAttachableFrameUrl ```ts const assertAttachableFrameUrl: (raw) => void; ``` #### Parameters ##### raw `string` #### Returns `void` *** ### assertFetchableUrl ```ts const assertFetchableUrl: (raw) => void; ``` #### Parameters ##### raw `string` #### Returns `void` *** ### attachFrame ```ts const attachFrame: AttachFrameFunction; ``` Attaches through the extension, on `cookies: 'native'` only: the other values, the default among them, are the cloud render proxy's, refused here with `ExtensionOperationUnsupportedError` (operation `'cookies'`) before any exposure wait (`AttachCookies`). A `domains` entry, of the attach or of a `goto`, or a `goto` target's host, that the frame's header rule would carry onto an FKN platform host (one of them, one under one, or a parent such as `app`) is refused with an Error before anything is armed. *** ### BACKGROUND\_STOPPED ```ts const BACKGROUND_STOPPED: "BackgroundStoppedError" = "BackgroundStoppedError"; ``` *** ### cookies ```ts const cookies: object; ``` #### Type Declaration ##### get ```ts get: (details) => Promise; ``` Reads one named cookie of another site behind a Network ask on its host, `null` when there is none. A url on an FKN platform host (`fkn.app`, `fkn.dev`, `sdbx.app` and their subdomains) is refused with an Error before anything is asked, and again by the extension. ###### Parameters ###### details [`CookieDetails`](#cookiedetails) ###### Returns `Promise`\<[`SiteCookie`](#sitecookie) \| `null`\> *** ### events ```ts const events: TypedEventTarget; ``` *** ### EXTENSION\_ABI ```ts const EXTENSION_ABI: 5 = 5; ``` What the extension half announces about itself. Increment when the callable surface changes in a way a page could notice: an operation added, removed, renamed, or given different semantics. Not the package or manifest version, which move for reasons unrelated to the protocol. *** ### fetch ```ts const fetch: (input, init?) => Promise; ``` Fetches through the extension. A credentialed fetch (`credentials: 'include'`) and one to the local network are asked for on the target's host first. A url on the extension's own pages or an FKN platform host is refused with an Error before anything is asked, and a `reason` over `MAX_REASON_LENGTH` characters with the TypeError `fetch: reason must be at most 100 characters, not `, whatever the request. A redirect onto an FKN platform host is not followed: the hop is blocked before it is sent, on both engines and in every spelling, and should one ever slip the block the final answer is still withheld with an Error. A fetch that follows redirects is refused before it is sent when the extension could not set the block up. #### Parameters ##### input `RequestInfo` \| `URL` ##### init? [`FetchInit`](#fetchinit) #### Returns `Promise`\<`Response`\> *** ### FORGEABLE\_HEADERS ```ts const FORGEABLE_HEADERS: string[]; ``` *** ### isBackgroundStopped ```ts const isBackgroundStopped: (error) => boolean; ``` Whether `error` is a `BackgroundStoppedError`, matched on `name` since it may arrive as a revived Error or a plain record. #### Parameters ##### error `unknown` #### Returns `boolean` *** ### isExtensionExposed ```ts const isExtensionExposed: () => boolean; ``` Unchanged on purpose: a page half built before versioning calls exactly this, so an extension that announces an ABI keeps answering it the same way. An outdated extension also answers true. #### Returns `boolean` *** ### isLocalNetworkUrl ```ts const isLocalNetworkUrl: (raw) => boolean; ``` #### Parameters ##### raw `string` #### Returns `boolean` *** ### isLocatorDenied ```ts const isLocatorDenied: (error) => boolean; ``` #### Parameters ##### error `unknown` #### Returns `boolean` *** ### isLocatorInvalid ```ts const isLocatorInvalid: (error) => boolean; ``` #### Parameters ##### error `unknown` #### Returns `boolean` *** ### isLocatorUnsupported ```ts const isLocatorUnsupported: (error) => boolean; ``` #### Parameters ##### error `unknown` #### Returns `boolean` *** ### isTerminalError ```ts const isTerminalError: (error) => boolean; ``` #### Parameters ##### error `unknown` #### Returns `boolean` *** ### LOCATOR\_DENIED ```ts const LOCATOR_DENIED: "LocatorDeniedError" = "LocatorDeniedError"; ``` *** ### LOCATOR\_ERROR ```ts const LOCATOR_ERROR: "LocatorError" = "LocatorError"; ``` *** ### LOCATOR\_INVALID ```ts const LOCATOR_INVALID: "LocatorInvalidError" = "LocatorInvalidError"; ``` *** ### LOCATOR\_UNSUPPORTED ```ts const LOCATOR_UNSUPPORTED: "LocatorUnsupportedError" = "LocatorUnsupportedError"; ``` *** ### permissions ```ts const permissions: object; ``` #### Type Declaration ##### request ```ts request: (requests) => Promise; ``` Asks for permissions on one sheet (extension) or card (cloud), in the order given, and answers one grant per request. A category ask needs `hosts`, the sites the grant applies to, and is answered `allow: true` only where every one of them was granted. It needs an extension that serves categories and throws `ExtensionOutdatedError` below that; a legacy `{ key, scope }` item is forwarded to any version. An ask naming a category or key the registry cannot place on a row is a `TypeError`, thrown before anything is sent: its answer would have to name a category the caller never asked for. A category ask naming an FKN platform host is an Error, also before anything is sent; the extension answers `allow: false` for any item, legacy ones included, that names one. A `reason` over `MAX_REASON_LENGTH` characters, on either form, is the TypeError `permissions.request: reason must be at most 100 characters, not `, also before anything is sent. ###### Parameters ###### requests [`PermissionRequest`](#permissionrequest)[] ###### Returns `Promise`\<[`PermissionGrant`](#permissiongrant)[]\> *** ### readExtensionHandshake ```ts const readExtensionHandshake: () => ExtensionHandshake; ``` The three-way answer: absent, present but too old, or usable. #### Returns [`ExtensionHandshake`](#extensionhandshake) *** ### removeRequestHeaderRule ```ts const removeRequestHeaderRule: (ruleId) => Promise; ``` #### Parameters ##### ruleId `number` #### Returns `Promise`\<`void`\> *** ### REQUIRED\_EXTENSION\_ABI ```ts const REQUIRED_EXTENSION_ABI: 0 = 0; ``` The oldest extension the page half will talk to. Raise it only when the page half starts depending on something older extensions cannot do, never merely because `EXTENSION_ABI` moved. Deliberately 0: extensions that predate versioning announce no ABI, and a floor of 1 would refuse all of them. *** ### setMissingExtensionHandler ```ts const setMissingExtensionHandler: (handler) => void; ``` #### Parameters ##### handler `MissingExtensionHandler` \| `null` #### Returns `void` *** ### setRequestHeaderRule ```ts const setRequestHeaderRule: (rule) => Promise<{ ruleId: number; }>; ``` Tab-scoped: the rule is dropped when the tab goes away. A domain the rule would carry onto an FKN platform host (one of them, one under one, or a parent such as `app`, since a rule also matches every host under each domain) is refused with an Error before anything is asked, and again by the extension. So is a header other than `Origin`, `Referer` and `Cookie` (`FORGEABLE_HEADERS`). A `reason` over `MAX_REASON_LENGTH` characters is the TypeError `setRequestHeaderRule: reason must be at most 100 characters, not `, before anything is asked. #### Parameters ##### rule [`RequestHeaderRule`](#requestheaderrule) #### Returns `Promise`\<\{ `ruleId`: `number`; \}\> *** ### supportsOperation ```ts const supportsOperation: (handshake, operation) => boolean; ``` Whether a named operation is callable. A `null` list answers true (the extension predates the list and supports the original surface); refusing a too-old extension is the ABI floor's job. #### Parameters ##### handshake [`ExtensionHandshake`](#extensionhandshake) ##### operation `string` #### Returns `boolean` *** ### waitForExtensionExposure ```ts const waitForExtensionExposure: (timeout?) => Promise; ``` Resolves once the FKN WebExtension on this page has announced a handshake it can use (`readExtensionHandshake()` reads `'ok'`): at once when it already has, else as soon as its content script announces one, however long after the page's load that is. With none `timeout` ms after the call (2000 by default) it stops waiting: an extension that announced an ABI below the one required rejects with `ExtensionOutdatedError`; otherwise the missing-extension handler runs (`@fkn/lib`'s install prompt, which waits on the person), and the call resolves if that left a usable extension, else rejects with "The FKN WebExtension is not installed, enabled or not exposed on this page." #### Parameters ##### timeout? `number` #### Returns `Promise`\<`void`\> ## Functions ### available() ```ts function available(): boolean; ``` #### Returns `boolean` *** ### promptInstall() ```ts function promptInstall(reason?): Promise; ``` Shows the install card with the app's `reason`, and resolves true once the extension is exposed (at once when it already is), false when the person dismisses the card or the realm has no window. A `reason` over `MAX_REASON_LENGTH` (100) characters is the TypeError `promptInstall: reason must be at most 100 characters, not `, in any realm, before anything is shown. #### Parameters ##### reason? `string` #### Returns `Promise`\<`boolean`\> ## References ### extension Renames and re-exports [events](#events) --- # @fkn/lib/packages URL: https://docs.fkn.dev/api/packages/ ## Type Aliases ### AppConnectOptions ```ts type AppConnectOptions = ConnectOptions & object; ``` #### Type Declaration ##### payload? ```ts optional payload?: unknown; ``` exposed to the package as ITS `remote` ##### raw? ```ts optional raw?: boolean; ``` skip the osra handshake and hand back the untouched port - e.g. to transfer it into a worker and attach() there ##### signal? ```ts optional signal?: AbortSignal; ``` *** ### Connect ```ts type Connect = { (uri, options?): Promise>; (uri, options): Promise; }; ``` #### Call Signature ```ts (uri, options?): Promise>; ``` ##### Type Parameters ###### T `T` = `unknown` ##### Parameters ###### uri `string` ###### options? [`ConnectOptions`](/api/contract/#connectoptions) & `object` & `object` ##### Returns `Promise`\<[`PackageConnection`](#packageconnection)\<`T`\>\> #### Call Signature ```ts (uri, options): Promise; ``` ##### Parameters ###### uri `string` ###### options [`ConnectOptions`](/api/contract/#connectoptions) & `object` & `object` ##### Returns `Promise`\<[`RawPackageConnection`](#rawpackageconnection)\> *** ### ConnectPayload ```ts type ConnectPayload = (info) => unknown; ``` produces the payload exposed to a connecting app - called once per incoming connection #### Parameters ##### info [`IncomingConnectionInfo`](#incomingconnectioninfo) #### Returns `unknown` *** ### IncomingConnection ```ts type IncomingConnection = IncomingConnectionInfo & PackageConnection; ``` #### Type Parameters ##### T `T` = `unknown` *** ### IncomingConnectionInfo ```ts type IncomingConnectionInfo = object; ``` #### Properties ##### brokered ```ts brokered: boolean; ``` True only when fkn.app's broker made this connection (`packages.connect`), so `from` is the app the broker identified by its browser-set origin. False under `packages.mount` and for any other embedder. Worked out here from the origin of the message that carried the port, never read from the message. Key what a connection is allowed (a grant you stored, an app named to the person) to `from` only when this is true. A package built on a lib older than this field gets none, so test `=== true`. ##### from ```ts from: string; ``` The connecting app's identity: its package uri when it runs on a sandbox origin, else its page origin. Proof of nothing unless `brokered` is true: under `packages.mount`, or in any page that frames this package's url itself, the embedder writes whatever it likes here. ##### name ```ts name: string; ``` this package's npm name ##### protocol ```ts protocol: string | null; ``` the contract tag the app passed to connect(), e.g. 'stub-source@1' ##### uri ```ts uri: string; ``` this package's normalized uri per the connecting app's install record, e.g. 'npm:@banou/stub-source-example' ##### version ```ts version: string; ``` the exact version this frame runs - the pin is encoded into the sandbox origin, immutable per version *** ### MountedPackage ```ts type MountedPackage = Omit, "closed"> & object; ``` #### Type Declaration ##### closed ```ts closed: Promise; ``` settles on `unmount()`, on a later `mount` into the same iframe, and when another page of the package starts in the iframe or fails to start there: the page reloaded or navigated itself, or its @fkn/lib took an update. Mount again then, or unmount. A page that replaces its document with `document.open()` keeps its connection. A stop, an uninstall, a navigation away from the package and a crash are not seen, so `closed` stays pending through them ##### frame ```ts frame: HTMLIFrameElement; ``` the iframe you passed in, unchanged apart from its `src` ##### unmount ```ts unmount: () => void; ``` blank the frame and settle `closed`; once a later `mount` took the iframe, it only settles `closed` and leaves the newer package alone. The element stays in your layout because it is yours ###### Returns `void` #### Type Parameters ##### T `T` = `unknown` *** ### MountOptions ```ts type MountOptions = AppConnectOptions & object; ``` #### Type Declaration ##### iframe ```ts iframe: HTMLIFrameElement; ``` the iframe the package is loaded into. YOU create it and YOU own it: its attributes, its styles and its place in your layout are yours, and `mount` only navigates it. Set `allow` yourself for anything the package needs delegated, e.g. `allow="fullscreen; autoplay"`. Permissions policy is not inherited, so a capability this frame is not granted cannot be recovered by the package or by anything it nests inside itself. A `sandbox` on it must include `allow-scripts` and `allow-same-origin`, and needs nothing else: the package runs script, and keeps its own origin for its service worker and storage. `mount` refuses a sandbox without either, naming the token it lacks. Every other token is yours to grant: the package starts without `allow-forms`, `allow-popups` or any navigation token, and everything it frames inherits what this frame withholds. The package's key is posted from an unsandboxed fkn.app document outside it: for an app fkn.app's `/app` page shows, that page; anywhere else, the FKN frame @fkn/lib keeps in this page. So in a page another site frames under a sandbox, `mount` cannot start the package. *** ### PackageConnection ```ts type PackageConnection = object; ``` #### Type Parameters ##### T `T` = `unknown` #### Properties ##### closed ```ts closed: Promise; ``` settles when the package side of the connection dies (uninstall, reload, crash) - reconnect by calling connect() again ##### port ```ts port: MessagePort; ``` the raw channel under `remote`, for direct messaging (osra envelopes ride it too - filter by your own message shape) ##### remote ```ts remote: Remote; ``` the package's exposed payload *** ### PackagesError ```ts type PackagesError = Error & object; ``` #### Type Declaration ##### code ```ts code: PackagesErrorCode; ``` *** ### PackageView ```ts type PackageView = object; ``` #### Properties ##### hide ```ts hide: () => void; ``` release this view; equivalent to `packages.hide(uri, { element })` ###### Returns `void` ##### refresh ```ts refresh: () => void; ``` force a re-measure, e.g. right after a layout change the tracker cannot observe ###### Returns `void` *** ### RawPackageConnection ```ts type RawPackageConnection = Omit, "remote">; ``` *** ### ShowOptions ```ts type ShowOptions = object; ``` #### Properties ##### element? ```ts optional element?: HTMLElement; ``` A placeholder the package frame is aligned to for as long as the view lives. The frame tracks its rect every animation frame, is clipped by its scrolling ancestors, and follows its border-radius, so it reads as inline content even though it renders in FKN's overlay. ##### rect? ```ts optional rect?: SurfaceRect; ``` an explicit viewport rect, for a caller that tracks placement itself ## Variables ### connect ```ts const connect: Connect; ``` Connect to an installed package. Throws a PackagesError with code 'not-installed' when it is not. ## Functions ### attach() ```ts function attach( port, payload?, options?): Promise>; ``` Run this end of an already-brokered connection port, e.g. after transferring it into a worker. #### Type Parameters ##### T `T` = `unknown` #### Parameters ##### port `MessagePort` ##### payload? `unknown` ##### options? ###### signal? `AbortSignal` #### Returns `Promise`\<`Remote`\<`T`\>\> *** ### hide() ```ts function hide(uri, options?): Promise; ``` Hide a package's frame again, the counterpart to `show()`. Pass the same `element` to release only the view bound to it; with no element every view of this package is released. The connection is untouched, so the package can be shown again. #### Parameters ##### uri `string` ##### options? [`ShowOptions`](#showoptions) = `{}` #### Returns `Promise`\<`void`\> *** ### install() ```ts function install(uri, options?): Promise; ``` Install a package for this app behind an FKN-rendered confirm, or with `{ noConfirm: true }` for a notice instead of a prompt. Resolves null when the user declines. `{ temporary: true }` installs it for this tab only, with no install record: see `InstallOptions.temporary`. Throws a PackagesError with code 'unsupported', having installed nothing, on an fkn.app too old to hold that, so an app never ends up keeping what it asked not to keep. #### Parameters ##### uri `string` ##### options? [`InstallOptions`](/api/contract/#installoptions) #### Returns `Promise`\<[`InstalledPackage`](/api/contract/#installedpackage) \| `null`\> *** ### isVisible() ```ts function isVisible(): boolean; ``` True while a host app is showing this package's frame. Packages start hidden. #### Returns `boolean` *** ### list() ```ts function list(): Promise; ``` The packages installed by this app, kept and temporary. A temporary one reads `temporary: true`. #### Returns `Promise`\<[`InstalledPackage`](/api/contract/#installedpackage)[]\> *** ### mount() ```ts function mount(uri, options): Promise>; ``` Load a package into an iframe of YOUR OWN and connect to it, instead of positioning a frame the broker owns and clipping the overlay to it the way `show()` does. You pass the iframe, the same way `cloud.attachFrame` takes one. It lays out, scrolls, stacks and fullscreens with the rest of your page, there is no geometry to translate, and every attribute on it stays exactly as you set it: `mount` reads `sandbox` and `allow` to check the package can boot, then writes nothing but `src`. The package still gets its own origin and its own broker connection. Grant capabilities through the iframe's own `allow`, before calling this. Permissions policy is read at navigation and is not inherited, so it cannot be added afterwards on the frame handed back. A `sandbox` needs `allow-scripts` and `allow-same-origin` and nothing more (`MountOptions.iframe`). Rejects with a PackagesError: 'invalid' for an iframe the package cannot start in, 'unavailable' with the reason the package's frame gives when it fails to start, or when another `mount` takes the iframe first, 'timeout' when it never answers. Needs a package built against this version of the lib: an older one only accepts a port from fkn.app. The package reads `brokered: false`. #### Type Parameters ##### T `T` = `unknown` #### Parameters ##### uri `string` ##### options [`MountOptions`](#mountoptions) #### Returns `Promise`\<[`MountedPackage`](#mountedpackage)\<`T`\>\> *** ### onConnect() ```ts function onConnect(createPayload, handler?): object; ``` Serve connections from apps that installed this package. The first argument is called once per incoming connection with the connection info and returns the payload exposed to that app (its `remote`). The latest registration receives new connections; existing connections are unaffected. Connections, and the messages that close them, keep arriving after the page replaces its document with `document.open()`. #### Type Parameters ##### T `T` = `unknown` #### Parameters ##### createPayload [`ConnectPayload`](#connectpayload) ##### handler? (`connection`) => `void` #### Returns `object` ##### unsubscribe ```ts unsubscribe: () => void; ``` ###### Returns `void` *** ### onVisibilityChange() ```ts function onVisibilityChange(handler): object; ``` Observe whether a host app is showing this package's frame, so it can render its UI only while on screen. The handler is called immediately with the current state, and on every change after, including after the page replaces its document with `document.open()`. #### Parameters ##### handler (`visible`) => `void` #### Returns `object` ##### unsubscribe ```ts unsubscribe: () => void; ``` ###### Returns `void` *** ### pick() ```ts function pick(query, options?): Promise; ``` FKN-rendered picker over the same search; resolves the user's selection, already installed. [] on cancel. #### Parameters ##### query [`PackageQuery`](/api/contract/#packagequery) ##### options? [`PickOptions`](/api/contract/#pickoptions) #### Returns `Promise`\<[`PackageResult`](/api/contract/#packageresult)[]\> *** ### search() ```ts function search(query): Promise; ``` Search npm for FKN packages, e.g. `search({ type: 'plugin', id: 'stub' })`. #### Parameters ##### query [`PackageQuery`](/api/contract/#packagequery) #### Returns `Promise`\<[`PackageResult`](/api/contract/#packageresult)[]\> *** ### show() ```ts function show(uri, options): Promise; ``` Show an installed, connected package's frame over this page, aligned to `element` (or an explicit `rect`). The package renders its own UI there; the app keeps the space in its own layout. Take it back down with `hide()` on the returned view, or with `packages.hide(uri)`. Throws a PackagesError with code 'not-installed' when the package has not been connected by this app. #### Parameters ##### uri `string` ##### options [`ShowOptions`](#showoptions) #### Returns `Promise`\<[`PackageView`](#packageview)\> *** ### supportsTemporary() ```ts function supportsTemporary(): Promise; ``` Whether fkn.app can install a package temporarily, asked with no install attempted. False on an fkn.app older than `InstallOptions.temporary`; on an @fkn/lib older than it this export is undefined, so `await packages.supportsTemporary?.() === true` holds for both. #### Returns `Promise`\<`boolean`\> *** ### uninstall() ```ts function uninstall(uri): Promise; ``` Uninstall a package from this app, kept or temporary; its frames and connections are torn down. #### Parameters ##### uri `string` #### Returns `Promise`\<`void`\> ## References ### ConnectOptions Re-exports [ConnectOptions](/api/contract/#connectoptions) *** ### InstalledPackage Re-exports [InstalledPackage](/api/contract/#installedpackage) *** ### InstallOptions Re-exports [InstallOptions](/api/contract/#installoptions) *** ### PackageQuery Re-exports [PackageQuery](/api/contract/#packagequery) *** ### PackageResult Re-exports [PackageResult](/api/contract/#packageresult) *** ### PackagesErrorCode Re-exports [PackagesErrorCode](/api/contract/#packageserrorcode) *** ### PickOptions Re-exports [PickOptions](/api/contract/#pickoptions) *** ### Placement Re-exports [Placement](/api/contract/#placement) *** ### Radii Re-exports [Radii](/api/contract/#radii) *** ### SurfaceRect Re-exports [SurfaceRect](/api/contract/#surfacerect) --- # @fkn/lib/rooms URL: https://docs.fkn.dev/api/rooms/ ## Type Aliases ### Room ```ts type Room = object; ``` A joined room. The same object survives a broker replacement, so it is safe to hold for as long as the chat lasts. #### Properties ##### backlog ```ts backlog: (after, limit?) => Promise; ``` replays the stored messages above `after` as `message` and `bytes` events, one page at a time: at most `limit` messages and never more than 200 or 64 KiB, though a page holds one while any is left. They come in seq order, all of them before the call resolves, so a list built from them is whole once it does. `replayed` marks the ones that predate this connection, so one sent since comes again unmarked: key a list by seq. A message that does not open under the room's key is skipped. `last` is the seq the next page starts after, and `more` whether the room holds messages past it. Refused `denied` (`rooms: permission denied`) without `receive`. ###### Parameters ###### after `number` ###### limit? `number` ###### Returns `Promise`\<[`RoomBacklog`](/api/contract/#roombacklog)\> ##### block ```ts block: (id) => Promise; ``` sends a member out of the room and keeps them out, with the `block` permission (`denied`, `rooms: permission denied`). On a room claimed under an app's scope, from another app of the claim's account, it is refused `denied` (`rooms: only the app that claimed the room can change it`), as `claim` says. ###### Parameters ###### id `string` ###### Returns `Promise`\<`void`\> ##### claim ```ts claim: (options?) => Promise; ``` keeps the name for the signed-in account, and a mailbox unless asked not to. A free account holds 5 claims and a premium one 10, in any scope, `global` included; once premium lapses the account keeps its 5 oldest claims and the others are released 30 days later. `description` says what the room is for, shown to the account in its fkn.app settings; a permanent claim with an unchanged one on every open is free. Claiming on every open also claims the room again after the account deletes it in fkn.app, so claim when the person wants the room kept, or make it `temporary`. `temporary` makes the claim end by itself, in milliseconds (`true` is 7 days), that long after its last claim: a temporary claim goes to the account's ledger every time, which is what restarts its clock. When it ends the app hears a `claim` event with `claimed: false`, exactly as when the account deletes the room in fkn.app, and the stored messages are gone. A broker too old to carry it refuses the call `unavailable` (`rooms: temporary claims are not available`) rather than make the claim permanent. `mailbox: false` keeps the name and stores nothing: the room relays as an unclaimed one does. It is read only when the call starts the claim and ignored on a room the account already holds, so claiming on every open never undoes the owner's choice. Who changes a claimed room depends on its scope. A room under an app's scope, which is every room but a `global` one, is changed by the claim's account only through the app that claimed it (the same app once it is verified): from another app of the account `setDefault`, `limit`, `grant`, `revoke`, `remove`, `block`, `unblock`, `setMailbox`, `setCap`, `clear`, `edit` and `delete` are refused `denied` (`rooms: only the app that claimed the room can change it`), the account's own messages included, and nothing changes. That other app, which reaches the room through its invite, still joins, reads and sends. A claimed `global` room is changed by any app of the account, which also describes it, sets its `temporary` and releases it. The account can delete any room it claimed from its fkn.app settings, whichever app claimed it, and members of other accounts are answered as in any room. While the room cannot tell whether two apps are one, such a change is refused `unavailable` (`rooms: rooms are unavailable`) and can be sent again. Past the account's room limit the call waits while fkn.app shows the person their claimed rooms over your app, with Unclaim on each: it resolves once one is unclaimed and this claim is made, and rejects `full` (`rooms: too many claims`) when they close the card or when fkn.app cannot show it. Nothing about the account's other rooms reaches your app. ###### Parameters ###### options? [`RoomClaimOptions`](/api/contract/#roomclaimoptions) ###### Returns `Promise`\<`void`\> ##### claimed ```ts readonly claimed: boolean; ``` whether an account keeps this name. Whether it keeps the messages too is `mailbox`. ##### clear ```ts clear: () => Promise; ``` drops every message a claimed room's mailbox stores, the archive included, without reading an archive back first as a `delete` over every seq would. When it held any, every member present with `receive`, this app included, hears one `deleted` event from 1 to the room's `seq` before the call resolves. The claim, the size limit and `seq` stay: the next message takes the next `seq`, and nothing dropped comes back. A mailbox that is off has nothing to drop, and the call resolves. `mailbox` stays as it was, and `usage()` reads the new figures. From the room's owner only, which in a claimed room is the claim's account. Refused `invalid` (`rooms: the room is not claimed`) on an unclaimed room, `denied` (`rooms: not the room owner`) from anyone else, and `denied` (`rooms: only the app that claimed the room can change it`) from another app of the claim's account on a room claimed under an app's scope, as `claim` says. An fkn.app older than this call refuses it `unavailable` (`rooms: size limits and clearing are not available`) with nothing sent. ###### Returns `Promise`\<`void`\> ##### closed ```ts readonly closed: Promise; ``` Settles once, when the room ends for this app. Never rejects. ##### defaults ```ts defaults: () => RoomDefaults; ``` ###### Returns [`RoomDefaults`](/api/contract/#roomdefaults) ##### delete ```ts delete: (from, to?) => Promise; ``` drops stored messages: one of your own, or any range as the owner. On a room claimed under an app's scope, from another app of the claim's account, it is refused `denied` (`rooms: only the app that claimed the room can change it`), the account's own messages included, as `claim` says. ###### Parameters ###### from `number` ###### to? `number` ###### Returns `Promise`\<`void`\> ##### grant ```ts grant: (id, permission) => Promise; ``` gives a member a permission over the room default, from the owner only (`denied`, `rooms: not the room owner`). On a room claimed under an app's scope, from another app of the claim's account, it is refused `denied` (`rooms: only the app that claimed the room can change it`), as `claim` says. ###### Parameters ###### id `string` ###### permission [`RoomPermission`](/api/contract/#roompermission) ###### Returns `Promise`\<`void`\> ##### id ```ts readonly id: string; ``` `/`: the name under this app's own scope, or under `global` ##### invite ```ts readonly invite: string; ``` `key` and `id` as one string, the thing to put in a link ##### key ```ts readonly key: string; ``` the room key, base64url. The server never sees it. Anyone holding it and the id can join. ##### leave ```ts leave: () => Promise; ``` ends this `Room`: `closed` settles with `left`, and later requests are refused `closed` (`rooms: the room has ended`). The room counts members, not `Room`s: an account whose key this device holds is one member in all of its tabs, apps and devices, and a guest, or a tab without the account's key, is one member in that tab and in any tab duplicated from it. While another `Room` of the same member is open the member stays and nobody present hears a thing; the last one's leave is the departure, a `left` event with reason `left` for everyone else. ###### Returns `Promise`\<`void`\> ##### limit ```ts limit: { (maxMessageBytes, id?): Promise; (maxMessageBytes, id): Promise; }; ``` the message size cap, from 1 to 8,388,608 (8 MiB). With no id it sets the room default, which is always a number. With an id it sets that member's override, and null clears the override. From the owner only (`denied`, `rooms: not the room owner`); on a room claimed under an app's scope, from another app of the claim's account, it is refused `denied` (`rooms: only the app that claimed the room can change it`), as `claim` says. ###### Call Signature ```ts (maxMessageBytes, id?): Promise; ``` ###### Parameters ###### maxMessageBytes `number` ###### id? `string` ###### Returns `Promise`\<`void`\> ###### Call Signature ```ts (maxMessageBytes, id): Promise; ``` ###### Parameters ###### maxMessageBytes `number` \| `null` ###### id `string` ###### Returns `Promise`\<`void`\> ##### mailbox ```ts readonly mailbox: RoomMailbox | null; ``` what the mailbox holds, as the room last said. Null while the room keeps no messages: nobody has claimed it, or its claim keeps none. The account can delete the room from its fkn.app settings, which the app hears as a `claim` event. `setCap` and `clear` leave it as it was; `usage()` reads the figures again. ##### members ```ts members: () => Promise; ``` ###### Returns `Promise`\<[`RoomMember`](/api/contract/#roommember)[]\> ##### name ```ts readonly name: string; ``` ##### on ```ts on: (listener) => Promise<() => void>; ``` Await the returned unsubscribe in cleanup, the `account.onChange` shape. ###### Parameters ###### listener (`event`) => `void` ###### Returns `Promise`\<() => `void`\> ##### owner ```ts readonly owner: string; ``` the owner's member id, or '' while a claimed room's owner has never joined ##### release ```ts release: () => Promise; ``` gives the claim back: the mailbox is deleted and whoever is present stays in an ordinary room. On a room under an app's scope, the app that claimed it only (the same app once it is verified), and from another app it is refused `denied` (`rooms: only the app that claimed the room can release it`); on a `global` room, any app of the account. The account can also delete it from its fkn.app settings. ###### Returns `Promise`\<`void`\> ##### remove ```ts remove: (id) => Promise; ``` sends a member out of the room, which they may join again, with the `remove` permission (`denied`, `rooms: permission denied`). On a room claimed under an app's scope, from another app of the claim's account, it is refused `denied` (`rooms: only the app that claimed the room can change it`), as `claim` says. ###### Parameters ###### id `string` ###### Returns `Promise`\<`void`\> ##### revoke ```ts revoke: (id, permission) => Promise; ``` takes a permission from a member over the room default, from the owner only (`denied`, `rooms: not the room owner`). On a room claimed under an app's scope, from another app of the claim's account, it is refused `denied` (`rooms: only the app that claimed the room can change it`), as `claim` says. ###### Parameters ###### id `string` ###### permission [`RoomPermission`](/api/contract/#roompermission) ###### Returns `Promise`\<`void`\> ##### schema ```ts schema: () => RoomSchema | null; ``` the room's schema as the room last said, null for a room without one ###### Returns [`RoomSchema`](/api/contract/#roomschema) \| `null` ##### self ```ts readonly self: RoomMember; ``` this app's member record, as this room sees it. The id is fresh in every room. ##### setCap ```ts setCap: (bytes) => Promise; ``` sets the most a claimed room's mailbox stores, in bytes: a whole number from 1,000,000 to 500,000,000, or null to remove the limit, counted as the mailbox counts. Past it a send, or an edit that grows a message, is refused `storage` (`rooms: the mailbox is full`). Nothing stored is evicted, so a limit under what the mailbox holds refuses new messages until enough are deleted. The schema's `maxStoredBytes` still applies, the smaller winning, and turning the mailbox off removes the limit. Resolves once the room holds it; `mailbox` stays as it was, and `usage()` reads the new `cap`. From the room's owner only, which in a claimed room is the claim's account. Refused `invalid` (`rooms: the room is not claimed`) on an unclaimed room, `invalid` (`rooms: the room keeps no messages`) while its mailbox is off, `denied` (`rooms: not the room owner`) from anyone else, `denied` (`rooms: only the app that claimed the room can change it`) from another app of the claim's account on a room claimed under an app's scope, as `claim` says, and `invalid` (`rooms: the limit is out of range`) for anything but null or a whole number in the range. An fkn.app older than this call refuses it `unavailable` (`rooms: size limits and clearing are not available`) with nothing sent. ###### Parameters ###### bytes `number` \| `null` ###### Returns `Promise`\<`void`\> ##### setDefault ```ts setDefault: (permission, value) => Promise; ``` whether a member with no override may send or receive, from the owner only (`denied`, `rooms: not the room owner`). On a room claimed under an app's scope, from another app of the claim's account, it is refused `denied` (`rooms: only the app that claimed the room can change it`), as `claim` says. ###### Parameters ###### permission `"send"` \| `"receive"` ###### value `boolean` ###### Returns `Promise`\<`void`\> ##### setMailbox ```ts setMailbox: (on) => Promise; ``` turns a claimed room's mailbox off or on, from the room's owner only, which in a claimed room is the claim's account. Off deletes every stored message at once, the archive included, and the room then relays as an unclaimed one does while keeping its claim; whoever is present hears a `claim` event with `mailbox: false` and no `deleted`, so what an app shows stays. On starts an empty mailbox that keeps messages from the next `seq`, and nothing deleted comes back. Neither way needs premium. Off also removes the size limit `setCap` set, so On starts with none. Setting what it already is changes nothing. Resolves once the room answered, with `mailbox` reading the new state, or a newer one when a release or another switch landed before the answer. Refused `invalid` (`rooms: the room is not claimed`) on an unclaimed room, `denied` (`rooms: not the room owner`) from anyone else, `denied` (`rooms: only the app that claimed the room can change it`) from another app of the claim's account on a room claimed under an app's scope, as `claim` says, and `invalid` (`rooms: malformed frame`) for anything but a boolean. A broker too old to carry it refuses `unavailable` (`rooms: the mailbox switch is not available`). ###### Parameters ###### on `boolean` ###### Returns `Promise`\<`void`\> ##### setSchema ```ts setSchema: (schema) => Promise; ``` replaces the room's schema with one of a higher `version`, from the next send on; everyone present hears a `schema` event. The same schema at the same `version` resolves and changes nothing, so set it on every open. A lower `version`, or another schema at the same one, is refused `invalid` (`rooms: the room holds a newer schema`), and one the room cannot take `invalid` (`rooms: the schema is not one a room can take`). From the owner only (`denied`, `rooms: not the room owner`), and on a room claimed under an app's scope only through the app that claimed it (`denied`, `rooms: only the app that claimed the room can change it`), as `claim` says. A schema is never removed. An fkn.app older than room schemas refuses it `unavailable` (`rooms: room schemas are not available`). ###### Parameters ###### schema [`RoomSchema`](/api/contract/#roomschema) ###### Returns `Promise`\<`void`\> ##### unblock ```ts unblock: (id) => Promise; ``` lets a blocked member join again, with the `block` permission (`denied`, `rooms: permission denied`). On a room claimed under an app's scope, from another app of the claim's account, it is refused `denied` (`rooms: only the app that claimed the room can change it`), as `claim` says. ###### Parameters ###### id `string` ###### Returns `Promise`\<`void`\> ##### usage ```ts usage: () => Promise; ``` ###### Returns `Promise`\<[`RoomMailbox`](/api/contract/#roommailbox) \| `null`\> #### Methods ##### edit() ```ts edit( seq, data, envelope?): Promise; ``` replaces a stored message: one of your own, or any as the owner, with text or bytes as `send` takes them, whatever it held. Members hear an `edited` event for text and a `bytes-edited` one for bytes, so a member that reads only text keeps what it had when a text message is edited into bytes. Checked exactly as a send is, `send` and the rate limits included; in a room with a schema `envelope` is required and names the message's own type, so a message stored before the room had a schema is deleted rather than edited. On a room claimed under an app's scope, from another app of the claim's account, it is refused `denied` (`rooms: only the app that claimed the room can change it`), the account's own messages included, as `claim` says. ###### Parameters ###### seq `number` ###### data `string` \| `ArrayBuffer` \| `ArrayBufferView`\<`ArrayBufferLike`\> ###### envelope? [`RoomEnvelope`](/api/contract/#roomenvelope) ###### Returns `Promise`\<`void`\> ##### send() ```ts send(data, envelope?): Promise; ``` `data` is text, or bytes as an `ArrayBuffer`, a typed array or a `DataView`, sealed before it leaves the browser. Every member receives the same kind: text as a `message` event, bytes as a `bytes` event holding exactly the bytes the view covers. Bytes are copied at the call, so changing or transferring them afterwards changes nothing sent; anything else, a detached buffer included, is refused `invalid` (`rooms: malformed frame`). Whether a message is text or bytes is sealed with it, so FKN cannot tell. An fkn.app older than bytes refuses them `unavailable` (`rooms: binary messages are not available`) with nothing sent, and a member whose fkn.app is that old never receives them. Rejects `too-large` past `self.maxMessageBytes`, both kinds counted as `RoomDefaults` says, never truncates. In a room with a schema `envelope` is required: it goes in plain beside the sealed part, which may be empty, and the sealed part opens only under it. The app chooses what is sealed at each send: put in the envelope only what every member and FKN may read, and the rest in `data`. The lib writes it with `JSON.stringify` and refuses `invalid` (`rooms: the message does not fit the room's schema`), with nothing sent, one that is not a JSON object with a string `type` or is past 2,048 characters; the room refuses the same for an envelope that does not fit its type, or a send without one. The size counted is the envelope's text and the sealed part together, against `self.maxMessageBytes` and the type's `maxBytes`. The type's sender rule refuses `denied` (`rooms: only the owner sends this type`, `rooms: sending this needs an account`), its per-account limit `full` (`rooms: you have as many of these here as the room allows`), and the room's cap `storage` (`rooms: the mailbox is full`). Without a schema an envelope is refused `invalid` (`rooms: the room has no schema`). An fkn.app older than room schemas refuses one `unavailable` (`rooms: room schemas are not available`) with nothing sent; a send without one goes as before. ###### Parameters ###### data `string` \| `ArrayBuffer` \| `ArrayBufferView`\<`ArrayBufferLike`\> ###### envelope? [`RoomEnvelope`](/api/contract/#roomenvelope) ###### Returns `Promise`\<`void`\> *** ### RoomsError ```ts type RoomsError = Error & object; ``` Thrown by every member of this namespace. Match on `code`, never on the message. #### Type Declaration ##### code ```ts code: RoomsErrorCode; ``` ## Functions ### available() ```ts function available(): Promise; ``` Whether this realm can join a room: false in Node, false in a worker nothing bridged, false against a shell older than named rooms. Answers rather than rejecting. #### Returns `Promise`\<`boolean`\> *** ### create() ```ts function create(options?): Promise; ``` Open a room under a random name and become its owner. Share `room.invite` to let anyone else in. #### Parameters ##### options? [`RoomOpenOptions`](/api/contract/#roomopenoptions) #### Returns `Promise`\<[`Room`](#room)\> *** ### join() ```ts function join(invite, options?): Promise; ``` `invite` is `room.invite`: a key and a room id joined by a dot. #### Parameters ##### invite `string` ##### options? [`RoomJoinOptions`](/api/contract/#roomjoinoptions) #### Returns `Promise`\<[`Room`](#room)\> *** ### open() ```ts function open(name, options?): Promise; ``` Open a room by name: a name under this app's own scope, or `global/` for the shared one. Nobody there means the room comes into being with you as its owner; somebody there means you join them, and the key has to match theirs. Share `room.invite` to let anyone else in. #### Parameters ##### name `string` ##### options? [`RoomOpenOptions`](/api/contract/#roomopenoptions) #### Returns `Promise`\<[`Room`](#room)\> ## References ### ClaimOptions Renames and re-exports [RoomClaimOptions](/api/contract/#roomclaimoptions) *** ### CreateOptions Renames and re-exports [RoomCreateOptions](/api/contract/#roomcreateoptions) *** ### JoinOptions Renames and re-exports [RoomJoinOptions](/api/contract/#roomjoinoptions) *** ### OpenOptions Renames and re-exports [RoomOpenOptions](/api/contract/#roomopenoptions) *** ### RoomBacklog Re-exports [RoomBacklog](/api/contract/#roombacklog) *** ### RoomBytesMessage Re-exports [RoomBytesMessage](/api/contract/#roombytesmessage) *** ### RoomDefaults Re-exports [RoomDefaults](/api/contract/#roomdefaults) *** ### RoomEnd Re-exports [RoomEnd](/api/contract/#roomend) *** ### RoomEnvelope Re-exports [RoomEnvelope](/api/contract/#roomenvelope) *** ### RoomEvent Re-exports [RoomEvent](/api/contract/#roomevent) *** ### RoomJson Re-exports [RoomJson](/api/contract/#roomjson) *** ### RoomMailbox Re-exports [RoomMailbox](/api/contract/#roommailbox) *** ### RoomMember Re-exports [RoomMember](/api/contract/#roommember) *** ### RoomMessage Re-exports [RoomMessage](/api/contract/#roommessage) *** ### RoomPermission Re-exports [RoomPermission](/api/contract/#roompermission) *** ### RoomPermissions Re-exports [RoomPermissions](/api/contract/#roompermissions) *** ### RoomSchema Re-exports [RoomSchema](/api/contract/#roomschema) *** ### RoomsErrorCode Re-exports [RoomsErrorCode](/api/contract/#roomserrorcode) *** ### RoomType Re-exports [RoomType](/api/contract/#roomtype) --- # @fkn/lib/storage URL: https://docs.fkn.dev/api/storage/ ## Type Aliases ### StorageError ```ts type StorageError = Error & object; ``` Thrown by every member of this namespace except on an aborted signal. Match on `code`, never on the message. #### Type Declaration ##### code ```ts code: StorageErrorCode; ``` *** ### StoredBlob ```ts type StoredBlob = object; ``` The bytes `get` opened, shaped like a `Blob`: `size`, `stream`, `arrayBuffer` and `slice`. Every read is by range and each 1 MiB record is checked before it is handed over, so a `slice` near the end of a large object fetches only that end. #### Properties ##### arrayBuffer ```ts arrayBuffer: () => Promise; ``` ###### Returns `Promise`\<`ArrayBuffer`\> ##### size ```ts size: number; ``` the plaintext bytes of this blob, a slice's own length ##### slice ```ts slice: (start?, end?) => StoredBlob; ``` `Blob.slice`'s arguments, negative ones counted from the end, and the same shape back ###### Parameters ###### start? `number` ###### end? `number` ###### Returns [`StoredBlob`](#storedblob) ##### stream ```ts stream: () => ReadableStream; ``` errors with `integrity` on the first record that does not open under the key ###### Returns `ReadableStream`\<`Uint8Array`\> ## Functions ### available() ```ts function available(): Promise; ``` Whether put, list and delete can run here now. `get` needs no account and does not depend on this. Answers rather than rejecting. #### Returns `Promise`\<`boolean`\> *** ### delete() ```ts function delete(url): Promise; ``` Deletes an object by its url: every later `get` of it answers `not-found`, and an upload in progress is aborted and stops counting. Only the app that stored it (the same app once it is verified) deletes it, `denied` otherwise. An object already gone resolves. #### Parameters ##### url `string` #### Returns `Promise`\<`void`\> *** ### get() ```ts function get( url, key, options?): Promise; ``` Opens an object any app stored, with no account: the broker reads its size from the first ranged answer and fetches the sealed bytes by range. Refused `invalid` for a url that names no stored object or a key that is not 32 bytes base64url, `not-found` for an object that was never made, was deleted or is still uploading (one answer for all of them). A wrong key shows on the first read, as `integrity`. A broker replaced while the object is held is asked to open it again on the next read. `signal` aborts the opening and every read of the blob or its slices still in flight, which then errors with the signal's reason as a fetch body does. It is followed only while one of them runs, so one long-lived signal can serve any number of calls and blobs. #### Parameters ##### url `string` ##### key `string` ##### options? ###### signal? `AbortSignal` #### Returns `Promise`\<[`StoredBlob`](#storedblob)\> *** ### list() ```ts function list(options?): Promise; ``` This app's objects, newest first, uploads in progress included: no key, which the service never holds. `limit` is 1 to 1,000 (1,000 by default), and `cursor` is the one a previous page answered; `invalid` otherwise. #### Parameters ##### options? ###### cursor? `string` ###### limit? `number` #### Returns `Promise`\<[`StoredPage`](/api/contract/#storedpage)\> *** ### put() ```ts function put(data, options?): Promise; ``` Seals the data in the broker and uploads it, then answers its url and the key that opens it: the app's own `key` unchanged, or the one the broker minted. Resolves once the object is `ready`. Needs a signed-in account, and counts the sealed size (28 bytes more per 1 MiB) against the account's storage from the moment it starts until the object is deleted or the upload is aborted. The account the call belongs to is the one this page is on when it is made, as for every storage call. `data` is a `Blob` (a `File` included) or a `ReadableStream` with its `size`. An upload survives the network dropping a part, not a reload: a reload starts the file again, and the upload left behind stops counting within the hour. Refused `invalid` for a stream without its size or one that delivers another, a file past the service's part ceiling, or a `key` that is not 32 bytes base64url; `denied` with no account; `quota`; `too-many` past the account's stored objects or this hour's uploads; `account-changed`. #### Parameters ##### data `Blob` \| `ReadableStream`\<`Uint8Array`\<`ArrayBufferLike`\>\> ##### options? [`StoragePutOptions`](/api/contract/#storageputoptions) = `{}` #### Returns `Promise`\<[`StoredObject`](/api/contract/#storedobject) & `object`\> ## References ### StorageErrorCode Re-exports [StorageErrorCode](/api/contract/#storageerrorcode) *** ### StorageProgress Re-exports [StorageProgress](/api/contract/#storageprogress) *** ### StoragePutOptions Re-exports [StoragePutOptions](/api/contract/#storageputoptions) *** ### StoredObject Re-exports [StoredObject](/api/contract/#storedobject) *** ### StoredPage Re-exports [StoredPage](/api/contract/#storedpage) --- # @fkn/lib/react URL: https://docs.fkn.dev/api/react/ ## Type Aliases ### ConnectButtonProps ```ts type ConnectButtonProps = object; ``` #### Properties ##### className? ```ts optional className?: string; ``` ##### style? ```ts optional style?: CSSProperties; ``` *** ### PoweredByFknProps ```ts type PoweredByFknProps = PoweredByOptions & object; ``` #### Type Declaration ##### className? ```ts optional className?: string; ``` ##### style? ```ts optional style?: CSSProperties; ``` *** ### PoweredByOptions ```ts type PoweredByOptions = object; ``` #### Properties ##### href? ```ts optional href?: string; ``` Where that link leads, in a new tab. Defaults to FKN's documentation, https://docs.fkn.dev/. ##### label? ```ts optional label?: string; ``` The mark's accessible name and tooltip, and the popup's heading. Defaults to "Powered by FKN". ##### linkLabel? ```ts optional linkLabel?: string; ``` The words of the popup's one link. Defaults to "How it works", as on fkn.app's "through FKN" popup. ## Functions ### ConnectButton() ```ts function ConnectButton(__namedParameters?): ReactElement; ``` #### Parameters ##### \_\_namedParameters? [`ConnectButtonProps`](#connectbuttonprops) = `{}` #### Returns `ReactElement` *** ### connectButtonUrl() ```ts function connectButtonUrl(): string; ``` #### Returns `string` *** ### PoweredByFkn() ```ts function PoweredByFkn(__namedParameters): ReactElement; ``` FKN's mark and its popup, in a span that takes `className` and `style` (its font size sizes the mark). Clicking opens the page's FKN header when connected, or toggles the popup otherwise. #### Parameters ##### \_\_namedParameters [`PoweredByFknProps`](#poweredbyfknprops) #### Returns `ReactElement` --- # @fkn/lib/desktop URL: https://docs.fkn.dev/api/desktop/ ## Variables ### dgram ```ts const dgram: object; ``` Planned desktop UDP backend. Every method throws in this release. #### Type Declaration ##### createSocket ```ts createSocket: (..._args) => never; ``` ###### Parameters ###### \_args ...`unknown`[] ###### Returns `never` *** ### dns ```ts const dns: object; ``` Planned desktop DNS backend. Every method throws in this release. #### Type Declaration ##### lookup ```ts lookup: (..._args) => never; ``` ###### Parameters ###### \_args ...`unknown`[] ###### Returns `never` *** ### fetch ```ts const fetch: (input, init?) => Promise; ``` Planned desktop fetch backend. Throws in this release. #### Parameters ##### input `RequestInfo` \| `URL` ##### init? `RequestInit` #### Returns `Promise`\<`Response`\> *** ### fs ```ts const fs: object; ``` Planned desktop storage backend. available() resolves false; storage operations throw. #### Type Declaration ##### appendFile ```ts appendFile: (..._args) => never; ``` ###### Parameters ###### \_args ...`unknown`[] ###### Returns `never` ##### appendFileSync ```ts appendFileSync: (..._args) => never; ``` ###### Parameters ###### \_args ...`unknown`[] ###### Returns `never` ##### available ```ts available: () => Promise; ``` ###### Returns `Promise`\<`boolean`\> ##### existsSync ```ts existsSync: (..._args) => never; ``` ###### Parameters ###### \_args ...`unknown`[] ###### Returns `never` ##### flush ```ts flush: (..._args) => never; ``` ###### Parameters ###### \_args ...`unknown`[] ###### Returns `never` ##### mkdir ```ts mkdir: (..._args) => never; ``` ###### Parameters ###### \_args ...`unknown`[] ###### Returns `never` ##### mkdirSync ```ts mkdirSync: (..._args) => never; ``` ###### Parameters ###### \_args ...`unknown`[] ###### Returns `never` ##### mount ```ts mount: (..._args) => never; ``` ###### Parameters ###### \_args ...`unknown`[] ###### Returns `never` ##### promises ```ts promises: object; ``` ###### promises.mkdir ```ts mkdir: (..._args) => never; ``` ###### Parameters ###### \_args ...`unknown`[] ###### Returns `never` ###### promises.readdir ```ts readdir: (..._args) => never; ``` ###### Parameters ###### \_args ...`unknown`[] ###### Returns `never` ###### promises.readFile ```ts readFile: (..._args) => never; ``` ###### Parameters ###### \_args ...`unknown`[] ###### Returns `never` ###### promises.rename ```ts rename: (..._args) => never; ``` ###### Parameters ###### \_args ...`unknown`[] ###### Returns `never` ###### promises.rm ```ts rm: (..._args) => never; ``` ###### Parameters ###### \_args ...`unknown`[] ###### Returns `never` ###### promises.stat ```ts stat: (..._args) => never; ``` ###### Parameters ###### \_args ...`unknown`[] ###### Returns `never` ###### promises.unlink ```ts unlink: (..._args) => never; ``` ###### Parameters ###### \_args ...`unknown`[] ###### Returns `never` ###### promises.writeFile ```ts writeFile: (..._args) => never; ``` ###### Parameters ###### \_args ...`unknown`[] ###### Returns `never` ##### readdir ```ts readdir: (..._args) => never; ``` ###### Parameters ###### \_args ...`unknown`[] ###### Returns `never` ##### readdirSync ```ts readdirSync: (..._args) => never; ``` ###### Parameters ###### \_args ...`unknown`[] ###### Returns `never` ##### readFile ```ts readFile: (..._args) => never; ``` ###### Parameters ###### \_args ...`unknown`[] ###### Returns `never` ##### readFileSync ```ts readFileSync: (..._args) => never; ``` ###### Parameters ###### \_args ...`unknown`[] ###### Returns `never` ##### rename ```ts rename: (..._args) => never; ``` ###### Parameters ###### \_args ...`unknown`[] ###### Returns `never` ##### renameSync ```ts renameSync: (..._args) => never; ``` ###### Parameters ###### \_args ...`unknown`[] ###### Returns `never` ##### rm ```ts rm: (..._args) => never; ``` ###### Parameters ###### \_args ...`unknown`[] ###### Returns `never` ##### rmSync ```ts rmSync: (..._args) => never; ``` ###### Parameters ###### \_args ...`unknown`[] ###### Returns `never` ##### stat ```ts stat: (..._args) => never; ``` ###### Parameters ###### \_args ...`unknown`[] ###### Returns `never` ##### statSync ```ts statSync: (..._args) => never; ``` ###### Parameters ###### \_args ...`unknown`[] ###### Returns `never` ##### unlink ```ts unlink: (..._args) => never; ``` ###### Parameters ###### \_args ...`unknown`[] ###### Returns `never` ##### unlinkSync ```ts unlinkSync: (..._args) => never; ``` ###### Parameters ###### \_args ...`unknown`[] ###### Returns `never` ##### writeFile ```ts writeFile: (..._args) => never; ``` ###### Parameters ###### \_args ...`unknown`[] ###### Returns `never` ##### writeFileSync ```ts writeFileSync: (..._args) => never; ``` ###### Parameters ###### \_args ...`unknown`[] ###### Returns `never` *** ### net ```ts const net: object; ``` Planned desktop TCP backend. Every method throws in this release. #### Type Declaration ##### connect ```ts connect: (..._args) => never; ``` ###### Parameters ###### \_args ...`unknown`[] ###### Returns `never` ##### createConnection ```ts createConnection: (..._args) => never; ``` ###### Parameters ###### \_args ...`unknown`[] ###### Returns `never` ##### createServer ```ts createServer: (..._args) => never; ``` ###### Parameters ###### \_args ...`unknown`[] ###### Returns `never` ## Functions ### available() ```ts function available(): boolean; ``` Typed placeholder for the planned desktop backend. Always false in this release. #### Returns `boolean` --- # @fkn/lib/broker-frame URL: https://docs.fkn.dev/api/broker-frame/ ## Variables ### brokerFrameScript ```ts const brokerFrameScript: string; ``` The source of an inline `