{"version":3,"sources":["../../src/react/index.tsx","../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/_dnt.shims.js","../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/consts.js","../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/kems/dhkemPrimitives/ec.js","../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/utils/noble.js","../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/hash/hash.js","../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/hash/hmac.js","../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/hash/u64.js","../../../node_modules/.pnpm/@hpke+common@1.10.1/node_modules/@hpke/common/esm/src/hash/sha3.js","../../../node_modules/.pnpm/@hpke+chacha20poly1305@1.8.0/node_modules/@hpke/chacha20poly1305/esm/src/chacha/utils.js","../../../node_modules/.pnpm/@hpke+chacha20poly1305@1.8.0/node_modules/@hpke/chacha20poly1305/esm/src/chacha/_arx.js","../../../node_modules/.pnpm/@hpke+chacha20poly1305@1.8.0/node_modules/@hpke/chacha20poly1305/esm/src/chacha/_poly1305.js","../../../node_modules/.pnpm/@hpke+chacha20poly1305@1.8.0/node_modules/@hpke/chacha20poly1305/esm/src/chacha/chacha.js","../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/exporterContext.js","../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/mutex.js","../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/recipientContext.js","../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/senderContext.js","../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/cipherSuiteNative.js","../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/kems/dhkemPrimitives/x25519.js","../../../node_modules/.pnpm/@hpke+core@1.9.0/node_modules/@hpke/core/esm/src/kems/dhkemPrimitives/x448.js","../../../core/src/config.ts","../../../core/src/errors.ts","../../../core/src/platform.ts","../../../core/src/pow.ts","../../../core/src/sealed.ts","../../../core/src/sealed-json.ts","../../../core/src/sealed-keys.ts","../../../core/src/url.ts","../../../core/src/http.ts","../../../core/src/token.ts","../../src/errors.ts","../../src/perf/url-redactor.ts","../../src/sse.ts","../../src/request.ts","../../src/state.ts","../../src/namespaces.ts","../../src/runtime-metadata.ts","../../src/version.ts","../../src/call.ts","../../src/room.ts","../../src/upload.ts","../../src/pb.ts","../../src/internal.ts"],"sourcesContent":["'use client';\n\n// `palbe/react` — thin React hooks over the observable `pb.*` facades. Each\n// value hook is a `useSyncExternalStore` (the React 18+ concurrent-safe\n// primitive) binding: `subscribe` is the facade's Unsubscribe-returning\n// listener, `getSnapshot` is the matching getter. NO new SDK behaviour lives\n// here — the hooks re-render exactly when (and only when) their slice of state\n// changes, mirroring the iOS `@Observable` granularity.\n//\n// `react` is an OPTIONAL peer dependency: importing `palbe` (the core entry)\n// never pulls React; only `palbe/react` does.\n//\n// Client-only: the module starts with `'use client'` (Next.js App Router). SSR\n// initial values come from the `getServerSnapshot` arms (null user, empty flag\n// set) so a server render never touches the runtime singleton.\n\nimport { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react';\nimport type { AuthUser, Unsubscribe } from '../auth-facade.js';\nimport type { FlagsView, FlagValue } from '../flags-facade.js';\nimport { onConfigured } from '../internal.js';\nimport type { Chat } from '../messaging/chat.js';\nimport type { ChatMember, ChatMessage } from '../messaging/types.js';\nimport { pb } from '../pb.js';\nimport type { RealtimeConnectionState, RealtimePayload } from '../realtime/facade.js';\n\n/** The session slice `useSession` exposes. */\nexport interface SessionState {\n  signedIn: boolean;\n  user: AuthUser | null;\n}\n\n/** Frozen empty flag view — the stable server/unconfigured fallback for\n * `useFlags` (a fresh `{}` each call would loop `useSyncExternalStore`). */\nconst EMPTY_FLAGS: FlagsView = Object.freeze({});\n\n/** The signed-out session snapshot — a single frozen instance so the\n * unconfigured/server snapshot is referentially stable across calls. */\nconst SIGNED_OUT: SessionState = Object.freeze({ signedIn: false, user: null });\n\n/**\n * Wraps a facade-listener factory so hooks that mount BEFORE `__configure`\n * runs self-heal when configuration arrives (or changes on re-configure /\n * watch-mode regen).\n *\n * Behaviour:\n *  - If already configured at subscribe time, attaches the facade listener\n *    immediately AND registers an `onConfigured` watcher for future re-configures.\n *  - If NOT yet configured at subscribe time, only registers `onConfigured`;\n *    the facade listener is attached when configuration arrives.\n *  - On every configure event: detaches the old facade listener (if any),\n *    attaches a fresh one against the new runtime, then calls `onStoreChange`\n *    so React re-reads the snapshot from the new runtime.\n *  - The returned unsubscribe tears down both the onConfigured registration\n *    and the current facade listener.\n *\n * @param getFacadeListener - factory called when a runtime is available;\n *   must return an Unsubscribe; called with `onStoreChange` as its argument.\n */\nfunction subscribeWithConfig(\n  getFacadeListener: (onStoreChange: () => void) => Unsubscribe,\n): (onStoreChange: () => void) => Unsubscribe {\n  return (onStoreChange: () => void): Unsubscribe => {\n    let currentFacadeUnsub: Unsubscribe | null = null;\n\n    function attachFacade(): void {\n      currentFacadeUnsub?.();\n      try {\n        currentFacadeUnsub = getFacadeListener(onStoreChange);\n      } catch {\n        // notConfigured — will be retried when onConfigured fires\n        currentFacadeUnsub = null;\n      }\n    }\n\n    // Register for future (re-)configure events.\n    const offConfigured = onConfigured(() => {\n      attachFacade();\n      // Notify React to re-read the snapshot from the new runtime.\n      onStoreChange();\n    });\n\n    // If already configured right now, attach immediately too.\n    attachFacade();\n\n    return () => {\n      offConfigured();\n      currentFacadeUnsub?.();\n      currentFacadeUnsub = null;\n    };\n  };\n}\n\n/**\n * Current authenticated user, or `null` when signed out. Re-renders on BOTH\n * auth-state transitions (sign-in adopts a user, sign-out clears it) and\n * user-profile changes (e.g. an email-verified flip via `refreshUser`).\n *\n * `getSnapshot` is guarded: before the generated `palbe.gen.ts` runs\n * `__configure`, `pb.auth` throws `notConfigured` — a tree rendered that early\n * gets `null`, never a render crash. Once `__configure` runs the hook\n * self-heals: it re-subscribes to the new runtime's auth facade and notifies\n * React to re-read the snapshot.\n */\nexport function useUser(): AuthUser | null {\n  return useSyncExternalStore(subscribeUserWithConfig, getUserSnapshot, getNullUser);\n}\n\nconst subscribeUserWithConfig = subscribeWithConfig((onStoreChange) => {\n  // Two sources, one composite unsubscribe:\n  //   onAuthStateChange → sign-in (new user) and sign-out (null)\n  //   onUserChange      → in-place profile edits (email-verified, …)\n  // Both fire immediately on subscribe (iOS parity), which simply re-reads the\n  // already-current snapshot — harmless.\n  const offState = pb.auth.onAuthStateChange(onStoreChange);\n  const offUser = pb.auth.onUserChange(onStoreChange);\n  return () => {\n    offState();\n    offUser();\n  };\n});\n\nfunction getUserSnapshot(): AuthUser | null {\n  try {\n    return pb.auth.currentUser;\n  } catch {\n    return null;\n  }\n}\n\nfunction getNullUser(): AuthUser | null {\n  return null;\n}\n\n/**\n * Session slice: `{ signedIn, user }`. Re-renders on auth-state transitions.\n *\n * `getSnapshot` MUST be referentially stable when nothing changed — returning a\n * fresh object every call would put `useSyncExternalStore` into an infinite\n * render loop. A per-component ref caches the last value and returns the SAME\n * object until `signedIn` or `user` actually changes.\n *\n * Self-heals when `__configure` runs after mount (same as `useUser`).\n */\nexport function useSession(): SessionState {\n  const lastRef = useRef<SessionState>(SIGNED_OUT);\n  const getSnapshot = useCallback((): SessionState => {\n    const next = readSession();\n    const prev = lastRef.current;\n    if (prev.signedIn === next.signedIn && prev.user === next.user) {\n      return prev; // unchanged — keep the stable reference\n    }\n    lastRef.current = next;\n    return next;\n  }, []);\n  return useSyncExternalStore(subscribeSessionWithConfig, getSnapshot, getSignedOut);\n}\n\nconst subscribeSessionWithConfig = subscribeWithConfig((onStoreChange) =>\n  pb.auth.onAuthStateChange(onStoreChange),\n);\n\nfunction readSession(): SessionState {\n  try {\n    const user = pb.auth.currentUser;\n    const signedIn = pb.auth.isSignedIn;\n    if (!signedIn && user === null) return SIGNED_OUT;\n    return { signedIn, user };\n  } catch {\n    return SIGNED_OUT;\n  }\n}\n\nfunction getSignedOut(): SessionState {\n  return SIGNED_OUT;\n}\n\n/**\n * Subscribe to ONE flag. Re-renders only when THIS key's value changes\n * (`pb.flags.subscribeKey` is the per-key source — structural compare for\n * objects), returning `fallback` until the key has a value.\n *\n * The value is read at the dynamic flag boundary where the concrete type `T`\n * is caller-asserted (the cached value is whatever the server sent); the\n * contained `as T` is the documented escape hatch — flags are untyped on the\n * wire, and the caller owns the `fallback`'s type.\n *\n * NOTE: passing an inline-object `fallback` for an absent key defeats snapshot\n * caching (a new object reference each render re-enters the last-value ref).\n * Memoize the fallback (e.g. a module-level const or `useMemo`) if it matters.\n *\n * Self-heals when `__configure` runs after mount (same as `useUser`).\n */\nexport function useFlag<T extends FlagValue>(key: string, fallback: T): T {\n  // Subscribe identity must change when `key` changes so useSyncExternalStore\n  // re-subscribes to the new key. subscribeWithConfig wraps the per-key\n  // factory so the hook also self-heals on (re-)configure.\n  // biome-ignore lint/correctness/useExhaustiveDependencies: `key` is a runtime param, not an outer-scope value — dependency IS required\n  const subscribe = useCallback(\n    subscribeWithConfig((onStoreChange) => pb.flags.subscribeKey(key, onStoreChange)),\n    [key],\n  );\n\n  // Cache the last value so getSnapshot is referentially stable (objects come\n  // back as the frozen pooled reference — stable identity until a real change).\n  const lastRef = useRef<T>(fallback);\n  const getSnapshot = useCallback((): T => {\n    let next: T;\n    try {\n      const value = pb.flags.get(key);\n      next = value === undefined ? fallback : (value as T);\n    } catch {\n      next = fallback;\n    }\n    if (!Object.is(next, lastRef.current)) {\n      lastRef.current = next;\n    }\n    return lastRef.current;\n  }, [key, fallback]);\n\n  return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n/**\n * Subscribe to the whole flag set. Re-renders on any change. `pb.flags.all()`\n * returns a frozen, identity-stable view (a NEW frozen object only when the set\n * actually changes), so it is `useSyncExternalStore`-safe as-is.\n *\n * Self-heals when `__configure` runs after mount (same as `useUser`).\n */\nexport function useFlags(): FlagsView {\n  return useSyncExternalStore(subscribeFlagsWithConfig, getFlagsSnapshot, getEmptyFlags);\n}\n\nconst subscribeFlagsWithConfig = subscribeWithConfig((onStoreChange) =>\n  pb.flags.onChange(onStoreChange),\n);\n\nfunction getFlagsSnapshot(): FlagsView {\n  try {\n    return pb.flags.all();\n  } catch {\n    return EMPTY_FLAGS;\n  }\n}\n\nfunction getEmptyFlags(): FlagsView {\n  return EMPTY_FLAGS;\n}\n\n/** The reported channel status: the shared-socket connection state, plus\n * `'unavailable'` when `pb.realtime.channel()` is not usable in this\n * environment (no WebSocket / SSR). */\nexport type ChannelStatus = RealtimeConnectionState | 'unavailable';\n\n/**\n * Subscribe a `handler` to one realtime `event` on `channel(name)` for the\n * lifetime of the component. Returns the live connection `{ status }`.\n *\n * The handler is held in a ref and refreshed every render, so passing a fresh\n * closure each render (the common case — callers needn't `useCallback`) does\n * NOT tear down and re-create the subscription. The subscription itself is\n * keyed on `[name, event]`: only a name/event change re-subscribes.\n *\n * StrictMode-safe: the facade refcounts joins, so React's mount→cleanup→\n * remount (double-invoke in dev) nets to exactly one live subscription via the\n * effect's `cancel()` cleanup — NO once-guard (a once-guard would leave the\n * subscription dead after the first cleanup; that was the P4 live-smoke bug).\n *\n * SSR / no-WebSocket: `pb.realtime.channel()` throws; the effect catches it and\n * reports `status: 'unavailable'` instead of crashing. (Effects don't run on\n * the server, so the initial server status is the idle default.)\n */\nexport function useChannel(\n  name: string,\n  event: string,\n  handler: (payload: RealtimePayload) => void,\n): { status: ChannelStatus } {\n  const handlerRef = useRef(handler);\n  // Refresh the handler every render WITHOUT re-subscribing — the effect below\n  // calls `handlerRef.current`, so the latest closure always runs.\n  useEffect(() => {\n    handlerRef.current = handler;\n  });\n\n  const [status, setStatus] = useState<ChannelStatus>('idle');\n\n  // A configure-epoch counter: bumped by onConfigured so the channel effect\n  // re-runs when a runtime arrives (handles the pre-config mount case and\n  // watch-mode runtime swaps). Does not re-subscribe on every render.\n  const [configEpoch, setConfigEpoch] = useState(0);\n  useEffect(() => {\n    return onConfigured(() => setConfigEpoch((n) => n + 1));\n  }, []);\n\n  // biome-ignore lint/correctness/useExhaustiveDependencies: `configEpoch` is intentionally a re-run trigger for configure-arrive / watch-mode\n  useEffect(() => {\n    let channel: ReturnType<typeof pb.realtime.channel>;\n    try {\n      channel = pb.realtime.channel(name);\n    } catch {\n      // notConfigured or no-WebSocket / server environment — degrade gracefully.\n      setStatus('unavailable');\n      return;\n    }\n    const sub = channel.on(event, (payload) => handlerRef.current(payload));\n    // Seed from the current connection state, then track transitions.\n    setStatus(pb.realtime.status.state);\n    const offStatus = pb.realtime.status.onChange((snapshot) => setStatus(snapshot.state));\n    return () => {\n      offStatus();\n      sub.cancel();\n    };\n  }, [name, event, configEpoch]);\n\n  return { status };\n}\n\n// ─── Messaging hooks (Web-MLS Phase 2) ───────────────────────────────────────\n\nconst EMPTY_CHATS: readonly Chat[] = Object.freeze([]);\nconst EMPTY_MESSAGES: readonly ChatMessage[] = Object.freeze([]);\nconst EMPTY_MEMBERS: readonly ChatMember[] = Object.freeze([]);\nconst EMPTY_TYPING: readonly ChatMember[] = Object.freeze([]);\n\n/**\n * The observable chat list (DMs + groups, active only). Re-renders when a chat\n * is added (you start one / a peer DMs you and the Welcome drains), removed, or\n * the list hydrates from the durable catalog on launch.\n *\n * Self-heals when `__configure` runs after mount (same as `useUser`).\n */\nexport function useChats(): readonly Chat[] {\n  const lastRef = useRef<readonly Chat[]>(EMPTY_CHATS);\n  const getSnapshot = useCallback((): readonly Chat[] => {\n    try {\n      const next = pb.messaging.chats;\n      // Identity-stable: only swap the cached array when the set changed.\n      if (next.length !== lastRef.current.length || next.some((c, i) => c !== lastRef.current[i])) {\n        lastRef.current = next.slice();\n      }\n      return lastRef.current;\n    } catch {\n      return EMPTY_CHATS;\n    }\n  }, []);\n  return useSyncExternalStore(subscribeChatsWithConfig, getSnapshot, getEmptyChats);\n}\n\nconst subscribeChatsWithConfig = subscribeWithConfig((onStoreChange) =>\n  pb.messaging.onChatsChange(onStoreChange),\n);\n\nfunction getEmptyChats(): readonly Chat[] {\n  return EMPTY_CHATS;\n}\n\n/**\n * Bind to one `Chat`'s changes. Re-renders whenever the chat's observable state\n * changes (a new message, members refresh, typing, materialize draft→active).\n * Returns the SAME `chat` instance for ergonomic access to `chat.messages`,\n * `chat.send(...)`, etc.\n */\nexport function useChat(chat: Chat): Chat {\n  const subscribe = useCallback(\n    (onStoreChange: () => void) => chat.onChange(onStoreChange),\n    [chat],\n  );\n  // The chat instance is pointer-stable; a per-render counter forces re-render\n  // on each onChange. Snapshot returns the instance itself (stable identity).\n  const getSnapshot = useCallback(() => chat, [chat]);\n  // Tick on every change so consumers reading chat.messages re-render.\n  const [, force] = useState(0);\n  useEffect(() => chat.onChange(() => force((n) => n + 1)), [chat]);\n  return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n}\n\n/**\n * The ordered message transcript for a chat (newest last). Re-renders on a new\n * message / history page / own-send echo. A cached snapshot keeps the array\n * reference stable until the list actually changes.\n */\nexport function useMessages(chat: Chat): readonly ChatMessage[] {\n  const lastRef = useRef<readonly ChatMessage[]>(EMPTY_MESSAGES);\n  const subscribe = useCallback(\n    (onStoreChange: () => void) => chat.onChange(onStoreChange),\n    [chat],\n  );\n  const getSnapshot = useCallback((): readonly ChatMessage[] => {\n    const next = chat.messages;\n    if (next.length !== lastRef.current.length || next.some((m, i) => m !== lastRef.current[i])) {\n      lastRef.current = next.slice();\n    }\n    return lastRef.current;\n  }, [chat]);\n  return useSyncExternalStore(subscribe, getSnapshot, () => EMPTY_MESSAGES);\n}\n\n/** The members of a chat (users). Re-renders when the roster changes. */\nexport function useChatMembers(chat: Chat): readonly ChatMember[] {\n  const lastRef = useRef<readonly ChatMember[]>(EMPTY_MEMBERS);\n  const subscribe = useCallback(\n    (onStoreChange: () => void) => chat.onChange(onStoreChange),\n    [chat],\n  );\n  const getSnapshot = useCallback((): readonly ChatMember[] => {\n    const next = chat.members;\n    if (next.length !== lastRef.current.length || next.some((m, i) => m !== lastRef.current[i])) {\n      lastRef.current = next.slice();\n    }\n    return lastRef.current;\n  }, [chat]);\n  return useSyncExternalStore(subscribe, getSnapshot, () => EMPTY_MEMBERS);\n}\n\n/** The users currently typing in a chat. Re-renders on typing start/stop. */\nexport function useTyping(chat: Chat): readonly ChatMember[] {\n  const lastRef = useRef<readonly ChatMember[]>(EMPTY_TYPING);\n  const subscribe = useCallback(\n    (onStoreChange: () => void) => chat.onChange(onStoreChange),\n    [chat],\n  );\n  const getSnapshot = useCallback((): readonly ChatMember[] => {\n    const next = chat.typing;\n    if (next.length !== lastRef.current.length || next.some((m, i) => m !== lastRef.current[i])) {\n      lastRef.current = next.slice();\n    }\n    return lastRef.current;\n  }, [chat]);\n  return useSyncExternalStore(subscribe, getSnapshot, () => EMPTY_TYPING);\n}\n","const dntGlobals = {};\nexport const dntGlobalThis = createMergeProxy(globalThis, dntGlobals);\nfunction createMergeProxy(baseObj, extObj) {\n    return new Proxy(baseObj, {\n        get(_target, prop, _receiver) {\n            if (prop in extObj) {\n                return extObj[prop];\n            }\n            else {\n                return baseObj[prop];\n            }\n        },\n        set(_target, prop, value) {\n            if (prop in extObj) {\n                delete extObj[prop];\n            }\n            baseObj[prop] = value;\n            return true;\n        },\n        deleteProperty(_target, prop) {\n            let success = false;\n            if (prop in extObj) {\n                delete extObj[prop];\n                success = true;\n            }\n            if (prop in baseObj) {\n                delete baseObj[prop];\n                success = true;\n            }\n            return success;\n        },\n        ownKeys(_target) {\n            const baseKeys = Reflect.ownKeys(baseObj);\n            const extKeys = Reflect.ownKeys(extObj);\n            const extKeysSet = new Set(extKeys);\n            return [...baseKeys.filter((k) => !extKeysSet.has(k)), ...extKeys];\n        },\n        defineProperty(_target, prop, desc) {\n            if (prop in extObj) {\n                delete extObj[prop];\n            }\n            Reflect.defineProperty(baseObj, prop, desc);\n            return true;\n        },\n        getOwnPropertyDescriptor(_target, prop) {\n            if (prop in extObj) {\n                return Reflect.getOwnPropertyDescriptor(extObj, prop);\n            }\n            else {\n                return Reflect.getOwnPropertyDescriptor(baseObj, prop);\n            }\n        },\n        has(_target, prop) {\n            return prop in extObj || prop in baseObj;\n        },\n    });\n}\n","// The input length limit (psk, psk_id, info, exporter_context, ikm).\nexport const INPUT_LENGTH_LIMIT = 8192;\nexport const INFO_LENGTH_LIMIT = 268435456;\n// The minimum length of a PSK.\nexport const MINIMUM_PSK_LENGTH = 32;\n// b\"\"\nexport const EMPTY = /* @__PURE__ */ new Uint8Array(0);\n// Common BigInt constants\nexport const N_0 = 0n;\nexport const N_1 = 1n;\nexport const N_2 = 2n;\nexport const N_7 = 7n;\nexport const N_32 = 32n;\nexport const N_256 = 256n;\nexport const N_0x71 = 0x71n;\nexport const BYTE_TO_BIGINT_256 = /* @__PURE__ */ (() => {\n    const out = new Array(256);\n    let i = 0;\n    let value = 0n;\n    while (i < 256) {\n        out[i] = value;\n        i++;\n        value += 1n;\n    }\n    return out;\n})();\n","import { NativeAlgorithm } from \"../../algorithm.js\";\nimport { BYTE_TO_BIGINT_256, EMPTY } from \"../../consts.js\";\nimport { toArrayBuffer } from \"../../kdfs/hkdf.js\";\nimport { DeriveKeyPairError, DeserializeError, NotSupportedError, SerializeError, } from \"../../errors.js\";\nimport { KemId } from \"../../identifiers.js\";\nimport { KEM_USAGES, LABEL_DKP_PRK } from \"../../interfaces/dhkemPrimitives.js\";\nimport { Bignum } from \"../../utils/bignum.js\";\nimport { base64UrlToBytes, i2Osp } from \"../../utils/misc.js\";\n// b\"candidate\"\n// deno-fmt-ignore\nconst LABEL_CANDIDATE = /* @__PURE__ */ new Uint8Array([\n    99, 97, 110, 100, 105, 100, 97, 116, 101,\n]);\n// the order of the curve being used.\n// deno-fmt-ignore\nconst ORDER_P_256 = /* @__PURE__ */ new Uint8Array([\n    0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xbc, 0xe6, 0xfa, 0xad, 0xa7, 0x17, 0x9e, 0x84,\n    0xf3, 0xb9, 0xca, 0xc2, 0xfc, 0x63, 0x25, 0x51,\n]);\n// deno-fmt-ignore\nconst ORDER_P_384 = /* @__PURE__ */ new Uint8Array([\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xc7, 0x63, 0x4d, 0x81, 0xf4, 0x37, 0x2d, 0xdf,\n    0x58, 0x1a, 0x0d, 0xb2, 0x48, 0xb0, 0xa7, 0x7a,\n    0xec, 0xec, 0x19, 0x6a, 0xcc, 0xc5, 0x29, 0x73,\n]);\n// deno-fmt-ignore\nconst ORDER_P_521 = /* @__PURE__ */ new Uint8Array([\n    0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n    0xff, 0xfa, 0x51, 0x86, 0x87, 0x83, 0xbf, 0x2f,\n    0x96, 0x6b, 0x7f, 0xcc, 0x01, 0x48, 0xf7, 0x09,\n    0xa5, 0xd0, 0x3b, 0xb5, 0xc9, 0xb8, 0x89, 0x9c,\n    0x47, 0xae, 0xbb, 0x6f, 0xb7, 0x1e, 0x91, 0x38,\n    0x64, 0x09,\n]);\n// deno-fmt-ignore\nconst PKCS8_ALG_ID_P_256 = /* @__PURE__ */ new Uint8Array([\n    48, 65, 2, 1, 0, 48, 19, 6, 7, 42,\n    134, 72, 206, 61, 2, 1, 6, 8, 42, 134,\n    72, 206, 61, 3, 1, 7, 4, 39, 48, 37,\n    2, 1, 1, 4, 32,\n]);\n// deno-fmt-ignore\nconst PKCS8_ALG_ID_P_384 = /* @__PURE__ */ new Uint8Array([\n    48, 78, 2, 1, 0, 48, 16, 6, 7, 42,\n    134, 72, 206, 61, 2, 1, 6, 5, 43, 129,\n    4, 0, 34, 4, 55, 48, 53, 2, 1, 1,\n    4, 48,\n]);\n// deno-fmt-ignore\nconst PKCS8_ALG_ID_P_521 = /* @__PURE__ */ new Uint8Array([\n    48, 96, 2, 1, 0, 48, 16, 6, 7, 42,\n    134, 72, 206, 61, 2, 1, 6, 5, 43, 129,\n    4, 0, 35, 4, 73, 48, 71, 2, 1, 1,\n    4, 66,\n]);\nconst EC_P_256_PARAMS = {\n    p: 0xffffffff00000001000000000000000000000000ffffffffffffffffffffffffn,\n    b: 0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604bn,\n    gx: 0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296n,\n    gy: 0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5n,\n    coordinateSize: 32,\n};\nconst EC_P_384_PARAMS = {\n    p: 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffffn,\n    b: 0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aefn,\n    gx: 0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7n,\n    gy: 0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5fn,\n    coordinateSize: 48,\n};\nconst EC_P_521_PARAMS = {\n    p: (1n << 521n) - 1n,\n    b: 0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00n,\n    gx: 0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66n,\n    gy: 0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650n,\n    coordinateSize: 66,\n};\nfunction mod(a, p) {\n    const r = a % p;\n    return r >= 0n ? r : r + p;\n}\nfunction modPow(base, exponent, p) {\n    let result = 1n;\n    let b = mod(base, p);\n    let e = exponent;\n    while (e > 0n) {\n        if ((e & 1n) === 1n) {\n            result = mod(result * b, p);\n        }\n        b = mod(b * b, p);\n        e >>= 1n;\n    }\n    return result;\n}\nfunction modSqrt(rhs, p) {\n    // P-256/P-384/P-521 primes satisfy p % 4 == 3.\n    const y = modPow(rhs, (p + 1n) >> 2n, p);\n    if (mod(y * y, p) !== mod(rhs, p)) {\n        throw new Error(\"Invalid ECDH point\");\n    }\n    return y;\n}\nfunction bytesToBigInt(bytes) {\n    let v = 0n;\n    for (const b of bytes) {\n        v = (v << 8n) | BYTE_TO_BIGINT_256[b];\n    }\n    return v;\n}\nfunction bigIntToBytes(v, len) {\n    const out = new Uint8Array(len);\n    let n = v;\n    for (let i = len - 1; i >= 0; i--) {\n        out[i] = Number(n & 0xffn);\n        n >>= 8n;\n    }\n    if (n !== 0n) {\n        throw new Error(\"Invalid coordinate length\");\n    }\n    return out;\n}\nfunction buildRawUncompressedPublicKey(x, y, coordinateSize) {\n    const out = new Uint8Array(1 + coordinateSize * 2);\n    out[0] = 0x04;\n    out.set(bigIntToBytes(x, coordinateSize), 1);\n    out.set(bigIntToBytes(y, coordinateSize), 1 + coordinateSize);\n    return out;\n}\nexport class Ec extends NativeAlgorithm {\n    constructor(kem, hkdf) {\n        super();\n        Object.defineProperty(this, \"_hkdf\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: void 0\n        });\n        Object.defineProperty(this, \"_alg\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: void 0\n        });\n        Object.defineProperty(this, \"_nPk\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: void 0\n        });\n        Object.defineProperty(this, \"_nSk\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: void 0\n        });\n        Object.defineProperty(this, \"_nDh\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: void 0\n        });\n        // EC specific arguments for deriving key pair.\n        Object.defineProperty(this, \"_order\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: void 0\n        });\n        Object.defineProperty(this, \"_bitmask\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: void 0\n        });\n        Object.defineProperty(this, \"_pkcs8AlgId\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: void 0\n        });\n        Object.defineProperty(this, \"_curveParams\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: void 0\n        });\n        this._hkdf = hkdf;\n        switch (kem) {\n            case KemId.DhkemP256HkdfSha256:\n                this._alg = { name: \"ECDH\", namedCurve: \"P-256\" };\n                this._nPk = 65;\n                this._nSk = 32;\n                this._nDh = 32;\n                this._order = ORDER_P_256;\n                this._bitmask = 0xFF;\n                this._pkcs8AlgId = PKCS8_ALG_ID_P_256;\n                this._curveParams = EC_P_256_PARAMS;\n                break;\n            case KemId.DhkemP384HkdfSha384:\n                this._alg = { name: \"ECDH\", namedCurve: \"P-384\" };\n                this._nPk = 97;\n                this._nSk = 48;\n                this._nDh = 48;\n                this._order = ORDER_P_384;\n                this._bitmask = 0xFF;\n                this._pkcs8AlgId = PKCS8_ALG_ID_P_384;\n                this._curveParams = EC_P_384_PARAMS;\n                break;\n            default:\n                // case KemId.DhkemP521HkdfSha512:\n                this._alg = { name: \"ECDH\", namedCurve: \"P-521\" };\n                this._nPk = 133;\n                this._nSk = 66;\n                this._nDh = 66;\n                this._order = ORDER_P_521;\n                this._bitmask = 0x01;\n                this._pkcs8AlgId = PKCS8_ALG_ID_P_521;\n                this._curveParams = EC_P_521_PARAMS;\n                break;\n        }\n    }\n    async serializePublicKey(key) {\n        await this._setup();\n        try {\n            return await this._api.exportKey(\"raw\", key);\n        }\n        catch (e) {\n            throw new SerializeError(e);\n        }\n    }\n    async deserializePublicKey(key) {\n        await this._setup();\n        try {\n            return await this._importRawKey(toArrayBuffer(key), true);\n        }\n        catch (e) {\n            throw new DeserializeError(e);\n        }\n    }\n    async serializePrivateKey(key) {\n        await this._setup();\n        try {\n            const jwk = await this._api.exportKey(\"jwk\", key);\n            if (!(\"d\" in jwk)) {\n                throw new Error(\"Not private key\");\n            }\n            return base64UrlToBytes(jwk[\"d\"]).buffer;\n        }\n        catch (e) {\n            throw new SerializeError(e);\n        }\n    }\n    async deserializePrivateKey(key) {\n        await this._setup();\n        try {\n            return await this._importRawKey(toArrayBuffer(key), false);\n        }\n        catch (e) {\n            throw new DeserializeError(e);\n        }\n    }\n    async importKey(format, key, isPublic) {\n        await this._setup();\n        try {\n            if (format === \"raw\") {\n                return await this._importRawKey(key, isPublic);\n            }\n            // jwk\n            if (key instanceof ArrayBuffer) {\n                throw new Error(\"Invalid jwk key format\");\n            }\n            return await this._importJWK(key, isPublic);\n        }\n        catch (e) {\n            throw new DeserializeError(e);\n        }\n    }\n    async generateKeyPair() {\n        await this._setup();\n        try {\n            return await this._api.generateKey(this._alg, true, KEM_USAGES);\n        }\n        catch (e) {\n            throw new NotSupportedError(e);\n        }\n    }\n    async deriveKeyPair(ikm) {\n        await this._setup();\n        try {\n            const rawIkm = toArrayBuffer(ikm);\n            const dkpPrk = await this._hkdf.labeledExtract(EMPTY, LABEL_DKP_PRK, new Uint8Array(rawIkm));\n            const bn = new Bignum(this._nSk);\n            for (let counter = 0; bn.isZero() || !bn.lessThan(this._order); counter++) {\n                if (counter > 255) {\n                    throw new Error(\"Faild to derive a key pair\");\n                }\n                const bytes = new Uint8Array(await this._hkdf.labeledExpand(dkpPrk, LABEL_CANDIDATE, i2Osp(counter, 1), this._nSk));\n                bytes[0] = bytes[0] & this._bitmask;\n                bn.set(bytes);\n            }\n            const sk = await this._deserializePkcs8Key(bn.val());\n            bn.reset();\n            return {\n                privateKey: sk,\n                publicKey: await this.derivePublicKey(sk),\n            };\n        }\n        catch (e) {\n            throw new DeriveKeyPairError(e);\n        }\n    }\n    async derivePublicKey(key) {\n        await this._setup();\n        try {\n            const jwk = await this._api.exportKey(\"jwk\", key);\n            delete jwk[\"d\"];\n            delete jwk[\"key_ops\"];\n            return await this._api.importKey(\"jwk\", jwk, this._alg, true, []);\n        }\n        catch {\n            try {\n                // Firefox fails to export JWK from some imported ECDH private keys.\n                return await this._derivePublicKeyWithoutJwkExport(key);\n            }\n            catch (e) {\n                throw new DeserializeError(e);\n            }\n        }\n    }\n    async dh(sk, pk) {\n        try {\n            await this._setup();\n            const bits = await this._api.deriveBits({\n                name: \"ECDH\",\n                public: pk,\n            }, sk, this._nDh * 8);\n            return bits;\n        }\n        catch (e) {\n            throw new SerializeError(e);\n        }\n    }\n    async _importRawKey(key, isPublic) {\n        if (isPublic && key.byteLength !== this._nPk) {\n            throw new Error(\"Invalid public key for the ciphersuite\");\n        }\n        if (!isPublic && key.byteLength !== this._nSk) {\n            throw new Error(\"Invalid private key for the ciphersuite\");\n        }\n        if (isPublic) {\n            return await this._api.importKey(\"raw\", key, this._alg, true, []);\n        }\n        return await this._deserializePkcs8Key(new Uint8Array(key));\n    }\n    async _importJWK(key, isPublic) {\n        if (typeof key.crv === \"undefined\" || key.crv !== this._alg.namedCurve) {\n            throw new Error(`Invalid crv: ${key.crv}`);\n        }\n        if (isPublic) {\n            if (typeof key.d !== \"undefined\") {\n                throw new Error(\"Invalid key: `d` should not be set\");\n            }\n            return await this._api.importKey(\"jwk\", key, this._alg, true, []);\n        }\n        if (typeof key.d === \"undefined\") {\n            throw new Error(\"Invalid key: `d` not found\");\n        }\n        return await this._api.importKey(\"jwk\", key, this._alg, true, KEM_USAGES);\n    }\n    async _deserializePkcs8Key(k) {\n        const pkcs8Key = new Uint8Array(this._pkcs8AlgId.length + k.length);\n        pkcs8Key.set(this._pkcs8AlgId, 0);\n        pkcs8Key.set(k, this._pkcs8AlgId.length);\n        return await this._api.importKey(\"pkcs8\", pkcs8Key, this._alg, true, KEM_USAGES);\n    }\n    async _derivePublicKeyWithoutJwkExport(key) {\n        const basePointRaw = buildRawUncompressedPublicKey(this._curveParams.gx, this._curveParams.gy, this._curveParams.coordinateSize);\n        const basePoint = await this._api.importKey(\"raw\", basePointRaw.buffer, this._alg, true, []);\n        const xBytes = new Uint8Array(await this._api.deriveBits({\n            name: \"ECDH\",\n            public: basePoint,\n        }, key, this._nDh * 8));\n        const p = this._curveParams.p;\n        const x = bytesToBigInt(xBytes);\n        const rhs = mod(modPow(x, 3n, p) - 3n * x + this._curveParams.b, p);\n        let y = modSqrt(rhs, p);\n        // Canonicalize sign so the encoded point is deterministic.\n        if ((y & 1n) === 1n) {\n            y = p - y;\n        }\n        const pubRaw = buildRawUncompressedPublicKey(x, y, this._curveParams.coordinateSize);\n        return await this._api.importKey(\"raw\", pubRaw.buffer, this._alg, true, []);\n    }\n}\n","// deno-lint-ignore-file no-explicit-any\n/**\n * This file is based on noble-curves (https://github.com/paulmillr/noble-curves).\n *\n * noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-curves/blob/b9d49d2b41d550571a0c5be443ecb62109fa3373/src/utils.ts\n */\n/**\n * Hex, bytes and number utilities.\n * @module\n */\nimport { loadCrypto } from \"./misc.js\";\nimport { N_0 } from \"../consts.js\";\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a) {\n    return a instanceof Uint8Array ||\n        (ArrayBuffer.isView(a) && a.constructor.name === \"Uint8Array\");\n}\n/** Asserts something is positive integer. */\nexport function anumber(n, title = \"\") {\n    if (!Number.isSafeInteger(n) || n < 0) {\n        const prefix = title && `\"${title}\" `;\n        throw new Error(`${prefix}expected integer >0, got ${n}`);\n    }\n}\n/** Asserts something is Uint8Array. */\nexport function abytes(value, length, title = \"\") {\n    const bytes = isBytes(value);\n    const len = value?.length;\n    const needsLen = length !== undefined;\n    if (!bytes || (needsLen && len !== length)) {\n        const prefix = title && `\"${title}\" `;\n        const ofLen = needsLen ? ` of length ${length}` : \"\";\n        const got = bytes ? `length=${len}` : `type=${typeof value}`;\n        throw new Error(prefix + \"expected Uint8Array\" + ofLen + \", got \" + got);\n    }\n    return value;\n}\n// ahash function is now imported from ../hash/hash.ts\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance, checkFinished = true) {\n    if (instance.destroyed)\n        throw new Error(\"Hash instance has been destroyed\");\n    if (checkFinished && instance.finished) {\n        throw new Error(\"Hash#digest() has already been called\");\n    }\n}\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out, instance) {\n    abytes(out, undefined, \"digestInto() output\");\n    const min = instance.outputLen;\n    if (out.length < min) {\n        throw new Error('\"digestInto() output\" expected to be of length >=' + min);\n    }\n}\n// Used in weierstrass, der\nfunction abignumer(n) {\n    if (typeof n === \"bigint\") {\n        if (!isPosBig(n))\n            throw new Error(\"positive bigint expected, got \" + n);\n    }\n    else\n        anumber(n);\n    return n;\n}\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr) {\n    return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays) {\n    for (let i = 0; i < arrays.length; i++) {\n        arrays[i].fill(0);\n    }\n}\n/** Pre-computed buffer for endianness detection */\nconst _endianTestBuffer = /* @__PURE__ */ new Uint32Array([0x11223344]);\nconst _endianTestBytes = /* @__PURE__ */ new Uint8Array(_endianTestBuffer.buffer);\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE = /* @__PURE__ */ _endianTestBytes[0] === 0x44;\n/** The byte swap operation for uint32 */\nexport function byteSwap(word) {\n    return (((word << 24) & 0xff000000) |\n        ((word << 8) & 0xff0000) |\n        ((word >>> 8) & 0xff00) |\n        ((word >>> 24) & 0xff));\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport function swap8IfBE(n) {\n    return isLE ? n : byteSwap(n);\n}\n/** @deprecated */\nexport const byteSwapIfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr) {\n    for (let i = 0; i < arr.length; i++) {\n        arr[i] = byteSwap(arr[i]);\n    }\n    return arr;\n}\nexport function swap32IfBE(u) {\n    return isLE ? u : byteSwap32(u);\n}\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr) {\n    return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word, shift) {\n    return (word << (32 - shift)) | (word >>> shift);\n}\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore: to use toHex\ntypeof Uint8Array.from([]).toHex === \"function\" &&\n    // @ts-ignore: to use fromHex\n    typeof Uint8Array.fromHex === \"function\")();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, \"0\"));\nconst HEX_TO_BIGINT = /* @__PURE__ */ [\n    0n,\n    1n,\n    2n,\n    3n,\n    4n,\n    5n,\n    6n,\n    7n,\n    8n,\n    9n,\n    10n,\n    11n,\n    12n,\n    13n,\n    14n,\n    15n,\n];\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n    abytes(bytes);\n    // @ts-ignore: to use toHex\n    if (hasHexBuiltin)\n        return bytes.toHex();\n    // pre-caching improves the speed 6x\n    let hex = \"\";\n    for (let i = 0; i < bytes.length; i++) {\n        hex += hexes[bytes[i]];\n    }\n    return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };\nfunction asciiToBase16(ch) {\n    if (ch >= asciis._0 && ch <= asciis._9)\n        return ch - asciis._0; // '2' => 50-48\n    if (ch >= asciis.A && ch <= asciis.F)\n        return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n    if (ch >= asciis.a && ch <= asciis.f)\n        return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n    return;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n    if (typeof hex !== \"string\") {\n        throw new Error(\"hex string expected, got \" + typeof hex);\n    }\n    // @ts-ignore: to use fromHex\n    if (hasHexBuiltin)\n        return Uint8Array.fromHex(hex);\n    const hl = hex.length;\n    const al = hl / 2;\n    if (hl % 2) {\n        throw new Error(\"hex string expected, got unpadded hex of length \" + hl);\n    }\n    const array = new Uint8Array(al);\n    for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n        const n1 = asciiToBase16(hex.charCodeAt(hi));\n        const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n        if (n1 === undefined || n2 === undefined) {\n            const char = hex[hi] + hex[hi + 1];\n            throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' +\n                hi);\n        }\n        array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n    }\n    return array;\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n    if (typeof str !== \"string\")\n        throw new Error(\"string expected\");\n    return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes) {\n    return new TextDecoder().decode(bytes);\n}\nexport function numberToHexUnpadded(num) {\n    const hex = abignumer(num).toString(16);\n    return hex.length & 1 ? \"0\" + hex : hex;\n}\nexport function hexToNumber(hex) {\n    if (typeof hex !== \"string\") {\n        throw new Error(\"hex string expected, got \" + typeof hex);\n    }\n    let out = N_0;\n    for (let i = 0; i < hex.length; i++) {\n        const n = asciiToBase16(hex.charCodeAt(i));\n        if (n === undefined) {\n            throw new Error('hex string expected, got non-hex character \"' + hex[i] +\n                '\" at index ' + i);\n        }\n        out = (out << 4n) | HEX_TO_BIGINT[n];\n    }\n    return out; // Big Endian\n}\nexport function numberToBigint(num) {\n    anumber(num, \"numberToBigint\");\n    let n = num;\n    let out = N_0;\n    let bit = 1n;\n    while (n > 0) {\n        if (n % 2 === 1)\n            out += bit;\n        n = Math.floor(n / 2);\n        bit <<= 1n;\n    }\n    return out;\n}\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes) {\n    return hexToNumber(bytesToHex(bytes));\n}\nexport function bytesToNumberLE(bytes) {\n    return hexToNumber(bytesToHex(copyBytes(abytes(bytes)).reverse()));\n}\nexport function numberToBytesBE(n, len) {\n    anumber(len);\n    n = abignumer(n);\n    const res = hexToBytes(n.toString(16).padStart(len * 2, \"0\"));\n    if (res.length !== len)\n        throw new Error(\"number too large\");\n    return res;\n}\nexport function numberToBytesLE(n, len) {\n    return numberToBytesBE(n, len).reverse();\n}\n/**\n * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer,\n * and Buffer#slice creates mutable copy. Never use Buffers!\n */\nexport function copyBytes(bytes) {\n    return Uint8Array.from(bytes);\n}\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays) {\n    let sum = 0;\n    for (let i = 0; i < arrays.length; i++) {\n        const a = arrays[i];\n        abytes(a);\n        sum += a.length;\n    }\n    const res = new Uint8Array(sum);\n    for (let i = 0, pad = 0; i < arrays.length; i++) {\n        const a = arrays[i];\n        res.set(a, pad);\n        pad += a.length;\n    }\n    return res;\n}\n/**\n * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols\n * Should be safe to use for things expected to be ASCII.\n * Returns exact same result as utf8ToBytes for ASCII or throws.\n */\nexport function asciiToBytes(ascii) {\n    return Uint8Array.from(ascii, (c, i) => {\n        const charCode = c.charCodeAt(0);\n        if (c.length !== 1 || charCode > 127) {\n            throw new Error(`string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`);\n        }\n        return charCode;\n    });\n}\n// Is positive bigint\nfunction isPosBig(n) {\n    return typeof n === \"bigint\" && N_0 <= n;\n}\nexport function inRange(n, min, max) {\n    return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n/**\n * Asserts min <= n < max. NOTE: It's < max and not <= max.\n * @example\n * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)\n */\nexport function aInRange(title, n, min, max) {\n    // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n    // consider P=256n, min=0n, max=P\n    // - a for min=0 would require -1:          `inRange('x', x, -1n, P)`\n    // - b would commonly require subtraction:  `inRange('x', x, 0n, P - 1n)`\n    // - our way is the cleanest:               `inRange('x', x, 0n, P)\n    if (!inRange(n, min, max)) {\n        throw new Error(\"expected valid \" + title + \": \" + min + \" <= n < \" + max + \", got \" + n);\n    }\n}\nexport function validateObject(object, fields = {}, optFields = {}) {\n    if (!object || typeof object !== \"object\") {\n        throw new Error(\"expected valid options object\");\n    }\n    function checkField(fieldName, expectedType, isOpt) {\n        const val = object[fieldName];\n        if (isOpt && val === undefined)\n            return;\n        const current = typeof val;\n        if (current !== expectedType || val === null) {\n            throw new Error(`param \"${fieldName}\" is invalid: expected ${expectedType}, got ${current}`);\n        }\n    }\n    const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n    iter(fields, false);\n    iter(optFields, true);\n}\n// createHasher function is now exported above with ahash\n// /** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\n// export function randomBytes(bytesLength = 32): Uint8Array {\n//   const cr = typeof globalThis != null && (globalThis as any).crypto;\n//   if (!cr || typeof cr.getRandomValues !== \"function\") {\n//     throw new Error(\"crypto.getRandomValues must be defined\");\n//   }\n//   return cr.getRandomValues(new Uint8Array(bytesLength));\n// }\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport async function randomBytesAsync(bytesLength = 32) {\n    const api = await loadCrypto();\n    const rnd = new Uint8Array(bytesLength);\n    api.getRandomValues(rnd);\n    return rnd;\n}\n// 06 09 60 86 48 01 65 03 04 02\nexport function oidNist(suffix) {\n    return {\n        oid: Uint8Array.from([\n            0x06,\n            0x09,\n            0x60,\n            0x86,\n            0x48,\n            0x01,\n            0x65,\n            0x03,\n            0x04,\n            0x02,\n            suffix,\n        ]),\n    };\n}\n","/**\n * This file is based on noble-curves (https://github.com/paulmillr/noble-curves).\n *\n * noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-curves/blob/b9d49d2b41d550571a0c5be443ecb62109fa3373/src/utils.ts\n */\n/**\n * Hash utilities and type definitions extracted from noble.ts\n * @module\n */\nimport { anumber } from \"../utils/noble.js\";\n/** Asserts something is hash */\nexport function ahash(h) {\n    if (typeof h !== \"function\" || typeof h.create !== \"function\") {\n        throw new Error(\"Hash must wrapped by utils.createHasher\");\n    }\n    anumber(h.outputLen);\n    anumber(h.blockLen);\n}\nexport function createHasher(hashCons, info = {}) {\n    const hashFn = (msg, opts) => hashCons(opts).update(msg).digest();\n    const tmp = hashCons(undefined);\n    const hashC = Object.assign(hashFn, {\n        outputLen: tmp.outputLen,\n        blockLen: tmp.blockLen,\n        create: (opts) => hashCons(opts),\n        ...info,\n    });\n    return Object.freeze(hashC);\n}\n","// deno-lint-ignore-file no-explicit-any\n/**\n * This file is based on noble-hashes (https://github.com/paulmillr/noble-hashes).\n *\n * noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-hashes/blob/2e0c00e1aa134082ba1380bf3afb8b1641f60fed/src/hmac.ts\n */\n/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, clean } from \"../utils/noble.js\";\nimport { ahash } from \"./hash.js\";\nexport class _HMAC {\n    constructor(hash, key) {\n        Object.defineProperty(this, \"oHash\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: void 0\n        });\n        Object.defineProperty(this, \"iHash\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: void 0\n        });\n        Object.defineProperty(this, \"blockLen\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: void 0\n        });\n        Object.defineProperty(this, \"outputLen\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: void 0\n        });\n        Object.defineProperty(this, \"finished\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: false\n        });\n        Object.defineProperty(this, \"destroyed\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: false\n        });\n        ahash(hash);\n        abytes(key, undefined, \"key\");\n        this.iHash = hash.create();\n        if (typeof this.iHash.update !== \"function\") {\n            throw new Error(\"Expected instance of class which extends utils.Hash\");\n        }\n        this.blockLen = this.iHash.blockLen;\n        this.outputLen = this.iHash.outputLen;\n        const blockLen = this.blockLen;\n        const pad = new Uint8Array(blockLen);\n        // blockLen can be bigger than outputLen\n        pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n        for (let i = 0; i < pad.length; i++)\n            pad[i] ^= 0x36;\n        this.iHash.update(pad);\n        // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n        this.oHash = hash.create();\n        // Undo internal XOR && apply outer XOR\n        for (let i = 0; i < pad.length; i++)\n            pad[i] ^= 0x36 ^ 0x5c;\n        this.oHash.update(pad);\n        clean(pad);\n    }\n    update(buf) {\n        aexists(this);\n        this.iHash.update(buf);\n        return this;\n    }\n    digestInto(out) {\n        aexists(this);\n        abytes(out, this.outputLen, \"output\");\n        this.finished = true;\n        this.iHash.digestInto(out);\n        this.oHash.update(out);\n        this.oHash.digestInto(out);\n        this.destroy();\n    }\n    digest() {\n        const out = new Uint8Array(this.oHash.outputLen);\n        this.digestInto(out);\n        return out;\n    }\n    _cloneInto(to) {\n        // Create new instance without calling constructor since key already in state and we don't know it.\n        to ||= Object.create(Object.getPrototypeOf(this), {});\n        const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n        to = to;\n        to.finished = finished;\n        to.destroyed = destroyed;\n        to.blockLen = blockLen;\n        to.outputLen = outputLen;\n        to.oHash = oHash._cloneInto(to.oHash);\n        to.iHash = iHash._cloneInto(to.iHash);\n        return to;\n    }\n    clone() {\n        return this._cloneInto();\n    }\n    destroy() {\n        this.destroyed = true;\n        this.oHash.destroy();\n        this.iHash.destroy();\n    }\n}\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n * @example\n * import { hmac } from '@noble/hashes/hmac';\n * import { sha256 } from '@noble/hashes/sha2';\n * const mac1 = hmac(sha256, 'key', 'message');\n */\nexport const hmac = (hash, key, message) => new _HMAC(hash, key).update(message).digest();\nhmac.create = (hash, key) => new _HMAC(hash, key);\n","/**\n * This file is based on noble-hashes (https://github.com/paulmillr/noble-hashes).\n *\n * noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-hashes/blob/4e358a46d682adfb005ae6314ec999f2513086b9/src/_u64.ts\n */\n/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = 0xffffffffn;\nconst _32n = 32n;\nfunction fromBig(n, le = false) {\n    if (le) {\n        return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n    }\n    return {\n        h: Number((n >> _32n) & U32_MASK64) | 0,\n        l: Number(n & U32_MASK64) | 0,\n    };\n}\nfunction split(lst, le = false) {\n    const len = lst.length;\n    const Ah = new Uint32Array(len);\n    const Al = new Uint32Array(len);\n    for (let i = 0; i < len; i++) {\n        const { h, l } = fromBig(lst[i], le);\n        [Ah[i], Al[i]] = [h, l];\n    }\n    return [Ah, Al];\n}\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h, _l, s) => h >>> s;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h, l) => l;\nconst rotr32L = (h, _l) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah, Al, Bh, Bl) {\n    const l = (Al >>> 0) + (Bl >>> 0);\n    return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig, };\n// prettier-ignore\nconst u64 = {\n    fromBig,\n    split,\n    toBig,\n    shrSH,\n    shrSL,\n    rotrSH,\n    rotrSL,\n    rotrBH,\n    rotrBL,\n    rotr32H,\n    rotr32L,\n    rotlSH,\n    rotlSL,\n    rotlBH,\n    rotlBL,\n    add,\n    add3L,\n    add3H,\n    add4L,\n    add4H,\n    add5H,\n    add5L,\n};\nexport default u64;\n","/**\n * This file is based on noble-hashes (https://github.com/paulmillr/noble-hashes).\n *\n * noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-hashes/blob/4e358a46d682adfb005ae6314ec999f2513086b9/src/sha3.ts\n */\n/**\n * SHA3 (keccak) hash function, based on a new \"Sponge function\" design.\n * Different from older hashes, the internal state is bigger than output size.\n *\n * Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),\n * [Website](https://keccak.team/keccak.html),\n * [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub).\n *\n * Check out `sha3-addons` module for cSHAKE, k12, and others.\n * @module\n */\nimport { rotlBH, rotlBL, rotlSH, rotlSL, split } from \"./u64.js\";\nimport { abytes, aexists, anumber, aoutput, clean, oidNist, swap32IfBE, u32, } from \"../utils/noble.js\";\nimport { createHasher, } from \"./hash.js\";\n// No __PURE__ annotations in sha3 header:\n// EVERYTHING is in fact used on every export.\n// Various per round constants calculations\nconst _0n = 0n;\nconst _1n = 1n;\nconst _2n = 2n;\nconst _7n = 7n;\nconst _256n = 256n;\nconst _0x71n = 0x71n;\nconst SHA3_PI = [];\nconst SHA3_ROTL = [];\nconst _SHA3_IOTA = []; // no pure annotation: var is always used\nfor (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {\n    // Pi\n    [x, y] = [y, (2 * x + 3 * y) % 5];\n    SHA3_PI.push(2 * (5 * y + x));\n    // Rotational\n    SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);\n    // Iota\n    let t = _0n;\n    for (let j = 0; j < 7; j++) {\n        R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;\n        if (R & _2n)\n            t ^= _1n << ((_1n << BigInt(j)) - _1n);\n    }\n    _SHA3_IOTA.push(t);\n}\nconst IOTAS = split(_SHA3_IOTA, true);\nconst SHA3_IOTA_H = IOTAS[0];\nconst SHA3_IOTA_L = IOTAS[1];\n// Left rotation (without 0, 32, 64)\nconst rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));\nconst rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));\n/** `keccakf1600` internal function, additionally allows to adjust round count. */\nexport function keccakP(s, rounds = 24, B) {\n    if (!B)\n        B = new Uint32Array(10);\n    // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)\n    for (let round = 24 - rounds; round < 24; round++) {\n        // Theta θ\n        for (let x = 0; x < 10; x++) {\n            B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];\n        }\n        // for (let x = 0; x < 10; x += 2) {\n        //   const idx1 = (x + 8) % 10;\n        //   const idx0 = (x + 2) % 10;\n        //   const B0 = B[idx0];\n        //   const B1 = B[idx0 + 1];\n        //   const Th = rotlH(B0, B1, 1) ^ B[idx1];\n        //   const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];\n        //   for (let y = 0; y < 50; y += 10) {\n        //     s[x + y] ^= Th;\n        //     s[x + y + 1] ^= Tl;\n        //   }\n        // }\n        { // x=0: idx0=2, idx1=8\n            const Th = rotlH(B[2], B[3], 1) ^ B[8];\n            const Tl = rotlL(B[2], B[3], 1) ^ B[9];\n            s[0] ^= Th;\n            s[1] ^= Tl;\n            s[10] ^= Th;\n            s[11] ^= Tl;\n            s[20] ^= Th;\n            s[21] ^= Tl;\n            s[30] ^= Th;\n            s[31] ^= Tl;\n            s[40] ^= Th;\n            s[41] ^= Tl;\n        }\n        { // x=2: idx0=4, idx1=0\n            const Th = rotlH(B[4], B[5], 1) ^ B[0];\n            const Tl = rotlL(B[4], B[5], 1) ^ B[1];\n            s[2] ^= Th;\n            s[3] ^= Tl;\n            s[12] ^= Th;\n            s[13] ^= Tl;\n            s[22] ^= Th;\n            s[23] ^= Tl;\n            s[32] ^= Th;\n            s[33] ^= Tl;\n            s[42] ^= Th;\n            s[43] ^= Tl;\n        }\n        { // x=4: idx0=6, idx1=2\n            const Th = rotlH(B[6], B[7], 1) ^ B[2];\n            const Tl = rotlL(B[6], B[7], 1) ^ B[3];\n            s[4] ^= Th;\n            s[5] ^= Tl;\n            s[14] ^= Th;\n            s[15] ^= Tl;\n            s[24] ^= Th;\n            s[25] ^= Tl;\n            s[34] ^= Th;\n            s[35] ^= Tl;\n            s[44] ^= Th;\n            s[45] ^= Tl;\n        }\n        { // x=6: idx0=8, idx1=4\n            const Th = rotlH(B[8], B[9], 1) ^ B[4];\n            const Tl = rotlL(B[8], B[9], 1) ^ B[5];\n            s[6] ^= Th;\n            s[7] ^= Tl;\n            s[16] ^= Th;\n            s[17] ^= Tl;\n            s[26] ^= Th;\n            s[27] ^= Tl;\n            s[36] ^= Th;\n            s[37] ^= Tl;\n            s[46] ^= Th;\n            s[47] ^= Tl;\n        }\n        { // x=8: idx0=0, idx1=6\n            const Th = rotlH(B[0], B[1], 1) ^ B[6];\n            const Tl = rotlL(B[0], B[1], 1) ^ B[7];\n            s[8] ^= Th;\n            s[9] ^= Tl;\n            s[18] ^= Th;\n            s[19] ^= Tl;\n            s[28] ^= Th;\n            s[29] ^= Tl;\n            s[38] ^= Th;\n            s[39] ^= Tl;\n            s[48] ^= Th;\n            s[49] ^= Tl;\n        }\n        // Rho (ρ) and Pi (π) — fully unrolled\n        let curH = s[2];\n        let curL = s[3];\n        // for (let t = 0; t < 24; t++) {\n        //   const shift = SHA3_ROTL[t];\n        //   const Th = rotlH(curH, curL, shift);\n        //   const Tl = rotlL(curH, curL, shift);\n        //   const PI = SHA3_PI[t];\n        //   curH = s[PI];\n        //   curL = s[PI + 1];\n        //   s[PI] = Th;\n        //   s[PI + 1] = Tl;\n        // }\n        let Th, Tl;\n        // t=0: shift=1(S), PI=20\n        Th = rotlSH(curH, curL, 1);\n        Tl = rotlSL(curH, curL, 1);\n        curH = s[20];\n        curL = s[21];\n        s[20] = Th;\n        s[21] = Tl;\n        // t=1: shift=3(S), PI=14\n        Th = rotlSH(curH, curL, 3);\n        Tl = rotlSL(curH, curL, 3);\n        curH = s[14];\n        curL = s[15];\n        s[14] = Th;\n        s[15] = Tl;\n        // t=2: shift=6(S), PI=22\n        Th = rotlSH(curH, curL, 6);\n        Tl = rotlSL(curH, curL, 6);\n        curH = s[22];\n        curL = s[23];\n        s[22] = Th;\n        s[23] = Tl;\n        // t=3: shift=10(S), PI=34\n        Th = rotlSH(curH, curL, 10);\n        Tl = rotlSL(curH, curL, 10);\n        curH = s[34];\n        curL = s[35];\n        s[34] = Th;\n        s[35] = Tl;\n        // t=4: shift=15(S), PI=36\n        Th = rotlSH(curH, curL, 15);\n        Tl = rotlSL(curH, curL, 15);\n        curH = s[36];\n        curL = s[37];\n        s[36] = Th;\n        s[37] = Tl;\n        // t=5: shift=21(S), PI=6\n        Th = rotlSH(curH, curL, 21);\n        Tl = rotlSL(curH, curL, 21);\n        curH = s[6];\n        curL = s[7];\n        s[6] = Th;\n        s[7] = Tl;\n        // t=6: shift=28(S), PI=10\n        Th = rotlSH(curH, curL, 28);\n        Tl = rotlSL(curH, curL, 28);\n        curH = s[10];\n        curL = s[11];\n        s[10] = Th;\n        s[11] = Tl;\n        // t=7: shift=36(B), PI=32\n        Th = rotlBH(curH, curL, 36);\n        Tl = rotlBL(curH, curL, 36);\n        curH = s[32];\n        curL = s[33];\n        s[32] = Th;\n        s[33] = Tl;\n        // t=8: shift=45(B), PI=16\n        Th = rotlBH(curH, curL, 45);\n        Tl = rotlBL(curH, curL, 45);\n        curH = s[16];\n        curL = s[17];\n        s[16] = Th;\n        s[17] = Tl;\n        // t=9: shift=55(B), PI=42\n        Th = rotlBH(curH, curL, 55);\n        Tl = rotlBL(curH, curL, 55);\n        curH = s[42];\n        curL = s[43];\n        s[42] = Th;\n        s[43] = Tl;\n        // t=10: shift=2(S), PI=48\n        Th = rotlSH(curH, curL, 2);\n        Tl = rotlSL(curH, curL, 2);\n        curH = s[48];\n        curL = s[49];\n        s[48] = Th;\n        s[49] = Tl;\n        // t=11: shift=14(S), PI=8\n        Th = rotlSH(curH, curL, 14);\n        Tl = rotlSL(curH, curL, 14);\n        curH = s[8];\n        curL = s[9];\n        s[8] = Th;\n        s[9] = Tl;\n        // t=12: shift=27(S), PI=30\n        Th = rotlSH(curH, curL, 27);\n        Tl = rotlSL(curH, curL, 27);\n        curH = s[30];\n        curL = s[31];\n        s[30] = Th;\n        s[31] = Tl;\n        // t=13: shift=41(B), PI=46\n        Th = rotlBH(curH, curL, 41);\n        Tl = rotlBL(curH, curL, 41);\n        curH = s[46];\n        curL = s[47];\n        s[46] = Th;\n        s[47] = Tl;\n        // t=14: shift=56(B), PI=38\n        Th = rotlBH(curH, curL, 56);\n        Tl = rotlBL(curH, curL, 56);\n        curH = s[38];\n        curL = s[39];\n        s[38] = Th;\n        s[39] = Tl;\n        // t=15: shift=8(S), PI=26\n        Th = rotlSH(curH, curL, 8);\n        Tl = rotlSL(curH, curL, 8);\n        curH = s[26];\n        curL = s[27];\n        s[26] = Th;\n        s[27] = Tl;\n        // t=16: shift=25(S), PI=24\n        Th = rotlSH(curH, curL, 25);\n        Tl = rotlSL(curH, curL, 25);\n        curH = s[24];\n        curL = s[25];\n        s[24] = Th;\n        s[25] = Tl;\n        // t=17: shift=43(B), PI=4\n        Th = rotlBH(curH, curL, 43);\n        Tl = rotlBL(curH, curL, 43);\n        curH = s[4];\n        curL = s[5];\n        s[4] = Th;\n        s[5] = Tl;\n        // t=18: shift=62(B), PI=40\n        Th = rotlBH(curH, curL, 62);\n        Tl = rotlBL(curH, curL, 62);\n        curH = s[40];\n        curL = s[41];\n        s[40] = Th;\n        s[41] = Tl;\n        // t=19: shift=18(S), PI=28\n        Th = rotlSH(curH, curL, 18);\n        Tl = rotlSL(curH, curL, 18);\n        curH = s[28];\n        curL = s[29];\n        s[28] = Th;\n        s[29] = Tl;\n        // t=20: shift=39(B), PI=44\n        Th = rotlBH(curH, curL, 39);\n        Tl = rotlBL(curH, curL, 39);\n        curH = s[44];\n        curL = s[45];\n        s[44] = Th;\n        s[45] = Tl;\n        // t=21: shift=61(B), PI=18\n        Th = rotlBH(curH, curL, 61);\n        Tl = rotlBL(curH, curL, 61);\n        curH = s[18];\n        curL = s[19];\n        s[18] = Th;\n        s[19] = Tl;\n        // t=22: shift=20(S), PI=12\n        Th = rotlSH(curH, curL, 20);\n        Tl = rotlSL(curH, curL, 20);\n        curH = s[12];\n        curL = s[13];\n        s[12] = Th;\n        s[13] = Tl;\n        // t=23: shift=44(B), PI=2\n        Th = rotlBH(curH, curL, 44);\n        Tl = rotlBL(curH, curL, 44);\n        s[2] = Th;\n        s[3] = Tl;\n        // Chi (χ)\n        for (let y = 0; y < 50; y += 10) {\n            B[0] = s[y];\n            B[1] = s[y + 1];\n            B[2] = s[y + 2];\n            B[3] = s[y + 3];\n            B[4] = s[y + 4];\n            B[5] = s[y + 5];\n            B[6] = s[y + 6];\n            B[7] = s[y + 7];\n            B[8] = s[y + 8];\n            B[9] = s[y + 9];\n            s[y + 0] ^= ~B[2] & B[4];\n            s[y + 1] ^= ~B[3] & B[5];\n            s[y + 2] ^= ~B[4] & B[6];\n            s[y + 3] ^= ~B[5] & B[7];\n            s[y + 4] ^= ~B[6] & B[8];\n            s[y + 5] ^= ~B[7] & B[9];\n            s[y + 6] ^= ~B[8] & B[0];\n            s[y + 7] ^= ~B[9] & B[1];\n            s[y + 8] ^= ~B[0] & B[2];\n            s[y + 9] ^= ~B[1] & B[3];\n        }\n        // Iota (ι)\n        s[0] ^= SHA3_IOTA_H[round];\n        s[1] ^= SHA3_IOTA_L[round];\n    }\n}\n/** Keccak sponge function. */\nexport class Keccak {\n    // NOTE: we accept arguments in bytes instead of bits here.\n    constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {\n        Object.defineProperty(this, \"state\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: void 0\n        });\n        Object.defineProperty(this, \"pos\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: 0\n        });\n        Object.defineProperty(this, \"posOut\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: 0\n        });\n        Object.defineProperty(this, \"finished\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: false\n        });\n        Object.defineProperty(this, \"state32\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: void 0\n        });\n        Object.defineProperty(this, \"destroyed\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: false\n        });\n        Object.defineProperty(this, \"_B\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: new Uint32Array(10)\n        });\n        Object.defineProperty(this, \"blockLen\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: void 0\n        });\n        Object.defineProperty(this, \"suffix\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: void 0\n        });\n        Object.defineProperty(this, \"outputLen\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: void 0\n        });\n        Object.defineProperty(this, \"enableXOF\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: false\n        });\n        Object.defineProperty(this, \"rounds\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: void 0\n        });\n        this.blockLen = blockLen;\n        this.suffix = suffix;\n        this.outputLen = outputLen;\n        this.enableXOF = enableXOF;\n        this.rounds = rounds;\n        // Can be passed from user as dkLen\n        anumber(outputLen, \"outputLen\");\n        // 1600 = 5x5 matrix of 64bit.  1600 bits === 200 bytes\n        // 0 < blockLen < 200\n        if (!(0 < blockLen && blockLen < 200)) {\n            throw new Error(\"only keccak-f1600 function is supported\");\n        }\n        this.state = new Uint8Array(200);\n        this.state32 = u32(this.state);\n    }\n    clone() {\n        return this._cloneInto();\n    }\n    /** Resets instance to initial (empty) state for reuse. */\n    reset() {\n        this.state.fill(0);\n        this.pos = 0;\n        this.posOut = 0;\n        this.finished = false;\n        this.destroyed = false;\n    }\n    keccak() {\n        swap32IfBE(this.state32);\n        keccakP(this.state32, this.rounds, this._B);\n        swap32IfBE(this.state32);\n        this.posOut = 0;\n        this.pos = 0;\n    }\n    update(data) {\n        aexists(this);\n        abytes(data);\n        return this.updateUnsafe(data);\n    }\n    /** Like update(), but skips validation. Caller must ensure valid state and input. */\n    updateUnsafe(data) {\n        const { blockLen, state } = this;\n        const len = data.length;\n        for (let pos = 0; pos < len;) {\n            const take = Math.min(blockLen - this.pos, len - pos);\n            for (let i = 0; i < take; i++)\n                state[this.pos++] ^= data[pos++];\n            if (this.pos === blockLen)\n                this.keccak();\n        }\n        return this;\n    }\n    finish() {\n        if (this.finished)\n            return;\n        this.finished = true;\n        const { state, suffix, pos, blockLen } = this;\n        // Do the padding\n        state[pos] ^= suffix;\n        if ((suffix & 0x80) !== 0 && pos === blockLen - 1)\n            this.keccak();\n        state[blockLen - 1] ^= 0x80;\n        this.keccak();\n    }\n    writeInto(out) {\n        aexists(this, false);\n        abytes(out);\n        return this.writeIntoUnsafe(out);\n    }\n    /** Like writeInto(), but skips validation. Caller must ensure valid state and output. */\n    writeIntoUnsafe(out) {\n        this.finish();\n        const bufferOut = this.state;\n        const { blockLen } = this;\n        for (let pos = 0, len = out.length; pos < len;) {\n            if (this.posOut >= blockLen)\n                this.keccak();\n            const take = Math.min(blockLen - this.posOut, len - pos);\n            out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);\n            this.posOut += take;\n            pos += take;\n        }\n        return out;\n    }\n    xofInto(out) {\n        // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF\n        if (!this.enableXOF) {\n            throw new Error(\"XOF is not possible for this instance\");\n        }\n        return this.writeInto(out);\n    }\n    xof(bytes) {\n        anumber(bytes);\n        return this.xofInto(new Uint8Array(bytes));\n    }\n    digestInto(out) {\n        aoutput(out, this);\n        if (this.finished)\n            throw new Error(\"digest() was already called\");\n        this.writeInto(out);\n        this.destroy();\n        return out;\n    }\n    digest() {\n        return this.digestInto(new Uint8Array(this.outputLen));\n    }\n    destroy() {\n        this.destroyed = true;\n        clean(this.state);\n    }\n    _cloneInto(to) {\n        const { blockLen, suffix, outputLen, rounds, enableXOF } = this;\n        to ||= new Keccak(blockLen, suffix, outputLen, enableXOF, rounds);\n        to.state32.set(this.state32);\n        to.pos = this.pos;\n        to.posOut = this.posOut;\n        to.finished = this.finished;\n        to.rounds = rounds;\n        // Suffix can change in cSHAKE\n        to.suffix = suffix;\n        to.outputLen = outputLen;\n        to.enableXOF = enableXOF;\n        to.destroyed = this.destroyed;\n        return to;\n    }\n}\nconst genKeccak = (suffix, blockLen, outputLen, info = {}) => createHasher(() => new Keccak(blockLen, suffix, outputLen), info);\n// /** SHA3-224 hash function. */\n// export const sha3_224: CHash = /* @__PURE__ */ genKeccak(\n//   0x06,\n//   144,\n//   28,\n//   /* @__PURE__ */ oidNist(0x07),\n// );\n/** SHA3-256 hash function. Different from keccak-256. */\nexport const sha3_256 = /* @__PURE__ */ genKeccak(0x06, 136, 32, \n/* @__PURE__ */ oidNist(0x08));\n/** SHA3-384 hash function. */\nexport const sha3_384 = /* @__PURE__ */ genKeccak(0x06, 104, 48, \n/* @__PURE__ */ oidNist(0x09));\n/** SHA3-512 hash function. */\nexport const sha3_512 = /* @__PURE__ */ genKeccak(0x06, 72, 64, \n/* @__PURE__ */ oidNist(0x0a));\n/** keccak-224 hash function. */\nexport const keccak_224 = /* @__PURE__ */ genKeccak(0x01, 144, 28);\n/** keccak-256 hash function. Different from SHA3-256. */\nexport const keccak_256 = /* @__PURE__ */ genKeccak(0x01, 136, 32);\n/** keccak-384 hash function. */\nexport const keccak_384 = /* @__PURE__ */ genKeccak(0x01, 104, 48);\n/** keccak-512 hash function. */\nexport const keccak_512 = /* @__PURE__ */ genKeccak(0x01, 72, 64);\nconst genShake = (suffix, blockLen, outputLen, info = {}) => createHasher((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true), info);\n/** SHAKE128 XOF with 128-bit security. */\nexport const shake128 = \n/* @__PURE__ */\ngenShake(0x1f, 168, 16, /* @__PURE__ */ oidNist(0x0b));\n/** SHAKE256 XOF with 256-bit security. */\nexport const shake256 = \n/* @__PURE__ */\ngenShake(0x1f, 136, 32, /* @__PURE__ */ oidNist(0x0c));\n// /** SHAKE128 XOF with 256-bit output (NIST version). */\n// export const shake128_32: CHashXOF<Keccak, ShakeOpts> =\n//   /* @__PURE__ */\n//   genShake(0x1f, 168, 32, /* @__PURE__ */ oidNist(0x0b));\n// /** SHAKE256 XOF with 512-bit output (NIST version). */\n// export const shake256_64: CHashXOF<Keccak, ShakeOpts> =\n//   /* @__PURE__ */\n//   genShake(0x1f, 136, 64, /* @__PURE__ */ oidNist(0x0c));\n","/**\n * This file is based on noble-ciphers (https://github.com/paulmillr/noble-ciphers).\n *\n * noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-ciphers/blob/749cdf9cd07ebdd19e9b957d0f172f1045179695/src/utils.ts\n */\n/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\nimport { abytes, aexists, anumber, aoutput, clean, copyBytes, createView, isLE, numberToBigint, u32, } from \"@hpke/common\";\nexport { abytes, aexists, anumber, aoutput, clean, copyBytes, createView, isLE, u32, };\n/** Asserts something is boolean. */\nexport function abool(b) {\n    if (typeof b !== \"boolean\")\n        throw new Error(`boolean expected, not ${b}`);\n}\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr) {\n    return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/**\n * Wraps a cipher: validates args, ensures encrypt() can only be called once.\n * @__NO_SIDE_EFFECTS__\n */\n// deno-lint-ignore no-explicit-any\nexport const wrapCipher = (params, constructor) => {\n    // deno-lint-ignore no-explicit-any\n    function wrappedCipher(key, ...args) {\n        // Validate key\n        abytes(key, undefined, \"key\");\n        // Big-Endian hardware is rare. Just in case someone still decides to run ciphers:\n        if (!isLE) {\n            throw new Error(\"Non little-endian hardware is not yet supported\");\n        }\n        // Validate nonce if nonceLength is present\n        if (params.nonceLength !== undefined) {\n            const nonce = args[0];\n            abytes(nonce, params.varSizeNonce ? undefined : params.nonceLength, \"nonce\");\n        }\n        // Validate AAD if tagLength present\n        const tagl = params.tagLength;\n        if (tagl && args[1] !== undefined)\n            abytes(args[1], undefined, \"AAD\");\n        const cipher = constructor(key, ...args);\n        const checkOutput = (fnLength, output) => {\n            if (output !== undefined) {\n                if (fnLength !== 2)\n                    throw new Error(\"cipher output not supported\");\n                abytes(output, undefined, \"output\");\n            }\n        };\n        // Create wrapped cipher with validation and single-use encryption\n        let called = false;\n        const wrCipher = {\n            encrypt(data, output) {\n                if (called) {\n                    throw new Error(\"cannot encrypt() twice with same key + nonce\");\n                }\n                called = true;\n                abytes(data);\n                checkOutput(cipher.encrypt.length, output);\n                return cipher.encrypt(data, output);\n            },\n            decrypt(data, output) {\n                abytes(data);\n                if (tagl && data.length < tagl) {\n                    throw new Error('\"ciphertext\" expected length bigger than tagLength=' + tagl);\n                }\n                checkOutput(cipher.decrypt.length, output);\n                return cipher.decrypt(data, output);\n            },\n        };\n        return wrCipher;\n    }\n    Object.assign(wrappedCipher, params);\n    return wrappedCipher;\n};\nexport function checkOpts(defaults, opts) {\n    if (opts == null || typeof opts !== \"object\") {\n        throw new Error(\"options must be defined\");\n    }\n    const merged = Object.assign(defaults, opts);\n    return merged;\n}\n/** Compares 2 uint8array-s in kinda constant time. */\nexport function equalBytes(a, b) {\n    if (a.length !== b.length)\n        return false;\n    let diff = 0;\n    for (let i = 0; i < a.length; i++)\n        diff |= a[i] ^ b[i];\n    return diff === 0;\n}\n/**\n * By default, returns u8a of length.\n * When out is available, it checks it for validity and uses it.\n */\nexport function getOutput(expectedLength, out, onlyAligned = true) {\n    if (out === undefined)\n        return new Uint8Array(expectedLength);\n    if (out.length !== expectedLength) {\n        throw new Error('\"output\" expected Uint8Array of length ' + expectedLength + \", got: \" +\n            out.length);\n    }\n    if (onlyAligned && !isAligned32(out)) {\n        throw new Error(\"invalid output, must be aligned\");\n    }\n    return out;\n}\nexport function u64Lengths(dataLength, aadLength, isLE) {\n    abool(isLE);\n    const num = new Uint8Array(16);\n    const view = createView(num);\n    view.setBigUint64(0, numberToBigint(aadLength), isLE);\n    view.setBigUint64(8, numberToBigint(dataLength), isLE);\n    return num;\n}\n// Is byte array aligned to 4 byte offset (u32)?\nexport function isAligned32(bytes) {\n    return bytes.byteOffset % 4 === 0;\n}\n// copy bytes to new u8a (aligned). Because Buffer.slice is broken.\n// Re-exported from @hpke/common.\n","/**\n * This file is based on noble-ciphers (https://github.com/paulmillr/noble-ciphers).\n *\n * noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-ciphers/blob/749cdf9cd07ebdd19e9b957d0f172f1045179695/src/_arx.ts\n */\n/**\n * Basic utils for ARX (add-rotate-xor) salsa and chacha ciphers.\n\nRFC8439 requires multi-step cipher stream, where\nauthKey starts with counter: 0, actual msg with counter: 1.\n\nFor this, we need a way to re-use nonce / counter:\n\n    const counter = new Uint8Array(4);\n    chacha(..., counter, ...); // counter is now 1\n    chacha(..., counter, ...); // counter is now 2\n\nThis is complicated:\n\n- 32-bit counters are enough, no need for 64-bit: max ArrayBuffer size in JS is 4GB\n- Original papers don't allow mutating counters\n- Counter overflow is undefined [^1]\n- Idea A: allow providing (nonce | counter) instead of just nonce, re-use it\n- Caveat: Cannot be re-used through all cases:\n- * chacha has (counter | nonce)\n- * xchacha has (nonce16 | counter | nonce16)\n- Idea B: separate nonce / counter and provide separate API for counter re-use\n- Caveat: there are different counter sizes depending on an algorithm.\n- salsa & chacha also differ in structures of key & sigma:\n  salsa20:      s[0] | k(4) | s[1] | nonce(2) | cnt(2) | s[2] | k(4) | s[3]\n  chacha:       s(4) | k(8) | cnt(1) | nonce(3)\n  chacha20orig: s(4) | k(8) | cnt(2) | nonce(2)\n- Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)`\n- Caveat: we can't re-use counter array\n\nxchacha [^2] uses the subkey and remaining 8 byte nonce with ChaCha20 as normal\n(prefixed by 4 NUL bytes, since [RFC8439] specifies a 12-byte nonce).\n\n[^1]: https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/\n[^2]: https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2\n\n * @module\n */\nimport { abool, abytes, anumber, checkOpts, clean, copyBytes, u32, } from \"./utils.js\";\n// Can't use similar utils.utf8ToBytes, because it uses `TextEncoder` - not available in all envs\nconst _utf8ToBytes = (str) => Uint8Array.from(str.split(\"\").map((c) => c.charCodeAt(0)));\nconst sigma16 = _utf8ToBytes(\"expand 16-byte k\");\nconst sigma32 = _utf8ToBytes(\"expand 32-byte k\");\nconst sigma16_32 = u32(sigma16);\nconst sigma32_32 = u32(sigma32);\n/** Rotate left. */\nexport function rotl(a, b) {\n    return (a << b) | (a >>> (32 - b));\n}\n// Is byte array aligned to 4 byte offset (u32)?\nfunction isAligned32(b) {\n    return b.byteOffset % 4 === 0;\n}\n// Salsa and Chacha block length is always 512-bit\nconst BLOCK_LEN = 64;\nconst BLOCK_LEN32 = 16;\n// new Uint32Array([2**32])   // => Uint32Array(1) [ 0 ]\n// new Uint32Array([2**32-1]) // => Uint32Array(1) [ 4294967295 ]\nconst MAX_COUNTER = 2 ** 32 - 1;\nconst U32_EMPTY = Uint32Array.of();\nfunction runCipher(core, sigma, key, nonce, data, output, counter, rounds) {\n    const len = data.length;\n    const block = new Uint8Array(BLOCK_LEN);\n    const b32 = u32(block);\n    // Make sure that buffers aligned to 4 bytes\n    const isAligned = isAligned32(data) && isAligned32(output);\n    const d32 = isAligned ? u32(data) : U32_EMPTY;\n    const o32 = isAligned ? u32(output) : U32_EMPTY;\n    for (let pos = 0; pos < len; counter++) {\n        core(sigma, key, nonce, b32, counter, rounds);\n        if (counter >= MAX_COUNTER)\n            throw new Error(\"arx: counter overflow\");\n        const take = Math.min(BLOCK_LEN, len - pos);\n        // aligned to 4 bytes\n        if (isAligned && take === BLOCK_LEN) {\n            const pos32 = pos / 4;\n            if (pos % 4 !== 0)\n                throw new Error(\"arx: invalid block position\");\n            for (let j = 0, posj; j < BLOCK_LEN32; j++) {\n                posj = pos32 + j;\n                o32[posj] = d32[posj] ^ b32[j];\n            }\n            pos += BLOCK_LEN;\n            continue;\n        }\n        for (let j = 0, posj; j < take; j++) {\n            posj = pos + j;\n            output[posj] = data[posj] ^ block[j];\n        }\n        pos += take;\n    }\n}\n/** Creates ARX-like (ChaCha, Salsa) cipher stream from core function. */\nexport function createCipher(core, opts) {\n    const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts({\n        allowShortKeys: false,\n        counterLength: 8,\n        counterRight: false,\n        rounds: 20,\n    }, opts);\n    if (typeof core !== \"function\")\n        throw new Error(\"core must be a function\");\n    anumber(counterLength);\n    anumber(rounds);\n    abool(counterRight);\n    abool(allowShortKeys);\n    return (key, nonce, data, output, counter = 0) => {\n        abytes(key, undefined, \"key\");\n        abytes(nonce, undefined, \"nonce\");\n        abytes(data, undefined, \"data\");\n        const len = data.length;\n        if (output === undefined)\n            output = new Uint8Array(len);\n        abytes(output, undefined, \"output\");\n        anumber(counter);\n        if (counter < 0 || counter >= MAX_COUNTER) {\n            throw new Error(\"arx: counter overflow\");\n        }\n        if (output.length < len) {\n            throw new Error(`arx: output (${output.length}) is shorter than data (${len})`);\n        }\n        const toClean = [];\n        // Key & sigma\n        // key=16 -> sigma16, k=key|key\n        // key=32 -> sigma32, k=key\n        const l = key.length;\n        let k;\n        let sigma;\n        if (l === 32) {\n            toClean.push(k = copyBytes(key));\n            sigma = sigma32_32;\n        }\n        else if (l === 16 && allowShortKeys) {\n            k = new Uint8Array(32);\n            k.set(key);\n            k.set(key, 16);\n            sigma = sigma16_32;\n            toClean.push(k);\n        }\n        else {\n            abytes(key, 32, \"arx key\");\n            throw new Error(\"invalid key size\");\n            // throw new Error(`\"arx key\" expected Uint8Array of length 32, got length=${l}`);\n        }\n        // Nonce\n        // salsa20:      8   (8-byte counter)\n        // chacha20orig: 8   (8-byte counter)\n        // chacha20:     12  (4-byte counter)\n        // xsalsa20:     24  (16 -> hsalsa,  8 -> old nonce)\n        // xchacha20:    24  (16 -> hchacha, 8 -> old nonce)\n        // Align nonce to 4 bytes\n        if (!isAligned32(nonce))\n            toClean.push(nonce = copyBytes(nonce));\n        const k32 = u32(k);\n        // hsalsa & hchacha: handle extended nonce\n        if (extendNonceFn) {\n            if (nonce.length !== 24) {\n                throw new Error(`arx: extended nonce must be 24 bytes`);\n            }\n            extendNonceFn(sigma, k32, u32(nonce.subarray(0, 16)), k32);\n            nonce = nonce.subarray(16);\n        }\n        // Handle nonce counter\n        const nonceNcLen = 16 - counterLength;\n        if (nonceNcLen !== nonce.length) {\n            throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`);\n        }\n        // Pad counter when nonce is 64 bit\n        if (nonceNcLen !== 12) {\n            const nc = new Uint8Array(12);\n            nc.set(nonce, counterRight ? 0 : 12 - nonce.length);\n            nonce = nc;\n            toClean.push(nonce);\n        }\n        const n32 = u32(nonce);\n        runCipher(core, sigma, k32, n32, data, output, counter, rounds);\n        clean(...toClean);\n        return output;\n    };\n}\n","/**\n * This file is based on noble-ciphers (https://github.com/paulmillr/noble-ciphers).\n *\n * noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-ciphers/blob/749cdf9cd07ebdd19e9b957d0f172f1045179695/src/_poly1305.ts\n */\n/**\n * Poly1305 ([PDF](https://cr.yp.to/mac/poly1305-20050329.pdf),\n * [wiki](https://en.wikipedia.org/wiki/Poly1305))\n * is a fast and parallel secret-key message-authentication code suitable for\n * a wide variety of applications. It was standardized in\n * [RFC 8439](https://www.rfc-editor.org/rfc/rfc8439) and is now used in TLS 1.3.\n *\n * Polynomial MACs are not perfect for every situation:\n * they lack Random Key Robustness: the MAC can be forged, and can't be used in PAKE schemes.\n * See [invisible salamanders attack](https://keymaterial.net/2020/09/07/invisible-salamanders-in-aes-gcm-siv/).\n * To combat invisible salamanders, `hash(key)` can be included in ciphertext,\n * however, this would violate ciphertext indistinguishability:\n * an attacker would know which key was used - so `HKDF(key, i)`\n * could be used instead.\n *\n * Check out [original website](https://cr.yp.to/mac.html).\n * Based on Public Domain [poly1305-donna](https://github.com/floodyberry/poly1305-donna).\n * @module\n */\nimport { abytes, aexists, aoutput, clean, copyBytes, } from \"./utils.js\";\nfunction u8to16(a, i) {\n    return (a[i++] & 0xff) | ((a[i++] & 0xff) << 8);\n}\n// function bytesToNumberLE(bytes: Uint8Array): bigint {\n//   return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));\n// }\n// /** Small version of `poly1305` without loop unrolling. Unused, provided for auditability. */\n// function poly1305_small(msg: Uint8Array, key: Uint8Array): Uint8Array {\n//   abytes(msg);\n//   abytes(key, 32, \"key\");\n//   const POW_2_130_5 = 2n ** 130n - 5n; // 2^130-5\n//   const POW_2_128_1 = 2n ** 128n - 1n; // 2^128-1\n//   const CLAMP_R = 0x0ffffffc0ffffffc0ffffffc0fffffffn;\n//   const r = bytesToNumberLE(key.subarray(0, 16)) & CLAMP_R;\n//   const s = bytesToNumberLE(key.subarray(16));\n//   // Process by 16 byte chunks\n//   let acc = 0n;\n//   for (let i = 0; i < msg.length; i += 16) {\n//     const m = msg.subarray(i, i + 16);\n//     const n = bytesToNumberLE(m) | (1n << (8n * mLen)); // mLen: bigint\n//     acc = ((acc + n) * r) % POW_2_130_5;\n//   }\n//   const res = (acc + s) & POW_2_128_1;\n//   return numberToBytesBE(res, 16).reverse(); // LE\n// }\n// Can be used to replace `computeTag` in chacha.ts. Unused, provided for auditability.\n// function poly1305_computeTag_small(\n//   authKey: Uint8Array,\n//   lengths: Uint8Array,\n//   ciphertext: Uint8Array,\n//   AAD?: Uint8Array,\n// ): Uint8Array {\n//   const res = [];\n//   const updatePadded2 = (msg: Uint8Array) => {\n//     res.push(msg);\n//     const leftover = msg.length % 16;\n//     if (leftover) res.push(new Uint8Array(16).slice(leftover));\n//   };\n//   if (AAD) updatePadded2(AAD);\n//   updatePadded2(ciphertext);\n//   res.push(lengths);\n//   return poly1305_small(concatBytes(...res), authKey);\n// }\n/** Poly1305 class. Prefer poly1305() function instead. */\nexport class Poly1305 {\n    // Can be speed-up using BigUint64Array, at the cost of complexity\n    constructor(key) {\n        Object.defineProperty(this, \"blockLen\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: 16\n        });\n        Object.defineProperty(this, \"outputLen\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: 16\n        });\n        Object.defineProperty(this, \"buffer\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: new Uint8Array(16)\n        });\n        Object.defineProperty(this, \"r\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: new Uint16Array(10)\n        }); // Allocating 1 array with .subarray() here is slower than 3\n        Object.defineProperty(this, \"h\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: new Uint16Array(10)\n        });\n        Object.defineProperty(this, \"pad\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: new Uint16Array(8)\n        });\n        Object.defineProperty(this, \"pos\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: 0\n        });\n        Object.defineProperty(this, \"finished\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: false\n        });\n        key = copyBytes(abytes(key, 32, \"key\"));\n        const t0 = u8to16(key, 0);\n        const t1 = u8to16(key, 2);\n        const t2 = u8to16(key, 4);\n        const t3 = u8to16(key, 6);\n        const t4 = u8to16(key, 8);\n        const t5 = u8to16(key, 10);\n        const t6 = u8to16(key, 12);\n        const t7 = u8to16(key, 14);\n        // https://github.com/floodyberry/poly1305-donna/blob/e6ad6e091d30d7f4ec2d4f978be1fcfcbce72781/poly1305-donna-16.h#L47\n        this.r[0] = t0 & 0x1fff;\n        this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;\n        this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;\n        this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;\n        this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;\n        this.r[5] = (t4 >>> 1) & 0x1ffe;\n        this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;\n        this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;\n        this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;\n        this.r[9] = (t7 >>> 5) & 0x007f;\n        for (let i = 0; i < 8; i++)\n            this.pad[i] = u8to16(key, 16 + 2 * i);\n    }\n    process(data, offset, isLast = false) {\n        const hibit = isLast ? 0 : 1 << 11;\n        const { h, r } = this;\n        const r0 = r[0];\n        const r1 = r[1];\n        const r2 = r[2];\n        const r3 = r[3];\n        const r4 = r[4];\n        const r5 = r[5];\n        const r6 = r[6];\n        const r7 = r[7];\n        const r8 = r[8];\n        const r9 = r[9];\n        const t0 = u8to16(data, offset + 0);\n        const t1 = u8to16(data, offset + 2);\n        const t2 = u8to16(data, offset + 4);\n        const t3 = u8to16(data, offset + 6);\n        const t4 = u8to16(data, offset + 8);\n        const t5 = u8to16(data, offset + 10);\n        const t6 = u8to16(data, offset + 12);\n        const t7 = u8to16(data, offset + 14);\n        const h0 = h[0] + (t0 & 0x1fff);\n        const h1 = h[1] + (((t0 >>> 13) | (t1 << 3)) & 0x1fff);\n        const h2 = h[2] + (((t1 >>> 10) | (t2 << 6)) & 0x1fff);\n        const h3 = h[3] + (((t2 >>> 7) | (t3 << 9)) & 0x1fff);\n        const h4 = h[4] + (((t3 >>> 4) | (t4 << 12)) & 0x1fff);\n        const h5 = h[5] + ((t4 >>> 1) & 0x1fff);\n        const h6 = h[6] + (((t4 >>> 14) | (t5 << 2)) & 0x1fff);\n        const h7 = h[7] + (((t5 >>> 11) | (t6 << 5)) & 0x1fff);\n        const h8 = h[8] + (((t6 >>> 8) | (t7 << 8)) & 0x1fff);\n        const h9 = h[9] + ((t7 >>> 5) | hibit);\n        let c = 0;\n        let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) +\n            h4 * (5 * r6);\n        c = d0 >>> 13;\n        d0 &= 0x1fff;\n        d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) +\n            h9 * (5 * r1);\n        c += d0 >>> 13;\n        d0 &= 0x1fff;\n        let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) +\n            h4 * (5 * r7);\n        c = d1 >>> 13;\n        d1 &= 0x1fff;\n        d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) +\n            h9 * (5 * r2);\n        c += d1 >>> 13;\n        d1 &= 0x1fff;\n        let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8);\n        c = d2 >>> 13;\n        d2 &= 0x1fff;\n        d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) +\n            h9 * (5 * r3);\n        c += d2 >>> 13;\n        d2 &= 0x1fff;\n        let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9);\n        c = d3 >>> 13;\n        d3 &= 0x1fff;\n        d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) +\n            h9 * (5 * r4);\n        c += d3 >>> 13;\n        d3 &= 0x1fff;\n        let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0;\n        c = d4 >>> 13;\n        d4 &= 0x1fff;\n        d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) +\n            h9 * (5 * r5);\n        c += d4 >>> 13;\n        d4 &= 0x1fff;\n        let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1;\n        c = d5 >>> 13;\n        d5 &= 0x1fff;\n        d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) +\n            h9 * (5 * r6);\n        c += d5 >>> 13;\n        d5 &= 0x1fff;\n        let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2;\n        c = d6 >>> 13;\n        d6 &= 0x1fff;\n        d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7);\n        c += d6 >>> 13;\n        d6 &= 0x1fff;\n        let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3;\n        c = d7 >>> 13;\n        d7 &= 0x1fff;\n        d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8);\n        c += d7 >>> 13;\n        d7 &= 0x1fff;\n        let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4;\n        c = d8 >>> 13;\n        d8 &= 0x1fff;\n        d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9);\n        c += d8 >>> 13;\n        d8 &= 0x1fff;\n        let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5;\n        c = d9 >>> 13;\n        d9 &= 0x1fff;\n        d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0;\n        c += d9 >>> 13;\n        d9 &= 0x1fff;\n        c = ((c << 2) + c) | 0;\n        c = (c + d0) | 0;\n        d0 = c & 0x1fff;\n        c = c >>> 13;\n        d1 += c;\n        h[0] = d0;\n        h[1] = d1;\n        h[2] = d2;\n        h[3] = d3;\n        h[4] = d4;\n        h[5] = d5;\n        h[6] = d6;\n        h[7] = d7;\n        h[8] = d8;\n        h[9] = d9;\n    }\n    finalize() {\n        const { h, pad } = this;\n        const g = new Uint16Array(10);\n        let c = h[1] >>> 13;\n        h[1] &= 0x1fff;\n        for (let i = 2; i < 10; i++) {\n            h[i] += c;\n            c = h[i] >>> 13;\n            h[i] &= 0x1fff;\n        }\n        h[0] += c * 5;\n        c = h[0] >>> 13;\n        h[0] &= 0x1fff;\n        h[1] += c;\n        c = h[1] >>> 13;\n        h[1] &= 0x1fff;\n        h[2] += c;\n        g[0] = h[0] + 5;\n        c = g[0] >>> 13;\n        g[0] &= 0x1fff;\n        for (let i = 1; i < 10; i++) {\n            g[i] = h[i] + c;\n            c = g[i] >>> 13;\n            g[i] &= 0x1fff;\n        }\n        g[9] -= 1 << 13;\n        let mask = (c ^ 1) - 1;\n        for (let i = 0; i < 10; i++)\n            g[i] &= mask;\n        mask = ~mask;\n        for (let i = 0; i < 10; i++)\n            h[i] = (h[i] & mask) | g[i];\n        h[0] = (h[0] | (h[1] << 13)) & 0xffff;\n        h[1] = ((h[1] >>> 3) | (h[2] << 10)) & 0xffff;\n        h[2] = ((h[2] >>> 6) | (h[3] << 7)) & 0xffff;\n        h[3] = ((h[3] >>> 9) | (h[4] << 4)) & 0xffff;\n        h[4] = ((h[4] >>> 12) | (h[5] << 1) | (h[6] << 14)) & 0xffff;\n        h[5] = ((h[6] >>> 2) | (h[7] << 11)) & 0xffff;\n        h[6] = ((h[7] >>> 5) | (h[8] << 8)) & 0xffff;\n        h[7] = ((h[8] >>> 8) | (h[9] << 5)) & 0xffff;\n        let f = h[0] + pad[0];\n        h[0] = f & 0xffff;\n        for (let i = 1; i < 8; i++) {\n            f = (((h[i] + pad[i]) | 0) + (f >>> 16)) | 0;\n            h[i] = f & 0xffff;\n        }\n        clean(g);\n    }\n    update(data) {\n        aexists(this);\n        abytes(data);\n        data = copyBytes(data);\n        const { buffer, blockLen } = this;\n        const len = data.length;\n        for (let pos = 0; pos < len;) {\n            const take = Math.min(blockLen - this.pos, len - pos);\n            // Fast path: we have at least one block in input\n            if (take === blockLen) {\n                for (; blockLen <= len - pos; pos += blockLen)\n                    this.process(data, pos);\n                continue;\n            }\n            buffer.set(data.subarray(pos, pos + take), this.pos);\n            this.pos += take;\n            pos += take;\n            if (this.pos === blockLen) {\n                this.process(buffer, 0, false);\n                this.pos = 0;\n            }\n        }\n        return this;\n    }\n    destroy() {\n        clean(this.h, this.r, this.buffer, this.pad);\n    }\n    digestInto(out) {\n        aexists(this);\n        aoutput(out, this);\n        this.finished = true;\n        const { buffer, h } = this;\n        let { pos } = this;\n        if (pos) {\n            buffer[pos++] = 1;\n            for (; pos < 16; pos++)\n                buffer[pos] = 0;\n            this.process(buffer, 0, true);\n        }\n        this.finalize();\n        let opos = 0;\n        for (let i = 0; i < 8; i++) {\n            out[opos++] = h[i] >>> 0;\n            out[opos++] = h[i] >>> 8;\n        }\n        return out;\n    }\n    digest() {\n        const { buffer, outputLen } = this;\n        this.digestInto(buffer);\n        const res = buffer.slice(0, outputLen);\n        this.destroy();\n        return res;\n    }\n}\nexport function wrapConstructorWithKey(hashCons) {\n    const hashC = (msg, key) => hashCons(key).update(msg).digest();\n    const tmp = hashCons(new Uint8Array(32)); // tmp array, used just once below\n    hashC.outputLen = tmp.outputLen;\n    hashC.blockLen = tmp.blockLen;\n    hashC.create = (key) => hashCons(key);\n    return hashC;\n}\n/** Poly1305 MAC from RFC 8439. */\nexport const poly1305 = \n/** @__PURE__ */ (() => wrapConstructorWithKey((key) => new Poly1305(key)))();\n","/**\n * This file is based on noble-ciphers (https://github.com/paulmillr/noble-ciphers).\n *\n * noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com)\n *\n * The original file is located at:\n * https://github.com/paulmillr/noble-ciphers/blob/749cdf9cd07ebdd19e9b957d0f172f1045179695/src/chacha.ts\n */\n/**\n * ChaCha stream cipher, released\n * in 2008. Developed after Salsa20, ChaCha aims to increase diffusion per round.\n * It was standardized in [RFC 8439](https://www.rfc-editor.org/rfc/rfc8439) and\n * is now used in TLS 1.3.\n *\n * [XChaCha20](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha)\n * extended-nonce variant is also provided. Similar to XSalsa, it's safe to use with\n * randomly-generated nonces.\n *\n * Check out [PDF](http://cr.yp.to/chacha/chacha-20080128.pdf) and\n * [wiki](https://en.wikipedia.org/wiki/Salsa20) and\n * [website](https://cr.yp.to/chacha.html).\n *\n * @module\n */\nimport { createCipher, rotl } from \"./_arx.js\";\nimport { poly1305 } from \"./_poly1305.js\";\nimport { abytes, clean, equalBytes, getOutput, u64Lengths, wrapCipher, } from \"./utils.js\";\n/**\n * ChaCha core function. It is implemented twice:\n * 1. Simple loop (chachaCore_small, hchacha_small)\n * 2. Unrolled loop (chachaCore, hchacha) - 4x faster, but larger & harder to read\n * The specific implementation is selected in `createCipher` below.\n */\nfunction chachaCore(s, k, n, out, cnt, rounds = 20) {\n    const y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], // \"expa\"   \"nd 3\"  \"2-by\"  \"te k\"\n    y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], // Key      Key     Key     Key\n    y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], // Key      Key     Key     Key\n    y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2]; // Counter  Counter\tNonce   Nonce\n    // Save state to temporary variables\n    let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;\n    for (let r = 0; r < rounds; r += 2) {\n        x00 = (x00 + x04) | 0;\n        x12 = rotl(x12 ^ x00, 16);\n        x08 = (x08 + x12) | 0;\n        x04 = rotl(x04 ^ x08, 12);\n        x00 = (x00 + x04) | 0;\n        x12 = rotl(x12 ^ x00, 8);\n        x08 = (x08 + x12) | 0;\n        x04 = rotl(x04 ^ x08, 7);\n        x01 = (x01 + x05) | 0;\n        x13 = rotl(x13 ^ x01, 16);\n        x09 = (x09 + x13) | 0;\n        x05 = rotl(x05 ^ x09, 12);\n        x01 = (x01 + x05) | 0;\n        x13 = rotl(x13 ^ x01, 8);\n        x09 = (x09 + x13) | 0;\n        x05 = rotl(x05 ^ x09, 7);\n        x02 = (x02 + x06) | 0;\n        x14 = rotl(x14 ^ x02, 16);\n        x10 = (x10 + x14) | 0;\n        x06 = rotl(x06 ^ x10, 12);\n        x02 = (x02 + x06) | 0;\n        x14 = rotl(x14 ^ x02, 8);\n        x10 = (x10 + x14) | 0;\n        x06 = rotl(x06 ^ x10, 7);\n        x03 = (x03 + x07) | 0;\n        x15 = rotl(x15 ^ x03, 16);\n        x11 = (x11 + x15) | 0;\n        x07 = rotl(x07 ^ x11, 12);\n        x03 = (x03 + x07) | 0;\n        x15 = rotl(x15 ^ x03, 8);\n        x11 = (x11 + x15) | 0;\n        x07 = rotl(x07 ^ x11, 7);\n        x00 = (x00 + x05) | 0;\n        x15 = rotl(x15 ^ x00, 16);\n        x10 = (x10 + x15) | 0;\n        x05 = rotl(x05 ^ x10, 12);\n        x00 = (x00 + x05) | 0;\n        x15 = rotl(x15 ^ x00, 8);\n        x10 = (x10 + x15) | 0;\n        x05 = rotl(x05 ^ x10, 7);\n        x01 = (x01 + x06) | 0;\n        x12 = rotl(x12 ^ x01, 16);\n        x11 = (x11 + x12) | 0;\n        x06 = rotl(x06 ^ x11, 12);\n        x01 = (x01 + x06) | 0;\n        x12 = rotl(x12 ^ x01, 8);\n        x11 = (x11 + x12) | 0;\n        x06 = rotl(x06 ^ x11, 7);\n        x02 = (x02 + x07) | 0;\n        x13 = rotl(x13 ^ x02, 16);\n        x08 = (x08 + x13) | 0;\n        x07 = rotl(x07 ^ x08, 12);\n        x02 = (x02 + x07) | 0;\n        x13 = rotl(x13 ^ x02, 8);\n        x08 = (x08 + x13) | 0;\n        x07 = rotl(x07 ^ x08, 7);\n        x03 = (x03 + x04) | 0;\n        x14 = rotl(x14 ^ x03, 16);\n        x09 = (x09 + x14) | 0;\n        x04 = rotl(x04 ^ x09, 12);\n        x03 = (x03 + x04) | 0;\n        x14 = rotl(x14 ^ x03, 8);\n        x09 = (x09 + x14) | 0;\n        x04 = rotl(x04 ^ x09, 7);\n    }\n    // Write output\n    let oi = 0;\n    out[oi++] = (y00 + x00) | 0;\n    out[oi++] = (y01 + x01) | 0;\n    out[oi++] = (y02 + x02) | 0;\n    out[oi++] = (y03 + x03) | 0;\n    out[oi++] = (y04 + x04) | 0;\n    out[oi++] = (y05 + x05) | 0;\n    out[oi++] = (y06 + x06) | 0;\n    out[oi++] = (y07 + x07) | 0;\n    out[oi++] = (y08 + x08) | 0;\n    out[oi++] = (y09 + x09) | 0;\n    out[oi++] = (y10 + x10) | 0;\n    out[oi++] = (y11 + x11) | 0;\n    out[oi++] = (y12 + x12) | 0;\n    out[oi++] = (y13 + x13) | 0;\n    out[oi++] = (y14 + x14) | 0;\n    out[oi++] = (y15 + x15) | 0;\n}\n/**\n * ChaCha stream cipher. Conforms to RFC 8439 (IETF, TLS). 12-byte nonce, 4-byte counter.\n * With smaller nonce, it's not safe to make it random (CSPRNG), due to collision chance.\n */\nexport const chacha20 = /* @__PURE__ */ createCipher(chachaCore, {\n    counterRight: false,\n    counterLength: 4,\n    allowShortKeys: false,\n});\nconst ZEROS16 = /* @__PURE__ */ new Uint8Array(16);\n// Pad to digest size with zeros\nconst updatePadded = (h, msg) => {\n    h.update(msg);\n    const leftover = msg.length % 16;\n    if (leftover)\n        h.update(ZEROS16.subarray(leftover));\n};\nconst ZEROS32 = /* @__PURE__ */ new Uint8Array(32);\nfunction computeTag(fn, key, nonce, ciphertext, AAD) {\n    if (AAD !== undefined)\n        abytes(AAD, undefined, \"AAD\");\n    const authKey = fn(key, nonce, ZEROS32);\n    const lengths = u64Lengths(ciphertext.length, AAD ? AAD.length : 0, true);\n    // Methods below can be replaced with\n    // return poly1305_computeTag_small(authKey, lengths, ciphertext, AAD)\n    const h = poly1305.create(authKey);\n    if (AAD)\n        updatePadded(h, AAD);\n    updatePadded(h, ciphertext);\n    h.update(lengths);\n    const res = h.digest();\n    clean(authKey, lengths);\n    return res;\n}\n/**\n * AEAD algorithm from RFC 8439.\n * Salsa20 and chacha (RFC 8439) use poly1305 differently.\n * We could have composed them, but it's hard because of authKey:\n * In salsa20, authKey changes position in salsa stream.\n * In chacha, authKey can't be computed inside computeTag, it modifies the counter.\n */\nexport const _poly1305_aead = (xorStream) => (key, nonce, AAD) => {\n    const tagLength = 16;\n    return {\n        encrypt(plaintext, output) {\n            const plength = plaintext.length;\n            output = getOutput(plength + tagLength, output, false);\n            output.set(plaintext);\n            const oPlain = output.subarray(0, -tagLength);\n            // Actual encryption\n            xorStream(key, nonce, oPlain, oPlain, 1);\n            const tag = computeTag(xorStream, key, nonce, oPlain, AAD);\n            output.set(tag, plength); // append tag\n            clean(tag);\n            return output;\n        },\n        decrypt(ciphertext, output) {\n            output = getOutput(ciphertext.length - tagLength, output, false);\n            const data = ciphertext.subarray(0, -tagLength);\n            const passedTag = ciphertext.subarray(-tagLength);\n            const tag = computeTag(xorStream, key, nonce, data, AAD);\n            if (!equalBytes(passedTag, tag))\n                throw new Error(\"invalid tag\");\n            output.set(ciphertext.subarray(0, -tagLength));\n            // Actual decryption\n            xorStream(key, nonce, output, output, 1); // start stream with i=1\n            clean(tag);\n            return output;\n        },\n    };\n};\n/**\n * ChaCha20-Poly1305 from RFC 8439.\n *\n * Unsafe to use random nonces under the same key, due to collision chance.\n * Prefer XChaCha instead.\n */\nexport const chacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 12, tagLength: 16 }, _poly1305_aead(chacha20));\n","import { ExportError, INPUT_LENGTH_LIMIT, InvalidParamError, toArrayBuffer, } from \"@hpke/common\";\nimport { emitNotSupported } from \"./utils/emitNotSupported.js\";\n// b\"sec\"\nconst LABEL_SEC = new Uint8Array([115, 101, 99]);\nexport class ExporterContextImpl {\n    constructor(api, kdf, exporterSecret) {\n        Object.defineProperty(this, \"_api\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: void 0\n        });\n        Object.defineProperty(this, \"exporterSecret\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: void 0\n        });\n        Object.defineProperty(this, \"_kdf\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: void 0\n        });\n        this._api = api;\n        this._kdf = kdf;\n        this.exporterSecret = exporterSecret;\n    }\n    async seal(_data, _aad) {\n        return await emitNotSupported();\n    }\n    async open(_data, _aad) {\n        return await emitNotSupported();\n    }\n    async export(exporterContext, len) {\n        const rawExporterContext = toArrayBuffer(exporterContext);\n        if (rawExporterContext.byteLength > INPUT_LENGTH_LIMIT) {\n            throw new InvalidParamError(\"Too long exporter context\");\n        }\n        try {\n            return await this._kdf.labeledExpand(this.exporterSecret, LABEL_SEC, new Uint8Array(rawExporterContext), len);\n        }\n        catch (e) {\n            throw new ExportError(e);\n        }\n    }\n}\nexport class RecipientExporterContextImpl extends ExporterContextImpl {\n}\nexport class SenderExporterContextImpl extends ExporterContextImpl {\n    constructor(api, kdf, exporterSecret, enc) {\n        super(api, kdf, exporterSecret);\n        Object.defineProperty(this, \"enc\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: void 0\n        });\n        this.enc = enc;\n        return;\n    }\n}\n","var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n    if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n    if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n    return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n    if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n    if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n    if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n    return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar _Mutex_locked;\nexport class Mutex {\n    constructor() {\n        _Mutex_locked.set(this, Promise.resolve());\n    }\n    async lock() {\n        let releaseLock;\n        const nextLock = new Promise((resolve) => {\n            releaseLock = resolve;\n        });\n        const previousLock = __classPrivateFieldGet(this, _Mutex_locked, \"f\");\n        __classPrivateFieldSet(this, _Mutex_locked, nextLock, \"f\");\n        await previousLock;\n        return releaseLock;\n    }\n}\n_Mutex_locked = new WeakMap();\n","var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n    if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n    if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n    return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n    if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n    if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n    if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n    return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar _RecipientContextImpl_mutex;\nimport { EMPTY, OpenError, toArrayBuffer } from \"@hpke/common\";\nimport { EncryptionContextImpl } from \"./encryptionContext.js\";\nimport { Mutex } from \"./mutex.js\";\nexport class RecipientContextImpl extends EncryptionContextImpl {\n    constructor() {\n        super(...arguments);\n        _RecipientContextImpl_mutex.set(this, void 0);\n    }\n    async open(data, aad = EMPTY.buffer) {\n        __classPrivateFieldSet(this, _RecipientContextImpl_mutex, __classPrivateFieldGet(this, _RecipientContextImpl_mutex, \"f\") ?? new Mutex(), \"f\");\n        const release = await __classPrivateFieldGet(this, _RecipientContextImpl_mutex, \"f\").lock();\n        let pt;\n        try {\n            pt = await this._ctx.key.open(this.computeNonce(this._ctx), toArrayBuffer(data), toArrayBuffer(aad));\n        }\n        catch (e) {\n            throw new OpenError(e);\n        }\n        finally {\n            release();\n        }\n        this.incrementSeq(this._ctx);\n        return pt;\n    }\n}\n_RecipientContextImpl_mutex = new WeakMap();\n","var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n    if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n    if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n    return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n    if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n    if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n    if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n    return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar _SenderContextImpl_mutex;\nimport { EMPTY, SealError, toArrayBuffer } from \"@hpke/common\";\nimport { EncryptionContextImpl } from \"./encryptionContext.js\";\nimport { Mutex } from \"./mutex.js\";\nexport class SenderContextImpl extends EncryptionContextImpl {\n    constructor(api, kdf, params, enc) {\n        super(api, kdf, params);\n        Object.defineProperty(this, \"enc\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: void 0\n        });\n        _SenderContextImpl_mutex.set(this, void 0);\n        this.enc = enc;\n    }\n    async seal(data, aad = EMPTY.buffer) {\n        __classPrivateFieldSet(this, _SenderContextImpl_mutex, __classPrivateFieldGet(this, _SenderContextImpl_mutex, \"f\") ?? new Mutex(), \"f\");\n        const release = await __classPrivateFieldGet(this, _SenderContextImpl_mutex, \"f\").lock();\n        let ct;\n        try {\n            ct = await this._ctx.key.seal(this.computeNonce(this._ctx), toArrayBuffer(data), toArrayBuffer(aad));\n        }\n        catch (e) {\n            throw new SealError(e);\n        }\n        finally {\n            release();\n        }\n        this.incrementSeq(this._ctx);\n        return ct;\n    }\n}\n_SenderContextImpl_mutex = new WeakMap();\n","import { AeadId, EMPTY, i2Osp, INFO_LENGTH_LIMIT, INPUT_LENGTH_LIMIT, InvalidParamError, MINIMUM_PSK_LENGTH, Mode, NativeAlgorithm, toUint8Array, } from \"@hpke/common\";\nimport { RecipientExporterContextImpl, SenderExporterContextImpl, } from \"./exporterContext.js\";\nimport { RecipientContextImpl } from \"./recipientContext.js\";\nimport { SenderContextImpl } from \"./senderContext.js\";\n// b\"base_nonce\"\n// deno-fmt-ignore\nconst LABEL_BASE_NONCE = new Uint8Array([\n    98, 97, 115, 101, 95, 110, 111, 110, 99, 101,\n]);\n// b\"exp\"\nconst LABEL_EXP = new Uint8Array([101, 120, 112]);\n// b\"info_hash\"\n// deno-fmt-ignore\nconst LABEL_INFO_HASH = new Uint8Array([\n    105, 110, 102, 111, 95, 104, 97, 115, 104,\n]);\n// b\"key\"\nconst LABEL_KEY = new Uint8Array([107, 101, 121]);\n// b\"psk_id_hash\"\n// deno-fmt-ignore\nconst LABEL_PSK_ID_HASH = new Uint8Array([\n    112, 115, 107, 95, 105, 100, 95, 104, 97, 115, 104,\n]);\n// b\"secret\"\nconst LABEL_SECRET = new Uint8Array([115, 101, 99, 114, 101, 116]);\n// b\"HPKE\"\n// deno-fmt-ignore\nconst SUITE_ID_HEADER_HPKE = new Uint8Array([\n    72, 80, 75, 69, 0, 0, 0, 0, 0, 0,\n]);\n/**\n * The Hybrid Public Key Encryption (HPKE) ciphersuite,\n * which is implemented using only\n * {@link https://www.w3.org/TR/WebCryptoAPI/ | Web Cryptography API}.\n *\n * This is the super class of {@link CipherSuite} and the same as\n * {@link https://jsr.io/@hpke/core/doc/~/CipherSuite | @hpke/core#CipherSuite} as follows:\n * which supports only the ciphersuites that can be implemented on the native\n * {@link https://www.w3.org/TR/WebCryptoAPI/ | Web Cryptography API}.\n * Therefore, the following cryptographic algorithms are not supported for now:\n *   - DHKEM(X25519, HKDF-SHA256)\n *   - DHKEM(X448, HKDF-SHA512)\n *   - ChaCha20Poly1305\n *\n * In addtion, the HKDF functions contained in this class can only derive\n * keys of the same length as the `hashSize`.\n *\n * If you want to use the unsupported cryptographic algorithms\n * above or derive keys longer than the `hashSize`,\n * please use {@link CipherSuite}.\n *\n * This class provides following functions:\n *\n * - Creates encryption contexts both for senders and recipients.\n *   - {@link createSenderContext}\n *   - {@link createRecipientContext}\n * - Provides single-shot encryption API.\n *   - {@link seal}\n *   - {@link open}\n *\n * The calling of the constructor of this class is the starting\n * point for HPKE operations for both senders and recipients.\n *\n * @example Use only ciphersuites supported by Web Cryptography API.\n *\n * ```ts\n * import {\n *   Aes128Gcm,\n *   DhkemP256HkdfSha256,\n *   HkdfSha256,\n *   CipherSuite,\n * } from \"@hpke/core\";\n *\n * const suite = new CipherSuite({\n *   kem: new DhkemP256HkdfSha256(),\n *   kdf: new HkdfSha256(),\n *   aead: new Aes128Gcm(),\n * });\n * ```\n *\n * @example Use a ciphersuite which is currently not supported by Web Cryptography API.\n *\n * ```ts\n * import { Aes128Gcm, HkdfSha256, CipherSuite } from \"@hpke/core\";\n * // Use an extension module.\n * import { DhkemX25519HkdfSha256 } from \"@hpke/dhkem-x25519\";\n *\n * const suite = new CipherSuite({\n *   kem: new DhkemX25519HkdfSha256(),\n *   kdf: new HkdfSha256(),\n *   aead: new Aes128Gcm(),\n * });\n * ```\n */\nexport class CipherSuiteNative extends NativeAlgorithm {\n    /**\n     * @param params A set of parameters for building a cipher suite.\n     *\n     * If the error occurred, throws {@link InvalidParamError}.\n     *\n     * @throws {@link InvalidParamError}\n     */\n    constructor(params) {\n        super();\n        Object.defineProperty(this, \"_kem\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: void 0\n        });\n        Object.defineProperty(this, \"_kdf\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: void 0\n        });\n        Object.defineProperty(this, \"_aead\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: void 0\n        });\n        Object.defineProperty(this, \"_suiteId\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: void 0\n        });\n        // KEM\n        if (typeof params.kem === \"number\") {\n            throw new InvalidParamError(\"KemId cannot be used\");\n        }\n        this._kem = params.kem;\n        // KDF\n        if (typeof params.kdf === \"number\") {\n            throw new InvalidParamError(\"KdfId cannot be used\");\n        }\n        this._kdf = params.kdf;\n        // AEAD\n        if (typeof params.aead === \"number\") {\n            throw new InvalidParamError(\"AeadId cannot be used\");\n        }\n        this._aead = params.aead;\n        this._suiteId = new Uint8Array(SUITE_ID_HEADER_HPKE);\n        this._suiteId.set(i2Osp(this._kem.id, 2), 4);\n        this._suiteId.set(i2Osp(this._kdf.id, 2), 6);\n        this._suiteId.set(i2Osp(this._aead.id, 2), 8);\n        this._kdf.init(this._suiteId);\n    }\n    /**\n     * Gets the KEM context of the ciphersuite.\n     */\n    get kem() {\n        return this._kem;\n    }\n    /**\n     * Gets the KDF context of the ciphersuite.\n     */\n    get kdf() {\n        return this._kdf;\n    }\n    /**\n     * Gets the AEAD context of the ciphersuite.\n     */\n    get aead() {\n        return this._aead;\n    }\n    /**\n     * Creates an encryption context for a sender.\n     *\n     * If the error occurred, throws {@link DecapError} | {@link ValidationError}.\n     *\n     * @param params A set of parameters for the sender encryption context.\n     * @returns A sender encryption context.\n     * @throws {@link EncapError}, {@link ValidationError}\n     */\n    async createSenderContext(params) {\n        this._validateInputLength(params);\n        await this._setup();\n        const dh = await this._kem.encap(params);\n        let mode;\n        if (params.psk !== undefined) {\n            mode = params.senderKey !== undefined ? Mode.AuthPsk : Mode.Psk;\n        }\n        else {\n            mode = params.senderKey !== undefined ? Mode.Auth : Mode.Base;\n        }\n        return await this._keyScheduleS(mode, dh.sharedSecret, dh.enc, params);\n    }\n    /**\n     * Creates an encryption context for a recipient.\n     *\n     * If the error occurred, throws {@link DecapError}\n     * | {@link DeserializeError} | {@link ValidationError}.\n     *\n     * @param params A set of parameters for the recipient encryption context.\n     * @returns A recipient encryption context.\n     * @throws {@link DecapError}, {@link DeserializeError}, {@link ValidationError}\n     */\n    async createRecipientContext(params) {\n        this._validateInputLength(params);\n        await this._setup();\n        const sharedSecret = await this._kem.decap(params);\n        let mode;\n        if (params.psk !== undefined) {\n            mode = params.senderPublicKey !== undefined ? Mode.AuthPsk : Mode.Psk;\n        }\n        else {\n            mode = params.senderPublicKey !== undefined ? Mode.Auth : Mode.Base;\n        }\n        return await this._keyScheduleR(mode, sharedSecret, params);\n    }\n    /**\n     * Encrypts a message to a recipient.\n     *\n     * If the error occurred, throws `EncapError` | `MessageLimitReachedError` | `SealError` | `ValidationError`.\n     *\n     * @param params A set of parameters for building a sender encryption context.\n     * @param pt A plain text as bytes to be encrypted.\n     * @param aad Additional authenticated data as bytes fed by an application.\n     * @returns A cipher text and an encapsulated key as bytes.\n     * @throws {@link EncapError}, {@link MessageLimitReachedError}, {@link SealError}, {@link ValidationError}\n     */\n    async seal(params, pt, aad = EMPTY.buffer) {\n        const ctx = await this.createSenderContext(params);\n        return {\n            ct: await ctx.seal(pt, aad),\n            enc: ctx.enc,\n        };\n    }\n    /**\n     * Decrypts a message from a sender.\n     *\n     * If the error occurred, throws `DecapError` | `DeserializeError` | `OpenError` | `ValidationError`.\n     *\n     * @param params A set of parameters for building a recipient encryption context.\n     * @param ct An encrypted text as bytes to be decrypted.\n     * @param aad Additional authenticated data as bytes fed by an application.\n     * @returns A decrypted plain text as bytes.\n     * @throws {@link DecapError}, {@link DeserializeError}, {@link OpenError}, {@link ValidationError}\n     */\n    async open(params, ct, aad = EMPTY.buffer) {\n        const ctx = await this.createRecipientContext(params);\n        return await ctx.open(ct, aad);\n    }\n    // private verifyPskInputs(mode: Mode, params: KeyScheduleParams) {\n    //   const gotPsk = (params.psk !== undefined);\n    //   const gotPskId = (params.psk !== undefined && params.psk.id.byteLength > 0);\n    //   if (gotPsk !== gotPskId) {\n    //     throw new Error('Inconsistent PSK inputs');\n    //   }\n    //   if (gotPsk && (mode === Mode.Base || mode === Mode.Auth)) {\n    //     throw new Error('PSK input provided when not needed');\n    //   }\n    //   if (!gotPsk && (mode === Mode.Psk || mode === Mode.AuthPsk)) {\n    //     throw new Error('Missing required PSK input');\n    //   }\n    //   return;\n    // }\n    async _keySchedule(mode, sharedSecret, params) {\n        // Currently, there is no point in executing this function\n        // because this hpke library does not allow users to explicitly specify the mode.\n        //\n        // this.verifyPskInputs(mode, params);\n        const pskId = params.psk === undefined\n            ? EMPTY\n            : toUint8Array(params.psk.id);\n        const pskIdHash = await this._kdf.labeledExtract(EMPTY, LABEL_PSK_ID_HASH, pskId);\n        const info = params.info === undefined ? EMPTY : toUint8Array(params.info);\n        const infoHash = await this._kdf.labeledExtract(EMPTY, LABEL_INFO_HASH, info);\n        const keyScheduleContext = new Uint8Array(1 + pskIdHash.byteLength + infoHash.byteLength);\n        keyScheduleContext.set(new Uint8Array([mode]), 0);\n        keyScheduleContext.set(new Uint8Array(pskIdHash), 1);\n        keyScheduleContext.set(new Uint8Array(infoHash), 1 + pskIdHash.byteLength);\n        const psk = params.psk === undefined ? EMPTY : toUint8Array(params.psk.key);\n        const ikm = this._kdf.buildLabeledIkm(LABEL_SECRET, psk);\n        const exporterSecretInfo = this._kdf.buildLabeledInfo(LABEL_EXP, keyScheduleContext, this._kdf.hashSize);\n        const exporterSecret = await this._kdf.extractAndExpand(sharedSecret, ikm, exporterSecretInfo, this._kdf.hashSize);\n        if (this._aead.id === AeadId.ExportOnly) {\n            return { aead: this._aead, exporterSecret: exporterSecret };\n        }\n        const keyInfo = this._kdf.buildLabeledInfo(LABEL_KEY, keyScheduleContext, this._aead.keySize);\n        const key = await this._kdf.extractAndExpand(sharedSecret, ikm, keyInfo, this._aead.keySize);\n        const baseNonceInfo = this._kdf.buildLabeledInfo(LABEL_BASE_NONCE, keyScheduleContext, this._aead.nonceSize);\n        const baseNonce = await this._kdf.extractAndExpand(sharedSecret, ikm, baseNonceInfo, this._aead.nonceSize);\n        return {\n            aead: this._aead,\n            exporterSecret: exporterSecret,\n            key: key,\n            baseNonce: new Uint8Array(baseNonce),\n            seq: 0,\n        };\n    }\n    async _keyScheduleS(mode, sharedSecret, enc, params) {\n        const res = await this._keySchedule(mode, sharedSecret, params);\n        if (res.key === undefined) {\n            return new SenderExporterContextImpl(this._api, this._kdf, res.exporterSecret, enc);\n        }\n        return new SenderContextImpl(this._api, this._kdf, res, enc);\n    }\n    async _keyScheduleR(mode, sharedSecret, params) {\n        const res = await this._keySchedule(mode, sharedSecret, params);\n        if (res.key === undefined) {\n            return new RecipientExporterContextImpl(this._api, this._kdf, res.exporterSecret);\n        }\n        return new RecipientContextImpl(this._api, this._kdf, res);\n    }\n    _validateInputLength(params) {\n        if (params.info !== undefined &&\n            params.info.byteLength > INFO_LENGTH_LIMIT) {\n            throw new InvalidParamError(\"Too long info\");\n        }\n        if (params.psk !== undefined) {\n            if (params.psk.key.byteLength < MINIMUM_PSK_LENGTH) {\n                throw new InvalidParamError(`PSK must have at least ${MINIMUM_PSK_LENGTH} bytes`);\n            }\n            if (params.psk.key.byteLength > INPUT_LENGTH_LIMIT) {\n                throw new InvalidParamError(\"Too long psk.key\");\n            }\n            if (params.psk.id.byteLength > INPUT_LENGTH_LIMIT) {\n                throw new InvalidParamError(\"Too long psk.id\");\n            }\n        }\n        return;\n    }\n}\n","import { base64UrlToBytes, DeriveKeyPairError, DeserializeError, EMPTY, KEM_USAGES, LABEL_DKP_PRK, LABEL_SK, NativeAlgorithm, NotSupportedError, SerializeError, toArrayBuffer, } from \"@hpke/common\";\nconst ALG_NAME = \"X25519\";\n// deno-fmt-ignore\nconst PKCS8_ALG_ID_X25519 = new Uint8Array([\n    0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06,\n    0x03, 0x2b, 0x65, 0x6e, 0x04, 0x22, 0x04, 0x20,\n]);\nconst BASE_POINT_X25519 = /* @__PURE__ */ (() => {\n    const p = new Uint8Array(32);\n    p[0] = 9;\n    return p;\n})();\nexport class X25519 extends NativeAlgorithm {\n    constructor(hkdf) {\n        super();\n        Object.defineProperty(this, \"_hkdf\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: void 0\n        });\n        Object.defineProperty(this, \"_alg\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: void 0\n        });\n        Object.defineProperty(this, \"_nPk\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: void 0\n        });\n        Object.defineProperty(this, \"_nSk\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: void 0\n        });\n        Object.defineProperty(this, \"_nDh\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: void 0\n        });\n        Object.defineProperty(this, \"_pkcs8AlgId\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: void 0\n        });\n        this._alg = { name: ALG_NAME };\n        this._hkdf = hkdf;\n        this._nPk = 32;\n        this._nSk = 32;\n        this._nDh = 32;\n        this._pkcs8AlgId = PKCS8_ALG_ID_X25519;\n    }\n    async serializePublicKey(key) {\n        await this._setup();\n        try {\n            return await this._api.exportKey(\"raw\", key);\n        }\n        catch (e) {\n            throw new SerializeError(e);\n        }\n    }\n    async deserializePublicKey(key) {\n        await this._setup();\n        try {\n            return await this._importRawKey(toArrayBuffer(key), true);\n        }\n        catch (e) {\n            throw new DeserializeError(e);\n        }\n    }\n    async serializePrivateKey(key) {\n        await this._setup();\n        try {\n            const jwk = await this._api.exportKey(\"jwk\", key);\n            if (!(\"d\" in jwk)) {\n                throw new Error(\"Not private key\");\n            }\n            return base64UrlToBytes(jwk[\"d\"]).buffer;\n        }\n        catch (e) {\n            throw new SerializeError(e);\n        }\n    }\n    async deserializePrivateKey(key) {\n        await this._setup();\n        try {\n            return await this._importRawKey(toArrayBuffer(key), false);\n        }\n        catch (e) {\n            throw new DeserializeError(e);\n        }\n    }\n    async importKey(format, key, isPublic) {\n        await this._setup();\n        try {\n            if (format === \"raw\") {\n                return await this._importRawKey(key, isPublic);\n            }\n            // jwk\n            if (key instanceof ArrayBuffer) {\n                throw new Error(\"Invalid jwk key format\");\n            }\n            return await this._importJWK(key, isPublic);\n        }\n        catch (e) {\n            throw new DeserializeError(e);\n        }\n    }\n    async generateKeyPair() {\n        await this._setup();\n        try {\n            return await this._api.generateKey(ALG_NAME, true, KEM_USAGES);\n        }\n        catch (e) {\n            throw new NotSupportedError(e);\n        }\n    }\n    async deriveKeyPair(ikm) {\n        await this._setup();\n        try {\n            const rawIkm = toArrayBuffer(ikm);\n            const dkpPrk = await this._hkdf.labeledExtract(EMPTY, LABEL_DKP_PRK, new Uint8Array(rawIkm));\n            const rawSk = await this._hkdf.labeledExpand(dkpPrk, LABEL_SK, EMPTY, this._nSk);\n            const rawSkBytes = new Uint8Array(rawSk);\n            const sk = await this._deserializePkcs8Key(rawSkBytes);\n            rawSkBytes.fill(0);\n            return {\n                privateKey: sk,\n                publicKey: await this.derivePublicKey(sk),\n            };\n        }\n        catch (e) {\n            throw new DeriveKeyPairError(e);\n        }\n    }\n    async derivePublicKey(key) {\n        await this._setup();\n        try {\n            const jwk = await this._api.exportKey(\"jwk\", key);\n            delete jwk[\"d\"];\n            delete jwk[\"key_ops\"];\n            return await this._api.importKey(\"jwk\", jwk, this._alg, true, []);\n        }\n        catch {\n            try {\n                // Firefox fails to export JWK from some imported X25519 private keys.\n                const bp = await this._api.importKey(\"raw\", BASE_POINT_X25519.buffer, this._alg, true, []);\n                const bits = await this._api.deriveBits({\n                    name: ALG_NAME,\n                    public: bp,\n                }, key, this._nPk * 8);\n                return await this._api.importKey(\"raw\", bits, this._alg, true, []);\n            }\n            catch (e) {\n                throw new DeserializeError(e);\n            }\n        }\n    }\n    async dh(sk, pk) {\n        await this._setup();\n        try {\n            const bits = await this._api.deriveBits({\n                name: ALG_NAME,\n                public: pk,\n            }, sk, this._nDh * 8);\n            return bits;\n        }\n        catch (e) {\n            throw new SerializeError(e);\n        }\n    }\n    async _importRawKey(key, isPublic) {\n        if (isPublic && key.byteLength !== this._nPk) {\n            throw new Error(\"Invalid public key for the ciphersuite\");\n        }\n        if (!isPublic && key.byteLength !== this._nSk) {\n            throw new Error(\"Invalid private key for the ciphersuite\");\n        }\n        if (isPublic) {\n            return await this._api.importKey(\"raw\", key, this._alg, true, []);\n        }\n        return await this._deserializePkcs8Key(new Uint8Array(key));\n    }\n    async _importJWK(key, isPublic) {\n        if (typeof key.kty === \"undefined\" || key.kty !== \"OKP\") {\n            throw new Error(`Invalid kty: ${key.crv}`);\n        }\n        if (typeof key.crv === \"undefined\" || key.crv !== ALG_NAME) {\n            throw new Error(`Invalid crv: ${key.crv}`);\n        }\n        if (isPublic) {\n            if (typeof key.d !== \"undefined\") {\n                throw new Error(\"Invalid key: `d` should not be set\");\n            }\n            return await this._api.importKey(\"jwk\", key, this._alg, true, []);\n        }\n        if (typeof key.d === \"undefined\") {\n            throw new Error(\"Invalid key: `d` not found\");\n        }\n        return await this._api.importKey(\"jwk\", key, this._alg, true, KEM_USAGES);\n    }\n    async _deserializePkcs8Key(k) {\n        const pkcs8Key = new Uint8Array(this._pkcs8AlgId.length + k.length);\n        pkcs8Key.set(this._pkcs8AlgId, 0);\n        pkcs8Key.set(k, this._pkcs8AlgId.length);\n        return await this._api.importKey(\"pkcs8\", pkcs8Key, this._alg, true, KEM_USAGES);\n    }\n}\n","import { base64UrlToBytes, DeriveKeyPairError, DeserializeError, EMPTY, KEM_USAGES, LABEL_DKP_PRK, LABEL_SK, NativeAlgorithm, NotSupportedError, SerializeError, toArrayBuffer, } from \"@hpke/common\";\nconst ALG_NAME = \"X448\";\n// deno-fmt-ignore\nconst PKCS8_ALG_ID_X448 = new Uint8Array([\n    0x30, 0x46, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06,\n    0x03, 0x2b, 0x65, 0x6f, 0x04, 0x3a, 0x04, 0x38,\n]);\nconst BASE_POINT_X448 = /* @__PURE__ */ (() => {\n    const p = new Uint8Array(56);\n    p[0] = 5;\n    return p;\n})();\nexport class X448 extends NativeAlgorithm {\n    constructor(hkdf) {\n        super();\n        Object.defineProperty(this, \"_hkdf\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: void 0\n        });\n        Object.defineProperty(this, \"_alg\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: void 0\n        });\n        Object.defineProperty(this, \"_nPk\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: void 0\n        });\n        Object.defineProperty(this, \"_nSk\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: void 0\n        });\n        Object.defineProperty(this, \"_nDh\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: void 0\n        });\n        Object.defineProperty(this, \"_pkcs8AlgId\", {\n            enumerable: true,\n            configurable: true,\n            writable: true,\n            value: void 0\n        });\n        this._alg = { name: ALG_NAME };\n        this._hkdf = hkdf;\n        this._nPk = 56;\n        this._nSk = 56;\n        this._nDh = 56;\n        this._pkcs8AlgId = PKCS8_ALG_ID_X448;\n    }\n    async serializePublicKey(key) {\n        await this._setup();\n        try {\n            return await this._api.exportKey(\"raw\", key);\n        }\n        catch (e) {\n            throw new SerializeError(e);\n        }\n    }\n    async deserializePublicKey(key) {\n        await this._setup();\n        try {\n            return await this._importRawKey(toArrayBuffer(key), true);\n        }\n        catch (e) {\n            throw new DeserializeError(e);\n        }\n    }\n    async serializePrivateKey(key) {\n        await this._setup();\n        try {\n            const jwk = await this._api.exportKey(\"jwk\", key);\n            if (!(\"d\" in jwk)) {\n                throw new Error(\"Not private key\");\n            }\n            return base64UrlToBytes(jwk[\"d\"]).buffer;\n        }\n        catch (e) {\n            throw new SerializeError(e);\n        }\n    }\n    async deserializePrivateKey(key) {\n        await this._setup();\n        try {\n            return await this._importRawKey(toArrayBuffer(key), false);\n        }\n        catch (e) {\n            throw new DeserializeError(e);\n        }\n    }\n    async importKey(format, key, isPublic) {\n        await this._setup();\n        try {\n            if (format === \"raw\") {\n                return await this._importRawKey(key, isPublic);\n            }\n            // jwk\n            if (key instanceof ArrayBuffer) {\n                throw new Error(\"Invalid jwk key format\");\n            }\n            return await this._importJWK(key, isPublic);\n        }\n        catch (e) {\n            throw new DeserializeError(e);\n        }\n    }\n    async generateKeyPair() {\n        await this._setup();\n        try {\n            return await this._api.generateKey(ALG_NAME, true, KEM_USAGES);\n        }\n        catch (e) {\n            throw new NotSupportedError(e);\n        }\n    }\n    async deriveKeyPair(ikm) {\n        await this._setup();\n        try {\n            const rawIkm = toArrayBuffer(ikm);\n            const dkpPrk = await this._hkdf.labeledExtract(EMPTY, LABEL_DKP_PRK, new Uint8Array(rawIkm));\n            const rawSk = await this._hkdf.labeledExpand(dkpPrk, LABEL_SK, EMPTY, this._nSk);\n            const rawSkBytes = new Uint8Array(rawSk);\n            const sk = await this._deserializePkcs8Key(rawSkBytes);\n            rawSkBytes.fill(0);\n            return {\n                privateKey: sk,\n                publicKey: await this.derivePublicKey(sk),\n            };\n        }\n        catch (e) {\n            throw new DeriveKeyPairError(e);\n        }\n    }\n    async derivePublicKey(key) {\n        await this._setup();\n        try {\n            const jwk = await this._api.exportKey(\"jwk\", key);\n            delete jwk[\"d\"];\n            delete jwk[\"key_ops\"];\n            return await this._api.importKey(\"jwk\", jwk, this._alg, true, []);\n        }\n        catch {\n            try {\n                // Some runtimes cannot export JWK from imported X448 private keys.\n                const bp = await this._api.importKey(\"raw\", BASE_POINT_X448.buffer, this._alg, true, []);\n                const bits = await this._api.deriveBits({\n                    name: ALG_NAME,\n                    public: bp,\n                }, key, this._nPk * 8);\n                return await this._api.importKey(\"raw\", bits, this._alg, true, []);\n            }\n            catch (e) {\n                throw new DeserializeError(e);\n            }\n        }\n    }\n    async dh(sk, pk) {\n        await this._setup();\n        try {\n            const bits = await this._api.deriveBits({\n                name: ALG_NAME,\n                public: pk,\n            }, sk, this._nDh * 8);\n            return bits;\n        }\n        catch (e) {\n            throw new SerializeError(e);\n        }\n    }\n    async _importRawKey(key, isPublic) {\n        if (isPublic && key.byteLength !== this._nPk) {\n            throw new Error(\"Invalid public key for the ciphersuite\");\n        }\n        if (!isPublic && key.byteLength !== this._nSk) {\n            throw new Error(\"Invalid private key for the ciphersuite\");\n        }\n        if (isPublic) {\n            return await this._api.importKey(\"raw\", key, this._alg, true, []);\n        }\n        return await this._deserializePkcs8Key(new Uint8Array(key));\n    }\n    async _importJWK(key, isPublic) {\n        if (typeof key.kty === \"undefined\" || key.kty !== \"OKP\") {\n            throw new Error(`Invalid kty: ${key.crv}`);\n        }\n        if (typeof key.crv === \"undefined\" || key.crv !== ALG_NAME) {\n            throw new Error(`Invalid crv: ${key.crv}`);\n        }\n        if (isPublic) {\n            if (typeof key.d !== \"undefined\") {\n                throw new Error(\"Invalid key: `d` should not be set\");\n            }\n            return await this._api.importKey(\"jwk\", key, this._alg, true, []);\n        }\n        if (typeof key.d === \"undefined\") {\n            throw new Error(\"Invalid key: `d` not found\");\n        }\n        return await this._api.importKey(\"jwk\", key, this._alg, true, KEM_USAGES);\n    }\n    async _deserializePkcs8Key(k) {\n        const pkcs8Key = new Uint8Array(this._pkcs8AlgId.length + k.length);\n        pkcs8Key.set(this._pkcs8AlgId, 0);\n        pkcs8Key.set(k, this._pkcs8AlgId.length);\n        return await this._api.importKey(\"pkcs8\", pkcs8Key, this._alg, true, KEM_USAGES);\n    }\n}\n","import type { HttpClient } from './http.js';\nimport type { ProjectConfig } from './types.js';\n\nconst CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes\n\nexport class ConfigFetcher {\n  protected readonly httpClient: HttpClient;\n  private cachedConfig: ProjectConfig | null = null;\n  private cacheTimestamp = 0;\n\n  constructor(httpClient: HttpClient) {\n    this.httpClient = httpClient;\n  }\n\n  async getConfig(): Promise<ProjectConfig | null> {\n    const now = Date.now();\n\n    if (this.cachedConfig && now - this.cacheTimestamp < CACHE_TTL_MS) {\n      return this.cachedConfig;\n    }\n\n    try {\n      const response = await this.httpClient.request<ProjectConfig>('GET', '/v1/config');\n\n      if (response.error || !response.data) {\n        return null;\n      }\n\n      this.cachedConfig = response.data;\n      this.cacheTimestamp = now;\n\n      return this.cachedConfig;\n    } catch {\n      return null;\n    }\n  }\n}\n","export class PalbaseError extends Error {\n  readonly code: string;\n  readonly status: number;\n  readonly details?: unknown;\n\n  constructor(code: string, message: string, status: number, details?: unknown) {\n    super(message);\n    this.name = 'PalbaseError';\n    this.code = code;\n    this.status = status;\n    this.details = details;\n  }\n}\n","export type Platform = 'browser' | 'node' | 'react-native' | 'deno' | 'bun';\n\ndeclare const Deno: unknown;\n\nexport function detectPlatform(): Platform {\n  if (typeof Deno !== 'undefined') {\n    return 'deno';\n  }\n\n  const runtime = globalThis as typeof globalThis & {\n    process?: { versions?: Record<string, string> };\n  };\n  if (runtime.process?.versions) {\n    if ('bun' in runtime.process.versions) {\n      return 'bun';\n    }\n    if ('node' in runtime.process.versions) {\n      return 'node';\n    }\n  }\n\n  if (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') {\n    return 'react-native';\n  }\n\n  return 'browser';\n}\n\n/**\n * The platform word this SDK puts on the wire (`X-Platform`), which the server\n * reads to target flags and to label telemetry.\n *\n * It is NOT `detectPlatform()`'s value verbatim: that reports the JS host\n * (\"browser\"), while the wire wants the platform. iOS sends \"ios\", not the name\n * of its runtime, and a condition author writes `client.platform == 'web'` —\n * the word every other flag vendor uses too. Server hosts keep their own names,\n * where the distinction is the useful part.\n */\nexport function wirePlatform(): string {\n  const host = detectPlatform();\n  return host === 'browser' ? 'web' : host;\n}\n","// Proof-of-work: the bot gate in front of /auth/signup and /auth/login.\n//\n// The server answers an unsolved request with 403 and a challenge in the body:\n//\n//   { \"error\": \"pow_required\", \"challenge\": { \"id\", \"prefix\", \"difficulty\" } }\n//\n// A client finds any nonce whose SHA-256(prefix + nonce) begins with\n// `difficulty` zero bits, then repeats the request carrying the id and nonce as\n// headers. The work is the point: a person signing up pays it once and does not\n// notice, a script signing up ten thousand times pays it ten thousand times.\n//\n// # Why this lives in core, and not one layer up\n//\n// Until 2026-08-14 nothing shipped could solve it: the gate was written with the\n// server and its own integration harness, and every real client sent requests\n// without the headers and got 403. It was then solved in @palbase/web's own\n// request path — which covers `pb.call` and the module facades and NOT\n// `pb.auth.*`, because those go through @palbase/auth's client and from there\n// into core's HttpClient. So the fix landed everywhere except the two endpoints\n// the gate actually guards, and `npm i @palbase/web` still could not sign a\n// person in. Measured 2026-08-18 against a real stack, on the published 7.3.0.\n//\n// The lesson is where a retry belongs: at the layer that ISSUES the request.\n// Core owns fetch for every client in this repo, so core owns the challenge.\n//\n// WebCrypto rather than a hashing dependency: `crypto.subtle` is present in\n// browsers and in Node 18+, which is the same floor the rest of the SDK sets.\n// Measured at the server's default difficulty of 16: ~330ms, ~65k digests.\n\n/** The challenge a `pow_required` response carries. */\nexport interface PowChallenge {\n  id: string;\n  prefix: string;\n  difficulty: number;\n}\n\n/** Header names the retry must carry. Mirrors the server's constants. */\nexport const POW_CHALLENGE_ID_HEADER = 'X-PoW-Challenge-ID';\nexport const POW_NONCE_HEADER = 'X-PoW-Nonce';\n\n/**\n * Reads a challenge out of an error envelope, or returns null when the envelope\n * is not a `pow_required` one.\n *\n * The whole wire envelope is stored on the error, so the challenge arrives\n * without the HTTP layer having to know about proof-of-work at all.\n */\nexport function asPowChallenge(details: unknown): PowChallenge | null {\n  if (typeof details !== 'object' || details === null) return null;\n  const env = details as Record<string, unknown>;\n  if (env.error !== 'pow_required') return null;\n  const c = env.challenge;\n  if (typeof c !== 'object' || c === null) return null;\n  const { id, prefix, difficulty } = c as Record<string, unknown>;\n  if (typeof id !== 'string' || typeof prefix !== 'string') return null;\n  if (typeof difficulty !== 'number' || !Number.isInteger(difficulty) || difficulty < 0)\n    return null;\n  return { id, prefix, difficulty };\n}\n\nconst encoder = new TextEncoder();\n\n/**\n * One SHA-256, by the fastest route this runtime offers.\n *\n * Awaiting `crypto.subtle.digest` once per nonce is what made this expensive,\n * and the cost is the await rather than the hashing. Measured on one machine,\n * 200k digests of a 40-byte input:\n *\n *\tawaited crypto.subtle.digest     105,597 digests/s\n *\tsync node:crypto createHash    1,324,503 digests/s   — 12.5x\n *\n * That is the difference between difficulty 24 taking 159 seconds and taking\n * 13. Node, Bun and Deno all have the sync one; a browser has only WebCrypto,\n * and there it stays async.\n *\n * The specifier is assembled at runtime so a browser bundler does not try to\n * resolve `node:crypto` and fail the build over a branch that never runs there.\n */\ntype Hasher = (input: string) => Uint8Array | Promise<Uint8Array>;\n\nlet hasher: Hasher | null = null;\n\nasync function digester(): Promise<Hasher> {\n  if (hasher) return hasher;\n  // Read off globalThis with an inline shape rather than by naming `process`,\n  // which needs @types/node — a dependency this package does not have and should\n  // not grow for one branch. It typechecked locally only because those types\n  // were hoisted into node_modules by a sibling package; the publish workflow's\n  // clean checkout is what said so, which is exactly what it is for.\n  const runtime = globalThis as {\n    process?: { versions?: { node?: string; bun?: string } };\n  };\n  const nodeish =\n    runtime.process?.versions?.node !== undefined || runtime.process?.versions?.bun !== undefined;\n  if (nodeish) {\n    try {\n      const mod = (await import(/* @vite-ignore */ `${'node:'}crypto`)) as {\n        createHash?: (alg: string) => { update(s: string): { digest(): Uint8Array } };\n      };\n      if (typeof mod.createHash === 'function') {\n        const createHash = mod.createHash;\n        hasher = (input: string) => new Uint8Array(createHash('sha256').update(input).digest());\n        return hasher;\n      }\n    } catch {\n      // No node:crypto here. WebCrypto below is not a fallback in the apologetic\n      // sense — it is the only hash a browser has, and it is correct.\n    }\n  }\n  hasher = async (input: string) =>\n    new Uint8Array(await crypto.subtle.digest('SHA-256', encoder.encode(input)));\n  return hasher;\n}\n\n/** Monotonic where it exists, wall-clock where it does not. */\nconst now = (): number =>\n  typeof performance !== 'undefined' && typeof performance.now === 'function'\n    ? performance.now()\n    : Date.now();\n\n/** Counts leading zero bits, stopping at the first byte that has a one. */\nfunction leadingZeroBits(hash: Uint8Array): number {\n  let bits = 0;\n  for (const byte of hash) {\n    if (byte === 0) {\n      bits += 8;\n      continue;\n    }\n    // clz32 counts across 32 bits; a byte occupies the low 8, so the first 24\n    // are always zero and get subtracted back off.\n    return bits + Math.clz32(byte) - 24;\n  }\n  return bits;\n}\n\n/**\n * The hardest challenge this client will attempt.\n *\n * Not a taste: it is the server's own ceiling. palauth maps a risk score to a\n * difficulty and its worst case is 24 (`DifficultyForRisk`, bot/pow.go:156-166).\n * Anything above that cannot have come from a stack behaving as designed, and\n * the cost of humouring it falls entirely on this side — each step up DOUBLES\n * the work, so difficulty 30 is sixty-four times a legitimate worst case and, on\n * the web, sixty-four times a frozen main thread. Refused immediately, by name.\n */\nexport const MAX_POW_DIFFICULTY = 24;\n\n/**\n * Finds a nonce satisfying the challenge and returns the headers a retry needs.\n *\n * THE BUDGET SCALES WITH THE CHALLENGE, and the first version of this did not.\n * It bounded the search at a flat `1 << 24` — which is not a generous bound for\n * difficulty 24, it is the EXPECTED number of attempts. Finding a nonce is a\n * geometric process: the chance of needing more than 2^d attempts is 1/e, so a\n * flat 2^24 would have failed roughly 37% of legitimate hardest-risk challenges,\n * and failed them for precisely the users the gate exists to slow down — who\n * would have been unable to sign in at all rather than made to wait.\n *\n * Eight times expected puts that at e^-8, about three in ten thousand, while\n * leaving the common case (the server's default 16, and 12 for an unremarkable\n * caller) exactly as cheap as it was.\n *\n * `powBudget` is exported and separate so the RELATIONSHIP can be asserted\n * directly. A test that only watches a cheap challenge succeed cannot tell this\n * budget from the flat one it replaced — measured: reinstating `1 << 24` left\n * such a test green.\n */\nexport function powBudget(difficulty: number): number {\n  return 8 * 2 ** difficulty;\n}\n\n/**\n * The longest a solve may be ALLOWED to take, and the difference from a\n * deadline is the whole point.\n *\n * The first version of this was a flat 120s deadline, and it was measured to be\n * worse than the flat iteration budget it was meant to backstop: at ~105k\n * digests/s, difficulty 24 EXPECTS 159 seconds, so a 120s clock killed the\n * majority of legitimate hardest-risk solves — reintroducing, larger, exactly\n * the class of defect that replacing `1 << 24` had removed. Guessing a number\n * for an unknown machine cannot work: the same difficulty is 13 seconds on a\n * runtime with a sync hasher and 159 on one without.\n *\n * So the machine is MEASURED, and the decision moves to the front. A short\n * calibration gives the rate this process actually hashes at; if the whole\n * iteration budget cannot fit in this window at that rate, the solve is refused\n * IMMEDIATELY, naming the numbers. A caller then learns in milliseconds that\n * this difficulty is unpayable here, instead of after two minutes of work\n * thrown away.\n *\n * What remains after that is a guarantee rather than a gamble: a solve that\n * starts can always finish inside its budget, so the only failure left is the\n * budget's own e^-8.\n */\nexport const POW_TIME_BUDGET_MS = 120_000;\n\n/**\n * The window the rate is measured over, and the warm-up it deliberately skips.\n *\n * All of these are REAL attempts — the search starts at nonce 0 and never\n * restarts — so calibration costs nothing but the reading. The first 1024 are\n * excluded from the timing because they include this loop's own JIT warm-up:\n * measured, timing from zero reported 747k digests/s on a machine whose steady\n * rate is 1.32M, and the decision below would have refused a difficulty this\n * machine can pay in half the allowance.\n */\nconst CALIBRATION_WARMUP = 1024;\nconst CALIBRATION_END = 9216;\n\nexport async function solvePowChallenge(\n  challenge: PowChallenge,\n  maxIterations = powBudget(challenge.difficulty),\n  // The caller's AbortSignal, honoured INSIDE the loop rather than only around\n  // the fetch it precedes — for the callers that have one. `pb.auth.signIn` does\n  // NOT: it reaches the network through @palbase/auth's client, which takes\n  // credentials and nothing else. So it is the extra a caller can opt into, and\n  // POW_TIME_BUDGET_MS below is what actually bounds the work.\n  signal?: AbortSignal,\n): Promise<Record<string, string>> {\n  if (challenge.difficulty > MAX_POW_DIFFICULTY) {\n    throw new Error(\n      `proof-of-work: refusing difficulty ${challenge.difficulty}; this client attempts at most ${MAX_POW_DIFFICULTY}, which is the highest a Palbase stack issues`,\n    );\n  }\n\n  const digest = await digester();\n  let warmedAt = 0;\n  let calibrated = false;\n  // Armed by the calibration below, never before it: until the rate is known\n  // there is no honest number to put here.\n  let deadline = Number.POSITIVE_INFINITY;\n\n  for (let nonce = 0; nonce < maxIterations; nonce++) {\n    // Checked in batches: reading them is cheap but not free, and a\n    // 1024-digest granularity bounds the delay at a few milliseconds.\n    if ((nonce & 1023) === 0) {\n      if (signal?.aborted) {\n        throw new DOMException('proof-of-work solve aborted', 'AbortError');\n      }\n      if (now() > deadline) {\n        throw new Error(\n          `proof-of-work: gave up on difficulty ${challenge.difficulty} after ${POW_TIME_BUDGET_MS / 1000}s ` +\n            `and ${nonce.toLocaleString()} attempts — the tail this run drew is longer than the allowance`,\n        );\n      }\n    }\n\n    // THE DECISION, TAKEN ONCE AND TAKEN EARLY.\n    //\n    // After CALIBRATION_DIGESTS real attempts the rate of THIS process is\n    // known, so the question \"can this machine pay this difficulty\" has an\n    // answer instead of an assumption. If the whole budget cannot fit in the\n    // time budget, refuse here — milliseconds in, with the numbers — rather\n    // than spend two minutes and throw them away. If it fits, everything after\n    // this point is guaranteed to finish inside the window, so the only\n    // remaining failure is the budget's own e^-8.\n    if (nonce === CALIBRATION_WARMUP) {\n      warmedAt = now();\n    }\n    if (!calibrated && nonce === CALIBRATION_END) {\n      calibrated = true;\n      const elapsed = Math.max(now() - warmedAt, 0.001);\n      const rate = (CALIBRATION_END - CALIBRATION_WARMUP) / (elapsed / 1000);\n      // EXPECTED, not worst case, and the difference is the whole judgement.\n      //\n      // Finding a nonce is geometric: 2^difficulty attempts on average, with a\n      // long tail the 8x budget covers. Refusing because the TAIL will not fit\n      // would turn away work whose expected cost is seventeen seconds — measured\n      // exactly that on this machine at difficulty 24. Refusing on the EXPECTED\n      // cost turns away only what is genuinely unpayable here, and what it lets\n      // through is then cut by the clock with probability e^-(budget/expected):\n      // at 120s against a 17s expectation that is one run in a thousand, and at\n      // difficulty 20 on a browser it is one in a hundred and fifty thousand.\n      const expectedMs = (2 ** challenge.difficulty / rate) * 1000;\n      if (expectedMs > POW_TIME_BUDGET_MS) {\n        throw new Error(\n          `proof-of-work: difficulty ${challenge.difficulty} needs about ${Math.round(expectedMs / 1000)}s here ` +\n            `(${Math.round(rate).toLocaleString()} digests/s) and this client allows ${POW_TIME_BUDGET_MS / 1000}s; ` +\n            `refusing before spending the time rather than after`,\n        );\n      }\n      deadline = now() + (POW_TIME_BUDGET_MS - (now() - warmedAt));\n    }\n\n    const hash = await digest(challenge.prefix + nonce);\n    if (leadingZeroBits(hash) >= challenge.difficulty) {\n      return {\n        [POW_CHALLENGE_ID_HEADER]: challenge.id,\n        [POW_NONCE_HEADER]: String(nonce),\n      };\n    }\n  }\n  throw new Error(\n    `proof-of-work: no nonce found for difficulty ${challenge.difficulty} within ${maxIterations} attempts`,\n  );\n}\n","import { Chacha20Poly1305 } from '@hpke/chacha20poly1305';\nimport { CipherSuite, HkdfSha256 } from '@hpke/core';\nimport { DhkemX25519HkdfSha256 } from '@hpke/dhkem-x25519';\nimport { PalbaseError } from './errors.js';\nimport { fromBase64, toBase64 } from './sealed-json.js';\nimport type { SealingKey } from './sealed-keys.js';\n\nexport const SEALED_CONTENT_TYPE = 'application/palbase-sealed+json';\nexport const SEALED_HEADER = 'X-Palbase-Sealed';\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder('utf-8', { fatal: true });\nconst responseLabel = 'palbase-sealed/response/v1';\n\nexport function sealingRequired(path: string): boolean {\n  // Mirrors v2/internal/server/sealed.go. Tenant/runtime routes cannot unseal.\n  return new URL(path, 'https://unused.invalid').pathname.startsWith('/auth/');\n}\n\nexport function requestAAD(\n  host: string,\n  method: string,\n  path: string,\n  ict: string,\n  ts: number,\n  idem: string,\n): Uint8Array<ArrayBuffer> {\n  const fields = [host, method, path, ict, idem].map((field) => encoder.encode(field));\n  const bytes = new Uint8Array(fields.reduce((size, field) => size + 4 + field.length, 8));\n  const view = new DataView(bytes.buffer);\n  let offset = 0;\n  for (const [index, field] of fields.entries()) {\n    if (index === 4) {\n      view.setBigUint64(offset, BigInt(ts));\n      offset += 8;\n    }\n    view.setUint32(offset, field.length);\n    offset += 4;\n    bytes.set(field, offset);\n    offset += field.length;\n  }\n  return bytes;\n}\n\nexport function sealingSuite(): CipherSuite {\n  return new CipherSuite({\n    kem: new DhkemX25519HkdfSha256(),\n    kdf: new HkdfSha256(),\n    aead: new Chacha20Poly1305(),\n  });\n}\n\nexport async function sealRequest(\n  key: SealingKey,\n  url: string,\n  init: RequestInit,\n): Promise<Uint8Array<ArrayBuffer>> {\n  const suite = sealingSuite();\n  const sender = await suite.createSenderContext({\n    recipientPublicKey: await suite.kem.importKey('raw', key.publicKey.buffer),\n  });\n  const headers = new Headers(init.headers);\n  const ict = headers.get('content-type') ?? 'application/json';\n  const ts = Math.floor(Date.now() / 1000);\n  const target = new URL(url);\n  const method = init.method ?? 'GET';\n  // Go binds r.URL.Path (decoded, without the query), not RequestURI.\n  const aad = requestAAD(\n    target.host,\n    method,\n    decodeURIComponent(target.pathname),\n    ict,\n    ts,\n    headers.get('idempotency-key') ?? '',\n  );\n  const ct = await sender.seal(encoder.encode(typeof init.body === 'string' ? init.body : ''), aad);\n  const envelope = JSON.stringify({\n    v: 2,\n    kid: key.kid,\n    enc: toBase64(new Uint8Array(sender.enc)),\n    ct: toBase64(new Uint8Array(ct)),\n    ict,\n    ts,\n  });\n  if (method === 'GET' || method === 'HEAD' || init.body === undefined) {\n    headers.set(\n      SEALED_HEADER,\n      toBase64(encoder.encode(envelope)).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, ''),\n    );\n    delete init.body;\n  } else {\n    headers.delete(SEALED_HEADER);\n    headers.set('Content-Type', SEALED_CONTENT_TYPE);\n    init.body = envelope;\n  }\n  headers.delete('Content-Length');\n  init.headers = Object.fromEntries(headers.entries());\n  // Do not redirect a credential-bearing envelope to a different endpoint.\n  init.redirect = 'error';\n  return new Uint8Array(await sender.export(encoder.encode(responseLabel), 32));\n}\n\nexport async function openSealedResponse(\n  response: Response,\n  exporter: Uint8Array | undefined,\n  method: string,\n): Promise<Response> {\n  if (\n    response.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase() !==\n    SEALED_CONTENT_TYPE\n  ) {\n    // Edge/middleware errors are plaintext. A successful auth result cannot be.\n    if (exporter && response.ok && method !== 'HEAD') {\n      throw new PalbaseError(\n        'sealed_response_invalid',\n        'The server returned an unencrypted response.',\n        response.status,\n      );\n    }\n    return response;\n  }\n  // HTTP HEAD has no response body, including when the handler sealed it.\n  if (method === 'HEAD') return response;\n  try {\n    if (!exporter) throw new Error('No sealing context');\n    const envelope = (await response.json()) as {\n      v: number;\n      n: string;\n      ct: string;\n      ict: string;\n      st: number;\n    };\n    if (\n      envelope.v !== 2 ||\n      !Number.isInteger(envelope.st) ||\n      envelope.st < 200 ||\n      envelope.st > 599 ||\n      typeof envelope.ict !== 'string'\n    ) {\n      throw new Error('Invalid response envelope');\n    }\n    const plaintext = await new Chacha20Poly1305()\n      .createEncryptionContext(exporter)\n      .open(\n        fromBase64(envelope.n),\n        fromBase64(envelope.ct),\n        encoder.encode(`${responseLabel}\\n${envelope.ict}\\n${envelope.st}`),\n      );\n    const headers = new Headers(response.headers);\n    headers.set('Content-Type', envelope.ict);\n    headers.delete('Content-Length');\n    headers.delete('Content-Encoding');\n    // The outer status is always 200; auth failures and PoW live inside the seal.\n    return new Response([204, 205, 304].includes(envelope.st) ? null : decoder.decode(plaintext), {\n      status: envelope.st,\n      headers,\n    });\n  } catch {\n    throw new PalbaseError(\n      'sealed_response_invalid',\n      'The encrypted server response could not be verified.',\n      response.status,\n    );\n  }\n}\n","// Signatures cover the original JSON bytes, not JSON.stringify(JSON.parse(raw)).\n// Go's encoder preserves struct field order and escapes characters differently.\nexport function rawObjectFields(raw: string): Map<string, string> {\n  const parsed: unknown = JSON.parse(raw);\n  if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n    throw new Error('Expected a JSON object');\n  }\n  const fields = new Map<string, string>();\n  let i = 0;\n  const space = () => {\n    while (/\\s/.test(raw[i] ?? '') && i < raw.length) i++;\n  };\n  const stringEnd = (start: number) => {\n    let end = start + 1;\n    while (end < raw.length) {\n      if (raw[end] === '\\\\') end += 2;\n      else if (raw[end++] === '\"') return end;\n    }\n    throw new Error('Unterminated JSON string');\n  };\n  space();\n  i++; // opening object, already validated by JSON.parse\n  while (true) {\n    space();\n    if (raw[i] === '}') return fields;\n    const nameEnd = stringEnd(i);\n    const name = JSON.parse(raw.slice(i, nameEnd)) as string;\n    i = nameEnd;\n    space();\n    i++; // colon\n    space();\n    const start = i;\n    if (raw[i] === '\"') i = stringEnd(i);\n    else if (raw[i] === '{' || raw[i] === '[') {\n      let depth = 0;\n      do {\n        const c = raw[i];\n        if (c === '\"') {\n          i = stringEnd(i);\n          continue;\n        }\n        if (c === '{' || c === '[') depth++;\n        if (c === '}' || c === ']') depth--;\n        i++;\n      } while (depth > 0 && i < raw.length);\n    } else {\n      while (i < raw.length && !/[\\s,}]/.test(raw[i] ?? '')) i++;\n    }\n    // A first-match slice and JSON.parse's last-match value must never disagree.\n    if (fields.has(name)) throw new Error('Duplicate JSON field');\n    fields.set(name, raw.slice(start, i));\n    space();\n    if (raw[i] === ',') i++;\n  }\n}\n\nexport function fromBase64(value: string): Uint8Array<ArrayBuffer> {\n  return Uint8Array.from(atob(value), (c) => c.charCodeAt(0));\n}\n\nexport function toBase64(bytes: Uint8Array): string {\n  // Avoid a spread: envelopes can exceed the engine's argument-count limit.\n  let binary = '';\n  for (const byte of bytes) binary += String.fromCharCode(byte);\n  return btoa(binary);\n}\n","import { ed25519 } from '@noble/curves/ed25519.js';\nimport { PalbaseError } from './errors.js';\nimport { fromBase64, rawObjectFields } from './sealed-json.js';\nimport type { HttpClientOptions } from './types.js';\nimport { endpointUrl } from './url.js';\n\nexport const SEALED_KEYSET_PATH = '/palbase-sealed-keys.json';\nexport const SEALED_SUITE = 'DHKEM-X25519-HKDF-SHA256/HKDF-SHA256/ChaCha20Poly1305';\n// Fleet PUBLIC key, identical to the iOS SDK pin. Never learned from a response.\nconst FLEET_ROOT = 'mRDTIWzhW0JCk0e2Jvkn679VeZBB38zOOfPTMO6vBpU=';\nconst REFRESH_MS = 5 * 60_000;\nconst FAILURE_COOLDOWN_MS = 60_000;\nconst encoder = new TextEncoder();\n\nexport interface SealingKey {\n  kid: string;\n  publicKey: Uint8Array<ArrayBuffer>;\n  expires: number;\n  version: number;\n}\n\nexport function expectedSealedStack(baseUrl: string, apiKey: string): string {\n  // Fleet tenant hosts name the stack even when a legacy key says pb_project_.\n  // Apex/custom/self-host URLs instead need the key's ref (or an explicit pin).\n  const host = new URL(baseUrl).hostname;\n  return (\n    /^([a-z0-9]{4,24})\\.(?:(?:dev|staging)\\.)?palbase\\.studio$/.exec(host)?.[1] ??\n    /^pb_([^_]+)_/.exec(apiKey)?.[1] ??\n    ''\n  );\n}\n\nfunction record(raw: string | undefined): Record<string, unknown> {\n  if (!raw) throw new Error('Missing signed object');\n  rawObjectFields(raw); // also refuses duplicate fields\n  return JSON.parse(raw) as Record<string, unknown>;\n}\n\nfunction string(value: unknown): string {\n  if (typeof value !== 'string' || !value) throw new Error('Missing string');\n  return value;\n}\n\nfunction integer(value: unknown): number {\n  if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) {\n    throw new Error('Invalid integer');\n  }\n  return value;\n}\n\nfunction verifySignature(raw: string, signed: Record<string, unknown>, publicKey: Uint8Array) {\n  if (\n    signed.alg !== 'ed25519' ||\n    publicKey.length !== 32 ||\n    !ed25519.verify(fromBase64(string(signed.sig)), encoder.encode(raw), publicKey, {\n      zip215: false,\n    })\n  )\n    throw new Error('Invalid sealed key signature');\n}\n\n/** Verify fleet → expected stack → keyset, retaining the exact signed bytes. */\nexport function verifySealingKey(\n  raw: string,\n  expectedRef: string,\n  root: string,\n  lastVersion: number,\n  now: number,\n): SealingKey {\n  const fields = rawObjectFields(raw);\n  const signed = record(raw);\n  const statementRaw = fields.get('binding');\n  const statement = record(statementRaw);\n  const bindingRaw = rawObjectFields(statementRaw ?? '').get('binding');\n  if (!bindingRaw || statement.rootKid !== 'sealed-root-v1') {\n    throw new Error('Unknown sealed trust root');\n  }\n  verifySignature(bindingRaw, statement, fromBase64(root));\n  const binding = record(bindingRaw);\n  if (\n    binding.v !== 1 ||\n    !expectedRef ||\n    string(binding.stackRef).trim().toLowerCase() !== expectedRef.toLowerCase()\n  ) {\n    throw new Error('Sealed binding belongs to another stack');\n  }\n  const bindingExpiry = integer(binding.expires);\n  if (bindingExpiry * 1000 <= now) throw new Error('Expired sealed binding');\n  const keysetRaw = fields.get('keyset');\n  if (!keysetRaw) throw new Error('Missing sealed keyset');\n  verifySignature(keysetRaw, signed, fromBase64(string(binding.signingKey)));\n  const keyset = record(keysetRaw);\n  const version = integer(keyset.version);\n  const expires = Math.min(integer(keyset.expires), bindingExpiry);\n  if (version < lastVersion) throw new Error('Sealed keyset version went backwards');\n  if (expires * 1000 <= now) throw new Error('Expired sealed keyset');\n  if (keyset.v !== 1 || !Array.isArray(keyset.keys)) throw new Error('Invalid sealed keyset');\n  for (const item of keyset.keys) {\n    if (item === null || typeof item !== 'object') continue;\n    const entry = item as Record<string, unknown>;\n    if (entry.alg !== SEALED_SUITE) continue;\n    const publicKey = fromBase64(string(entry.pub));\n    if (publicKey.length !== 32) throw new Error('Invalid sealing public key');\n    return { kid: string(entry.kid), publicKey, expires, version };\n  }\n  throw new Error('No supported sealing key');\n}\n\nexport class SealedKeyStore {\n  private cached?: SealingKey;\n  private pending?: Promise<SealingKey>;\n  private fetchedAt = 0;\n  private retryAfter = 0;\n  private lastVersion = 0;\n  private lastError?: PalbaseError;\n  private rotationRefreshAt = 0;\n\n  constructor(\n    private readonly baseUrl: string,\n    private readonly apiKey: string,\n    private readonly options?: Exclude<HttpClientOptions['sealed'], false>,\n  ) {}\n\n  async current(signal?: AbortSignal, rotate = false): Promise<SealingKey> {\n    signal?.throwIfAborted();\n    const now = Date.now();\n    const valid = this.cached && this.cached.expires * 1000 > now ? this.cached : undefined;\n    if (this.pending) return this.waitFor(this.pending, signal);\n    // A forged unknown-kid response cannot turn every request into a key fetch.\n    if (rotate && now - this.rotationRefreshAt >= FAILURE_COOLDOWN_MS) {\n      this.fetchedAt = 0;\n      this.retryAfter = 0;\n      this.rotationRefreshAt = now;\n    }\n    if (valid && now - this.fetchedAt < REFRESH_MS) return valid;\n    if (now < this.retryAfter) {\n      if (valid) return valid;\n      throw this.lastError;\n    }\n    const pending = this.fetchKey()\n      .then((key) => {\n        this.cached = key;\n        this.lastVersion = key.version;\n        this.fetchedAt = Date.now();\n        this.retryAfter = 0;\n        return key;\n      })\n      .catch((error: unknown) => {\n        this.retryAfter = Date.now() + FAILURE_COOLDOWN_MS;\n        this.lastError =\n          error instanceof PalbaseError\n            ? error\n            : new PalbaseError(\n                'sealed_key_unavailable',\n                'The server encryption key could not be verified. Please try again later.',\n                0,\n              );\n        // A transient refresh failure may reuse a verified, unexpired key only.\n        if (this.cached && this.cached.expires * 1000 > Date.now()) return this.cached;\n        throw this.lastError;\n      })\n      .finally(() => {\n        this.pending = undefined;\n      });\n    this.pending = pending;\n    return this.waitFor(pending, signal);\n  }\n\n  private async fetchKey(): Promise<SealingKey> {\n    const controller = new AbortController();\n    const timer = setTimeout(() => controller.abort(), 15_000);\n    try {\n      const response = await fetch(endpointUrl(this.baseUrl, SEALED_KEYSET_PATH), {\n        headers: this.apiKey ? { apikey: this.apiKey } : {},\n        signal: controller.signal,\n        cache: 'no-store',\n        redirect: 'error',\n      });\n      if (!response.ok) throw new Error('Sealed keyset unavailable');\n      const raw = await response.text();\n      if (raw.length > 64 * 1024) throw new Error('Sealed keyset too large');\n      const expectedRef = this.options?.stackRef ?? expectedSealedStack(this.baseUrl, this.apiKey);\n      return verifySealingKey(\n        raw,\n        expectedRef,\n        this.options?.root ?? FLEET_ROOT,\n        this.lastVersion,\n        Date.now(),\n      );\n    } finally {\n      clearTimeout(timer);\n    }\n  }\n\n  // One caller's cancellation must not abort a shared key fetch for other calls.\n  private waitFor(pending: Promise<SealingKey>, signal?: AbortSignal): Promise<SealingKey> {\n    if (!signal) return pending;\n    return new Promise((resolve, reject) => {\n      const aborted = () => reject(signal.reason);\n      signal.addEventListener('abort', aborted, { once: true });\n      pending.then(resolve, reject).finally(() => signal.removeEventListener('abort', aborted));\n      if (signal.aborted) aborted();\n    });\n  }\n}\n","/**\n * Join the configured base URL with an SDK path.\n *\n * A BASE URL MAY CARRY A PATH, NOT JUST AN ORIGIN — a self-host published\n * under `https://api.example.com/palbase`, or an app that routes the browser\n * through its own server (`<origin>/pb`, rewritten upstream) because the\n * Environment's edge does not answer its origin with CORS headers.\n *\n * `new URL('/palbase-sealed-keys.json', base)` reads as the careful way to do\n * this and is the one form that DROPS that path: the leading slash makes the\n * path absolute against the base's ORIGIN. The sealed key store used it while\n * every ordinary request concatenated, so one request in the client asked a\n * different server than all the others — measured live 2026-09-11, the keyset\n * fetch landed on the app's own 404 page and every sealed call failed with\n * `sealed_key_unavailable`. The other two SDK surfaces never had the split:\n * iOS appends (`SealedKeyStore.swift`), Android concatenates onto a\n * slash-trimmed base (`SealedKeyStore.kt`) — this is their shape.\n */\nexport function endpointUrl(base: string, path: string): string {\n  return `${base.replace(/\\/+$/, '')}${path}`;\n}\n","import { PalbaseError } from './errors.js';\nimport { wirePlatform } from './platform.js';\nimport { asPowChallenge, solvePowChallenge } from './pow.js';\nimport { openSealedResponse, sealingRequired, sealRequest } from './sealed.js';\nimport { SealedKeyStore } from './sealed-keys.js';\nimport type { TokenManager } from './token.js';\nimport type { HttpClientOptions, PalbaseResponse, RequestOptions } from './types.js';\nimport { endpointUrl } from './url.js';\n\n/**\n * Default production host. Dev / staging / local callers override via\n * `options.url`. Apex-style routing is the only supported production path;\n * Kong resolves Environment identity from the API key.\n */\nconst PALBASE_DEFAULT_HOST = 'api.palbase.studio';\n\n/**\n * Parse the Environment ref from a Palbase API key.\n *\n * Canonical shape: `pb_{environment_ref}_c{random}`, where the Environment ref\n * is 4-24 lowercase ASCII alphanumeric characters and random is AT LEAST 20\n * base62 chars.\n *\n * The length is a floor, not an equality. The stack's own minter writes 20\n * (v2/cmd/palsvc/initenv.go) and the cloud control plane writes 32\n * (cloud/platform/server/services/keys.ts), and the door that admits the\n * request refuses to rule on the difference: *\"a shorter or longer secret is\n * not a security property this door can rule on\"*\n * (v2/internal/platform/identitymw.go: parseAPIKey). A client that is stricter\n * than the server does not add safety — it just refuses working keys, which is\n * exactly what this one did to every cloud project until 2026-08-25.\n *\n * Returns the Environment ref on match; `null` otherwise.\n */\nconst API_KEY_RE = /^pb_([a-z0-9]{4,24})_c[A-Za-z0-9]{20,}$/;\n\nfunction parseEnvironmentRef(apiKey: string): string | null {\n  return API_KEY_RE.exec(apiKey)?.[1] ?? null;\n}\nconst MAX_RETRIES = 3;\nconst INITIAL_BACKOFF_MS = 200;\n/**\n * Upper bound on a single 429 retry sleep. A server may return a long\n * Retry-After (a locked account can send minutes/hours); honoring it verbatim\n * would HANG the request for that whole window. Cap each retry at 10s — after\n * MAX_RETRIES the 429 envelope surfaces to the caller (fail fast, don't sleep\n * minutes). The clamp never skips a retry; it only bounds how long each waits.\n */\nconst MAX_RETRY_DELAY_MS = 10_000;\n\n/**\n * The edge's refusals this client is allowed to WAIT for — an ALLOWLIST.\n *\n * NEVER a denylist. Enumerating the exceptions cannot see the set GROW: a name\n * added at the edge tomorrow would be waited for by a client that never heard\n * of it. The client waits only for what it was taught.\n *\n * `request_too_large` is absent on purpose — the same body earns the same\n * refusal, so waiting cannot help. `handoff_failed` is absent because the\n * project may ALREADY have applied the request: the edge counts a hand-off\n * ATTEMPT before it knows the outcome, and a connection can break after the\n * body was fully delivered. A silent retry there writes an insert twice.\n */\nconst RETRYABLE_HOLD_REFUSALS: ReadonlySet<string> = new Set([\n  'holder_full',\n  'wake_budget_exceeded',\n]);\n\n/**\n * How long to wait for a held-request refusal, or null when it must surface.\n *\n * READS THE NAME, NEVER THE STATUS: an unnamed 503 is Envoy's `no healthy\n * upstream` and this client keeps surfacing it exactly as it does today.\n *\n * READS THE HINT FROM THE PARSED BODY, never from the header alone. A browser\n * cannot see `Retry-After` unless CORS exposes it, and the edge does not — it\n * was measured live on an AWAKE project, whose expose list carries\n * `x-request-id, palbase-auth-contract, etag` and not `Retry-After`. A\n * header-only read is inert exactly where this fix matters.\n */\nfunction heldRefusalWait(\n  status: number,\n  body: { error?: string; retry_after?: number } | undefined,\n): number | null {\n  if (status !== 503) return null;\n  if (body?.error === undefined || !RETRYABLE_HOLD_REFUSALS.has(body.error)) return null;\n  const seconds = body.retry_after;\n  const advertised =\n    typeof seconds === 'number' && Number.isFinite(seconds) && seconds > 0\n      ? seconds * 1000\n      : INITIAL_BACKOFF_MS;\n  // The 429 path's own ceiling — no second backoff is invented.\n  return Math.min(advertised, MAX_RETRY_DELAY_MS);\n}\n\n/**\n * Carry a 429's retry hint into the error envelope when only the header has it.\n *\n * A REFUSAL FROM THE EDGE CARRIES NOTHING BUT THE HEADER. Envoy and the\n * gateway limiter answer before any Palbase service is reached, so their 429\n * has no `retry_after` and no `data.retryAfter` — and every reader above this\n * layer (`@palbase/web`'s BackendError, the iOS SDK) looks in the BODY. The\n * seconds were on the wire and unreachable to all of them.\n *\n * Lifted under `retry_after`, the platform's own name for it (palauth's\n * rate-limit envelope), never overwriting a hint the service itself sent — a\n * service knows its window, the edge only knows its own.\n */\nfunction withRetryHint(\n  body: Record<string, unknown> | undefined,\n  response: Response,\n): Record<string, unknown> | undefined {\n  // 429, OR a 503 the edge NAMED as a held request. NOT \"any 503\": an unnamed\n  // 503 is Envoy's `no healthy upstream` and FR-006 keeps it exactly as it is\n  // today — gaining a hint would already be a behaviour change.\n  const namedHold =\n    response.status === 503 &&\n    typeof body?.error === 'string' &&\n    RETRYABLE_HOLD_REFUSALS.has(body.error);\n  if (response.status !== 429 && !namedHold) return body;\n  const data = body?.data;\n  const alreadyStated =\n    typeof body?.retry_after === 'number' ||\n    (typeof data === 'object' && data !== null && 'retryAfter' in data);\n  if (alreadyStated) return body;\n  const seconds = Number.parseInt(response.headers.get('Retry-After') ?? '', 10);\n  if (Number.isNaN(seconds) || seconds <= 0) return body;\n  return { ...body, retry_after: seconds };\n}\n\n/**\n * Request interceptor. Runs before every HTTP request.\n * Can modify headers, body, or reject the request.\n */\nexport type RequestInterceptor = (request: {\n  headers: Record<string, string>;\n  method: string;\n  path: string;\n}) => void | Promise<void>;\n\nexport class HttpClient {\n  protected readonly apiKey: string;\n  protected readonly options?: HttpClientOptions;\n\n  tokenManager: TokenManager | null = null;\n\n  /**\n   * Admin JWT used for platform admin endpoints (/admin/*).\n   * When set, takes precedence over tokenManager access token in the\n   * Authorization header.\n   */\n  adminToken: string | null = null;\n\n  private readonly interceptors: RequestInterceptor[] = [];\n  private readonly forbiddenListeners = new Set<(body: Record<string, unknown>) => void>();\n  private sealedKeys?: SealedKeyStore;\n\n  constructor(apiKey: string, options?: HttpClientOptions) {\n    this.apiKey = apiKey;\n    this.options = options;\n  }\n\n  /** Set (or clear) the admin JWT used on admin endpoints. */\n  setAdminToken(token: string | null): void {\n    this.adminToken = token;\n  }\n\n  /**\n   * Called with the RAW body of every 403 this client receives (FR-010). Core\n   * does not know the envelope's fields — the layer that does (palbe) reads\n   * `required` out of it. Nothing is retried or swallowed: the error still\n   * returns to the caller.\n   */\n  onForbidden(handler: (body: Record<string, unknown>) => void): () => void {\n    this.forbiddenListeners.add(handler);\n    return () => {\n      this.forbiddenListeners.delete(handler);\n    };\n  }\n\n  /**\n   * Create a scoped HttpClient that adds the given extra headers to every\n   * request. The returned client shares the admin token and token manager\n   * with the parent at runtime — later changes on the parent propagate to\n   * the scope and vice versa.\n   *\n   * Typical use: adding an Environment-routing header for an admin call.\n   */\n  withHeaders(extra: Record<string, string>): HttpClient {\n    const mergedHeaders = { ...(this.options?.headers ?? {}), ...extra };\n\n    const scoped: HttpClient = new HttpClient(this.apiKey, {\n      ...this.options,\n      headers: mergedHeaders,\n    });\n    scoped.tokenManager = this.tokenManager;\n    // Delegate adminToken reads + writes to the parent so the scope always\n    // sees the latest token, and setAdminToken on the scope affects the parent.\n    // The scope shares the parent's 403 listeners: a refusal is a refusal\n    // whichever header set the request carried.\n    Object.defineProperty(scoped, 'forbiddenListeners', {\n      get: () => this.forbiddenListeners,\n    });\n    Object.defineProperty(scoped, 'adminToken', {\n      get: () => this.adminToken,\n      set: (v: string | null) => {\n        this.adminToken = v;\n      },\n      configurable: true,\n    });\n    Object.defineProperty(scoped, 'sealedKeys', {\n      get: () => this.sealedKeys,\n      set: (v: SealedKeyStore | undefined) => {\n        this.sealedKeys = v;\n      },\n    });\n    return scoped;\n  }\n\n  /** Add a request interceptor. Runs before every request. */\n  addInterceptor(interceptor: RequestInterceptor): void {\n    this.interceptors.push(interceptor);\n  }\n\n  async request<T>(\n    method: string,\n    path: string,\n    options?: RequestOptions,\n  ): Promise<PalbaseResponse<T>> {\n    // If token is expired and refresh is available, refresh before making the request\n    if (\n      !options?.skipSessionRefresh &&\n      this.tokenManager?.isExpired() &&\n      this.tokenManager.getRefreshToken() &&\n      this.tokenManager.refreshFunction\n    ) {\n      try {\n        await this.tokenManager.refreshSession();\n      } catch (e) {\n        const status = e instanceof PalbaseError ? e.status : 0;\n        if (status === 400 || status === 401 || status === 403) {\n          // Terminal: the refresh token is dead (revoked/expired/forbidden).\n          // Clear the session (listeners persist the sign-out) and proceed\n          // unauthenticated — the endpoint will 401 into the normal error\n          // envelope instead of bricking every subsequent call including\n          // the recovery sign-in.\n          this.tokenManager.clearSession();\n        } else {\n          throw e; // network/5xx: transient, stay loud\n        }\n      }\n    }\n\n    return this.executeWithRetry<T>(method.toUpperCase(), path, options, 0);\n  }\n\n  /**\n   * A response read as it arrives, for `text/event-stream` routes.\n   *\n   * Deliberately NOT `executeWithRetry`: a retry replays the request, and a\n   * stream the caller has already begun reading cannot be replayed — the frames\n   * it handed over would arrive a second time. A stream that fails to open fails\n   * to the caller, once, with its status.\n   *\n   * The buffered path's headers, base URL and interceptors are reused verbatim,\n   * so a streaming call is authenticated exactly like every other call; only the\n   * body handling differs. `Accept` says what the caller wants, and the status\n   * is returned beside the body because the CALLER decides what a non-2xx means\n   * (an error envelope arrives as an ordinary buffered body).\n   */\n  async requestStream(\n    method: string,\n    path: string,\n    options?: RequestOptions,\n  ): Promise<{ status: number; body: ReadableStream<Uint8Array> | null; contentType: string }> {\n    method = method.toUpperCase();\n    if (\n      !options?.skipSessionRefresh &&\n      this.tokenManager?.isExpired() &&\n      this.tokenManager.getRefreshToken() &&\n      this.tokenManager.refreshFunction\n    ) {\n      try {\n        await this.tokenManager.refreshSession();\n      } catch (e) {\n        const status = e instanceof PalbaseError ? e.status : 0;\n        if (status === 400 || status === 401 || status === 403) {\n          this.tokenManager.clearSession();\n        } else {\n          throw e;\n        }\n      }\n    }\n\n    const url = endpointUrl(this.getBaseUrl(), path);\n    const headers = { ...this.buildHeaders(options), Accept: 'text/event-stream' };\n    for (const interceptor of this.interceptors) {\n      await interceptor({ headers, method, path });\n    }\n\n    const fetchOptions: RequestInit = { method, headers, signal: options?.signal };\n    if (options?.body !== undefined) fetchOptions.body = JSON.stringify(options.body);\n    const exporter = await this.prepareSealed(url, path, fetchOptions);\n\n    const response = await openSealedResponse(await fetch(url, fetchOptions), exporter, method);\n    return {\n      status: response.status,\n      body: response.body,\n      contentType: response.headers.get('content-type') ?? '',\n    };\n  }\n\n  private async prepareSealed(\n    url: string,\n    path: string,\n    init: RequestInit,\n  ): Promise<Uint8Array<ArrayBuffer> | undefined> {\n    if (this.options?.sealed === false || !sealingRequired(path)) return undefined;\n    this.sealedKeys ??= new SealedKeyStore(this.getBaseUrl(), this.apiKey, this.options?.sealed);\n    const key = await this.sealedKeys.current(init.signal ?? undefined);\n    init.signal?.throwIfAborted();\n    try {\n      return await sealRequest(key, url, init);\n    } catch (error) {\n      init.signal?.throwIfAborted();\n      if (error instanceof PalbaseError) throw error;\n      throw new PalbaseError('sealed_request_failed', 'The request could not be encrypted.', 0);\n    }\n  }\n\n  private getBaseUrl(): string {\n    // Explicit URL always wins (local dev, staging, test rigs).\n    if (this.options?.url) {\n      return this.options.url;\n    }\n\n    // Validate the key shape up front so apex-routed callers still\n    // fail loud on a malformed key instead of hitting the gateway\n    // with bad credentials.\n    if (this.apiKey && parseEnvironmentRef(this.apiKey) === null) {\n      throw new PalbaseError(\n        'invalid_api_key',\n        'Invalid API key format. Expected pb_{environment_ref}_c{at least 20 base62 chars}. For dev/staging pass `url: \"https://api.dev.palbase.studio\"` via options.',\n        0,\n      );\n    }\n\n    return `https://${PALBASE_DEFAULT_HOST}`;\n  }\n\n  private buildHeaders(options?: RequestOptions): Record<string, string> {\n    const headers: Record<string, string> = {\n      'Content-Type': 'application/json',\n      // Client identity, the web counterpart of the iOS SDK's\n      // ClientInfo.augment(). The server reads these to resolve flag targeting\n      // conditions and to label telemetry, so an app declares nothing and calls\n      // nothing — whatever the SDK can know, it sends.\n      'X-Platform': wirePlatform(),\n    };\n    // The host app's own version is not knowable on the web (no bundle to read\n    // it from), so it is opt-in; when given it fills the same header iOS fills\n    // from CFBundleShortVersionString.\n    const appVersion = this.options?.appVersion?.trim();\n    if (appVersion) {\n      headers['X-Palbase-Client-Version'] = appVersion;\n    }\n\n    // Palbase Environment keys live in the `apikey` header — never in\n    // `Authorization` — because Kong's key-auth resolves them on that\n    // header and the gateway's pre-function plugin stamps the downstream\n    // identity.\n    const effectiveKey = this.apiKey;\n    if (effectiveKey) {\n      headers['apikey'] = effectiveKey;\n    }\n\n    // User session token, if any. Kong's pre-function plugin strips\n    // Authorization on /v1/* routes anyway (PostgREST has no JWT\n    // secret and would crash on a Bearer it can't decode), but\n    // sending it preserves the contract for /auth/* endpoints that\n    // do consume the bearer (e.g. session refresh).\n    const token = this.tokenManager?.getAccessToken();\n    if (token) {\n      headers['Authorization'] = `Bearer ${token}`;\n    }\n\n    // adminToken (platform admin JWT) takes precedence — used by the\n    // @palbase/admin internal flows that hit /admin/* routes; those\n    // routes verify the bearer themselves and aren't subject to the\n    // /v1/* Authorization-strip rule.\n    if (this.adminToken) {\n      headers['Authorization'] = `Bearer ${this.adminToken}`;\n    }\n\n    // Merge global custom headers\n    if (this.options?.headers) {\n      Object.assign(headers, this.options.headers);\n    }\n\n    // Merge per-request headers\n    if (options?.headers) {\n      Object.assign(headers, options.headers);\n    }\n\n    return headers;\n  }\n\n  private async executeWithRetry<T>(\n    method: string,\n    path: string,\n    options: RequestOptions | undefined,\n    attempt: number,\n    // Headers a PREVIOUS attempt earned and this one has to carry. Today that\n    // is only the solved proof-of-work pair; it is a parameter rather than a\n    // field because it belongs to one request's second try, and a field would\n    // leak it onto every later call made through this client.\n    earned?: Record<string, string>,\n    rotated = false,\n  ): Promise<PalbaseResponse<T>> {\n    const url = endpointUrl(this.getBaseUrl(), path);\n    const headers = { ...this.buildHeaders(options), ...earned };\n\n    // Run interceptors\n    for (const interceptor of this.interceptors) {\n      await interceptor({ headers, method, path });\n    }\n\n    const fetchOptions: RequestInit = {\n      method,\n      headers,\n      signal: options?.signal,\n    };\n\n    if (options?.body !== undefined) {\n      fetchOptions.body = JSON.stringify(options.body);\n    }\n    // A fresh HPKE encapsulation on EVERY attempt: reusing an envelope trips\n    // the server replay guard, even when the first response was lost.\n    const exporter = await this.prepareSealed(url, path, fetchOptions);\n\n    let response: Response;\n    try {\n      response = await fetch(url, fetchOptions);\n    } catch (error) {\n      options?.signal?.throwIfAborted();\n      // Network error — retry with backoff\n      if (options?.retry !== false && attempt < MAX_RETRIES - 1) {\n        const backoff = INITIAL_BACKOFF_MS * 2 ** attempt;\n        await this.delay(backoff);\n        // WITHOUT `earned`, and that is the whole point of this line.\n        //\n        // A network error means the response was lost, not that the request\n        // was. If it reached the server, the challenge is already SPENT —\n        // palauth's VerifyChallenge reads and deletes in one step\n        // (bot/pow.go:96-104), deliberately, because a proof presented twice is\n        // not proof. Replaying the nonce would then answer `pow_invalid`, and\n        // the one-solve guard below would refuse to try again: a request one\n        // fresh solve away from succeeding, failed. Dropping it costs nothing\n        // in the other case — if the server never saw the request, a fresh\n        // challenge works exactly as well as the old one.\n        return this.executeWithRetry<T>(method, path, options, attempt + 1, undefined, rotated);\n      }\n\n      // All retries exhausted — throw PalbaseError\n      throw new PalbaseError(\n        'network_error',\n        error instanceof Error ? error.message : 'Network request failed',\n        0,\n      );\n    }\n    response = await openSealedResponse(response, exporter, method);\n\n    // Handle 429 Too Many Requests — retry with Retry-After or backoff;\n    // if retries exhausted, fall through to normal error response handling below\n    if (response.status === 429) {\n      if (options?.retry !== false && attempt < MAX_RETRIES - 1) {\n        const retryAfter = response.headers.get('Retry-After');\n        const parsed = retryAfter ? Number.parseInt(retryAfter, 10) : Number.NaN;\n        // Clamp the server-requested wait: a long Retry-After (locked account)\n        // must not hang the request — cap each sleep, exhaust MAX_RETRIES, then\n        // fall through to surface the 429 envelope below.\n        const delayMs = Number.isNaN(parsed)\n          ? INITIAL_BACKOFF_MS * 2 ** attempt\n          : Math.min(parsed * 1000, MAX_RETRY_DELAY_MS);\n        await this.delay(delayMs);\n        // WITH `earned`, unlike the network path above: a 429 is a refusal the\n        // server issued INSTEAD of doing the work, so the challenge was never\n        // consumed. The edge's rate limiter answers before palsvc, and on the\n        // auth routes palauth's own limiter runs BEFORE the proof-of-work\n        // middleware (auth/internal/server/server.go: rl.LoginByIP, then powMW).\n        return this.executeWithRetry<T>(method, path, options, attempt + 1, earned, rotated);\n      }\n    }\n\n    // Parse response body\n    let data: T | null = null;\n    let errorBody:\n      | {\n          error?: string;\n          error_description?: string;\n          status?: number;\n          required?: string;\n          retry_after?: number;\n        }\n      | undefined;\n\n    // HEAD responses have no body by spec — skip parsing.\n    const contentType = response.headers.get('Content-Type');\n    if (\n      method !== 'HEAD' &&\n      ![204, 205, 304].includes(response.status) &&\n      contentType?.includes('json')\n    ) {\n      if (response.ok) {\n        data = (await response.json()) as T;\n      } else {\n        // A REFUSAL WHOSE BODY DID NOT ARRIVE WHOLE IS STILL A REFUSAL.\n        //\n        // This path became REACHABLE with the edge's named envelope: before it,\n        // a held-request refusal was `text/plain` and was never parsed, so a\n        // truncated body could not surface. Now the edge answers 503 with\n        // `application/json`, and a body cut short mid-flight would throw a\n        // bare `SyntaxError` straight out of this client — no `PalbaseError`,\n        // no status, nothing the application can read. That is exactly the\n        // failure this whole change exists to remove, re-entering through the\n        // door it opened.\n        //\n        // The refusal keeps its status and surfaces as `unknown_error` below;\n        // an unreadable body costs the NAME, not the answer.\n        //\n        // Only on the error path: a SUCCESS body that cannot be parsed is a\n        // real failure and must keep throwing — swallowing it would hand the\n        // caller `{ data: null, error: null }`, which is a silent lie.\n        errorBody = (await response.json().catch(() => undefined)) as typeof errorBody;\n      }\n    }\n\n    // A HELD REQUEST IS NOT AN ERROR — the edge is starting a sleeping project.\n    //\n    // This sits AFTER the body parse, and not beside the 429 check above, on\n    // purpose: the name and the hint live in the BODY, and the body does not\n    // exist yet where the 429 block runs.\n    if (options?.retry !== false && attempt < MAX_RETRIES - 1) {\n      const heldWait = heldRefusalWait(response.status, errorBody);\n      if (heldWait !== null) {\n        await this.delay(heldWait);\n        // WITH `earned`, like the 429 path: the edge refused INSTEAD of doing\n        // the work, so the challenge was never consumed.\n        return this.executeWithRetry<T>(method, path, options, attempt + 1, earned, rotated);\n      }\n    }\n\n    if (\n      exporter &&\n      !rotated &&\n      response.status === 400 &&\n      errorBody?.error === 'sealed_unknown_kid'\n    ) {\n      await this.sealedKeys?.current(options?.signal, true);\n      return this.executeWithRetry<T>(method, path, options, attempt, earned, true);\n    }\n\n    // Proof-of-work: /auth/signup and /auth/token sit behind a bot gate that\n    // answers an unsolved request with 403 and the challenge in the body. Solve\n    // it and repeat the request carrying the two headers; the caller never\n    // learns the gate is there.\n    //\n    // HERE, in core, because this is the layer that issues the request for every\n    // client in the repo — @palbase/auth's sign-in, @palbase/web's facades, the\n    // server SDK. The same retry lived one layer up in @palbase/web until\n    // 2026-08-18 and covered everything EXCEPT `pb.auth.*`, which reaches the\n    // network through this method; so the gate stayed unsatisfiable on exactly\n    // the two endpoints it guards.\n    //\n    // ONE retry, and only when the body really carries a challenge: `earned`\n    // being set already means this IS the second try. A 403 that says\n    // pow_required without a challenge is a server the client cannot satisfy,\n    // and looping on it would turn a broken gate into a hang.\n    if (response.status === 403 && !earned) {\n      const challenge = asPowChallenge(errorBody);\n      if (challenge) {\n        return this.executeWithRetry<T>(\n          method,\n          path,\n          options,\n          attempt,\n          await solvePowChallenge(challenge, undefined, options?.signal),\n          rotated,\n        );\n      }\n    }\n\n    if (!response.ok) {\n      if (response.status === 403 && errorBody !== undefined) {\n        const body: Record<string, unknown> = errorBody;\n        for (const listener of this.forbiddenListeners) {\n          try {\n            listener(body);\n          } catch {\n            // A consumer's handler must not turn a well-formed refusal into a\n            // thrown error, nor stop the listeners after it (same rule as\n            // internal.ts' configured listeners).\n          }\n        }\n      }\n      return {\n        data: null,\n        error: new PalbaseError(\n          errorBody?.error ?? 'unknown_error',\n          errorBody?.error_description ?? response.statusText,\n          response.status,\n          withRetryHint(errorBody, response),\n        ),\n        status: response.status,\n      };\n    }\n\n    // Parse PostgREST Content-Range for count queries (e.g. \"0-9/42\" or \"*/42\").\n    const contentRange = response.headers.get('Content-Range');\n    let count: number | undefined;\n    if (contentRange) {\n      const slash = contentRange.lastIndexOf('/');\n      if (slash >= 0) {\n        const totalPart = contentRange.slice(slash + 1);\n        if (totalPart !== '*') {\n          const parsed = Number.parseInt(totalPart, 10);\n          if (!Number.isNaN(parsed)) {\n            count = parsed;\n          }\n        }\n      }\n    }\n\n    // Header names are case-insensitive and `Headers.get` already honours that;\n    // the wire spells this one lowercase.\n    const etag = response.headers.get('etag');\n\n    return {\n      data,\n      error: null,\n      status: response.status,\n      ...(count !== undefined ? { count } : {}),\n      ...(etag ? { etag } : {}),\n    };\n  }\n\n  private delay(ms: number): Promise<void> {\n    return new Promise((resolve) => setTimeout(resolve, ms));\n  }\n}\n","import type { AuthStateCallback, Session, Unsubscribe } from './types.js';\n\nexport class TokenManager {\n  private session: Session | null = null;\n  private listeners: Set<AuthStateCallback> = new Set();\n  private refreshPromise: Promise<void> | null = null;\n  private refreshing = false;\n\n  refreshFunction: ((refreshToken: string) => Promise<Session>) | null = null;\n\n  setSession(session: Session): void {\n    this.session = session;\n    this.notify('SESSION_SET', session);\n  }\n\n  getAccessToken(): string | null {\n    return this.session?.accessToken ?? null;\n  }\n\n  getRefreshToken(): string | null {\n    return this.session?.refreshToken ?? null;\n  }\n\n  clearSession(): void {\n    this.session = null;\n    this.notify('SESSION_CLEARED', null);\n  }\n\n  isExpired(): boolean {\n    if (!this.session) return true;\n    return Date.now() >= this.session.expiresAt;\n  }\n\n  async refreshSession(): Promise<void> {\n    if (!this.session?.refreshToken || !this.refreshFunction) {\n      return;\n    }\n\n    // Collapse concurrent refresh calls into a single request\n    if (this.refreshPromise) {\n      return this.refreshPromise;\n    }\n\n    // Re-entrancy guard: the wired refreshFunction issues its own HTTP request\n    // (POST /auth/token/refresh) through HttpClient, whose pre-flight calls\n    // refreshSession() again SYNCHRONOUSLY — before `refreshPromise` below is\n    // assigned (the whole chain runs before the first real await). Without\n    // this flag that recursion is unbounded (stack overflow). Returning early\n    // lets the refresh request itself proceed unauthenticated — it carries\n    // the refresh token in its body, not the Bearer header.\n    if (this.refreshing) {\n      return;\n    }\n\n    this.refreshing = true;\n    this.refreshPromise = this.executeRefresh(this.session.refreshToken);\n\n    try {\n      await this.refreshPromise;\n    } finally {\n      this.refreshPromise = null;\n      this.refreshing = false;\n    }\n  }\n\n  onAuthStateChange(callback: AuthStateCallback): Unsubscribe {\n    this.listeners.add(callback);\n    return () => {\n      this.listeners.delete(callback);\n    };\n  }\n\n  private async executeRefresh(refreshToken: string): Promise<void> {\n    if (!this.refreshFunction) return;\n    const startedSession = this.session;\n    try {\n      const newSession = await this.refreshFunction(refreshToken);\n      // Sign-out, a new sign-in, or another session adoption takes precedence\n      // over a refresh that started against an older session.\n      if (this.session === startedSession) this.setSession(newSession);\n    } catch (error) {\n      // The caller would clear its session on a terminal refresh error. An\n      // error from an older session must not clear a newer one.\n      if (this.session === startedSession) throw error;\n    }\n  }\n\n  private notify(event: 'SESSION_SET' | 'SESSION_CLEARED', session: Session | null): void {\n    for (const listener of this.listeners) {\n      listener(event, session);\n    }\n  }\n}\n","import { PalbaseError, type PalbaseResponse } from '@palbase/core';\n\nexport interface FieldError {\n  field: string;\n  message: string;\n}\n\nexport type BackendErrorKind =\n  | 'notConfigured'\n  | 'validation'\n  | 'unauthorized'\n  | 'rateLimited'\n  | 'server'\n  | 'network'\n  | 'decode';\n\ninterface BackendErrorParams {\n  code: string;\n  message: string;\n  status?: number;\n  requestId?: string;\n  fields?: FieldError[];\n  retryAfter?: number;\n  data?: unknown;\n}\n\nexport class BackendError extends Error {\n  readonly kind: BackendErrorKind;\n  readonly code: string;\n  readonly status: number;\n  readonly requestId?: string;\n  readonly fields?: FieldError[];\n  readonly retryAfter?: number;\n  readonly data?: unknown;\n\n  constructor(kind: BackendErrorKind, params: BackendErrorParams) {\n    super(params.message);\n    this.name = 'BackendError';\n    this.kind = kind;\n    this.code = params.code;\n    this.status = params.status ?? 0;\n    this.requestId = params.requestId;\n    this.fields = params.fields;\n    this.retryAfter = params.retryAfter;\n    this.data = params.data;\n  }\n\n  static notConfigured(): BackendError {\n    return new BackendError('notConfigured', {\n      code: 'not_configured',\n      message:\n        \"Palbe is not configured. Run 'palbase web link' in your project and make sure palbe.gen.ts is imported once at app startup.\",\n    });\n  }\n}\n\nfunction isFieldErrorArray(value: unknown): value is FieldError[] {\n  return (\n    Array.isArray(value) &&\n    value.length > 0 &&\n    value.every(\n      (v) =>\n        typeof v === 'object' &&\n        v !== null &&\n        typeof (v as Record<string, unknown>).field === 'string' &&\n        typeof (v as Record<string, unknown>).message === 'string',\n    )\n  );\n}\n\n/**\n * Find the field-error array in a wire envelope.\n *\n * `data.fields` IS THE CONTRACT: the backend SDK declares\n * `bad_request: { fields: [{ field, message }] }` in its error registry, so\n * codegen types it as `error.data.fields`, `throw new BadRequest({ fields })`\n * answers in that shape, and — since 22.1.0 — so do the engine's own automatic\n * `@Body`/`@QueryParams`/`@Headers` refusals.\n *\n * The top-level `fields` is the SAME array as emitted by backend 22.0.x and\n * earlier, which is still what every tenant deployed before that release\n * answers. A browser gets the SDK long before its tenant redeploys, so this\n * reader covers both until the fleet has rolled; drop it once it has.\n *\n * A nested `details: [{ field, message }]` was read here until 8.0.0 and is NOT\n * read any more: no Palbase surface has ever emitted it. Believing in it is why\n * `kind: 'validation'` was unreachable for every real 400 the platform sends.\n */\nfunction fieldErrorsOf(envelope: unknown): FieldError[] | undefined {\n  const scoped = pickField(pickField(envelope, 'data'), 'fields');\n  if (isFieldErrorArray(scoped)) return scoped;\n  const flat = pickField(envelope, 'fields');\n  return isFieldErrorArray(flat) ? flat : undefined;\n}\n\n/**\n * Find the rate-limit hint in a wire envelope.\n *\n * Two producers, both real and both measured. palauth answers a lockout with a\n * top-level `retry_after` (`auth/internal/ratelimit/limiter.go`). Everything\n * built on the backend SDK — the engine's per-route limiter, and\n * `throw new TooManyRequests({ retryAfter })` — answers with `data.retryAfter`,\n * the name its error registry publishes and codegen types.\n */\nfunction retryAfterOf(envelope: unknown): number | undefined {\n  return (\n    pickNumber(envelope, 'retry_after') ?? pickNumber(pickField(envelope, 'data'), 'retryAfter')\n  );\n}\n\nfunction pickField(value: unknown, key: string): unknown {\n  if (typeof value === 'object' && value !== null) {\n    return (value as Record<string, unknown>)[key];\n  }\n  return undefined;\n}\n\nfunction pickNumber(value: unknown, key: string): number | undefined {\n  const n = pickField(value, key);\n  return typeof n === 'number' ? n : undefined;\n}\n\nfunction pickString(value: unknown, key: string): string | undefined {\n  const s = pickField(value, key);\n  return typeof s === 'string' ? s : undefined;\n}\n\nexport function fromPalbaseError(err: PalbaseError): BackendError {\n  // HttpClient stores the WHOLE wire envelope as err.details:\n  // { error, error_description, status, request_id, retry_after?, data? }\n  const base: BackendErrorParams = {\n    code: err.code,\n    message: err.message,\n    status: err.status,\n    requestId: pickString(err.details, 'request_id'),\n    data: pickField(err.details, 'data'),\n  };\n  if (err.code === 'network_error') return new BackendError('network', base);\n  if (err.status === 401) return new BackendError('unauthorized', base);\n  if (err.status === 429)\n    return new BackendError('rateLimited', { ...base, retryAfter: retryAfterOf(err.details) });\n  const fields = fieldErrorsOf(err.details);\n  if (err.status === 400 && fields) return new BackendError('validation', { ...base, fields });\n  // Fallthrough also covers status-0 non-network errors (e.g. auth client's\n  // synthetic 'no_refresh_token' with status 0) — those intentionally map to 'server'.\n  return new BackendError('server', base);\n}\n\n/** Decode a raw wire body (used by paths that bypass HttpClient, e.g. upload). */\nexport function fromEnvelope(status: number, body: unknown): BackendError {\n  const code = pickString(body, 'error') ?? 'http_error';\n  const message = pickString(body, 'error_description') ?? `HTTP ${status}`;\n  const requestId = pickString(body, 'request_id');\n  const params: BackendErrorParams = {\n    code,\n    message,\n    status,\n    requestId,\n    data: pickField(body, 'data'),\n  };\n  if (status === 401) return new BackendError('unauthorized', params);\n  if (status === 429)\n    return new BackendError('rateLimited', { ...params, retryAfter: retryAfterOf(body) });\n  const fields = fieldErrorsOf(body);\n  if (status === 400 && fields) return new BackendError('validation', { ...params, fields });\n  return new BackendError('server', params);\n}\n\n/**\n * Type guard for BackendError that survives module-identity splits.\n * This package ships dual ESM + CJS builds; if both end up loaded (or the\n * package is installed twice), two distinct BackendError classes coexist and\n * `instanceof` fails for errors thrown by \"the other\" copy. Falls back to a\n * structural check on `name` + `kind`.\n */\nexport function isBackendError(e: unknown): e is BackendError {\n  return (\n    e instanceof BackendError ||\n    (typeof e === 'object' &&\n      e !== null &&\n      (e as Record<string, unknown>).name === 'BackendError' &&\n      typeof (e as Record<string, unknown>).kind === 'string')\n  );\n}\n\n/**\n * Structural fallback after instanceof for PalbaseError — same dual ESM+CJS\n * identity-split rationale as isBackendError above: two loaded PalbaseError\n * classes break `instanceof` across copies; the name check bridges that.\n * Returns the error as PalbaseError, or null when it isn't one.\n */\nexport function asPalbaseError(e: unknown): PalbaseError | null {\n  if (e instanceof PalbaseError) return e;\n  if (e instanceof Error && e.name === 'PalbaseError') return e as PalbaseError;\n  return null;\n}\n\n/** Convert an internal {data,error} envelope into data-or-throw. */\nexport function unwrap<T>(res: PalbaseResponse<T>): T {\n  if (res.error) throw fromPalbaseError(res.error);\n  return res.data as T;\n}\n","const ID_SEGMENT =\n  /^(?:\\d+|[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;\n\n// An email lands in a path segment as `jane@acme.com` or percent-encoded\n// `jane%40acme.com`. Either form is PII and must never survive into a metric\n// name, so a segment carrying an `@` (encoded or raw) is masked like an id.\nconst EMAIL_SEGMENT = /(?:@|%40)/i;\n\nfunction isSensitiveSegment(seg: string): boolean {\n  return ID_SEGMENT.test(seg) || EMAIL_SEGMENT.test(seg);\n}\n\n/**\n * Capture-time URL redaction (§4.1 privacy, client half). Collapses a request\n * URL to a PII-free, low-cardinality path pattern BEFORE it leaves the browser:\n * query string dropped wholesale, id-like segments masked. The ingest scrubber\n * re-applies server-side (defense in depth).\n *\n * Rules:\n *  - absolute URL → keep only `pathname` (scheme/host/query/hash dropped);\n *  - relative URL → drop everything from the first `?` onward;\n *  - any segment that is purely numeric, a UUID, or carries an email (`@` /\n *    `%40`) → `:id`;\n *  - credentials/tokens live in the query (dropped wholesale), emails in a\n *    path segment (masked), so neither survives into the metric name.\n */\nexport function redactUrl(rawUrl: string): string {\n  let path = rawUrl;\n  try {\n    // Absolute URLs: take the pathname (drops scheme/host/query/hash).\n    path = new URL(rawUrl).pathname;\n  } catch {\n    const q = path.indexOf('?');\n    if (q >= 0) path = path.slice(0, q);\n  }\n  return path\n    .split('/')\n    .map((seg) => (isSensitiveSegment(seg) ? ':id' : seg))\n    .join('/');\n}\n","import { BackendError } from './errors.js';\n\n/**\n * The web half of streaming responses.\n *\n * The rule the parser exists to keep: a frame ends at a BLANK line, never at a\n * chunk boundary. Nothing about how the bytes were split on the way here may\n * change what the caller sees — a `data:` line arriving in three pieces is one\n * frame, and two frames arriving in one piece are two.\n */\n\nexport interface SseFrame {\n  /** `undefined` for a plain `data:` frame; `\"error\"` for the terminal one. */\n  event?: string;\n  payload: string;\n}\n\n/** Incremental SSE parser. Feed it decoded text; it answers with completed frames. */\nexport class SseParser {\n  private pending = '';\n  private dataLines: string[] = [];\n  private eventName: string | undefined;\n\n  consume(chunk: string): SseFrame[] {\n    // CRLF is normalised on the way IN. A server that writes \\r\\n would\n    // otherwise leave a stray \\r on every field value, and `JSON.parse` of\n    // `{\"n\":1}\\r` throws — a decode failure invented by the transport.\n    this.pending += chunk.replace(/\\r\\n/g, '\\n');\n    const out: SseFrame[] = [];\n    let nl = this.pending.indexOf('\\n');\n    while (nl !== -1) {\n      const line = this.pending.slice(0, nl);\n      this.pending = this.pending.slice(nl + 1);\n      const trimmed = line.endsWith('\\r') ? line.slice(0, -1) : line;\n\n      if (trimmed === '') {\n        // A blank line with nothing accumulated is a keep-alive separator or the\n        // gap after a comment — emitting nothing for it is correct.\n        if (this.dataLines.length > 0) {\n          out.push({ event: this.eventName, payload: this.dataLines.join('\\n') });\n        }\n        this.dataLines = [];\n        this.eventName = undefined;\n      } else if (trimmed.startsWith(':')) {\n        // A comment — the conventional keep-alive. Ignored, not surfaced.\n      } else if (trimmed.startsWith('data:')) {\n        const v = trimmed.slice(5);\n        this.dataLines.push(v.startsWith(' ') ? v.slice(1) : v);\n      } else if (trimmed.startsWith('event:')) {\n        const v = trimmed.slice(6);\n        this.eventName = v.startsWith(' ') ? v.slice(1) : v;\n      }\n      // Unknown fields (id:, retry:) are ignored rather than refused: a reader\n      // that rejects a field it does not know breaks when the server adds one.\n      nl = this.pending.indexOf('\\n');\n    }\n    return out;\n  }\n}\n\n/**\n * Turn a byte stream into the decoded frames a generated client hands its caller.\n *\n * `controller` is aborted when the caller stops iterating — `for await`'s early\n * exit calls `return()` on the iterator, which reaches the `finally` below. That\n * is the whole cancellation story on the web, and it is what stops the server's\n * producer being pulled.\n */\nexport async function* sseIterable(\n  body: ReadableStream<Uint8Array>,\n  controller: AbortController,\n): AsyncGenerator<unknown, void, undefined> {\n  const reader = body.getReader();\n  const decoder = new TextDecoder();\n  const parser = new SseParser();\n  try {\n    for (;;) {\n      const { done, value } = await reader.read();\n      if (done) break;\n      for (const frame of parser.consume(decoder.decode(value, { stream: true }))) {\n        if (frame.event === 'error') {\n          // After the first frame the status line is already spent, so this is\n          // how a failure reaches the caller: as a throw out of their loop.\n          throw new BackendError('network', {\n            code: 'stream_failed',\n            message: `stream failed: ${frame.payload}`,\n          });\n        }\n        let decoded: unknown;\n        try {\n          decoded = JSON.parse(frame.payload);\n        } catch {\n          // A frame that will not decode ends the stream rather than being\n          // skipped: a silently dropped frame is a hole in the middle of the\n          // caller's data, and holes are worse than failures.\n          throw new BackendError('decode', {\n            code: 'invalid_frame',\n            message: `stream frame is not valid JSON: ${frame.payload.slice(0, 120)}`,\n          });\n        }\n        yield decoded;\n      }\n    }\n  } finally {\n    controller.abort();\n    try {\n      await reader.cancel();\n    } catch {\n      // The reader may already be closed — that is a normal ending, not a fault.\n    }\n  }\n}\n","import { asPowChallenge, solvePowChallenge } from '@palbase/core';\nimport {\n  asPalbaseError,\n  BackendError,\n  fromEnvelope,\n  fromPalbaseError,\n  isBackendError,\n  unwrap,\n} from './errors.js';\nimport { redactUrl } from './perf/url-redactor.js';\nimport type { PalbeRuntime } from './runtime.js';\nimport { sseIterable } from './sse.js';\n\nexport interface RequestSpec {\n  body?: unknown;\n  headers?: Record<string, string>;\n  signal?: AbortSignal;\n}\n\nexport interface CallOptions {\n  headers?: Record<string, string>;\n  signal?: AbortSignal;\n}\n\nconst MUTATING = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);\n\n// The perf flush (`POST /v1/analytics/perf`) and analytics event ingest\n// (`/v1/analytics/*`) BOTH funnel through `palbeRequest`. Tracing them would\n// make every flush emit another `network` item that the next flush ships,\n// then traces again — a self-measurement loop. Excluding the whole\n// `/v1/analytics/` prefix breaks it. This is the SAME self-exclusion shape as\n// the iOS network trace (1b-3), keyed on the identical ingest prefix.\nconst PERF_EXCLUDED_PREFIX = '/v1/analytics/';\n\nfunction isSelfTraced(path: string): boolean {\n  return path.startsWith(PERF_EXCLUDED_PREFIX);\n}\n\n/**\n * Codes meaning the server-side session is GONE — a token refresh cannot help\n * and the client must tear its local session down. `subject_fenced` is palauth's\n * wire-true erasure-fence code (`bridge.go`); `subject_erased` is accepted for\n * forward-compat. `session_revoked` is palauth's revoked-session 401.\n * A PLAIN 403 (ordinary authz / RLS denial) is intentionally NOT here — matching\n * all 403s would sign users out on routine permission errors.\n */\nfunction isSessionKilled(status: number, code: string): boolean {\n  if (status === 401) return code === 'session_revoked';\n  if (status === 403) return code === 'subject_fenced' || code === 'subject_erased';\n  return false;\n}\n\n/** Monotonic millisecond clock — `performance.now()` when present, else\n * `Date.now()`. Mirrors `perf-facade.ts`'s `nowMs()` so network durations and\n * custom-trace durations share one time base. */\nfunction nowMs(): number {\n  return typeof performance !== 'undefined' && typeof performance.now === 'function'\n    ? performance.now()\n    : Date.now();\n}\n\n/** An `AbortError` (caller-cancelled request) is NOT a completed network call,\n * so it must never produce a trace. */\nfunction isAbort(e: unknown): boolean {\n  return e instanceof Error && e.name === 'AbortError';\n}\n\n/**\n * `palbeRequest`'s streaming sibling: opens the response and hands back the\n * frames as an async iterable.\n *\n * No retry and no reactive-401 refresh loop here, on purpose. Both replay the\n * request, and a stream the caller has begun reading cannot be replayed — the\n * frames it already yielded would arrive twice. A stream that fails to OPEN\n * fails to the caller once, with the status the server gave.\n *\n * An `AbortController` is chained to the caller's signal so that leaving the\n * loop aborts the request: that is what stops the server's producer being\n * pulled, and it is the half that decides the customer's bill.\n */\nexport async function palbeStream(\n  rt: PalbeRuntime,\n  method: string,\n  path: string,\n  spec: RequestSpec = {},\n): Promise<AsyncIterable<unknown>> {\n  const controller = new AbortController();\n  if (spec.signal) {\n    if (spec.signal.aborted) controller.abort();\n    else spec.signal.addEventListener('abort', () => controller.abort(), { once: true });\n  }\n\n  const headers: Record<string, string> = { ...spec.headers };\n  const callerHasKey = Object.keys(headers).some((k) => k.toLowerCase() === 'idempotency-key');\n  if (MUTATING.has(method) && !callerHasKey) {\n    headers['Idempotency-Key'] = crypto.randomUUID();\n  }\n\n  const open = async (extra?: Record<string, string>) =>\n    rt.http.requestStream(method, path, {\n      body: spec.body,\n      headers: extra ? { ...headers, ...extra } : headers,\n      signal: controller.signal,\n    });\n\n  let opened: Awaited<ReturnType<typeof rt.http.requestStream>>;\n  try {\n    opened = await open();\n\n    // The abuse gate answers the same way here as anywhere else, and a stream\n    // that has not yielded a frame yet can be retried safely — nothing was\n    // handed to the caller. ONE solve, exactly as the buffered path: a 403 that\n    // says `pow_required` without a challenge is a gate the client cannot\n    // satisfy, and looping would turn it into a hang.\n    // Reactive 401, on the same terms as the buffered path. A route that a\n    // customer converts to `@Sse` must not silently lose session recovery: the\n    // failure would look like \"streaming is flaky\" and be blamed on streaming.\n    if (\n      opened.status === 401 &&\n      rt.tokenManager.getRefreshToken() &&\n      rt.tokenManager.refreshFunction\n    ) {\n      const text = opened.body ? await new Response(opened.body).text() : '';\n      let envelope: unknown;\n      try {\n        envelope = JSON.parse(text);\n      } catch {\n        envelope = undefined;\n      }\n      // A revoked session is terminal — a refresh cannot resurrect it.\n      const code = (envelope as { error?: string } | undefined)?.error;\n      if (code === 'session_revoked') throw fromEnvelope(401, envelope);\n      try {\n        await rt.tokenManager.refreshSession();\n      } catch (refreshErr) {\n        const pe = asPalbaseError(refreshErr);\n        const status = pe?.status ?? 0;\n        if (status === 400 || status === 401 || status === 403) {\n          // The refresh token is dead: sign out and surface the ORIGINAL 401.\n          rt.tokenManager.clearSession();\n          throw fromEnvelope(401, envelope);\n        }\n        throw pe ? fromPalbaseError(pe) : refreshErr;\n      }\n      opened = await open();\n    }\n\n    if (opened.status === 403) {\n      const text = opened.body ? await new Response(opened.body).text() : '';\n      let envelope: unknown;\n      try {\n        envelope = JSON.parse(text);\n      } catch {\n        envelope = undefined;\n      }\n      // `asPowChallenge` reads the WHOLE envelope (it checks `error` and\n      // `challenge` itself), so it is handed the parsed body rather than a\n      // hand-picked field — one place that knows the challenge's shape.\n      const challenge = asPowChallenge(envelope);\n      if (challenge) {\n        opened = await open(await solvePowChallenge(challenge));\n      } else {\n        // A 403 that is not a solvable challenge is an ordinary refusal.\n        throw fromEnvelope(403, envelope);\n      }\n    }\n  } catch (e) {\n    if (isBackendError(e)) throw e;\n    const pe = asPalbaseError(e);\n    throw pe ? fromPalbaseError(pe) : e;\n  }\n\n  if (opened.status < 200 || opened.status >= 300) {\n    // Before the first frame the status line is still available, so a failure\n    // here is an ORDINARY error — same shape as any other call's.\n    const text = opened.body ? await new Response(opened.body).text() : '';\n    let envelope: unknown;\n    try {\n      envelope = JSON.parse(text);\n    } catch {\n      envelope = undefined;\n    }\n\n    // The SAME mapping the buffered path uses. A streaming route that refuses\n    // must be indistinguishable, to the caller, from any other route refusing —\n    // a second status→kind table here would be a second chance to disagree.\n    throw fromEnvelope(opened.status, envelope);\n  }\n\n  if (!opened.body) {\n    throw new BackendError('network', {\n      code: 'empty_stream',\n      message: 'the server answered a streaming route with no body',\n    });\n  }\n\n  return sseIterable(opened.body, controller);\n}\n\nexport async function palbeRequest<T>(\n  rt: PalbeRuntime,\n  method: string,\n  path: string,\n  spec: RequestSpec = {},\n): Promise<T> {\n  const headers: Record<string, string> = { ...spec.headers };\n  // Case-insensitive scan: a caller-supplied `idempotency-key` must suppress\n  // generation, otherwise Headers merges both casings and dedup breaks.\n  const callerHasKey = Object.keys(headers).some((k) => k.toLowerCase() === 'idempotency-key');\n  if (MUTATING.has(method) && !callerHasKey) {\n    headers['Idempotency-Key'] = crypto.randomUUID();\n  }\n\n  // `extra` carries the proof-of-work headers on the one retry that needs them.\n  // The base `headers` are reused rather than rebuilt, so a retry keeps the same\n  // Idempotency-Key and the server still sees one logical request.\n  const attempt = async (extra?: Record<string, string>) => {\n    try {\n      return await rt.http.request<T>(method, path, {\n        body: spec.body,\n        headers: extra ? { ...headers, ...extra } : headers,\n        signal: spec.signal,\n        // A header alone does not implement server-side deduplication. A lost\n        // response can follow a successful COMMIT; replaying a write here may\n        // duplicate it. Surface overload too, so domain recovery is explicit.\n        retry: method === 'GET' || method === 'HEAD',\n      });\n    } catch (e) {\n      const pe = asPalbaseError(e);\n      throw pe ? fromPalbaseError(pe) : e;\n    }\n  };\n\n  // The single network-trace choke point: every SDK fetch funnels through\n  // `palbeRequest`, so timing it here records one `network` PerfItem per call —\n  // redacted URL + method + final HTTP status + wall-clock duration. The\n  // `/v1/analytics/` ingest paths are self-excluded (no recursion) and aborts\n  // are skipped (not a completed call).\n  // `rt.perf` is guarded too: `buildRuntime` always wires it, but a hand-built\n  // runtime (tests, embedders) may omit it — a missing facade must never break\n  // the request path.\n  const traced = !isSelfTraced(path) && rt.perf !== undefined;\n  const startedAt = traced ? nowMs() : 0;\n  // Exactly ONE trace per `palbeRequest`: the inner refresh-catch records with\n  // the precise status and rethrows; that rethrow is then caught by the outer\n  // catch, so the guard keeps the second `record()` a no-op (no double-count).\n  let recorded = false;\n  const record = (status: number): void => {\n    if (!traced || recorded) return;\n    recorded = true;\n    rt.perf.recordNetwork(method, redactUrl(path), status, nowMs() - startedAt);\n  };\n\n  let res: Awaited<ReturnType<typeof attempt>>;\n  try {\n    res = await attempt();\n\n    // Reactive 401: refresh once, retry once with the same Idempotency-Key.\n    // A revoked session (401 session_revoked) is terminal — a refresh cannot\n    // resurrect it, so skip straight to the teardown check below.\n    if (\n      res.error?.status === 401 &&\n      res.error.code !== 'session_revoked' &&\n      rt.tokenManager.getRefreshToken() &&\n      rt.tokenManager.refreshFunction\n    ) {\n      try {\n        await rt.tokenManager.refreshSession();\n      } catch (refreshErr) {\n        const pe = asPalbaseError(refreshErr);\n        const status = pe?.status ?? 0;\n        if (status === 400 || status === 401 || status === 403) {\n          // Terminal: the refresh token is dead. Sign out and surface the\n          // ORIGINAL 401 (mirrors HttpClient's pre-flight terminal split).\n          rt.tokenManager.clearSession();\n          record(res.error.status);\n          throw fromPalbaseError(res.error);\n        }\n        // Transient (network/5xx): keep the session, surface the refresh failure.\n        record(pe?.status ?? 0);\n        throw pe ? fromPalbaseError(pe) : refreshErr;\n      }\n      res = await attempt();\n    }\n\n    // Reactive proof-of-work: signup and login sit behind a bot gate that\n    // answers an unsolved request with 403 and the challenge in the body. Solve\n    // it once and repeat the request with the headers; the caller never learns\n    // the gate is there.\n    //\n    // Placed after the 401 branch so it sees whichever response is current — a\n    // refresh-and-retry can land on the gate just as a first attempt can.\n    //\n    // Only ONE retry, and only when the body really carries a challenge. A 403\n    // that merely says pow_required without one is a server the client cannot\n    // satisfy, and looping on it would turn a broken gate into a hang.\n    if (res.error?.status === 403 && res.error.code === 'pow_required') {\n      const challenge = asPowChallenge(res.error.details);\n      if (challenge) {\n        res = await attempt(await solvePowChallenge(challenge));\n      }\n    }\n  } catch (e) {\n    // A thrown error here is a network/transport failure (the `{data,error}`\n    // envelope never throws). Record it as a completed-with-error call unless\n    // the caller aborted — an abort is a cancellation, not a measurement.\n    if (!isAbort(e)) record(asPalbaseError(e)?.status ?? 0);\n    throw e;\n  }\n\n  // Reactive session teardown: a server-side session kill (subject erased /\n  // session revoked) means the local session is dead regardless of which facade\n  // issued this call — tear it down + emit signedOut{sessionInvalid} once. Scoped\n  // to the exact codes so an ordinary 403 authz denial does NOT sign the user out.\n  if (res.error && isSessionKilled(res.error.status, res.error.code)) {\n    rt.auth.reactiveTeardown();\n  }\n\n  // Response resolved (2xx or an error envelope): record the real HTTP status\n  // BEFORE `unwrap` may throw, so a 4xx/5xx is measured with its true status.\n  record(res.error?.status ?? 200);\n  return unwrap(res);\n}\n","import type { NamespaceTree } from './namespaces.js';\nimport type { PalbeRuntime } from './runtime.js';\n\nexport interface PalbeGlobalState {\n  runtime: PalbeRuntime | null;\n  registry: NamespaceTree;\n  /** Memoized materialized namespaces (per top-level key); reset on (re-)register. */\n  nsCache: Record<string, unknown>;\n  /** Listeners fired synchronously after every successful __configure call. */\n  configuredListeners: Set<() => void>;\n}\n\n/**\n * Module-level state would split between the ESM and CJS bundles of the two\n * entries (esbuild only code-splits ESM) and between dual-package copies in\n * one process. A globalThis slot keyed by Symbol.for converges them all.\n */\nconst STATE_KEY: unique symbol = Symbol.for('palbe.state.v1');\n\ninterface PalbeGlobals {\n  [STATE_KEY]?: PalbeGlobalState;\n}\n\nexport function palbeState(): PalbeGlobalState {\n  // Single direct widening view of globalThis — typed via the unique-symbol\n  // key above so reads/writes of the slot stay fully typed.\n  const g = globalThis as PalbeGlobals;\n  let state = g[STATE_KEY];\n  if (!state) {\n    state = { runtime: null, registry: {}, nsCache: {}, configuredListeners: new Set() };\n    g[STATE_KEY] = state;\n  }\n  return state;\n}\n","import { BackendError, isBackendError } from './errors.js';\nimport { getRuntime } from './internal.js';\nimport { type CallOptions, palbeRequest, palbeStream } from './request.js';\nimport type { PalbeRuntime } from './runtime.js';\nimport { palbeState } from './state.js';\n\nexport interface EndpointDescriptor {\n  method: string;\n  path: string;\n  /** `{name}` segments consumed as leading call args, in order. */\n  pathParams?: string[];\n  /**\n   * 'body' (default for non-GET) | 'query' (serialize input into the URL) |\n   * 'none' (no input arg — options come straight after path params).\n   */\n  input?: 'body' | 'query' | 'none';\n  /** wire error code → lift fn; the materializer rethrows the lifted error. */\n  errors?: Record<string, (e: BackendError) => Error>;\n  /**\n   * The route answers `text/event-stream`. Emitted by the generator for an\n   * operation carrying `x-palbase-sse`, and it changes what the call RETURNS:\n   * an async iterable of frames instead of one parsed body. Without this branch\n   * the generated signature would be a lie — it declares `AsyncIterable<T>`\n   * while the buffered path hands back a single object (measured 2026-08-30,\n   * against a real stack).\n   */\n  sse?: boolean;\n}\n\nexport type NamespaceTree = { [key: string]: NamespaceTree | EndpointDescriptor };\n\n// Reserved surface names on pb — cannot be shadowed at the top level by codegen\n// namespaces. `perf` sits next to `analytics`: `pb.perf` is the PalPerf facade,\n// so a generated controller named `perf` must NOT collide with it.\nexport const RESERVED = new Set([\n  'call',\n  'upload',\n  'auth',\n  'flags',\n  'realtime',\n  'analytics',\n  'calls',\n  'messaging',\n  'perf',\n]);\n\nfunction reservedNamespaceError(key: string): BackendError {\n  return new BackendError('validation', {\n    code: 'reserved_namespace',\n    message: `Cannot register endpoint namespace '${key}': the name is reserved on pb.`,\n  });\n}\n\nfunction isDescriptor(node: NamespaceTree | EndpointDescriptor): node is EndpointDescriptor {\n  return (\n    typeof (node as EndpointDescriptor).path === 'string' &&\n    typeof (node as EndpointDescriptor).method === 'string'\n  );\n}\n\n/**\n * Validate + normalize one tree level, recursively:\n * - plain-object guard (a literal `__proto__:` in a hand-written tree would\n *   swap the node's prototype — cheap proto-pollution insurance);\n * - reject 'then' at EVERY level (a nested then makes that namespace object\n *   thenable → `await pb.rooms` hangs) and every Object.prototype member\n *   name (`'valueOf' in {}` is true — covers toString, __proto__, …);\n * - uppercase descriptor methods (request.ts matches mutating methods\n *   against an uppercase set; a codegen 'get' would otherwise send a body\n *   and an Idempotency-Key).\n */\nfunction validateDescriptorExtensions(d: EndpointDescriptor, path: string): void {\n  if (d.pathParams !== undefined) {\n    if (!Array.isArray(d.pathParams) || !d.pathParams.every((p) => typeof p === 'string')) {\n      throw new BackendError('validation', {\n        code: 'invalid_namespace_tree',\n        message: `Descriptor '${path}': pathParams must be an array of strings.`,\n      });\n    }\n    // Cross-check: a pathParams entry without a matching placeholder would\n    // silently consume a call arg and substitute nothing — fail at registration.\n    for (const p of d.pathParams) {\n      if (!d.path.includes(`{${p}}`)) {\n        throw new BackendError('validation', {\n          code: 'invalid_namespace_tree',\n          message: `Descriptor '${path}': pathParams entry '${p}' has no '{${p}}' placeholder in the path.`,\n        });\n      }\n    }\n  }\n  if (d.sse !== undefined && typeof d.sse !== 'boolean') {\n    throw new BackendError('validation', {\n      code: 'invalid_namespace_tree',\n      message: `Descriptor '${path}': sse must be a boolean.`,\n    });\n  }\n  if (d.sse === true && d.input === 'query') {\n    // A streaming route's input travels in the body; serializing it into the\n    // query would silently send nothing. Refuse at registration, not at 3am.\n    throw new BackendError('validation', {\n      code: 'invalid_namespace_tree',\n      message: `Descriptor '${path}': an sse endpoint cannot take query input.`,\n    });\n  }\n  if (d.input !== undefined && d.input !== 'body' && d.input !== 'query' && d.input !== 'none') {\n    throw new BackendError('validation', {\n      code: 'invalid_namespace_tree',\n      message: `Descriptor '${path}': input must be 'body', 'query' or 'none'.`,\n    });\n  }\n  if (d.errors !== undefined) {\n    for (const [code, fn] of Object.entries(d.errors)) {\n      if (typeof fn !== 'function') {\n        throw new BackendError('validation', {\n          code: 'invalid_namespace_tree',\n          message: `Descriptor '${path}': errors['${code}'] must be a function.`,\n        });\n      }\n    }\n  }\n}\n\nfunction validateTree(node: NamespaceTree): void {\n  const proto = Object.getPrototypeOf(node) as unknown;\n  if (proto !== Object.prototype && proto !== null) {\n    throw new BackendError('validation', {\n      code: 'invalid_namespace_tree',\n      message: 'Namespace tree nodes must be plain objects.',\n    });\n  }\n  for (const [key, child] of Object.entries(node)) {\n    if (key === 'then' || key in {}) throw reservedNamespaceError(key);\n    if (isDescriptor(child)) {\n      child.method = child.method.toUpperCase();\n      validateDescriptorExtensions(child, child.path);\n    } else {\n      validateTree(child);\n    }\n  }\n}\n\nexport function __registerNamespaces(tree: NamespaceTree): void {\n  for (const key of Object.keys(tree)) {\n    if (RESERVED.has(key)) throw reservedNamespaceError(key);\n  }\n  validateTree(tree);\n  const state = palbeState();\n  state.registry = tree;\n  state.nsCache = {};\n}\n\nexport function resetNamespaces(): void {\n  const state = palbeState();\n  state.registry = {};\n  state.nsCache = {};\n}\n\nexport function getRegistry(): NamespaceTree {\n  return palbeState().registry;\n}\n\nfunction serializeQuery(input: unknown): string {\n  if (input === undefined || input === null) return '';\n  const entries = Object.entries(input as Record<string, unknown>)\n    .filter(([, v]) => v !== undefined && v !== null)\n    .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n  if (entries.length === 0) return '';\n  const parts = entries.map(([k, v]) => {\n    if (typeof v !== 'string' && typeof v !== 'number' && typeof v !== 'boolean') {\n      // Objects/arrays would stringify to '[object Object]' on the wire — fail loud.\n      throw new BackendError('validation', {\n        code: 'invalid_query_value',\n        message: `Query parameter '${k}' must be a string, number, or boolean.`,\n      });\n    }\n    return `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`;\n  });\n  return `?${parts.join('&')}`;\n}\n\nasync function invokeDescriptor(\n  rt: PalbeRuntime,\n  d: EndpointDescriptor,\n  args: unknown[],\n): Promise<unknown> {\n  const params = d.pathParams ?? [];\n  let path = d.path;\n  for (let i = 0; i < params.length; i++) {\n    const v = args[i];\n    if (typeof v !== 'string' && typeof v !== 'number') {\n      throw new BackendError('validation', {\n        code: 'missing_path_param',\n        message: `${d.path}: path parameter '${params[i]}' must be a string or number`,\n      });\n    }\n    path = path.replace(`{${params[i]}}`, encodeURIComponent(String(v)));\n  }\n  // input:'none' ops have NO input slot — options come straight after the\n  // path params (a generated `get(id, options?)` would otherwise drop its\n  // options into the input slot: GET throws, POST sends them as the body).\n  if (d.input === 'none' && args.length > params.length + 1) {\n    throw new BackendError('validation', {\n      code: 'unexpected_argument',\n      message: `${d.path}: endpoint takes no input — pass only path params and options`,\n    });\n  }\n  const input = d.input === 'none' ? undefined : args[params.length];\n  const optionsSlot = d.input === 'none' ? params.length : params.length + 1;\n  const options = args[optionsSlot] as CallOptions | undefined;\n  let body: unknown;\n  if (d.input === 'query') {\n    path += serializeQuery(input);\n  } else if (d.input !== 'none') {\n    if (d.method === 'GET') {\n      if (input !== undefined) {\n        throw new BackendError('validation', {\n          code: 'unsupported_get_input',\n          message: `${d.path}: GET endpoints take no body input`,\n        });\n      }\n    } else {\n      body = input;\n    }\n  }\n  try {\n    if (d.sse === true) {\n      return await palbeStream(rt, d.method, path, {\n        body,\n        headers: options?.headers,\n        signal: options?.signal,\n      });\n    }\n    return await palbeRequest(rt, d.method, path, {\n      body,\n      headers: options?.headers,\n      signal: options?.signal,\n    });\n  } catch (e) {\n    if (d.errors && isBackendError(e)) {\n      const lift = d.errors[e.code];\n      if (lift) throw lift(e);\n    }\n    throw e;\n  }\n}\n\n/**\n * The runtime is resolved AT CALL TIME via `resolveRt` (late binding): the\n * global path passes `getRuntime` so a `__configure` swap is picked up by\n * already-materialized namespaces; bound clients pass `() => rt` so the\n * captured runtime never changes.\n */\nfunction materialize(\n  node: NamespaceTree | EndpointDescriptor,\n  resolveRt: () => PalbeRuntime,\n): unknown {\n  if (isDescriptor(node)) {\n    // async wrapper: resolveRt() may throw (notConfigured) — endpoint methods\n    // must ALWAYS reject, never throw synchronously (callers use .catch()).\n    return async (...args: unknown[]) => invokeDescriptor(resolveRt(), node, args);\n  }\n  const out: Record<string, unknown> = {};\n  for (const [key, child] of Object.entries(node)) {\n    out[key] = materialize(child, resolveRt);\n  }\n  return out;\n}\n\n/** Global path: resolves the global runtime slot, memoizes in the global nsCache. */\nexport function getNamespace(name: string): unknown {\n  const state = palbeState();\n  const cached = state.nsCache[name];\n  if (cached !== undefined) return cached;\n  const node = state.registry[name];\n  if (node === undefined) return undefined;\n  const ns = materialize(node, getRuntime);\n  state.nsCache[name] = ns;\n  return ns;\n}\n\n/**\n * Bound path: namespaces materialize against ONE fixed runtime, memoized in a\n * per-client closure cache (the global nsCache stays global-only — a bound\n * entry there would leak one request's runtime into every other client).\n * The cache is invalidated when the registry object is swapped\n * (__registerNamespaces replaces it wholesale, e.g. watch-mode regen).\n */\nexport function boundNamespaceAccessor(rt: PalbeRuntime): (name: string) => unknown {\n  let cacheRegistry = palbeState().registry;\n  let cache: Record<string, unknown> = {};\n  return (name: string): unknown => {\n    const registry = palbeState().registry;\n    if (registry !== cacheRegistry) {\n      cacheRegistry = registry;\n      cache = {};\n    }\n    const cached = cache[name];\n    if (cached !== undefined) return cached;\n    const node = registry[name];\n    if (node === undefined) return undefined;\n    const ns = materialize(node, () => rt);\n    cache[name] = ns;\n    return ns;\n  };\n}\n","const APP_METADATA_HEADER = 'X-Palbase-Bundle';\n\n/**\n * Stamp the live browser origin metadata on an app-key request. Final headers\n * are inspected case-insensitively so an explicit caller/config value wins.\n * The authenticated app identity is the app-bound API key plus its app_id;\n * this header is diagnostic metadata, not an authorization proof. Server\n * runtimes have no browser origin and intentionally add nothing.\n */\nexport function applyBrowserOriginHeader(headers: Record<string, string>): void {\n  if (Object.keys(headers).some((key) => key.toLowerCase() === 'x-palbase-bundle')) return;\n  const origin =\n    typeof window !== 'undefined' && typeof window.location !== 'undefined'\n      ? window.location.origin\n      : '';\n  if (origin !== '') headers[APP_METADATA_HEADER] = origin;\n}\n","// AUTO-GENERATED from package.json — do not edit\nexport const VERSION = '11.2.2';\n","import { BackendError } from './errors.js';\nimport { type CallOptions, palbeRequest } from './request.js';\nimport type { PalbeRuntime } from './runtime.js';\n\n/**\n * Runtime resolution is deferred behind `resolveRt` (global pb passes\n * `getRuntime`, bound clients pass `() => rt`) — but name validation runs\n * FIRST so an empty name fails as `validation` even before `notConfigured`.\n */\nexport async function callEndpoint<O>(\n  resolveRt: () => PalbeRuntime,\n  name: string,\n  input?: unknown,\n  options?: CallOptions,\n): Promise<O> {\n  if (!name || name === '/') {\n    throw new BackendError('validation', {\n      code: 'invalid_endpoint_name',\n      message: 'Endpoint name must be a non-empty path like \"todos/create\"',\n    });\n  }\n  const rt = resolveRt();\n  const path = name.startsWith('/') ? name : `/${name}`;\n  return palbeRequest<O>(rt, 'POST', path, {\n    body: input,\n    headers: options?.headers,\n    signal: options?.signal,\n  });\n}\n","// room.ts — the TYPED cap over a realtime channel, on the web side.\n//\n// Realtime arrives untyped today: a handler is given `Record<string, unknown>`\n// and every field is a cast. A room changes that — the backend DECLARES its\n// events and its messages, the generator emits them as real types, and this file\n// is where those types meet the socket.\n//\n// What this file deliberately does NOT do is manage membership. `PalbeRealtime`\n// already joins a channel on its first handler and leaves on its last, so FR-016\n// is satisfied by DELEGATING to that count. A second refcount here would be a\n// second thing to get wrong, and the two would disagree the first time an app\n// mixed `pb.join` with `pb.realtime.channel`.\n\nimport type { RealtimePayload, RealtimeSubscription } from './realtime/facade.js';\n\n/** What a room needs from the socket. `PalbeRealtime` provides it; a test\n *  supplies its own, so the typed layer can be measured without a connection. */\nexport interface RoomTransport {\n  /** Subscribe to one event on one topic. Returns the undo. */\n  subscribe(topic: string, event: string, handler: (payload: RealtimePayload) => void): () => void;\n  /** Push one client frame. */\n  send(topic: string, event: string, payload: RealtimePayload): void;\n}\n\n/**\n * A room, as the generator emits one. An app never writes this by hand.\n *\n * `send` and `event` are TYPE CARRIERS — their values are never read. They exist\n * so `room.send('say', {...})` checks the payload against the right shape\n * without the app ever naming that shape.\n */\nexport interface RoomDescriptor<\n  E extends { event: string; payload: unknown },\n  S,\n  P extends readonly string[] = readonly string[],\n> {\n  /** The channel pattern the backend declared: `ai:{sessionId}`. */\n  pattern: string;\n  /** The `{param}` names, in pattern order.\n   *\n   *  Typed as a literal tuple (the generator emits `as const`) so `join` can\n   *  demand EXACTLY these keys. Without that, `params` is `Record<string,\n   *  string>` and a typo'd key type-checks — it then builds a topic with an\n   *  unfilled `{param}`, which matches no room on the server and fails as\n   *  SILENCE. Measured: the runtime guard caught it, the compiler did not. */\n  params: P;\n  /** The declared event names — what the handle subscribes to. Without the list\n   *  it would have to guess, and a room's events are what it must not guess. */\n  events: readonly string[];\n  /** The declared message names. `send` is a TYPE carrier with no runtime keys,\n   *  so this is the half a JavaScript caller can be checked against. */\n  messages: readonly string[];\n  send: S;\n  event: E;\n}\n\n/** A live room. Hold it for as long as the view is on screen. */\nexport interface RoomHandle<E extends { event: string; payload: unknown }, S> {\n  /** The topic this handle is attached to. An app never has to build it. */\n  readonly topic: string;\n  /** Start receiving. Returns a token for `off`. */\n  on(handler: (event: E) => void): RoomToken;\n  /** Stop one callback. */\n  off(token: RoomToken): void;\n  /** Send one declared message. The event name comes from the descriptor. */\n  send<K extends keyof S & string>(name: K, payload: S[K]): void;\n  /** Drop every callback this handle registered. */\n  leave(): void;\n}\n\n/** Opaque handle to one registration. Callback + token, deliberately: a room\n *  routinely has several interested parties (a transcript, a badge, a logger),\n *  and an async iterator has exactly one consumer. */\nexport type RoomToken = { readonly __room: unique symbol } | symbol;\n\n/**\n * Attach to a room.\n *\n *     const room = pb.join(AiSessionIdRoom, { sessionId })\n *     const token = room.on((e) => {\n *       switch (e.event) {\n *         case 'token': transcript.push(e.payload.text); break\n *         case 'done':  finish(e.payload.reason); break\n *       }\n *     })\n *     room.send('say', { text: 'hello' })\n *     room.off(token)\n *\n * `switch` is exhaustive: when the backend adds an event, the compiler points at\n * every place that has to handle it.\n */\nexport function joinRoom<\n  E extends { event: string; payload: unknown },\n  S,\n  P extends readonly string[],\n>(\n  descriptor: RoomDescriptor<E, S, P>,\n  params: Record<P[number], string>,\n  transport: RoomTransport,\n): RoomHandle<E, S> {\n  const topic = fillPattern(descriptor.pattern, params as Record<string, string>);\n  // One app-facing callback holds several socket unsubscribes — one per declared\n  // event — so `off` has to undo all of them together.\n  const registrations = new Map<symbol, (() => void)[]>();\n\n  return {\n    topic,\n\n    on(handler) {\n      const token = Symbol('room');\n      const undos: (() => void)[] = [];\n      for (const name of descriptor.events) {\n        undos.push(\n          transport.subscribe(topic, name, (payload) => {\n            handler({ event: name, payload } as E);\n          }),\n        );\n      }\n      registrations.set(token, undos);\n      return token;\n    },\n\n    off(token) {\n      const undos = registrations.get(token as symbol);\n      if (!undos) return;\n      registrations.delete(token as symbol);\n      for (const undo of undos) undo();\n    },\n\n    send(name, payload) {\n      if (!descriptor.messages.includes(name)) {\n        // NAMED, and before the socket is touched. TypeScript already refuses\n        // this, but a JavaScript caller has no compiler — and a message the room\n        // never declared is dropped server-side with nothing said, which is the\n        // hardest failure shape to trace back.\n        throw new Error(\n          `room \"${descriptor.pattern}\" declares no message \"${String(name)}\" — ` +\n            `check the backend's @OnMessage names and re-run the generator.`,\n        );\n      }\n      transport.send(topic, name, payload as RealtimePayload);\n    },\n\n    leave() {\n      for (const undos of registrations.values()) {\n        for (const undo of undos) undo();\n      }\n      registrations.clear();\n    },\n  };\n}\n\n/** Build the live topic. A `{param}` left unfilled would produce a topic that\n *  matches no room on the server and fails as SILENCE — the hardest failure to\n *  trace — so it is refused here, by name. */\nfunction fillPattern(pattern: string, params: Record<string, string>): string {\n  return pattern\n    .split(':')\n    .map((seg) => {\n      if (!seg.startsWith('{') || !seg.endsWith('}')) return seg;\n      const name = seg.slice(1, -1);\n      const value = params[name];\n      if (value === undefined || value === '') {\n        throw new Error(`room \"${pattern}\" needs a value for \"${name}\".`);\n      }\n      return value;\n    })\n    .join(':');\n}\n\nexport type { RealtimeSubscription };\n","import { asPalbaseError, BackendError, fromEnvelope, fromPalbaseError } from './errors.js';\nimport type { PalbeRuntime } from './runtime.js';\nimport { applyBrowserOriginHeader } from './runtime-metadata.js';\nimport { VERSION } from './version.js';\n\nexport interface UploadProgress {\n  /** Bytes sent so far. */\n  sent: number;\n  /**\n   * Total bytes. Always > 0 when delivered — progress events whose length is\n   * not computable are skipped entirely.\n   */\n  total: number;\n}\n\nexport interface UploadOptions {\n  file: Blob;\n  filename?: string;\n  contentType?: string;\n  /**\n   * The request body sent beside the file. Folded into the single `body` part\n   * storage reads and handed to the route's schema — pass a pre-encoded JSON\n   * string as `body` to own the envelope yourself.\n   */\n  fields?: Record<string, string>;\n  onProgress?: (progress: UploadProgress) => void;\n  signal?: AbortSignal;\n  headers?: Record<string, string>;\n  /** Client-side pre-send validation (iOS parity). */\n  constraints?: { maxSize?: number; allowedTypes?: string[] };\n}\n\n/** Storage's client-facing door: `POST /v1/storage/upload/{route...}`. */\nconst UPLOAD_PATH = '/v1/storage/upload';\n\nfunction abortError(): BackendError {\n  return new BackendError('network', { code: 'aborted', message: 'Upload aborted' });\n}\n\nfunction checkConstraints(options: UploadOptions): void {\n  const c = options.constraints;\n  if (!c) return;\n  if (c.maxSize !== undefined && options.file.size > c.maxSize) {\n    const message = `File size ${options.file.size} exceeds max ${c.maxSize} bytes`;\n    throw new BackendError('validation', {\n      code: 'file_too_large',\n      message,\n      fields: [{ field: 'file', message }],\n    });\n  }\n  // Empty allowedTypes = no type check (iOS contract). Validate the EFFECTIVE\n  // type: a contentType override wins over file.type (it is what gets sent).\n  const effType = options.contentType ?? options.file.type;\n  if (c.allowedTypes && c.allowedTypes.length > 0 && !c.allowedTypes.includes(effType)) {\n    const message = `File type '${effType}' is not allowed`;\n    throw new BackendError('validation', {\n      code: 'file_type_not_allowed',\n      message,\n      fields: [{ field: 'file', message }],\n    });\n  }\n}\n\nasync function buildHeaders(\n  rt: PalbeRuntime,\n  extra?: Record<string, string>,\n): Promise<Record<string, string>> {\n  // Pre-flight refresh: mirrors the pattern in request.ts / HttpClient.\n  if (\n    rt.tokenManager.isExpired() &&\n    rt.tokenManager.getRefreshToken() &&\n    rt.tokenManager.refreshFunction\n  ) {\n    try {\n      await rt.tokenManager.refreshSession();\n    } catch (e) {\n      const pe = asPalbaseError(e);\n      const status = pe?.status ?? 0;\n      if (status === 400 || status === 401 || status === 403) {\n        rt.tokenManager.clearSession(); // terminal — proceed unauthenticated\n      } else {\n        throw pe ? fromPalbaseError(pe) : e;\n      }\n    }\n  }\n\n  // Uploads bypass @palbase/core to stream multipart bodies. Kong derives the\n  // Environment identity from the API key, matching the iOS upload path.\n  const headers: Record<string, string> = {\n    apikey: rt.config.apiKey,\n    'X-Client-Info': `palbe-web/${VERSION}`,\n    ...rt.config.headers,\n  };\n  const token = rt.tokenManager.getAccessToken();\n  if (token) headers.Authorization = `Bearer ${token}`;\n  // Case-insensitive scan (mirrors request.ts): a caller-supplied\n  // `idempotency-key` in any casing must suppress generation.\n  const callerHasKey = Object.keys(extra ?? {}).some((k) => k.toLowerCase() === 'idempotency-key');\n  if (!callerHasKey) headers['Idempotency-Key'] = crypto.randomUUID();\n  // extra spreads LAST so a caller-pinned Authorization wins (HttpClient/iOS precedence).\n  const merged = { ...headers, ...extra };\n  applyBrowserOriginHeader(merged);\n  return merged;\n}\n\nfunction buildForm(options: UploadOptions): FormData {\n  const form = new FormData();\n  // The handler's own body travels as a SINGLE `body` part carrying JSON, not\n  // as loose form fields: storage reads exactly `r.FormValue(\"body\")` and hands\n  // that to the route's schema (`upload.go`, receiveUpload). One part per field\n  // was appended here and every one of them was dropped on the other side — the\n  // upload still answered 200 and the handler's `@Body` was `undefined`.\n  // Same folding as the iOS SDK (BackendUpload.swift): a caller who supplies\n  // `body` themselves has already encoded the envelope, so it is sent verbatim.\n  const { body, ...loose } = options.fields ?? {};\n  if (body !== undefined) form.append('body', body);\n  else if (Object.keys(loose).length > 0) form.append('body', JSON.stringify(loose));\n  const file =\n    options.contentType && options.file.type !== options.contentType\n      ? new Blob([options.file], { type: options.contentType })\n      : options.file;\n  const filename =\n    options.filename ??\n    (typeof File !== 'undefined' && options.file instanceof File ? options.file.name : 'file');\n  form.append('file', file, filename);\n  return form;\n}\n\nfunction decode<O>(status: number, text: string): O {\n  let body: unknown;\n  try {\n    body = text === '' ? null : JSON.parse(text);\n  } catch {\n    if (status >= 200 && status < 300) {\n      throw new BackendError('decode', {\n        code: 'decode_error',\n        message: 'Invalid JSON in response',\n        status,\n      });\n    }\n    body = text;\n  }\n  if (status < 200 || status >= 300) throw fromEnvelope(status, body);\n  return body as O;\n}\n\nfunction uploadViaXHR<O>(\n  url: string,\n  form: FormData,\n  headers: Record<string, string>,\n  options: UploadOptions,\n): Promise<O> {\n  return new Promise<O>((resolve, reject) => {\n    // Pre-aborted signal: never send. (xhr.abort() before send() fires no\n    // abort event per spec, so routing this through onabort would hang.)\n    if (options.signal?.aborted) {\n      reject(abortError());\n      return;\n    }\n    const xhr = new XMLHttpRequest();\n    xhr.open('POST', url);\n    for (const [k, v] of Object.entries(headers)) xhr.setRequestHeader(k, v);\n    xhr.upload.onprogress = (e: { lengthComputable: boolean; loaded: number; total: number }) => {\n      if (!e.lengthComputable) return;\n      options.onProgress?.({ sent: e.loaded, total: e.total });\n    };\n    const onAbort = () => xhr.abort();\n    const cleanup = () => options.signal?.removeEventListener('abort', onAbort);\n    xhr.onload = () => {\n      cleanup();\n      try {\n        resolve(decode<O>(xhr.status, xhr.responseText));\n      } catch (err) {\n        reject(err);\n      }\n    };\n    xhr.onerror = () => {\n      cleanup();\n      reject(new BackendError('network', { code: 'network_error', message: 'Upload failed' }));\n    };\n    xhr.onabort = () => {\n      cleanup();\n      reject(abortError());\n    };\n    options.signal?.addEventListener('abort', onAbort, { once: true });\n    xhr.send(form);\n  });\n}\n\nasync function uploadViaFetch<O>(\n  url: string,\n  form: FormData,\n  headers: Record<string, string>,\n  options: UploadOptions,\n): Promise<O> {\n  let res: Response;\n  try {\n    res = await fetch(url, { method: 'POST', body: form, headers, signal: options.signal });\n  } catch (e) {\n    // DOMException extends Error in modern runtimes — name check covers both.\n    if (e instanceof Error && e.name === 'AbortError') throw abortError();\n    throw new BackendError('network', {\n      code: 'network_error',\n      message: e instanceof Error ? e.message : 'Upload failed',\n    });\n  }\n  return decode<O>(res.status, await res.text());\n}\n\n/** Runtime resolution deferred behind `resolveRt` — see call.ts for the pattern. */\nexport async function uploadEndpoint<O>(\n  resolveRt: () => PalbeRuntime,\n  name: string,\n  options: UploadOptions,\n): Promise<O> {\n  const rt = resolveRt();\n  checkConstraints(options); // pre-send guard — rejects before any network I/O\n  // `name` is the tenant ROUTE, and the door is STORAGE's — storage authorizes\n  // against the route's own `@Upload` declaration, writes the bytes, renders\n  // the variants and only then calls the handler. Posting the multipart\n  // straight at the route is what the runtime refuses (\"this endpoint accepts\n  // uploads through storage, not directly\"), so every upload from a browser was\n  // a 401 no app could act on. Mirrors the iOS path (BackendUpload.swift).\n  const route = name.startsWith('/') ? name : `/${name}`;\n  const url = `${rt.config.url}${UPLOAD_PATH}${route}`;\n  const headers = await buildHeaders(rt, options.headers);\n  const form = buildForm(options);\n  const useXHR = options.onProgress !== undefined && typeof XMLHttpRequest !== 'undefined';\n  return useXHR\n    ? uploadViaXHR<O>(url, form, headers, options)\n    : uploadViaFetch<O>(url, form, headers, options);\n}\n","import type { PalbeAnalytics } from './analytics-facade.js';\nimport type { PalbeAuth } from './auth-facade.js';\nimport { callEndpoint } from './call.js';\nimport type { PalbeCalls } from './calls/facade.js';\nimport type { PalbeFlags } from './flags-facade.js';\nimport { getRuntime } from './internal.js';\nimport type { PalbeMessaging } from './messaging/facade.js';\nimport { boundNamespaceAccessor, getNamespace, getRegistry } from './namespaces.js';\nimport type { PalbePerf } from './perf/perf-facade.js';\nimport type { PalbeRealtime } from './realtime/facade.js';\nimport type { CallOptions } from './request.js';\nimport { joinRoom, type RoomDescriptor, type RoomHandle } from './room.js';\nimport type { PalbeRuntime } from './runtime.js';\nimport type { UploadOptions } from './upload.js';\nimport { uploadEndpoint } from './upload.js';\n\n/**\n * The Palbe surface. Codegen augments this interface with typed endpoint\n * namespaces:  declare module '@palbase/web' { interface PB { rooms: ... } }\n */\nexport interface PB {\n  call<O = unknown>(name: string, input?: unknown, options?: CallOptions): Promise<O>;\n  upload<O = unknown>(name: string, options: UploadOptions): Promise<O>;\n  readonly auth: PalbeAuth;\n  readonly flags: PalbeFlags;\n  readonly realtime: PalbeRealtime;\n  /**\n   * Join a room the backend declared with `@Room`.\n   *\n   *     const room = pb.join(AiSessionIdRoom, { sessionId })\n   *     const token = room.on((e) => { … })\n   *     room.send('say', { text: 'hello' })\n   *\n   * The descriptor is GENERATED: the pattern, the event names and the message\n   * names all come from the backend's declaration, so the app writes no channel\n   * string and no payload type of its own.\n   */\n  join<E extends { event: string; payload: unknown }, S, P extends readonly string[]>(\n    descriptor: RoomDescriptor<E, S, P>,\n    params: Record<P[number], string>,\n  ): RoomHandle<E, S>;\n  readonly analytics: PalbeAnalytics;\n  readonly calls: PalbeCalls;\n  readonly messaging: PalbeMessaging;\n  /** The PalPerf surface: custom traces (`startTrace`) + the buffered flush of\n   * network/app-start/custom items. `pb.perf.record(...)` is also how the\n   * runtime feeds the cold-start measurement in. */\n  readonly perf: PalbePerf;\n  /** Mark (or unmark) this client's traffic as test — flips the facade's flag\n   * so every subsequent perf flush carries `X-Palbase-Test-Device: 1` (the\n   * SAME header the iOS SDK sends; the server reads it → `is_test_traffic`). */\n  setTestDevice(on: boolean): void;\n}\n\n/**\n * One proxy construction for BOTH client flavors:\n * - global `pb`: resolveRt = getRuntime (late-bound — a __configure swap is\n *   visible to every subsequent call), nsAccessor = the globally-cached path;\n * - bound clients: resolveRt = () => rt (captured once, immune to global\n *   swaps), nsAccessor = a per-client cache (see namespaces.ts).\n */\nfunction createClientProxy(\n  resolveRt: () => PalbeRuntime,\n  nsAccessor: (name: string) => unknown,\n): PB {\n  const base = {\n    call<O = unknown>(name: string, input?: unknown, options?: CallOptions): Promise<O> {\n      return callEndpoint<O>(resolveRt, name, input, options);\n    },\n    upload<O = unknown>(name: string, options: UploadOptions): Promise<O> {\n      return uploadEndpoint<O>(resolveRt, name, options);\n    },\n    get auth(): PalbeAuth {\n      return resolveRt().auth;\n    },\n    get flags(): PalbeFlags {\n      return resolveRt().flags;\n    },\n    get realtime(): PalbeRealtime {\n      return resolveRt().realtime;\n    },\n    /**\n     * Join a room the backend declared with `@Room`.\n     *\n     *     const room = pb.join(AiSessionIdRoom, { sessionId })\n     *     const token = room.on((e) => {\n     *       switch (e.event) {\n     *         case 'token': transcript.push(e.payload.text); break\n     *         case 'done':  finish(e.payload.reason); break\n     *       }\n     *     })\n     *     room.send('say', { text: 'hello' })\n     *     room.off(token)\n     *\n     * The descriptor is GENERATED, so the app writes no channel string and no\n     * payload type of its own. Several handles on the same room share ONE\n     * subscription and the room is left when the last one goes \\u2014 the socket's\n     * own refcount, not a second one.\n     */\n    join<E extends { event: string; payload: unknown }, S, P extends readonly string[]>(\n      descriptor: RoomDescriptor<E, S, P>,\n      params: Record<P[number], string>,\n    ): RoomHandle<E, S> {\n      const realtime = resolveRt().realtime;\n      return joinRoom(descriptor, params, {\n        subscribe(topic, event, handler) {\n          const sub = realtime.subscribe(topic, event, handler);\n          return () => sub.cancel();\n        },\n        send(topic, event, payload) {\n          realtime.send(topic, event, payload);\n        },\n      });\n    },\n    get analytics(): PalbeAnalytics {\n      return resolveRt().analytics;\n    },\n    get calls(): PalbeCalls {\n      return resolveRt().calls;\n    },\n    get messaging(): PalbeMessaging {\n      return resolveRt().messaging;\n    },\n    get perf(): PalbePerf {\n      return resolveRt().perf;\n    },\n    setTestDevice(on: boolean): void {\n      resolveRt().perf.setTestDevice(on);\n    },\n  };\n  return new Proxy(base, {\n    get(target, prop, receiver) {\n      if (prop in target) return Reflect.get(target, prop, receiver);\n      // `then` must NEVER resolve to a namespace: a thenable pb would make\n      // `await pb` (or Promise.resolve(pb)) hang on the proxy. Registration\n      // also rejects it (see namespaces.ts) — this is defense in depth.\n      if (prop === 'then') return undefined;\n      if (typeof prop === 'string') {\n        const ns = nsAccessor(prop);\n        if (ns !== undefined) return ns;\n      }\n      return undefined;\n    },\n    has(target, prop) {\n      if (prop in target) return true;\n      return typeof prop === 'string' && prop !== 'then' && getRegistry()[prop] !== undefined;\n    },\n  }) as PB;\n}\n\nexport const pb: PB = createClientProxy(getRuntime, getNamespace);\n\n/**\n * A `PB` client permanently bound to ONE runtime — typed namespaces, `call`,\n * `upload` and `auth` all resolve `rt`, NEVER the global slot. This is the\n * per-request isolation primitive for server adapters (palbe/next pbServer):\n * two bound clients serving concurrent requests cannot leak each other's\n * sessions, and global `__configure` swaps don't touch them.\n */\nexport function createBoundClient(rt: PalbeRuntime): PB {\n  return createClientProxy(() => rt, boundNamespaceAccessor(rt));\n}\n","import { __resetPermissionDeniedHandlers } from './auth-facade.js';\nimport type { PalbeConfig } from './config.js';\nimport { BackendError } from './errors.js';\nimport { __registerNamespaces, resetNamespaces } from './namespaces.js';\nimport { buildRuntime, type PalbeRuntime } from './runtime.js';\nimport { palbeState } from './state.js';\n\n// Runtime lives in a process-global slot (see state.ts) so every build copy\n// (ESM/CJS, palbe + palbe/internal entries) converges on one singleton.\n// This is the BROWSER path (one runtime per tab). Server-side per-request\n// runtimes arrive with palbe/next (P3); do not sign in from shared server\n// code against this singleton.\n\n/**\n * Called by the generated palbe.gen.ts on import. REPLACES the runtime\n * (re-runs storage hydration) — safe to call repeatedly, e.g. watch-mode\n * regen. The namespace registry intentionally survives re-configure: the\n * gen file re-registers its static descriptors right after.\n */\nexport function __configure(config: PalbeConfig): void {\n  const state = palbeState();\n  // Destroy the old realtime facade if it was constructed — closes the socket\n  // and clears heartbeat timers so they do not outlive the replaced runtime.\n  state.runtime?.destroyRealtime();\n  state.runtime = buildRuntime(config);\n  // Fire after the runtime is in place so listeners that read pb.* immediately\n  // (e.g. useSyncExternalStore getSnapshot) see the new runtime.\n  for (const cb of state.configuredListeners) {\n    try {\n      cb();\n    } catch {\n      // consumer errors must not abort delivery to other listeners\n    }\n  }\n}\n\n/**\n * Register a callback that fires synchronously after every successful\n * `__configure` call (including re-configure / watch-mode regen).\n *\n * Returns an unsubscribe function. Safe to call before the first `__configure`.\n *\n * Consumed by `palbe/react`; not part of the public `palbe` surface — which is\n * what the separate `palbe/internal` ENTRY expresses, and the only thing that\n * may. DO NOT mark this doc comment with the TSDoc internal tag (not even in\n * prose — the compiler matches the token anywhere in the block): `stripInternal`\n * in tsconfig.json reads the whole src tree, so the tag deletes this declaration\n * from the shipped `internal.d.ts` while the JS keeps exporting it, and every\n * honest importer fails typecheck (WEB-9).\n */\nexport function onConfigured(cb: () => void): () => void {\n  const state = palbeState();\n  state.configuredListeners.add(cb);\n  return () => state.configuredListeners.delete(cb);\n}\n\n/** The configured runtime, or a guided `notConfigured` throw. Package-internal\n * (hence the `palbe/internal` entry) but part of THAT entry's shipped surface —\n * carries no TSDoc internal tag, which `stripInternal` would honour by deleting\n * this declaration from `internal.d.ts` (see `onConfigured` above). */\nexport function getRuntime(): PalbeRuntime {\n  const rt = palbeState().runtime;\n  if (!rt) throw BackendError.notConfigured();\n  return rt;\n}\n\n/** Test-only: drop runtime + registered namespaces. */\nexport function __reset(): void {\n  __resetPermissionDeniedHandlers();\n  const state = palbeState();\n  state.runtime?.destroyRealtime();\n  state.runtime = null;\n  state.configuredListeners.clear();\n  resetNamespaces();\n}\n\nexport type { EndpointDescriptor, NamespaceTree } from './namespaces.js';\nexport type { PB } from './pb.js';\nexport { createBoundClient } from './pb.js';\nexport type { PalbeConfig, PalbeRuntime };\n// Server-adapter seams (palbe/next): per-request runtime + bound client.\nexport { __registerNamespaces, buildRuntime };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAgBA,mBAA+E;;;AChB/E,IAAM,aAAa,CAAC;AACb,IAAM,gBAAgB,iBAAiB,YAAY,UAAU;AACpE,SAAS,iBAAiB,SAAS,QAAQ;AACvC,SAAO,IAAI,MAAM,SAAS;AAAA,IACtB,IAAI,SAAS,MAAM,WAAW;AAC1B,UAAI,QAAQ,QAAQ;AAChB,eAAO,OAAO,IAAI;AAAA,MACtB,OACK;AACD,eAAO,QAAQ,IAAI;AAAA,MAC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