{"version":3,"sources":["../src/auto.ts"],"names":["patchPermissionsAPI","api","originalQuery","descriptor","requestedDeviceId","devices","granted","device","frozenDevices","target","W3C_BLUETOOTH_MEMBERS","isEventHandlerMember","prop","buildW3CFacade","BeacioW3CBluetooth","facade","source","member","value","resolveAutoReconnectConfig","raw","forwardingProxy","overrides","boundCache","obj","receiver","bound","superviseCharacteristic","characteristic","serviceUuid","state","key","result","superviseService","service","uuid","c","superviseServer","server","s","superviseGatt","gatt","recoverSubscriptions","startReconnectLoop","backoff","serviceUUIDs","delay","attempt","resolve","fastPath","superviseDevice","supervisedGatt","withAutoReconnect","config","originalRequestDevice","args","createUnsupportedBluetoothStub","BeacioUnsupportedBluetooth","stub","_args","detect","beacioDomException","UNSUPPORTED_PLATFORM_INSTALL","eventType","current","next","CDN_STUB_MARKER","polyfillApplied","applyPolyfill","bluetoothNavigator","BluetoothUUID","platform","detectPlatform","BEACIO_EVENTS","getBluetoothAPI","apiRec","ios","ownStub","upgraded"],"mappings":"wKAmCA,SAASA,EAAoBC,CAAAA,CAA8D,CACzF,GAAI,OAAO,UAAc,GAAA,EAAe,CAAC,SAAA,CAAU,WAAA,CAAa,OAEhE,IAAMC,CAAAA,CAAgB,SAAA,CAAU,WAAA,CAAY,MAAM,IAAA,CAAK,SAAA,CAAU,WAAW,CAAA,CAC5E,UAAU,WAAA,CAAY,KAAA,CAAQ,eAC5BC,CAAAA,CAC2B,CAC3B,GAAKA,CAAAA,CAAgC,IAAA,GAAS,WAAA,CAC5C,OAAOD,CAAAA,CAAcC,CAAU,CAAA,CAGjC,IAAMC,EAAqBD,CAAAA,CAAqC,QAAA,CAC5DE,CAAAA,CAA6B,GACjC,GAAI,OAAOJ,CAAAA,CAAI,UAAA,EAAe,WAC5B,GAAI,CACF,IAAMK,CAAAA,CAAU,MAAML,CAAAA,CAAI,UAAA,EAAW,CACrCI,CAAAA,CAAUD,IAAsB,KAAA,CAAA,CAC5B,CAAC,GAAGE,CAAO,EACXA,CAAAA,CAAQ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AAAA,EAA+B,CAChGqB,CAAAA,GAAY,MACd,MAAA,CAAO,cAAA,CAAe,SAAA,CAAW,WAAA,CAAa,CAC5C,GAAA,CAAK,IAAMA,CAAAA,CACX,YAAA,CAAc,IAChB,CAAC,CAAA,CAUC,OAAO,MAAA,CAAW,KACpB,MAAA,CAAO,gBAAA,CAAiBJ,CAAAA,CAAc,eAAA,CAAiB,IAAM,CAC3D,GAAID,CAAAA,EAAe,GAAM,mBAAoB,OAC7C,IAAMvE,CAAAA,CAAMyE,GAAAA,GACZ,GAAI,CAACzE,CAAAA,CAAK,OAIV,IAAM+D,CAAAA,CAAW,SAAA,CAAqC,SAAA,CACtD,GAAIa,IAAY,IAAA,GAASb,CAAAA,GAAY,MAAA,EAAaA,CAAAA,GAAYa,GAAU,CACtE,IAAMC,CAAAA,CAAWjE,CAAAA,CAAeuC,EAAkBnD,CAAG,CAAC,CAAA,CACtD,MAAA,CAAO,eAAe,SAAA,CAAW,WAAA,CAAa,CAC5C,GAAA,CAAK,IAAM6E,CAAAA,CACX,YAAA,CAAc,IAChB,CAAC,EACH,CAEA9E,CAAAA,CAAoBC,CAAwD,EAC9E,EAAG,CAAE,IAAA,CAAM,IAAK,CAAC,EAErB,CAEAmE,CAAAA,EAAc","file":"auto.mjs","sourcesContent":["/**\n * @beacio/core/auto — Transparent Web Bluetooth polyfill.\n *\n * Usage: import '@beacio/core/auto';\n *\n * - Chrome/Edge (native bluetooth): no-op\n * - Safari iOS (with extension): ensures navigator.bluetooth maps to extension API\n * - Safari iOS (without extension): lazy-loads install prompt on first requestDevice()\n * - Unsupported platforms: no-op (graceful degradation)\n */\n\nimport { detectPlatform, getBluetoothAPI, CDN_STUB_MARKER } from './platform';\nimport { BluetoothUUID } from './uuid';\nimport { BEACIO_EVENTS } from './events';\nimport type { RawAutoReconnectConfig } from './types';\n// S5-D: the unsupported-platform-install CONDITION row + factory. RELATIVE import on\n// purpose — tsup knows nothing of the repo's BEACIO_ALIASES and must not need to.\n// auto.mjs budget note: tree-shaking carries exactly this one row (MAX_AUTO_GZIP pin).\nimport { UNSUPPORTED_PLATFORM_INSTALL, beacioDomException } from './error-conditions';\n\n/**\n * Patch navigator.permissions.query to support { name: 'bluetooth' } (§4.1\n * Permission API Integration).\n *\n * Honesty rules (permissions-query-bluetooth-unsupported):\n * - Patched ONLY when an extension-backed bluetooth API actually exists —\n *   unsupported platforms keep the browser's native behavior (TypeError on\n *   the name, matching Chrome).\n * - `state` is always 'prompt': with a chooser-based UA every new-device\n *   access can prompt, so 'granted' is never synthesized.\n * - The §4.1 BluetoothPermissionResult.devices array is backed by the native\n *   grant query (getDevices()), filtered by descriptor.deviceId when present.\n *   descriptor.filters matching needs advertisement data the page does not\n *   have, so filters are ignored (best-effort superset, never an error).\n */\nfunction patchPermissionsAPI(api: { getDevices?: () => Promise<BluetoothDevice[]> }): void {\n  if (typeof navigator === 'undefined' || !navigator.permissions) return;\n\n  const originalQuery = navigator.permissions.query.bind(navigator.permissions);\n  navigator.permissions.query = async function (\n    descriptor: PermissionDescriptor\n  ): Promise<PermissionStatus> {\n    if ((descriptor as { name: string }).name !== 'bluetooth') {\n      return originalQuery(descriptor);\n    }\n\n    const requestedDeviceId = (descriptor as { deviceId?: string }).deviceId;\n    let devices: BluetoothDevice[] = [];\n    if (typeof api.getDevices === 'function') {\n      try {\n        const granted = await api.getDevices();\n        devices = requestedDeviceId === undefined\n          ? [...granted]\n          : granted.filter((device) => (device as { id?: string }).id === requestedDeviceId);\n      } catch {\n        devices = [];\n      }\n    }\n    const frozenDevices = Object.freeze(devices);\n\n    const target = new EventTarget();\n    const status = Object.create(target, {\n      state: { get: () => 'prompt' as PermissionState, enumerable: true },\n      name: { get: () => 'bluetooth', enumerable: true },\n      onchange: { value: null, writable: true, enumerable: true },\n      devices: { get: () => frozenDevices, enumerable: true },\n    }) as PermissionStatus;\n    return status;\n  };\n}\n\n/**\n * Members allowed on the polyfilled `navigator.bluetooth`. Everything else\n * (peripheral, backgroundSync, getCapabilities, debug, __beacio, etc.) is\n * filtered out so the polyfill surface matches the W3C Web Bluetooth spec\n * exactly. iOS-specific capabilities are reached via `window.beacioIOS`.\n */\nconst W3C_BLUETOOTH_MEMBERS: ReadonlySet<string> = new Set([\n  // Bluetooth interface (spec §4)\n  'requestDevice',\n  'getAvailability',\n  'getDevices',\n  // §4 \"[SameObject] readonly attribute BluetoothDevice? referringDevice\" —\n  // constant null on iOS (no referring-device navigation mechanism exists),\n  // but the attribute must be present and read null, never undefined.\n  'referringDevice',\n  // §6.6.6 IDL event handlers — Bluetooth includes\n  // BluetoothDeviceEventHandlers, CharacteristicEventHandlers AND\n  // ServiceEventHandlers, so all mixin onX attributes are part of the\n  // standard surface (bubbled §6.6.1 tree events are handled at the root).\n  'onavailabilitychanged',\n  'onadvertisementreceived',\n  'ongattserverdisconnected',\n  'oncharacteristicvaluechanged',\n  'onserviceadded',\n  'onservicechanged',\n  'onserviceremoved',\n  // EventTarget\n  'addEventListener',\n  'removeEventListener',\n  'dispatchEvent',\n]);\n\n/**\n * Event-handler IDL attributes must round-trip with identity (the getter\n * returns the exact function assigned) and their accessors must run against\n * the real Bluetooth instance — never bind them and never route their\n * get/set through the proxy receiver.\n */\nfunction isEventHandlerMember(prop: string): boolean {\n  return prop.startsWith('on');\n}\n\n/**\n * W3C facade over the live vendor API.\n *\n * A PLAIN EventTarget-derived object instead of a Proxy\n * (facade-proxy-violates-essential-invariants): the injected vendor object\n * carries NON-CONFIGURABLE own properties (`debug`, `__beacio`), and any\n * Proxy whose traps hide non-configurable target properties throws\n * TypeError during ordinary introspection (Object.keys, spread, `in`,\n * JSON.stringify). A plain object satisfies every ES invariant by\n * construction — vendor members are simply absent.\n *\n * - Methods are bound ONCE at build time → stable identities ([SameObject]\n *   method-identity half of navigator-bluetooth-getter-new-proxy-per-access).\n * - onX EventHandler attributes forward get/set to the live instance so the\n *   accessor runs against its real private storage and assignment reads back\n *   (proxy-receiver-breaks-handler-attribute-readback).\n * - referringDevice forwards (defaulting to null per §4) and stays readonly.\n * - Expando writes behave like any plain platform object wrapper and never\n *   reach the vendor surface.\n */\nfunction buildW3CFacade(api: object): object {\n  class BeacioW3CBluetooth extends EventTarget {}\n  const facade = new BeacioW3CBluetooth();\n  const source = api as { [key: string]: EventListener | BluetoothServiceUUID | BluetoothCharacteristicUUID | object };\n\n  for (const member of W3C_BLUETOOTH_MEMBERS) {\n    if (isEventHandlerMember(member)) {\n      Object.defineProperty(facade, member, {\n        get: () => (source[member] as EventListener) ?? null,\n        set: (value) => { source[member] = value; },\n        enumerable: true,\n        configurable: true,\n      });\n      continue;\n    }\n    if (member === 'referringDevice') {\n      Object.defineProperty(facade, member, {\n        get: () => (source[member] as BluetoothDevice | null) ?? null,\n        enumerable: true,\n        configurable: true,\n      });\n      continue;\n    }\n    const value = source[member];\n    if (typeof value === 'function') {\n      Object.defineProperty(facade, member, {\n        value: (value as (...args: object[]) => object).bind(api),\n        writable: true,\n        enumerable: true,\n        configurable: true,\n      });\n    }\n    // Members the live API does not implement as functions (e.g. EventTarget\n    // methods on a partial mock) fall through to the facade's own inherited\n    // EventTarget implementation.\n  }\n  return facade;\n}\n\n// ---------------------------------------------------------------------------\n// SB-SDK-13 — Foreground auto-reconnect + subscription recovery for the RAW\n// polyfilled navigator.bluetooth path.\n//\n// beacio's free foreground reconnect engine lives on the BeacioDevice wrapper\n// (device.ts handleDisconnect/startAutoReconnect + notification-manager\n// recoverSubscriptions). Real drop-in apps — the Storz & Bickel demo — consume\n// the BARE global (navigator.bluetooth.requestDevice / device.gatt /\n// characteristic.startNotifications) and so never reach that engine: a transient\n// drop forces a full page reload.\n//\n// We close that gap WITHOUT touching the W3C facade surface or asking the app to\n// instantiate Beacio: requestDevice's returned device is interposed by a thin,\n// invariant-safe forwarding Proxy (get-trap only — it hides and lies about\n// nothing, only swapping a handful of prototype METHOD identities, so frozen\n// vendor instances and their readonly own props pass through untouched, unlike\n// the facade's rejected hide-non-configurable Proxy). The interposer records the\n// live gatt server, the discovered service UUIDs, and the (service,\n// characteristic) pairs that had startNotifications active, then on an UNEXPECTED\n// gattserverdisconnected runs the documented exponential backoff loop\n// (defaults mirror AutoReconnectOptions: 1s/30s/2x/Infinity), reconnecting via\n// the discovery fast-path (gatt.connectAndDiscover) when present and re-arming\n// every recorded subscription. An intentional gatt.disconnect() flips a flag so\n// the echoed event is ignored (matches device.ts:861 intentional/unexpected\n// classification). Default-on for the beacio runtime; never installed off it.\n// ---------------------------------------------------------------------------\n\n/** Resolved backoff knobs for the supervisor (mirrors device.ts:898-901 defaults). */\ninterface ResolvedBackoff {\n  maxAttempts: number;\n  initialDelayMs: number;\n  maxDelayMs: number;\n  backoffMultiplier: number;\n}\n\nfunction resolveAutoReconnectConfig(): { enabled: boolean; backoff: ResolvedBackoff } {\n  const raw = (typeof window !== 'undefined'\n    ? (window as { beacioAutoReconnect?: RawAutoReconnectConfig }).beacioAutoReconnect\n    : undefined) ?? {};\n  return {\n    enabled: raw.enabled !== false,\n    backoff: {\n      maxAttempts: raw.maxAttempts ?? Infinity,\n      initialDelayMs: raw.initialDelayMs ?? 1000,\n      maxDelayMs: raw.maxDelayMs ?? 30000,\n      backoffMultiplier: raw.backoffMultiplier ?? 2,\n    },\n  };\n}\n\n/**\n * Per-device reconnect state shared between the interposing proxies and the\n * disconnect supervisor.\n */\ninterface SupervisorState {\n  /** Live gatt server from the most recent connect()/connectAndDiscover(). */\n  server: BluetoothRemoteGATTServer | null;\n  /** Whether the app called gatt.disconnect() itself (→ ignore the echoed event). */\n  intentional: boolean;\n  /** Whether a backoff loop is already running (guards against re-entrancy). */\n  reconnecting: boolean;\n  /** `service|characteristic` → the UUIDs needed to re-walk + re-arm on reconnect. */\n  subscriptions: Map<string, { service: string; characteristic: string }>;\n}\n\n/**\n * A transparent get-trap forwarding Proxy. The `overrides` map supplies replacement\n * values (typically wrapped methods) for specific keys; every other access reflects\n * the target faithfully so the proxy preserves all ES essential invariants —\n * including readonly own props on a frozen vendor instance — because it never hides\n * a property nor reports a value different from the target for any OWN property\n * (the overridden keys are prototype methods, which carry no own-descriptor on the\n * instance). This is why a plain forwarding interposer is safe here even though the\n * facade (which had to HIDE non-configurable vendor own props) could not be a Proxy.\n */\nfunction forwardingProxy<T extends object>(target: T, overrides: { [key: string]: object }): T {\n  // PROTOTYPE methods (EventTarget's addEventListener, the GATT class methods) are\n  // bound to the target so they keep a valid `this` when called as `proxy.method()`\n  // — otherwise WebKit throws \"Illegal invocation\" / private-field brand-check\n  // errors. OWN function-valued props are returned UNBOUND so app-assigned event\n  // handlers (navigator.bluetooth.onX = fn) round-trip with their exact identity\n  // and so partial-mock own methods keep their jest-spy reference. Bindings are\n  // cached per key for a STABLE identity across reads ([SameObject]).\n  const boundCache = new Map<PropertyKey, (...args: object[]) => object>();\n  return new Proxy(target, {\n    get(obj, prop, receiver) {\n      if (typeof prop === 'string' && Object.prototype.hasOwnProperty.call(overrides, prop)) {\n        return overrides[prop];\n      }\n      const value = Reflect.get(obj, prop, receiver);\n      if (typeof value !== 'function') return value;\n      if (Object.prototype.hasOwnProperty.call(obj, prop)) return value;\n      let bound = boundCache.get(prop) as ((...a: object[]) => object) | undefined;\n      if (!bound) {\n        bound = value.bind(obj) as (...a: object[]) => object;\n        boundCache.set(prop, bound);\n      }\n      return bound;\n    },\n  });\n}\n\n/** Wrap a characteristic so start/stopNotifications keep the recovery registry in sync. */\nfunction superviseCharacteristic(\n  characteristic: BluetoothRemoteGATTCharacteristic,\n  serviceUuid: string,\n  state: SupervisorState,\n): BluetoothRemoteGATTCharacteristic {\n  const key = `${serviceUuid}|${characteristic.uuid}`;\n  return forwardingProxy(characteristic, {\n    startNotifications: async () => {\n      const result = await characteristic.startNotifications();\n      state.subscriptions.set(key, { service: serviceUuid, characteristic: characteristic.uuid });\n      return result;\n    },\n    stopNotifications: async () => {\n      const result = await characteristic.stopNotifications();\n      state.subscriptions.delete(key);\n      return result;\n    },\n  }) as BluetoothRemoteGATTCharacteristic;\n}\n\n/** Wrap a service so characteristics it hands out are supervised. */\nfunction superviseService(\n  service: BluetoothRemoteGATTService,\n  state: SupervisorState,\n): BluetoothRemoteGATTService {\n  return forwardingProxy(service, {\n    getCharacteristic: async (uuid: BluetoothCharacteristicUUID) => {\n      const characteristic = await service.getCharacteristic(uuid);\n      return superviseCharacteristic(characteristic, service.uuid, state);\n    },\n    getCharacteristics: async (uuid?: BluetoothCharacteristicUUID) => {\n      const characteristics = await (service as {\n        getCharacteristics: (u?: BluetoothCharacteristicUUID) => Promise<BluetoothRemoteGATTCharacteristic[]>;\n      }).getCharacteristics(uuid);\n      return characteristics.map((c) => superviseCharacteristic(c, service.uuid, state));\n    },\n  }) as BluetoothRemoteGATTService;\n}\n\n/** Wrap a gatt server so service lookups are supervised and the live server is recorded. */\nfunction superviseServer(\n  server: BluetoothRemoteGATTServer,\n  state: SupervisorState,\n): BluetoothRemoteGATTServer {\n  state.server = server;\n  return forwardingProxy(server, {\n    getPrimaryService: async (uuid: BluetoothServiceUUID) => {\n      const service = await server.getPrimaryService(uuid);\n      return superviseService(service, state);\n    },\n    getPrimaryServices: async (uuid?: BluetoothServiceUUID) => {\n      const services = await server.getPrimaryServices(uuid);\n      return services.map((s) => superviseService(s, state));\n    },\n  }) as BluetoothRemoteGATTServer;\n}\n\n/** Wrap a device's gatt so connect/disconnect feed the supervisor. */\nfunction superviseGatt(\n  gatt: BluetoothRemoteGATTServer,\n  state: SupervisorState,\n): BluetoothRemoteGATTServer {\n  return forwardingProxy(gatt, {\n    connect: async () => {\n      state.intentional = false;\n      const server = await gatt.connect();\n      return superviseServer(server, state);\n    },\n    disconnect: () => {\n      // App-initiated teardown — the next gattserverdisconnected is its echo and\n      // must NOT trigger auto-reconnect (matches device.ts:861).\n      state.intentional = true;\n      state.subscriptions.clear();\n      state.server = null;\n      gatt.disconnect();\n    },\n  }) as BluetoothRemoteGATTServer;\n}\n\n/** Re-acquire and re-subscribe every recorded characteristic after a reconnect. */\nasync function recoverSubscriptions(\n  server: BluetoothRemoteGATTServer,\n  state: SupervisorState,\n): Promise<void> {\n  for (const { service, characteristic } of [...state.subscriptions.values()]) {\n    try {\n      const svc = await server.getPrimaryService(service);\n      const ch = await svc.getCharacteristic(characteristic);\n      await ch.startNotifications();\n    } catch {\n      // Characteristic may no longer exist after a firmware/service change; drop\n      // the stale entry so we stop trying to re-arm it (mirrors\n      // notification-manager.recoverSubscriptions deleting stale registry keys).\n      state.subscriptions.delete(`${service}|${characteristic}`);\n    }\n  }\n}\n\n/** Run the documented exponential-backoff reconnect loop after an unexpected drop. */\nfunction startReconnectLoop(state: SupervisorState, backoff: ResolvedBackoff): void {\n  if (state.reconnecting) return;\n  const server = state.server;\n  if (!server) return;\n  state.reconnecting = true;\n\n  // Snapshot which UUIDs to discover so the fast-path can warm them in one round-trip.\n  const serviceUUIDs = [...new Set([...state.subscriptions.values()].map((s) => s.service))];\n\n  void (async () => {\n    let delay = backoff.initialDelayMs;\n    for (let attempt = 1; attempt <= backoff.maxAttempts; attempt += 1) {\n      if (state.intentional) break;\n      await new Promise<void>((resolve) => setTimeout(resolve, delay));\n      if (state.intentional) break;\n      try {\n        const fastPath = (server as {\n          connectAndDiscover?: (uuids: BluetoothServiceUUID[]) => Promise<BluetoothRemoteGATTService[]>;\n        }).connectAndDiscover;\n        if (typeof fastPath === 'function' && serviceUUIDs.length > 0) {\n          // Discovery fast-path (AC#3): one warm-up round-trip for all services\n          // instead of a connect() then per-service getPrimaryService chain.\n          await fastPath.call(server, serviceUUIDs);\n        } else {\n          await server.connect();\n        }\n        await recoverSubscriptions(server, state);\n        state.reconnecting = false;\n        return;\n      } catch {\n        delay = Math.min(delay * backoff.backoffMultiplier, backoff.maxDelayMs);\n      }\n    }\n    state.reconnecting = false;\n  })();\n}\n\n/**\n * Interpose a foreground auto-reconnect supervisor over a device returned by the\n * polyfilled requestDevice. No-op-safe: a device without addEventListener/gatt\n * (e.g. a partial shape) is returned untouched.\n */\nfunction superviseDevice(device: BluetoothDevice, backoff: ResolvedBackoff): BluetoothDevice {\n  if (!device || typeof device.addEventListener !== 'function') return device;\n\n  const state: SupervisorState = {\n    server: null,\n    intentional: false,\n    reconnecting: false,\n    subscriptions: new Map(),\n  };\n\n  // Attach to the RAW device so we see the extension's gattserverdisconnected\n  // regardless of any listener the app adds through the wrapper.\n  device.addEventListener('gattserverdisconnected', () => {\n    if (state.intentional) {\n      state.intentional = false;\n      return;\n    }\n    startReconnectLoop(state, backoff);\n  });\n\n  let supervisedGatt: BluetoothRemoteGATTServer | undefined;\n  return forwardingProxy(device, {\n    get gatt(): BluetoothRemoteGATTServer | undefined {\n      const raw = device.gatt;\n      if (!raw) return undefined;\n      // Cache so the intentional flag set via device.gatt.disconnect() is visible\n      // to the same supervised gatt the app keeps using ([SameObject]-style).\n      if (!supervisedGatt) supervisedGatt = superviseGatt(raw, state);\n      return supervisedGatt;\n    },\n  } as { [key: string]: object }) as BluetoothDevice;\n}\n\n/**\n * Wrap a vendor API's requestDevice so every returned device is supervised\n * (SB-SDK-13). Returns the SAME api object when auto-reconnect is disabled or the\n * api has no requestDevice, so the W3C facade build is unaffected off the feature.\n */\nfunction withAutoReconnect(api: object): object {\n  const config = resolveAutoReconnectConfig();\n  const source = api as { requestDevice?: (...args: RequestDeviceOptions[]) => Promise<BluetoothDevice> };\n  if (!config.enabled || typeof source.requestDevice !== 'function') return api;\n\n  const originalRequestDevice = source.requestDevice.bind(api);\n  return forwardingProxy(api, {\n    requestDevice: async (...args: RequestDeviceOptions[]) => {\n      const device = await originalRequestDevice(...args);\n      return superviseDevice(device, config.backoff);\n    },\n  });\n}\n\n/**\n * §4 IDL-shaped fallback for platforms with no Web Bluetooth support\n * (unsupported-platform-stub-shape-nonconformant): a real EventTarget with\n * the full Bluetooth member set. requestDevice rejects with a NotFoundError\n * DOMException (never a plain Error), getAvailability resolves false,\n * getDevices resolves [], referringDevice is null.\n */\nfunction createUnsupportedBluetoothStub(): object {\n  class BeacioUnsupportedBluetooth extends EventTarget {}\n  const stub = new BeacioUnsupportedBluetooth();\n\n  Object.defineProperty(stub, 'requestDevice', {\n    value: async (..._args: RequestDeviceOptions[]) => {\n      // Lazy-load the local detect surface for the install banner. detect now\n      // lives INSIDE @beacio/core (src/detect/), so this is an intra-package\n      // dynamic import — code-split into its own chunk so the eager polyfill\n      // graph never carries the banner UI until the unsupported stub is used.\n      // SB-SDK-07: this zero-config call passes NO lang, so the banner's i18n\n      // seam (src/detect/i18n.ts resolveStrings) derives the language from\n      // navigator.language — a German-locale iPhone gets the German banner with\n      // no config here. An explicit `lang` is only ever supplied by a caller that\n      // wires showInstallBanner/initBeacio directly (e.g. the S&B demo passes\n      // lang:'de'); core's stub stays config-free and localizable.\n      try {\n        const detect = await import('./detect');\n        if (typeof detect.showInstallBanner === 'function') {\n          detect.showInstallBanner();\n        }\n      } catch {\n        // Defensive — the banner import must never break the rejection path.\n      }\n      // §4 requestDevice: when no device/chooser can ever match, the spec\n      // rejection class is NotFoundError — never a plain Error. The sentence's\n      // LEADING clause is Chromium's WEB_BLUETOOTH_NOT_SUPPORTED verbatim; only\n      // the full beacio sentence may ever classify EXTENSION_NOT_INSTALLED.\n      throw beacioDomException(UNSUPPORTED_PLATFORM_INSTALL);\n    },\n    writable: true,\n    enumerable: true,\n    configurable: true,\n  });\n  Object.defineProperty(stub, 'getAvailability', {\n    value: async () => false,\n    writable: true,\n    enumerable: true,\n    configurable: true,\n  });\n  Object.defineProperty(stub, 'getDevices', {\n    value: async () => [],\n    writable: true,\n    enumerable: true,\n    configurable: true,\n  });\n  Object.defineProperty(stub, 'referringDevice', {\n    get: () => null,\n    enumerable: true,\n    configurable: true,\n  });\n\n  for (const member of W3C_BLUETOOTH_MEMBERS) {\n    if (!isEventHandlerMember(member)) continue;\n    const eventType = member.slice(2);\n    let current: EventListener | null = null;\n    Object.defineProperty(stub, member, {\n      get: () => current,\n      set: (next: EventListener | null) => {\n        if (current !== null) stub.removeEventListener(eventType, current);\n        current = typeof next === 'function' ? (next as EventListener) : null;\n        if (current !== null) stub.addEventListener(eventType, current);\n      },\n      enumerable: true,\n      configurable: true,\n    });\n  }\n\n  // Marker so detectPlatform()/getBluetoothAPI() never mistake our own stub\n  // for a native implementation (same convention as the CDN stubs). Keyed off the\n  // shared CDN_STUB_MARKER so the writer can never drift from the readers.\n  Object.defineProperty(stub, CDN_STUB_MARKER, {\n    value: true,\n    writable: false,\n    enumerable: false,\n    configurable: true,\n  });\n  return stub;\n}\n\nlet polyfillApplied = false;\n\n/**\n * Install the transparent W3C `navigator.bluetooth` polyfill for the current\n * platform (no-op on native/unsupported per the branches below). Runs once at\n * module load via the bottom-of-file call for `import '@beacio/core/auto'`\n * consumers; also EXPORTED so the consolidated `browser-auto` entry can invoke\n * it explicitly (a bare side-effect import is tree-shakeable under the package's\n * `sideEffects` allowlist). Idempotent: the module-level guard makes a second\n * call a no-op so the two entry points never double-register the permissions\n * shim or the extension-ready listener.\n */\nexport function applyPolyfill(): void {\n  if (polyfillApplied) return;\n  if (typeof navigator === 'undefined') return;\n  polyfillApplied = true;\n\n  const bluetoothNavigator = navigator as Navigator & {\n    bluetooth?: Bluetooth;\n  };\n\n  // Expose BluetoothUUID global (spec §4) on all platforms\n  if (typeof window !== 'undefined' && !(window as { BluetoothUUID?: object }).BluetoothUUID) {\n    (window as { BluetoothUUID?: object }).BluetoothUUID = BluetoothUUID;\n  }\n\n  // §10 [SecureContext] (polyfill-installs-in-insecure-contexts): the spec\n  // marks `Navigator.bluetooth` [SecureContext], so plain-http pages must\n  // never get the attribute — not even the throwing \"unsupported\" stub — and\n  // navigator.permissions must stay unpatched. BluetoothUUID (above) is a\n  // plain global and may stay. `=== false` keeps SSR/legacy environments that\n  // do not implement isSecureContext on their previous behavior.\n  if (typeof window !== 'undefined' && window.isSecureContext === false) {\n    return;\n  }\n\n  const platform = detectPlatform();\n\n  if (platform === 'native') {\n    // Chrome, Edge, etc. — native Web Bluetooth already works.\n    //\n    // A DORMANT beacio origin also detects as 'native': the extension's page\n    // bootstrap already occupies navigator.bluetooth while navigator.beacio\n    // (and its __beacio sentinel) is only mounted once the origin is\n    // activated. Without this retry an SDK imported before activation — the\n    // common case, a <script> in <head> — would never get the §4.1 permissions\n    // shim. Re-derive the platform when the extension announces itself; on\n    // genuine Chrome/Edge the event never fires and this listener is inert.\n    //\n    // navigator.bluetooth is deliberately NOT touched here: the bootstrap\n    // facade owns it ([SameObject]), which is also why the safari-extension\n    // branch's own `!bluetoothNavigator.bluetooth` guard below stands down.\n    // window.beacioIOS needs no mirror either — the injected script mounts it\n    // itself post-activation.\n    if (typeof window !== 'undefined') {\n      window.addEventListener(BEACIO_EVENTS.EXTENSION_READY, () => {\n        if (detectPlatform() !== 'safari-extension') return;\n        const api = getBluetoothAPI();\n        if (api) {\n          patchPermissionsAPI(api as { getDevices?: () => Promise<BluetoothDevice[]> });\n        }\n      }, { once: true });\n    }\n    return;\n  }\n\n  if (platform === 'safari-extension') {\n    // Extension provides the full vendor surface on navigator.beacio. We expose\n    // two distinct facades here:\n    //   1. navigator.bluetooth — W3C-only proxy (requestDevice, getAvailability,\n    //      getDevices, onavailabilitychanged, EventTarget). Non-standard iOS\n    //      members (peripheral, backgroundSync, getCapabilities) are hidden so\n    //      portable code matches Chrome/Edge exactly.\n    //   2. window.beacioIOS — vendor-prefixed iOS capabilities. The extension\n    //      already mounts this; we only mirror when missing (e.g. if the\n    //      polyfill loads in a context where it wasn't mounted).\n    const api = getBluetoothAPI();\n    if (api && !bluetoothNavigator.bluetooth) {\n      // [SameObject] (navigator-bluetooth-getter-new-proxy-per-access): build\n      // the facade ONCE — every access returns the identical object with\n      // stable method identities. The facade is built over the auto-reconnect\n      // interposer (SB-SDK-13) so requestDevice hands back supervised devices on\n      // the beacio runtime; every other W3C member forwards to the vendor api\n      // unchanged, and the surface is byte-for-byte identical off the feature.\n      const facade = buildW3CFacade(withAutoReconnect(api));\n      Object.defineProperty(navigator, 'bluetooth', {\n        get: () => facade,\n        configurable: true,\n      });\n    }\n    if (typeof window !== 'undefined' && !(window as { beacioIOS?: object }).beacioIOS) {\n      const apiRec = api as { peripheral?: object; backgroundSync?: object; getCapabilities?: () => object } | undefined;\n      const ios = apiRec?.peripheral || apiRec?.backgroundSync\n        ? { peripheral: apiRec.peripheral, backgroundSync: apiRec.backgroundSync, getCapabilities: () => apiRec?.getCapabilities?.() }\n        : undefined;\n      if (ios) {\n        Object.defineProperty(window, 'beacioIOS', {\n          value: Object.freeze(ios as { peripheral?: object; backgroundSync?: object; getCapabilities?: () => object }), writable: false, enumerable: true, configurable: false,\n        });\n      }\n    }\n    // Permissions API (§4.1): extension active — honest shim backed by the\n    // native grant query. State is 'prompt' (never synthetic 'granted').\n    if (api) {\n      patchPermissionsAPI(api as { getDevices?: () => Promise<BluetoothDevice[]> });\n    }\n    return;\n  }\n\n  // Unsupported or Safari without extension — install the §4 IDL-shaped stub\n  // (unsupported-platform-stub-shape-nonconformant).\n  // navigator.permissions is intentionally NOT patched here: with no working\n  // bluetooth API behind it, a synthetic PermissionStatus would be a lie —\n  // the browser's native TypeError on the name matches Chrome's behavior.\n  // [SameObject]: one stub for the page's lifetime — and ONLY when the slot is\n  // free. A truthy navigator.bluetooth on an 'unsupported' page is always a\n  // CDN_STUB_MARKER-stamped stub someone else installed (a real implementation\n  // would have detected as 'native'), so the SDK owns nothing there.\n  const ownStub: object | null = bluetoothNavigator.bluetooth ? null : createUnsupportedBluetoothStub();\n  if (ownStub !== null) {\n    Object.defineProperty(navigator, 'bluetooth', {\n      get: () => ownStub,\n      configurable: true,\n    });\n  }\n\n  // §10 (api-unavailable-at-document-start): this one-shot probe can lose\n  // the race against the extension's injected script — the throwing\n  // \"unsupported\" stub must not stay installed forever on a page where the\n  // extension comes up moments later. Re-bind deterministically on the\n  // extension's ready signal. Registered even when the slot was already taken:\n  // the §4.1 shim is slot-owner-independent, so a page whose navigator.bluetooth\n  // belongs to the CDN script still gets the honest permissions shim.\n  if (typeof window !== 'undefined') {\n    window.addEventListener(BEACIO_EVENTS.EXTENSION_READY, () => {\n      if (detectPlatform() !== 'safari-extension') return;\n      const api = getBluetoothAPI();\n      if (!api) return;\n      // Ownership: only ever swap the stub THIS module created — compared by\n      // IDENTITY, never by CDN_STUB_MARKER (the CDN stamps the same marker).\n      // A CDN stub, a bootstrap facade or a native impl keeps the slot.\n      const current = (navigator as { bluetooth?: object }).bluetooth;\n      if (ownStub !== null && (current === undefined || current === ownStub)) {\n        const upgraded = buildW3CFacade(withAutoReconnect(api));\n        Object.defineProperty(navigator, 'bluetooth', {\n          get: () => upgraded,\n          configurable: true,\n        });\n      }\n      // Extension active — the honest §4.1 permissions shim now applies.\n      patchPermissionsAPI(api as { getDevices?: () => Promise<BluetoothDevice[]> });\n    }, { once: true });\n  }\n}\n\napplyPolyfill();\n"]}