@ait-co/polyfill 0.1.2 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -54,6 +54,54 @@ async function loadTossSdk() {
54
54
  }
55
55
  }
56
56
  //#endregion
57
+ //#region src/shims/_install-helpers.ts
58
+ /**
59
+ * Install `descriptor` at `navigator[prop]`. Prefer instance-level; if the
60
+ * browser refuses (property is non-configurable on the instance), install on
61
+ * `Navigator.prototype` instead.
62
+ *
63
+ * Returns a snapshot describing where the original value was, which
64
+ * `restoreNavigatorProperty` uses to undo the install.
65
+ */
66
+ function installNavigatorProperty(prop, descriptor) {
67
+ const nav = navigator;
68
+ const instanceDesc = Object.getOwnPropertyDescriptor(nav, prop);
69
+ const instanceHadOwn = instanceDesc !== void 0;
70
+ if (!instanceDesc || instanceDesc.configurable) try {
71
+ Object.defineProperty(nav, prop, descriptor);
72
+ return {
73
+ location: "instance",
74
+ originalDescriptor: instanceDesc,
75
+ instanceHadOwn
76
+ };
77
+ } catch {}
78
+ const proto = Object.getPrototypeOf(nav);
79
+ const protoDesc = Object.getOwnPropertyDescriptor(proto, prop);
80
+ if (instanceHadOwn) try {
81
+ delete nav[prop];
82
+ } catch {}
83
+ Object.defineProperty(proto, prop, descriptor);
84
+ return {
85
+ location: "prototype",
86
+ originalDescriptor: protoDesc,
87
+ instanceHadOwn
88
+ };
89
+ }
90
+ /**
91
+ * Reverse the install recorded in `snapshot`. If the original descriptor was
92
+ * `undefined` (property didn't exist before), delete the property instead of
93
+ * re-defining it.
94
+ */
95
+ function restoreNavigatorProperty(prop, snapshot) {
96
+ const target = snapshot.location === "instance" ? navigator : Object.getPrototypeOf(navigator);
97
+ if (snapshot.originalDescriptor) try {
98
+ Object.defineProperty(target, prop, snapshot.originalDescriptor);
99
+ } catch {}
100
+ else try {
101
+ delete target[prop];
102
+ } catch {}
103
+ }
104
+ //#endregion
57
105
  //#region src/shims/clipboard.ts
58
106
  /**
59
107
  * `navigator.clipboard` shim.
@@ -66,7 +114,7 @@ async function loadTossSdk() {
66
114
  * surfaces unchanged — we don't paper over missing support.
67
115
  */
68
116
  const BACKUP_KEY = Symbol.for("@ait-co/polyfill/clipboard.original");
69
- const HAD_KEY = Symbol.for("@ait-co/polyfill/clipboard.hadOriginal");
117
+ const SNAPSHOT_KEY = Symbol.for("@ait-co/polyfill/clipboard.snapshot");
70
118
  /**
71
119
  * Produces a Clipboard-compatible object whose `readText` / `writeText` methods
72
120
  * route to the SDK when in Toss, else fall through to the supplied `fallback`.
@@ -117,34 +165,24 @@ function installClipboardShim() {
117
165
  if (BACKUP_KEY in host) return () => uninstallClipboardShim();
118
166
  const original = navigator.clipboard;
119
167
  host[BACKUP_KEY] = original;
120
- host[HAD_KEY] = "clipboard" in navigator;
121
- const shim = createClipboardShim(original);
122
- Object.defineProperty(navigator, "clipboard", {
123
- value: shim,
168
+ host[SNAPSHOT_KEY] = installNavigatorProperty("clipboard", {
169
+ value: createClipboardShim(original),
124
170
  configurable: true,
125
171
  writable: true
126
172
  });
127
173
  return uninstallClipboardShim;
128
174
  }
129
175
  /**
130
- * Remove the shim and restore the pre-install shape. Uses delete + conditional
131
- * redefine so a prototype-level `navigator.clipboard` (non-configurable in real
132
- * browsers) becomes visible again instead of being permanently shadowed.
176
+ * Remove the shim and restore the pre-install shape.
133
177
  */
134
178
  function uninstallClipboardShim() {
135
179
  if (typeof navigator === "undefined") return;
136
180
  const host = navigator;
137
181
  if (!(BACKUP_KEY in host)) return;
138
- const original = host[BACKUP_KEY];
139
- const had = host[HAD_KEY];
140
- delete navigator.clipboard;
141
- if (had && navigator.clipboard !== original) Object.defineProperty(navigator, "clipboard", {
142
- value: original,
143
- configurable: true,
144
- writable: true
145
- });
182
+ const snapshot = host[SNAPSHOT_KEY];
183
+ if (snapshot) restoreNavigatorProperty("clipboard", snapshot);
146
184
  delete host[BACKUP_KEY];
147
- delete host[HAD_KEY];
185
+ delete host[SNAPSHOT_KEY];
148
186
  }
149
187
  //#endregion
150
188
  export { installClipboardShim, uninstallClipboardShim };
@@ -1 +1 @@
1
- {"version":3,"file":"clipboard.js","names":[],"sources":["../../src/detect.ts","../../src/shims/clipboard.ts"],"sourcesContent":["/**\n * Environment detection: are we running inside Apps in Toss, or a plain browser?\n *\n * Strategy: call the SDK's `getAppsInTossGlobals()` — a synchronous export\n * that returns the runtime's Toss globals (deploymentId, brand name, …)\n * inside the Apps in Toss runtime and throws (RN bridge unavailable)\n * anywhere else. The SDK itself is an **optional** peer dependency; if its\n * module can't be imported we are definitely not inside Toss.\n *\n * Just having the SDK module resolvable is not enough — apps can bundle it\n * and still run in a plain browser. We need the bridge probe to confirm.\n *\n * UA sniffing (spoofable) is avoided. We do call `getAppsInTossGlobals`, but\n * that's a constant read from the bridge — no permission dialogs, no\n * analytics fire. In a plain browser the bridge lookup fails fast (sync\n * throw, microsecond-scale), so the startup cost is negligible.\n */\n\nlet cached: boolean | undefined;\n\n/**\n * Reset the cached detection result. Primarily for tests.\n */\nexport function resetDetection(): void {\n cached = undefined;\n}\n\n/**\n * Synchronous read of the cached detection result. Returns:\n * - `true` / `false` if an override is active or the async detection has\n * already resolved\n * - `undefined` if detection hasn't run yet\n *\n * Used by spec-sync APIs (e.g. `navigator.canShare`) that can't `await`\n * detection.\n */\nexport function isTossEnvironmentCached(): boolean | undefined {\n const force = globalThis.__AIT_POLYFILL_FORCE__;\n if (force === 'toss') return true;\n if (force === 'browser') return false;\n return cached;\n}\n\n/**\n * Returns `true` iff we detect we are running in an environment where the\n * Apps in Toss SDK (`@apps-in-toss/web-framework`) is present and usable.\n *\n * Async because we use dynamic `import()` to probe the optional peer dep\n * without forcing it into the consumer's bundle.\n */\nexport async function isTossEnvironment(): Promise<boolean> {\n // Override check precedes cache so `devtools` / tests can flip the result\n // mid-session without a `resetDetection()` call.\n const force = globalThis.__AIT_POLYFILL_FORCE__;\n if (force === 'toss') return true;\n if (force === 'browser') return false;\n\n if (cached !== undefined) return cached;\n\n const mod = await loadTossSdk();\n if (typeof mod?.getAppsInTossGlobals !== 'function') {\n cached = false;\n return cached;\n }\n // Inside Toss the bridge returns a populated globals object. In a plain\n // browser the RN bridge isn't attached and the call throws — that's our\n // signal. Any non-throwing call with an object return is treated as Toss.\n try {\n const globals = mod.getAppsInTossGlobals();\n cached = Boolean(globals) && typeof globals === 'object';\n } catch {\n cached = false;\n }\n return cached;\n}\n\n/**\n * Lazy SDK accessor — returns the module if available, else `null`. Callers\n * are expected to `await` and null-check. Never throws.\n */\nexport async function loadTossSdk(): Promise<typeof import('@apps-in-toss/web-framework') | null> {\n try {\n return await import('@apps-in-toss/web-framework');\n } catch {\n return null;\n }\n}\n","/**\n * `navigator.clipboard` shim.\n *\n * Inside Apps in Toss → routes `readText` / `writeText` through the SDK\n * (`getClipboardText` / `setClipboardText`).\n *\n * Outside Apps in Toss → defers to the browser's native `navigator.clipboard`.\n * If the browser doesn't implement it, the standard `TypeError` / `DOMException`\n * surfaces unchanged — we don't paper over missing support.\n */\n\nimport { isTossEnvironment, loadTossSdk } from '../detect.js';\n\nconst BACKUP_KEY = Symbol.for('@ait-co/polyfill/clipboard.original');\nconst HAD_KEY = Symbol.for('@ait-co/polyfill/clipboard.hadOriginal');\n\ninterface BackupHost {\n [BACKUP_KEY]?: Clipboard | undefined;\n [HAD_KEY]?: boolean;\n}\n\n/**\n * Produces a Clipboard-compatible object whose `readText` / `writeText` methods\n * route to the SDK when in Toss, else fall through to the supplied `fallback`.\n */\nfunction createClipboardShim(fallback: Clipboard | undefined): Clipboard {\n const shim = {\n async readText(): Promise<string> {\n if (await isTossEnvironment()) {\n const sdk = await loadTossSdk();\n if (sdk?.getClipboardText) {\n return sdk.getClipboardText();\n }\n }\n if (!fallback) {\n throw new DOMException(\n '[@ait-co/polyfill] navigator.clipboard.readText is not available in this environment.',\n 'NotSupportedError',\n );\n }\n return fallback.readText();\n },\n\n async writeText(text: string): Promise<void> {\n if (await isTossEnvironment()) {\n const sdk = await loadTossSdk();\n if (sdk?.setClipboardText) {\n return sdk.setClipboardText(text);\n }\n }\n if (!fallback) {\n throw new DOMException(\n '[@ait-co/polyfill] navigator.clipboard.writeText is not available in this environment.',\n 'NotSupportedError',\n );\n }\n return fallback.writeText(text);\n },\n\n // `read` / `write` (ClipboardItem-based) are passed through to the\n // fallback when in browser mode; the SDK has no rich-content counterpart,\n // so in Toss mode they throw.\n async read(): Promise<ClipboardItems> {\n if (await isTossEnvironment()) {\n throw new DOMException(\n '[@ait-co/polyfill] navigator.clipboard.read (rich content) is not supported in the Apps in Toss environment. Use readText instead.',\n 'NotSupportedError',\n );\n }\n if (!fallback?.read) {\n throw new DOMException(\n '[@ait-co/polyfill] navigator.clipboard.read is not available.',\n 'NotSupportedError',\n );\n }\n return fallback.read();\n },\n\n async write(items: ClipboardItems): Promise<void> {\n if (await isTossEnvironment()) {\n throw new DOMException(\n '[@ait-co/polyfill] navigator.clipboard.write (rich content) is not supported in the Apps in Toss environment. Use writeText instead.',\n 'NotSupportedError',\n );\n }\n if (!fallback?.write) {\n throw new DOMException(\n '[@ait-co/polyfill] navigator.clipboard.write is not available.',\n 'NotSupportedError',\n );\n }\n return fallback.write(items);\n },\n\n // EventTarget passthrough. `navigator.clipboard` extends EventTarget in the\n // spec; mini-apps rarely use it. We forward to the fallback when one exists;\n // in Toss mode (no fallback) we silently drop subscriptions — the SDK emits\n // no clipboard events, so there is nothing to dispatch. This is lossy but\n // preserves the spec-compatible shape.\n addEventListener: (\n ...args: Parameters<EventTarget['addEventListener']>\n ): ReturnType<EventTarget['addEventListener']> => fallback?.addEventListener(...args),\n removeEventListener: (\n ...args: Parameters<EventTarget['removeEventListener']>\n ): ReturnType<EventTarget['removeEventListener']> => fallback?.removeEventListener(...args),\n // Returns `false` in Toss mode (no backing EventTarget). A caller that reads\n // this as \"default action cancelled\" should check context — there are no\n // listeners to run because the SDK doesn't surface clipboard events.\n dispatchEvent: (event: Event): boolean => fallback?.dispatchEvent(event) ?? false,\n } satisfies Clipboard;\n\n return shim;\n}\n\n/**\n * Install the `navigator.clipboard` shim.\n *\n * @returns an uninstall function that restores the original `navigator.clipboard`.\n * Calling install twice without uninstalling is a no-op on the second call\n * and returns the same uninstall function.\n */\nexport function installClipboardShim(): () => void {\n if (typeof navigator === 'undefined') {\n // No-op in non-DOM environments (pure Node).\n return () => {};\n }\n\n const host = navigator as unknown as BackupHost;\n if (BACKUP_KEY in host) {\n // Already installed. Use `in` (not `!== undefined`) because the stored\n // backup is legitimately `undefined` when the browser has no native\n // `navigator.clipboard` — without this, we'd re-wrap on each install.\n // Note: the returned uninstall is global. Any caller's uninstall fully\n // removes the shim; callers do not have independent install handles.\n return () => uninstallClipboardShim();\n }\n\n const original = navigator.clipboard as Clipboard | undefined;\n host[BACKUP_KEY] = original;\n host[HAD_KEY] = 'clipboard' in navigator;\n\n const shim = createClipboardShim(original);\n Object.defineProperty(navigator, 'clipboard', {\n value: shim,\n configurable: true,\n writable: true,\n });\n\n return uninstallClipboardShim;\n}\n\n/**\n * Remove the shim and restore the pre-install shape. Uses delete + conditional\n * redefine so a prototype-level `navigator.clipboard` (non-configurable in real\n * browsers) becomes visible again instead of being permanently shadowed.\n */\nexport function uninstallClipboardShim(): void {\n if (typeof navigator === 'undefined') return;\n const host = navigator as unknown as BackupHost;\n if (!(BACKUP_KEY in host)) return;\n\n const original = host[BACKUP_KEY];\n const had = host[HAD_KEY];\n delete (navigator as unknown as { clipboard?: Clipboard }).clipboard;\n if (had && navigator.clipboard !== original) {\n Object.defineProperty(navigator, 'clipboard', {\n value: original,\n configurable: true,\n writable: true,\n });\n }\n delete host[BACKUP_KEY];\n delete host[HAD_KEY];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkBA,IAAI;;;;;;;;AAgCJ,eAAsB,oBAAsC;CAG1D,MAAM,QAAQ,WAAW;AACzB,KAAI,UAAU,OAAQ,QAAO;AAC7B,KAAI,UAAU,UAAW,QAAO;AAEhC,KAAI,WAAW,KAAA,EAAW,QAAO;CAEjC,MAAM,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AU,iBAAiB,GAAG,KAAK;EACrF,sBACE,GAAG,SACgD,UAAU,oBAAoB,GAAG,KAAK;EAI3F,gBAAgB,UAA0B,UAAU,cAAc,MAAM,IAAI;EAC7E;;;;;;;;;AAYH,SAAgB,uBAAmC;AACjD,KAAI,OAAO,cAAc,YAEvB,cAAa;CAGf,MAAM,OAAO;AACb,KAAI,cAAc,KAMhB,cAAa,wBAAwB;CAGvC,MAAM,WAAW,UAAU;AAC3B,MAAK,cAAc;AACnB,MAAK,WAAW,eAAe;CAE/B,MAAM,OAAO,oBAAoB,SAAS;AAC1C,QAAO,eAAe,WAAW,aAAa;EAC5C,OAAO;EACP,cAAc;EACd,UAAU;EACX,CAAC;AAEF,QAAO;;;;;;;AAQT,SAAgB,yBAA+B;AAC7C,KAAI,OAAO,cAAc,YAAa;CACtC,MAAM,OAAO;AACb,KAAI,EAAE,cAAc,MAAO;CAE3B,MAAM,WAAW,KAAK;CACtB,MAAM,MAAM,KAAK;AACjB,QAAQ,UAAmD;AAC3D,KAAI,OAAO,UAAU,cAAc,SACjC,QAAO,eAAe,WAAW,aAAa;EAC5C,OAAO;EACP,cAAc;EACd,UAAU;EACX,CAAC;AAEJ,QAAO,KAAK;AACZ,QAAO,KAAK"}
1
+ {"version":3,"file":"clipboard.js","names":[],"sources":["../../src/detect.ts","../../src/shims/_install-helpers.ts","../../src/shims/clipboard.ts"],"sourcesContent":["/**\n * Environment detection: are we running inside Apps in Toss, or a plain browser?\n *\n * Strategy: call the SDK's `getAppsInTossGlobals()` — a synchronous export\n * that returns the runtime's Toss globals (deploymentId, brand name, …)\n * inside the Apps in Toss runtime and throws (RN bridge unavailable)\n * anywhere else. The SDK itself is an **optional** peer dependency; if its\n * module can't be imported we are definitely not inside Toss.\n *\n * Just having the SDK module resolvable is not enough — apps can bundle it\n * and still run in a plain browser. We need the bridge probe to confirm.\n *\n * UA sniffing (spoofable) is avoided. We do call `getAppsInTossGlobals`, but\n * that's a constant read from the bridge — no permission dialogs, no\n * analytics fire. In a plain browser the bridge lookup fails fast (sync\n * throw, microsecond-scale), so the startup cost is negligible.\n */\n\nlet cached: boolean | undefined;\n\n/**\n * Reset the cached detection result. Primarily for tests.\n */\nexport function resetDetection(): void {\n cached = undefined;\n}\n\n/**\n * Synchronous read of the cached detection result. Returns:\n * - `true` / `false` if an override is active or the async detection has\n * already resolved\n * - `undefined` if detection hasn't run yet\n *\n * Used by spec-sync APIs (e.g. `navigator.canShare`) that can't `await`\n * detection.\n */\nexport function isTossEnvironmentCached(): boolean | undefined {\n const force = globalThis.__AIT_POLYFILL_FORCE__;\n if (force === 'toss') return true;\n if (force === 'browser') return false;\n return cached;\n}\n\n/**\n * Returns `true` iff we detect we are running in an environment where the\n * Apps in Toss SDK (`@apps-in-toss/web-framework`) is present and usable.\n *\n * Async because we use dynamic `import()` to probe the optional peer dep\n * without forcing it into the consumer's bundle.\n */\nexport async function isTossEnvironment(): Promise<boolean> {\n // Override check precedes cache so `devtools` / tests can flip the result\n // mid-session without a `resetDetection()` call.\n const force = globalThis.__AIT_POLYFILL_FORCE__;\n if (force === 'toss') return true;\n if (force === 'browser') return false;\n\n if (cached !== undefined) return cached;\n\n const mod = await loadTossSdk();\n if (typeof mod?.getAppsInTossGlobals !== 'function') {\n cached = false;\n return cached;\n }\n // Inside Toss the bridge returns a populated globals object. In a plain\n // browser the RN bridge isn't attached and the call throws — that's our\n // signal. Any non-throwing call with an object return is treated as Toss.\n try {\n const globals = mod.getAppsInTossGlobals();\n cached = Boolean(globals) && typeof globals === 'object';\n } catch {\n cached = false;\n }\n return cached;\n}\n\n/**\n * Lazy SDK accessor — returns the module if available, else `null`. Callers\n * are expected to `await` and null-check. Never throws.\n */\nexport async function loadTossSdk(): Promise<typeof import('@apps-in-toss/web-framework') | null> {\n try {\n return await import('@apps-in-toss/web-framework');\n } catch {\n return null;\n }\n}\n","/**\n * Shared helpers for installing shims on `navigator`.\n *\n * Chromium now marks a handful of `navigator` properties (e.g. `geolocation`,\n * `clipboard`) as non-configurable **own** properties on the instance. That\n * means a plain `Object.defineProperty(navigator, 'x', …)` throws\n * `TypeError: Cannot redefine property`.\n *\n * The workaround is to shim at the prototype level — `Navigator.prototype`\n * keeps these as configurable accessors, so we can swap them there and every\n * instance that falls through to the prototype (including `window.navigator`)\n * sees the shim. We only reach for the prototype when the instance-level\n * assignment refuses.\n *\n * For restoration we remember the descriptor chain (instance + prototype) so\n * `uninstall()` puts the browser back in its original state.\n */\n\ntype PropertyLocation = 'instance' | 'prototype';\n\nexport interface InstallSnapshot {\n /** Where we ended up writing the shim. */\n location: PropertyLocation;\n /** Original descriptor at that location (may be undefined if nothing was there). */\n originalDescriptor: PropertyDescriptor | undefined;\n /** `true` iff the original property lived on the instance before we touched it. */\n instanceHadOwn: boolean;\n}\n\n/**\n * Install `descriptor` at `navigator[prop]`. Prefer instance-level; if the\n * browser refuses (property is non-configurable on the instance), install on\n * `Navigator.prototype` instead.\n *\n * Returns a snapshot describing where the original value was, which\n * `restoreNavigatorProperty` uses to undo the install.\n */\nexport function installNavigatorProperty(\n prop: string,\n descriptor: PropertyDescriptor,\n): InstallSnapshot {\n const nav = navigator as unknown as Record<PropertyKey, unknown>;\n const instanceDesc = Object.getOwnPropertyDescriptor(nav, prop);\n const instanceHadOwn = instanceDesc !== undefined;\n\n // Fast path: instance-level property is missing or configurable.\n if (!instanceDesc || instanceDesc.configurable) {\n try {\n Object.defineProperty(nav, prop, descriptor);\n return { location: 'instance', originalDescriptor: instanceDesc, instanceHadOwn };\n } catch {\n // Fall through to prototype-level install.\n }\n }\n\n // Prototype-level install. Drop the instance-level shadow so the prototype\n // accessor is visible to readers on `navigator`.\n const proto = Object.getPrototypeOf(nav) as object;\n const protoDesc = Object.getOwnPropertyDescriptor(proto, prop);\n\n if (instanceHadOwn) {\n // Try to remove the instance-level shadow. On non-configurable it throws —\n // we deliberately ignore that; prototype-level install still wins because\n // the prototype accessor shows through when we read via `navigator[prop]`.\n try {\n delete nav[prop];\n } catch {\n /* non-configurable own — leave it; prototype install still useful */\n }\n }\n\n Object.defineProperty(proto, prop, descriptor);\n return { location: 'prototype', originalDescriptor: protoDesc, instanceHadOwn };\n}\n\n/**\n * Reverse the install recorded in `snapshot`. If the original descriptor was\n * `undefined` (property didn't exist before), delete the property instead of\n * re-defining it.\n */\nexport function restoreNavigatorProperty(prop: string, snapshot: InstallSnapshot): void {\n const target =\n snapshot.location === 'instance'\n ? (navigator as unknown as Record<PropertyKey, unknown>)\n : (Object.getPrototypeOf(navigator) as object);\n\n if (snapshot.originalDescriptor) {\n try {\n Object.defineProperty(target, prop, snapshot.originalDescriptor);\n } catch {\n /* descriptor was non-configurable upstream; we can't undo — rare. */\n }\n } else {\n try {\n // biome-ignore lint/performance/noDelete: property deletion is the uninstall intent\n delete (target as Record<PropertyKey, unknown>)[prop];\n } catch {\n /* non-configurable — rare. */\n }\n }\n\n // If our install pushed past an instance shadow, we leave the instance alone\n // — the descriptor we captured for `instanceHadOwn: true` lives on the\n // instance and was not modified at install time.\n}\n","/**\n * `navigator.clipboard` shim.\n *\n * Inside Apps in Toss → routes `readText` / `writeText` through the SDK\n * (`getClipboardText` / `setClipboardText`).\n *\n * Outside Apps in Toss → defers to the browser's native `navigator.clipboard`.\n * If the browser doesn't implement it, the standard `TypeError` / `DOMException`\n * surfaces unchanged — we don't paper over missing support.\n */\n\nimport { isTossEnvironment, loadTossSdk } from '../detect.js';\nimport {\n type InstallSnapshot,\n installNavigatorProperty,\n restoreNavigatorProperty,\n} from './_install-helpers.js';\n\nconst BACKUP_KEY = Symbol.for('@ait-co/polyfill/clipboard.original');\nconst SNAPSHOT_KEY = Symbol.for('@ait-co/polyfill/clipboard.snapshot');\n\ninterface BackupHost {\n [BACKUP_KEY]?: Clipboard | undefined;\n [SNAPSHOT_KEY]?: InstallSnapshot | undefined;\n}\n\n/**\n * Produces a Clipboard-compatible object whose `readText` / `writeText` methods\n * route to the SDK when in Toss, else fall through to the supplied `fallback`.\n */\nfunction createClipboardShim(fallback: Clipboard | undefined): Clipboard {\n const shim = {\n async readText(): Promise<string> {\n if (await isTossEnvironment()) {\n const sdk = await loadTossSdk();\n if (sdk?.getClipboardText) {\n return sdk.getClipboardText();\n }\n }\n if (!fallback) {\n throw new DOMException(\n '[@ait-co/polyfill] navigator.clipboard.readText is not available in this environment.',\n 'NotSupportedError',\n );\n }\n return fallback.readText();\n },\n\n async writeText(text: string): Promise<void> {\n if (await isTossEnvironment()) {\n const sdk = await loadTossSdk();\n if (sdk?.setClipboardText) {\n return sdk.setClipboardText(text);\n }\n }\n if (!fallback) {\n throw new DOMException(\n '[@ait-co/polyfill] navigator.clipboard.writeText is not available in this environment.',\n 'NotSupportedError',\n );\n }\n return fallback.writeText(text);\n },\n\n // `read` / `write` (ClipboardItem-based) are passed through to the\n // fallback when in browser mode; the SDK has no rich-content counterpart,\n // so in Toss mode they throw.\n async read(): Promise<ClipboardItems> {\n if (await isTossEnvironment()) {\n throw new DOMException(\n '[@ait-co/polyfill] navigator.clipboard.read (rich content) is not supported in the Apps in Toss environment. Use readText instead.',\n 'NotSupportedError',\n );\n }\n if (!fallback?.read) {\n throw new DOMException(\n '[@ait-co/polyfill] navigator.clipboard.read is not available.',\n 'NotSupportedError',\n );\n }\n return fallback.read();\n },\n\n async write(items: ClipboardItems): Promise<void> {\n if (await isTossEnvironment()) {\n throw new DOMException(\n '[@ait-co/polyfill] navigator.clipboard.write (rich content) is not supported in the Apps in Toss environment. Use writeText instead.',\n 'NotSupportedError',\n );\n }\n if (!fallback?.write) {\n throw new DOMException(\n '[@ait-co/polyfill] navigator.clipboard.write is not available.',\n 'NotSupportedError',\n );\n }\n return fallback.write(items);\n },\n\n // EventTarget passthrough. `navigator.clipboard` extends EventTarget in the\n // spec; mini-apps rarely use it. We forward to the fallback when one exists;\n // in Toss mode (no fallback) we silently drop subscriptions — the SDK emits\n // no clipboard events, so there is nothing to dispatch. This is lossy but\n // preserves the spec-compatible shape.\n addEventListener: (\n ...args: Parameters<EventTarget['addEventListener']>\n ): ReturnType<EventTarget['addEventListener']> => fallback?.addEventListener(...args),\n removeEventListener: (\n ...args: Parameters<EventTarget['removeEventListener']>\n ): ReturnType<EventTarget['removeEventListener']> => fallback?.removeEventListener(...args),\n // Returns `false` in Toss mode (no backing EventTarget). A caller that reads\n // this as \"default action cancelled\" should check context — there are no\n // listeners to run because the SDK doesn't surface clipboard events.\n dispatchEvent: (event: Event): boolean => fallback?.dispatchEvent(event) ?? false,\n } satisfies Clipboard;\n\n return shim;\n}\n\n/**\n * Install the `navigator.clipboard` shim.\n *\n * @returns an uninstall function that restores the original `navigator.clipboard`.\n * Calling install twice without uninstalling is a no-op on the second call\n * and returns the same uninstall function.\n */\nexport function installClipboardShim(): () => void {\n if (typeof navigator === 'undefined') {\n // No-op in non-DOM environments (pure Node).\n return () => {};\n }\n\n const host = navigator as unknown as BackupHost;\n if (BACKUP_KEY in host) {\n // Already installed. Use `in` (not `!== undefined`) because the stored\n // backup is legitimately `undefined` when the browser has no native\n // `navigator.clipboard` — without this, we'd re-wrap on each install.\n // Note: the returned uninstall is global. Any caller's uninstall fully\n // removes the shim; callers do not have independent install handles.\n return () => uninstallClipboardShim();\n }\n\n const original = navigator.clipboard as Clipboard | undefined;\n host[BACKUP_KEY] = original;\n\n const shim = createClipboardShim(original);\n host[SNAPSHOT_KEY] = installNavigatorProperty('clipboard', {\n value: shim,\n configurable: true,\n writable: true,\n });\n\n return uninstallClipboardShim;\n}\n\n/**\n * Remove the shim and restore the pre-install shape.\n */\nexport function uninstallClipboardShim(): void {\n if (typeof navigator === 'undefined') return;\n const host = navigator as unknown as BackupHost;\n if (!(BACKUP_KEY in host)) return;\n\n const snapshot = host[SNAPSHOT_KEY];\n if (snapshot) restoreNavigatorProperty('clipboard', snapshot);\n delete host[BACKUP_KEY];\n delete host[SNAPSHOT_KEY];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkBA,IAAI;;;;;;;;AAgCJ,eAAsB,oBAAsC;CAG1D,MAAM,QAAQ,WAAW;AAC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C;AAEF,QAAO;;;;;AAMT,SAAgB,yBAA+B;AAC7C,KAAI,OAAO,cAAc,YAAa;CACtC,MAAM,OAAO;AACb,KAAI,EAAE,cAAc,MAAO;CAE3B,MAAM,WAAW,KAAK;AACtB,KAAI,SAAU,0BAAyB,aAAa,SAAS;AAC7D,QAAO,KAAK;AACZ,QAAO,KAAK"}
@@ -1 +1 @@
1
- {"version":3,"file":"geolocation.d.ts","names":[],"sources":["../../src/shims/geolocation.ts"],"mappings":";;AAsQA;;;;;AAuBA;;;;;;;;;;;;;;;;;;;;;;iBAvBgB,sBAAA,CAAA;AAAA,iBAuBA,wBAAA,CAAA"}
1
+ {"version":3,"file":"geolocation.d.ts","names":[],"sources":["../../src/shims/geolocation.ts"],"mappings":";;AA6QA;;;;;AAuBA;;;;;;;;;;;;;;;;;;;;;;iBAvBgB,sBAAA,CAAA;AAAA,iBAuBA,wBAAA,CAAA"}
@@ -54,6 +54,54 @@ async function loadTossSdk() {
54
54
  }
55
55
  }
56
56
  //#endregion
57
+ //#region src/shims/_install-helpers.ts
58
+ /**
59
+ * Install `descriptor` at `navigator[prop]`. Prefer instance-level; if the
60
+ * browser refuses (property is non-configurable on the instance), install on
61
+ * `Navigator.prototype` instead.
62
+ *
63
+ * Returns a snapshot describing where the original value was, which
64
+ * `restoreNavigatorProperty` uses to undo the install.
65
+ */
66
+ function installNavigatorProperty(prop, descriptor) {
67
+ const nav = navigator;
68
+ const instanceDesc = Object.getOwnPropertyDescriptor(nav, prop);
69
+ const instanceHadOwn = instanceDesc !== void 0;
70
+ if (!instanceDesc || instanceDesc.configurable) try {
71
+ Object.defineProperty(nav, prop, descriptor);
72
+ return {
73
+ location: "instance",
74
+ originalDescriptor: instanceDesc,
75
+ instanceHadOwn
76
+ };
77
+ } catch {}
78
+ const proto = Object.getPrototypeOf(nav);
79
+ const protoDesc = Object.getOwnPropertyDescriptor(proto, prop);
80
+ if (instanceHadOwn) try {
81
+ delete nav[prop];
82
+ } catch {}
83
+ Object.defineProperty(proto, prop, descriptor);
84
+ return {
85
+ location: "prototype",
86
+ originalDescriptor: protoDesc,
87
+ instanceHadOwn
88
+ };
89
+ }
90
+ /**
91
+ * Reverse the install recorded in `snapshot`. If the original descriptor was
92
+ * `undefined` (property didn't exist before), delete the property instead of
93
+ * re-defining it.
94
+ */
95
+ function restoreNavigatorProperty(prop, snapshot) {
96
+ const target = snapshot.location === "instance" ? navigator : Object.getPrototypeOf(navigator);
97
+ if (snapshot.originalDescriptor) try {
98
+ Object.defineProperty(target, prop, snapshot.originalDescriptor);
99
+ } catch {}
100
+ else try {
101
+ delete target[prop];
102
+ } catch {}
103
+ }
104
+ //#endregion
57
105
  //#region src/shims/geolocation.ts
58
106
  /**
59
107
  * `navigator.geolocation` shim.
@@ -84,6 +132,7 @@ async function loadTossSdk() {
84
132
  * `uninstall()`.
85
133
  */
86
134
  const BACKUP_KEY = Symbol.for("@ait-co/polyfill/geolocation.original");
135
+ const SNAPSHOT_KEY = Symbol.for("@ait-co/polyfill/geolocation.snapshot");
87
136
  const ACCURACY_BALANCED = 3;
88
137
  const ACCURACY_HIGH = 4;
89
138
  function toStandardPosition(sdk) {
@@ -240,9 +289,8 @@ function installGeolocationShim() {
240
289
  if (BACKUP_KEY in host) return () => uninstallGeolocationShim();
241
290
  const original = navigator.geolocation;
242
291
  host[BACKUP_KEY] = original;
243
- const shim = createGeolocationShim(original);
244
- Object.defineProperty(navigator, "geolocation", {
245
- value: shim,
292
+ host[SNAPSHOT_KEY] = installNavigatorProperty("geolocation", {
293
+ value: createGeolocationShim(original),
246
294
  configurable: true,
247
295
  writable: true
248
296
  });
@@ -252,14 +300,10 @@ function uninstallGeolocationShim() {
252
300
  if (typeof navigator === "undefined") return;
253
301
  const host = navigator;
254
302
  if (!(BACKUP_KEY in host)) return;
255
- const original = host[BACKUP_KEY];
256
- delete navigator.geolocation;
257
- if (original !== void 0 && navigator.geolocation !== original) Object.defineProperty(navigator, "geolocation", {
258
- value: original,
259
- configurable: true,
260
- writable: true
261
- });
303
+ const snapshot = host[SNAPSHOT_KEY];
304
+ if (snapshot) restoreNavigatorProperty("geolocation", snapshot);
262
305
  delete host[BACKUP_KEY];
306
+ delete host[SNAPSHOT_KEY];
263
307
  }
264
308
  //#endregion
265
309
  export { installGeolocationShim, uninstallGeolocationShim };
@@ -1 +1 @@
1
- {"version":3,"file":"geolocation.js","names":[],"sources":["../../src/detect.ts","../../src/shims/geolocation.ts"],"sourcesContent":["/**\n * Environment detection: are we running inside Apps in Toss, or a plain browser?\n *\n * Strategy: call the SDK's `getAppsInTossGlobals()` — a synchronous export\n * that returns the runtime's Toss globals (deploymentId, brand name, …)\n * inside the Apps in Toss runtime and throws (RN bridge unavailable)\n * anywhere else. The SDK itself is an **optional** peer dependency; if its\n * module can't be imported we are definitely not inside Toss.\n *\n * Just having the SDK module resolvable is not enough — apps can bundle it\n * and still run in a plain browser. We need the bridge probe to confirm.\n *\n * UA sniffing (spoofable) is avoided. We do call `getAppsInTossGlobals`, but\n * that's a constant read from the bridge — no permission dialogs, no\n * analytics fire. In a plain browser the bridge lookup fails fast (sync\n * throw, microsecond-scale), so the startup cost is negligible.\n */\n\nlet cached: boolean | undefined;\n\n/**\n * Reset the cached detection result. Primarily for tests.\n */\nexport function resetDetection(): void {\n cached = undefined;\n}\n\n/**\n * Synchronous read of the cached detection result. Returns:\n * - `true` / `false` if an override is active or the async detection has\n * already resolved\n * - `undefined` if detection hasn't run yet\n *\n * Used by spec-sync APIs (e.g. `navigator.canShare`) that can't `await`\n * detection.\n */\nexport function isTossEnvironmentCached(): boolean | undefined {\n const force = globalThis.__AIT_POLYFILL_FORCE__;\n if (force === 'toss') return true;\n if (force === 'browser') return false;\n return cached;\n}\n\n/**\n * Returns `true` iff we detect we are running in an environment where the\n * Apps in Toss SDK (`@apps-in-toss/web-framework`) is present and usable.\n *\n * Async because we use dynamic `import()` to probe the optional peer dep\n * without forcing it into the consumer's bundle.\n */\nexport async function isTossEnvironment(): Promise<boolean> {\n // Override check precedes cache so `devtools` / tests can flip the result\n // mid-session without a `resetDetection()` call.\n const force = globalThis.__AIT_POLYFILL_FORCE__;\n if (force === 'toss') return true;\n if (force === 'browser') return false;\n\n if (cached !== undefined) return cached;\n\n const mod = await loadTossSdk();\n if (typeof mod?.getAppsInTossGlobals !== 'function') {\n cached = false;\n return cached;\n }\n // Inside Toss the bridge returns a populated globals object. In a plain\n // browser the RN bridge isn't attached and the call throws — that's our\n // signal. Any non-throwing call with an object return is treated as Toss.\n try {\n const globals = mod.getAppsInTossGlobals();\n cached = Boolean(globals) && typeof globals === 'object';\n } catch {\n cached = false;\n }\n return cached;\n}\n\n/**\n * Lazy SDK accessor — returns the module if available, else `null`. Callers\n * are expected to `await` and null-check. Never throws.\n */\nexport async function loadTossSdk(): Promise<typeof import('@apps-in-toss/web-framework') | null> {\n try {\n return await import('@apps-in-toss/web-framework');\n } catch {\n return null;\n }\n}\n","/**\n * `navigator.geolocation` shim.\n *\n * Inside Apps in Toss → routes through the SDK:\n * - `getCurrentPosition` → `getCurrentLocation({ accuracy })`\n * - `watchPosition` / `clearWatch` → `startUpdateLocation({ onEvent, onError, options })`\n *\n * Outside Apps in Toss → defers to the browser's native `navigator.geolocation`.\n * If neither is available, the error callback receives a `GeolocationPositionError`.\n *\n * SDK/Web shape mismatch handled here:\n * - SDK `Accuracy` is a numeric enum (1 = Lowest … 6 = BestForNavigation); the\n * standard `PositionOptions.enableHighAccuracy` is a boolean. We map\n * `true → Accuracy.High (4, \"~10m\")` and `false → Accuracy.Balanced (3)`.\n * `Highest (5)` / `BestForNavigation (6)` are available but carry a battery\n * cost that's rarely what mini-apps want; consumers who need them should\n * call the SDK directly.\n * - SDK coords lack `speed`; we surface `null` (per the W3C spec when unknown).\n * - SDK `startUpdateLocation` returns an `unsubscribe` fn; we wrap it behind\n * a numeric watch id so `clearWatch(id)` behaves like the standard.\n *\n * Caveat: watch ids reset whenever the shim is uninstalled and reinstalled;\n * they are not stable across such cycles. Ids obtained before uninstall\n * cannot be cleared after uninstall — `clearWatch(id)` on the restored native\n * `navigator.geolocation` uses a different id space, so the SDK subscription\n * leaks. Consumers should `clearWatch` all outstanding ids before calling\n * `uninstall()`.\n */\n\nimport { isTossEnvironment, loadTossSdk } from '../detect.js';\n\nconst BACKUP_KEY = Symbol.for('@ait-co/polyfill/geolocation.original');\n\ninterface BackupHost {\n [BACKUP_KEY]?: Geolocation | undefined;\n}\n\n// SDK Accuracy enum values. We don't import the enum at runtime (peer is\n// optional), so we hard-code the numeric constants used by the SDK. Stable\n// ABI per the SDK's exported numeric enum.\nconst ACCURACY_BALANCED = 3;\nconst ACCURACY_HIGH = 4;\n\ninterface SdkLocationCoords {\n latitude: number;\n longitude: number;\n altitude: number;\n accuracy: number;\n altitudeAccuracy: number;\n heading: number;\n}\n\ninterface SdkLocation {\n timestamp: number;\n coords: SdkLocationCoords;\n}\n\nfunction toStandardPosition(sdk: SdkLocation): GeolocationPosition {\n const coordsData = {\n latitude: sdk.coords.latitude,\n longitude: sdk.coords.longitude,\n altitude: sdk.coords.altitude,\n accuracy: sdk.coords.accuracy,\n altitudeAccuracy: sdk.coords.altitudeAccuracy,\n heading: sdk.coords.heading,\n // SDK does not surface speed. Per spec, null means \"unknown\".\n speed: null,\n };\n const coords: GeolocationCoordinates = {\n ...coordsData,\n toJSON() {\n return { ...coordsData };\n },\n };\n return {\n coords,\n timestamp: sdk.timestamp,\n toJSON() {\n return { coords: { ...coordsData }, timestamp: sdk.timestamp };\n },\n };\n}\n\nfunction toPositionError(code: 1 | 2 | 3, message: string): GeolocationPositionError {\n // Prefer the real constructor when available (every real browser ships it).\n // The spec says GeolocationPositionError is not constructable, so we fall\n // through to a fabricated object whose prototype is patched via\n // `setPrototypeOf` — that keeps `instanceof` checks in consumer code working\n // and picks up the spec's PERMISSION_DENIED / POSITION_UNAVAILABLE / TIMEOUT\n // constants from the real prototype rather than hard-coding them (avoids\n // drift if the spec ever grows a new code).\n const Ctor = (globalThis as { GeolocationPositionError?: unknown }).GeolocationPositionError;\n if (typeof Ctor === 'function') {\n const proto = (Ctor as { prototype?: object }).prototype;\n if (proto) {\n const shape: { code: number; message: string } = { code, message };\n Object.setPrototypeOf(shape, proto);\n return shape as GeolocationPositionError;\n }\n }\n // jsdom / last-resort fallback: fabricate the spec shape with hard-coded\n // constants since there's no prototype to delegate to.\n return {\n code,\n message,\n PERMISSION_DENIED: 1,\n POSITION_UNAVAILABLE: 2,\n TIMEOUT: 3,\n } as GeolocationPositionError;\n}\n\nfunction accuracyFromOptions(options: PositionOptions | undefined): number {\n return options?.enableHighAccuracy ? ACCURACY_HIGH : ACCURACY_BALANCED;\n}\n\nfunction createGeolocationShim(fallback: Geolocation | undefined): Geolocation {\n // Numeric watch id → SDK unsubscribe fn. Keeps the shim's API in line with\n // the standard even though the SDK issues unsubscribe closures instead.\n // `pendingWatches` closes the race where `clearWatch` is called before the\n // async `watchPosition` installer resolves — without it we'd leak the SDK\n // subscription.\n let nextWatchId = 1;\n const sdkWatches = new Map<number, () => void>();\n const nativeWatches = new Map<number, number>();\n const pendingWatches = new Map<number, { cancelled: boolean }>();\n\n const shim: Geolocation = {\n getCurrentPosition(success, error, options) {\n void (async () => {\n if (await isTossEnvironment()) {\n const sdk = await loadTossSdk();\n const fn = (sdk as { getCurrentLocation?: unknown } | null)?.getCurrentLocation;\n if (typeof fn === 'function') {\n try {\n const loc = (await (fn as (o: { accuracy: number }) => Promise<SdkLocation>)({\n accuracy: accuracyFromOptions(options),\n })) as SdkLocation;\n success(toStandardPosition(loc));\n } catch (e) {\n error?.(\n toPositionError(\n 2,\n e instanceof Error ? e.message : '[@ait-co/polyfill] getCurrentLocation failed.',\n ),\n );\n }\n return;\n }\n }\n if (!fallback) {\n error?.(\n toPositionError(\n 2,\n '[@ait-co/polyfill] navigator.geolocation is not available in this environment.',\n ),\n );\n return;\n }\n fallback.getCurrentPosition(success, error, options);\n })();\n },\n\n watchPosition(success, error, options) {\n const id = nextWatchId++;\n const pending = { cancelled: false };\n pendingWatches.set(id, pending);\n\n void (async () => {\n if (await isTossEnvironment()) {\n const sdk = await loadTossSdk();\n const fn = (sdk as { startUpdateLocation?: unknown } | null)?.startUpdateLocation;\n if (typeof fn === 'function') {\n if (pending.cancelled) {\n pendingWatches.delete(id);\n return;\n }\n const unsubscribe = (\n fn as (p: {\n onEvent: (loc: SdkLocation) => void;\n onError: (err: unknown) => void;\n options: { accuracy: number; timeInterval: number; distanceInterval: number };\n }) => () => void\n )({\n onEvent: (loc) => success(toStandardPosition(loc)),\n onError: (err) =>\n error?.(\n toPositionError(\n 2,\n err instanceof Error\n ? err.message\n : '[@ait-co/polyfill] startUpdateLocation failed.',\n ),\n ),\n options: {\n accuracy: accuracyFromOptions(options),\n // Sensible defaults — web `watchPosition` has no analogues.\n // Consumers needing sub-second updates should use the SDK directly.\n timeInterval: 1000,\n distanceInterval: 0,\n },\n });\n if (pending.cancelled) {\n unsubscribe();\n pendingWatches.delete(id);\n return;\n }\n sdkWatches.set(id, unsubscribe);\n pendingWatches.delete(id);\n return;\n }\n }\n if (!fallback) {\n pendingWatches.delete(id);\n error?.(\n toPositionError(\n 2,\n '[@ait-co/polyfill] navigator.geolocation is not available in this environment.',\n ),\n );\n return;\n }\n if (pending.cancelled) {\n pendingWatches.delete(id);\n return;\n }\n const nativeId = fallback.watchPosition(success, error, options);\n if (pending.cancelled) {\n fallback.clearWatch(nativeId);\n pendingWatches.delete(id);\n return;\n }\n nativeWatches.set(id, nativeId);\n pendingWatches.delete(id);\n })();\n\n return id;\n },\n\n clearWatch(id) {\n const pending = pendingWatches.get(id);\n if (pending) {\n pending.cancelled = true;\n pendingWatches.delete(id);\n return;\n }\n const unsubscribe = sdkWatches.get(id);\n if (unsubscribe) {\n unsubscribe();\n sdkWatches.delete(id);\n return;\n }\n const nativeId = nativeWatches.get(id);\n if (nativeId !== undefined && fallback) {\n fallback.clearWatch(nativeId);\n nativeWatches.delete(id);\n }\n },\n };\n\n return shim;\n}\n\nexport function installGeolocationShim(): () => void {\n if (typeof navigator === 'undefined') {\n return () => {};\n }\n\n const host = navigator as unknown as BackupHost;\n if (BACKUP_KEY in host) {\n return () => uninstallGeolocationShim();\n }\n\n const original = navigator.geolocation as Geolocation | undefined;\n host[BACKUP_KEY] = original;\n\n const shim = createGeolocationShim(original);\n Object.defineProperty(navigator, 'geolocation', {\n value: shim,\n configurable: true,\n writable: true,\n });\n\n return uninstallGeolocationShim;\n}\n\nexport function uninstallGeolocationShim(): void {\n if (typeof navigator === 'undefined') return;\n const host = navigator as unknown as BackupHost;\n if (!(BACKUP_KEY in host)) return;\n\n const original = host[BACKUP_KEY];\n // Delete our instance-level override so the prototype getter (on real\n // browsers) shows through again. `defineProperty` with value would leave\n // a permanent instance shadow.\n delete (navigator as unknown as { geolocation?: Geolocation }).geolocation;\n if (original !== undefined && navigator.geolocation !== original) {\n // In jsdom or test shims where the original lived on the instance, put it\n // back explicitly — the delete above would otherwise leave nothing behind.\n Object.defineProperty(navigator, 'geolocation', {\n value: original,\n configurable: true,\n writable: true,\n });\n }\n delete host[BACKUP_KEY];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkBA,IAAI;;;;;;;;AAgCJ,eAAsB,oBAAsC;CAG1D,MAAM,QAAQ,WAAW;AACzB,KAAI,UAAU,OAAQ,QAAO;AAC7B,KAAI,UAAU,UAAW,QAAO;AAEhC,KAAI,WAAW,KAAA,EAAW,QAAO;CAEjC,MAAM,MAAM,MAAM,aAAa;AAC/B,KAAI,OAAO,KAAK,yBAAyB,YAAY;AACnD,WAAS;AACT,SAAO;;AAKT,KAAI;EACF,MAAM,UAAU,IAAI,sBAAsB;AAC1C,WAAS,QAAQ,QAAQ,IAAI,OAAO,YAAY;SAC1C;AACN,WAAS;;AAEX,QAAO;;;;;;AAOT,eAAsB,cAA4E;AAChG,KAAI;AACF,SAAO,MAAM,OAAO;SACd;AACN,SAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACrDX,MAAM,aAAa,OAAO,IAAI,wCAAwC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,OAAI,SAAS;AACX,YAAQ,YAAY;AACpB,mBAAe,OAAO,GAAG;AACzB;;GAEF,MAAM,cAAc,WAAW,IAAI,GAAG;AACtC,OAAI,aAAa;AACf,iBAAa;AACb,eAAW,OAAO,GAAG;AACrB;;GAEF,MAAM,WAAW,cAAc,IAAI,GAAG;AACtC,OAAI,aAAa,KAAA,KAAa,UAAU;AACtC,aAAS,WAAW,SAAS;AAC7B,kBAAc,OAAO,GAAG;;;EAG7B;;AAKH,SAAgB,yBAAqC;AACnD,KAAI,OAAO,cAAc,YACvB,cAAa;CAGf,MAAM,OAAO;AACb,KAAI,cAAc,KAChB,cAAa,0BAA0B;CAGzC,MAAM,WAAW,UAAU;AAC3B,MAAK,cAAc;CAEnB,MAAM,OAAO,sBAAsB,SAAS;AAC5C,QAAO,eAAe,WAAW,eAAe;EAC9C,OAAO;EACP,cAAc;EACd,UAAU;EACX,CAAC;AAEF,QAAO;;AAGT,SAAgB,2BAAiC;AAC/C,KAAI,OAAO,cAAc,YAAa;CACtC,MAAM,OAAO;AACb,KAAI,EAAE,cAAc,MAAO;CAE3B,MAAM,WAAW,KAAK;AAItB,QAAQ,UAAuD;AAC/D,KAAI,aAAa,KAAA,KAAa,UAAU,gBAAgB,SAGtD,QAAO,eAAe,WAAW,eAAe;EAC9C,OAAO;EACP,cAAc;EACd,UAAU;EACX,CAAC;AAEJ,QAAO,KAAK"}
1
+ {"version":3,"file":"geolocation.js","names":[],"sources":["../../src/detect.ts","../../src/shims/_install-helpers.ts","../../src/shims/geolocation.ts"],"sourcesContent":["/**\n * Environment detection: are we running inside Apps in Toss, or a plain browser?\n *\n * Strategy: call the SDK's `getAppsInTossGlobals()` — a synchronous export\n * that returns the runtime's Toss globals (deploymentId, brand name, …)\n * inside the Apps in Toss runtime and throws (RN bridge unavailable)\n * anywhere else. The SDK itself is an **optional** peer dependency; if its\n * module can't be imported we are definitely not inside Toss.\n *\n * Just having the SDK module resolvable is not enough — apps can bundle it\n * and still run in a plain browser. We need the bridge probe to confirm.\n *\n * UA sniffing (spoofable) is avoided. We do call `getAppsInTossGlobals`, but\n * that's a constant read from the bridge — no permission dialogs, no\n * analytics fire. In a plain browser the bridge lookup fails fast (sync\n * throw, microsecond-scale), so the startup cost is negligible.\n */\n\nlet cached: boolean | undefined;\n\n/**\n * Reset the cached detection result. Primarily for tests.\n */\nexport function resetDetection(): void {\n cached = undefined;\n}\n\n/**\n * Synchronous read of the cached detection result. Returns:\n * - `true` / `false` if an override is active or the async detection has\n * already resolved\n * - `undefined` if detection hasn't run yet\n *\n * Used by spec-sync APIs (e.g. `navigator.canShare`) that can't `await`\n * detection.\n */\nexport function isTossEnvironmentCached(): boolean | undefined {\n const force = globalThis.__AIT_POLYFILL_FORCE__;\n if (force === 'toss') return true;\n if (force === 'browser') return false;\n return cached;\n}\n\n/**\n * Returns `true` iff we detect we are running in an environment where the\n * Apps in Toss SDK (`@apps-in-toss/web-framework`) is present and usable.\n *\n * Async because we use dynamic `import()` to probe the optional peer dep\n * without forcing it into the consumer's bundle.\n */\nexport async function isTossEnvironment(): Promise<boolean> {\n // Override check precedes cache so `devtools` / tests can flip the result\n // mid-session without a `resetDetection()` call.\n const force = globalThis.__AIT_POLYFILL_FORCE__;\n if (force === 'toss') return true;\n if (force === 'browser') return false;\n\n if (cached !== undefined) return cached;\n\n const mod = await loadTossSdk();\n if (typeof mod?.getAppsInTossGlobals !== 'function') {\n cached = false;\n return cached;\n }\n // Inside Toss the bridge returns a populated globals object. In a plain\n // browser the RN bridge isn't attached and the call throws — that's our\n // signal. Any non-throwing call with an object return is treated as Toss.\n try {\n const globals = mod.getAppsInTossGlobals();\n cached = Boolean(globals) && typeof globals === 'object';\n } catch {\n cached = false;\n }\n return cached;\n}\n\n/**\n * Lazy SDK accessor — returns the module if available, else `null`. Callers\n * are expected to `await` and null-check. Never throws.\n */\nexport async function loadTossSdk(): Promise<typeof import('@apps-in-toss/web-framework') | null> {\n try {\n return await import('@apps-in-toss/web-framework');\n } catch {\n return null;\n }\n}\n","/**\n * Shared helpers for installing shims on `navigator`.\n *\n * Chromium now marks a handful of `navigator` properties (e.g. `geolocation`,\n * `clipboard`) as non-configurable **own** properties on the instance. That\n * means a plain `Object.defineProperty(navigator, 'x', …)` throws\n * `TypeError: Cannot redefine property`.\n *\n * The workaround is to shim at the prototype level — `Navigator.prototype`\n * keeps these as configurable accessors, so we can swap them there and every\n * instance that falls through to the prototype (including `window.navigator`)\n * sees the shim. We only reach for the prototype when the instance-level\n * assignment refuses.\n *\n * For restoration we remember the descriptor chain (instance + prototype) so\n * `uninstall()` puts the browser back in its original state.\n */\n\ntype PropertyLocation = 'instance' | 'prototype';\n\nexport interface InstallSnapshot {\n /** Where we ended up writing the shim. */\n location: PropertyLocation;\n /** Original descriptor at that location (may be undefined if nothing was there). */\n originalDescriptor: PropertyDescriptor | undefined;\n /** `true` iff the original property lived on the instance before we touched it. */\n instanceHadOwn: boolean;\n}\n\n/**\n * Install `descriptor` at `navigator[prop]`. Prefer instance-level; if the\n * browser refuses (property is non-configurable on the instance), install on\n * `Navigator.prototype` instead.\n *\n * Returns a snapshot describing where the original value was, which\n * `restoreNavigatorProperty` uses to undo the install.\n */\nexport function installNavigatorProperty(\n prop: string,\n descriptor: PropertyDescriptor,\n): InstallSnapshot {\n const nav = navigator as unknown as Record<PropertyKey, unknown>;\n const instanceDesc = Object.getOwnPropertyDescriptor(nav, prop);\n const instanceHadOwn = instanceDesc !== undefined;\n\n // Fast path: instance-level property is missing or configurable.\n if (!instanceDesc || instanceDesc.configurable) {\n try {\n Object.defineProperty(nav, prop, descriptor);\n return { location: 'instance', originalDescriptor: instanceDesc, instanceHadOwn };\n } catch {\n // Fall through to prototype-level install.\n }\n }\n\n // Prototype-level install. Drop the instance-level shadow so the prototype\n // accessor is visible to readers on `navigator`.\n const proto = Object.getPrototypeOf(nav) as object;\n const protoDesc = Object.getOwnPropertyDescriptor(proto, prop);\n\n if (instanceHadOwn) {\n // Try to remove the instance-level shadow. On non-configurable it throws —\n // we deliberately ignore that; prototype-level install still wins because\n // the prototype accessor shows through when we read via `navigator[prop]`.\n try {\n delete nav[prop];\n } catch {\n /* non-configurable own — leave it; prototype install still useful */\n }\n }\n\n Object.defineProperty(proto, prop, descriptor);\n return { location: 'prototype', originalDescriptor: protoDesc, instanceHadOwn };\n}\n\n/**\n * Reverse the install recorded in `snapshot`. If the original descriptor was\n * `undefined` (property didn't exist before), delete the property instead of\n * re-defining it.\n */\nexport function restoreNavigatorProperty(prop: string, snapshot: InstallSnapshot): void {\n const target =\n snapshot.location === 'instance'\n ? (navigator as unknown as Record<PropertyKey, unknown>)\n : (Object.getPrototypeOf(navigator) as object);\n\n if (snapshot.originalDescriptor) {\n try {\n Object.defineProperty(target, prop, snapshot.originalDescriptor);\n } catch {\n /* descriptor was non-configurable upstream; we can't undo — rare. */\n }\n } else {\n try {\n // biome-ignore lint/performance/noDelete: property deletion is the uninstall intent\n delete (target as Record<PropertyKey, unknown>)[prop];\n } catch {\n /* non-configurable — rare. */\n }\n }\n\n // If our install pushed past an instance shadow, we leave the instance alone\n // — the descriptor we captured for `instanceHadOwn: true` lives on the\n // instance and was not modified at install time.\n}\n","/**\n * `navigator.geolocation` shim.\n *\n * Inside Apps in Toss → routes through the SDK:\n * - `getCurrentPosition` → `getCurrentLocation({ accuracy })`\n * - `watchPosition` / `clearWatch` → `startUpdateLocation({ onEvent, onError, options })`\n *\n * Outside Apps in Toss → defers to the browser's native `navigator.geolocation`.\n * If neither is available, the error callback receives a `GeolocationPositionError`.\n *\n * SDK/Web shape mismatch handled here:\n * - SDK `Accuracy` is a numeric enum (1 = Lowest … 6 = BestForNavigation); the\n * standard `PositionOptions.enableHighAccuracy` is a boolean. We map\n * `true → Accuracy.High (4, \"~10m\")` and `false → Accuracy.Balanced (3)`.\n * `Highest (5)` / `BestForNavigation (6)` are available but carry a battery\n * cost that's rarely what mini-apps want; consumers who need them should\n * call the SDK directly.\n * - SDK coords lack `speed`; we surface `null` (per the W3C spec when unknown).\n * - SDK `startUpdateLocation` returns an `unsubscribe` fn; we wrap it behind\n * a numeric watch id so `clearWatch(id)` behaves like the standard.\n *\n * Caveat: watch ids reset whenever the shim is uninstalled and reinstalled;\n * they are not stable across such cycles. Ids obtained before uninstall\n * cannot be cleared after uninstall — `clearWatch(id)` on the restored native\n * `navigator.geolocation` uses a different id space, so the SDK subscription\n * leaks. Consumers should `clearWatch` all outstanding ids before calling\n * `uninstall()`.\n */\n\nimport { isTossEnvironment, loadTossSdk } from '../detect.js';\nimport {\n type InstallSnapshot,\n installNavigatorProperty,\n restoreNavigatorProperty,\n} from './_install-helpers.js';\n\nconst BACKUP_KEY = Symbol.for('@ait-co/polyfill/geolocation.original');\nconst SNAPSHOT_KEY = Symbol.for('@ait-co/polyfill/geolocation.snapshot');\n\ninterface BackupHost {\n [BACKUP_KEY]?: Geolocation | undefined;\n [SNAPSHOT_KEY]?: InstallSnapshot | undefined;\n}\n\n// SDK Accuracy enum values. We don't import the enum at runtime (peer is\n// optional), so we hard-code the numeric constants used by the SDK. Stable\n// ABI per the SDK's exported numeric enum.\nconst ACCURACY_BALANCED = 3;\nconst ACCURACY_HIGH = 4;\n\ninterface SdkLocationCoords {\n latitude: number;\n longitude: number;\n altitude: number;\n accuracy: number;\n altitudeAccuracy: number;\n heading: number;\n}\n\ninterface SdkLocation {\n timestamp: number;\n coords: SdkLocationCoords;\n}\n\nfunction toStandardPosition(sdk: SdkLocation): GeolocationPosition {\n const coordsData = {\n latitude: sdk.coords.latitude,\n longitude: sdk.coords.longitude,\n altitude: sdk.coords.altitude,\n accuracy: sdk.coords.accuracy,\n altitudeAccuracy: sdk.coords.altitudeAccuracy,\n heading: sdk.coords.heading,\n // SDK does not surface speed. Per spec, null means \"unknown\".\n speed: null,\n };\n const coords: GeolocationCoordinates = {\n ...coordsData,\n toJSON() {\n return { ...coordsData };\n },\n };\n return {\n coords,\n timestamp: sdk.timestamp,\n toJSON() {\n return { coords: { ...coordsData }, timestamp: sdk.timestamp };\n },\n };\n}\n\nfunction toPositionError(code: 1 | 2 | 3, message: string): GeolocationPositionError {\n // Prefer the real constructor when available (every real browser ships it).\n // The spec says GeolocationPositionError is not constructable, so we fall\n // through to a fabricated object whose prototype is patched via\n // `setPrototypeOf` — that keeps `instanceof` checks in consumer code working\n // and picks up the spec's PERMISSION_DENIED / POSITION_UNAVAILABLE / TIMEOUT\n // constants from the real prototype rather than hard-coding them (avoids\n // drift if the spec ever grows a new code).\n const Ctor = (globalThis as { GeolocationPositionError?: unknown }).GeolocationPositionError;\n if (typeof Ctor === 'function') {\n const proto = (Ctor as { prototype?: object }).prototype;\n if (proto) {\n const shape: { code: number; message: string } = { code, message };\n Object.setPrototypeOf(shape, proto);\n return shape as GeolocationPositionError;\n }\n }\n // jsdom / last-resort fallback: fabricate the spec shape with hard-coded\n // constants since there's no prototype to delegate to.\n return {\n code,\n message,\n PERMISSION_DENIED: 1,\n POSITION_UNAVAILABLE: 2,\n TIMEOUT: 3,\n } as GeolocationPositionError;\n}\n\nfunction accuracyFromOptions(options: PositionOptions | undefined): number {\n return options?.enableHighAccuracy ? ACCURACY_HIGH : ACCURACY_BALANCED;\n}\n\nfunction createGeolocationShim(fallback: Geolocation | undefined): Geolocation {\n // Numeric watch id → SDK unsubscribe fn. Keeps the shim's API in line with\n // the standard even though the SDK issues unsubscribe closures instead.\n // `pendingWatches` closes the race where `clearWatch` is called before the\n // async `watchPosition` installer resolves — without it we'd leak the SDK\n // subscription.\n let nextWatchId = 1;\n const sdkWatches = new Map<number, () => void>();\n const nativeWatches = new Map<number, number>();\n const pendingWatches = new Map<number, { cancelled: boolean }>();\n\n const shim: Geolocation = {\n getCurrentPosition(success, error, options) {\n void (async () => {\n if (await isTossEnvironment()) {\n const sdk = await loadTossSdk();\n const fn = (sdk as { getCurrentLocation?: unknown } | null)?.getCurrentLocation;\n if (typeof fn === 'function') {\n try {\n const loc = (await (fn as (o: { accuracy: number }) => Promise<SdkLocation>)({\n accuracy: accuracyFromOptions(options),\n })) as SdkLocation;\n success(toStandardPosition(loc));\n } catch (e) {\n error?.(\n toPositionError(\n 2,\n e instanceof Error ? e.message : '[@ait-co/polyfill] getCurrentLocation failed.',\n ),\n );\n }\n return;\n }\n }\n if (!fallback) {\n error?.(\n toPositionError(\n 2,\n '[@ait-co/polyfill] navigator.geolocation is not available in this environment.',\n ),\n );\n return;\n }\n fallback.getCurrentPosition(success, error, options);\n })();\n },\n\n watchPosition(success, error, options) {\n const id = nextWatchId++;\n const pending = { cancelled: false };\n pendingWatches.set(id, pending);\n\n void (async () => {\n if (await isTossEnvironment()) {\n const sdk = await loadTossSdk();\n const fn = (sdk as { startUpdateLocation?: unknown } | null)?.startUpdateLocation;\n if (typeof fn === 'function') {\n if (pending.cancelled) {\n pendingWatches.delete(id);\n return;\n }\n const unsubscribe = (\n fn as (p: {\n onEvent: (loc: SdkLocation) => void;\n onError: (err: unknown) => void;\n options: { accuracy: number; timeInterval: number; distanceInterval: number };\n }) => () => void\n )({\n onEvent: (loc) => success(toStandardPosition(loc)),\n onError: (err) =>\n error?.(\n toPositionError(\n 2,\n err instanceof Error\n ? err.message\n : '[@ait-co/polyfill] startUpdateLocation failed.',\n ),\n ),\n options: {\n accuracy: accuracyFromOptions(options),\n // Sensible defaults — web `watchPosition` has no analogues.\n // Consumers needing sub-second updates should use the SDK directly.\n timeInterval: 1000,\n distanceInterval: 0,\n },\n });\n if (pending.cancelled) {\n unsubscribe();\n pendingWatches.delete(id);\n return;\n }\n sdkWatches.set(id, unsubscribe);\n pendingWatches.delete(id);\n return;\n }\n }\n if (!fallback) {\n pendingWatches.delete(id);\n error?.(\n toPositionError(\n 2,\n '[@ait-co/polyfill] navigator.geolocation is not available in this environment.',\n ),\n );\n return;\n }\n if (pending.cancelled) {\n pendingWatches.delete(id);\n return;\n }\n const nativeId = fallback.watchPosition(success, error, options);\n if (pending.cancelled) {\n fallback.clearWatch(nativeId);\n pendingWatches.delete(id);\n return;\n }\n nativeWatches.set(id, nativeId);\n pendingWatches.delete(id);\n })();\n\n return id;\n },\n\n clearWatch(id) {\n const pending = pendingWatches.get(id);\n if (pending) {\n pending.cancelled = true;\n pendingWatches.delete(id);\n return;\n }\n const unsubscribe = sdkWatches.get(id);\n if (unsubscribe) {\n unsubscribe();\n sdkWatches.delete(id);\n return;\n }\n const nativeId = nativeWatches.get(id);\n if (nativeId !== undefined && fallback) {\n fallback.clearWatch(nativeId);\n nativeWatches.delete(id);\n }\n },\n };\n\n return shim;\n}\n\nexport function installGeolocationShim(): () => void {\n if (typeof navigator === 'undefined') {\n return () => {};\n }\n\n const host = navigator as unknown as BackupHost;\n if (BACKUP_KEY in host) {\n return () => uninstallGeolocationShim();\n }\n\n const original = navigator.geolocation as Geolocation | undefined;\n host[BACKUP_KEY] = original;\n\n const shim = createGeolocationShim(original);\n host[SNAPSHOT_KEY] = installNavigatorProperty('geolocation', {\n value: shim,\n configurable: true,\n writable: true,\n });\n\n return uninstallGeolocationShim;\n}\n\nexport function uninstallGeolocationShim(): void {\n if (typeof navigator === 'undefined') return;\n const host = navigator as unknown as BackupHost;\n if (!(BACKUP_KEY in host)) return;\n\n const snapshot = host[SNAPSHOT_KEY];\n if (snapshot) restoreNavigatorProperty('geolocation', snapshot);\n delete host[BACKUP_KEY];\n delete host[SNAPSHOT_KEY];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkBA,IAAI;;;;;;;;AAgCJ,eAAsB,oBAAsC;CAG1D,MAAM,QAAQ,WAAW;AACzB,KAAI,UAAU,OAAQ,QAAO;AAC7B,KAAI,UAAU,UAAW,QAAO;AAEhC,KAAI,WAAW,KAAA,EAAW,QAAO;CAEjC,MAAM,MAAM,MAAM,aAAa;AAC/B,KAAI,OAAO,KAAK,yBAAyB,YAAY;AACnD,WAAS;AACT,SAAO;;AAKT,KAAI;EACF,MAAM,UAAU,IAAI,sBAAsB;AAC1C,WAAS,QAAQ,QAAQ,IAAI,OAAO,YAAY;SAC1C;AACN,WAAS;;AAEX,QAAO;;;;;;AAOT,eAA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,OAAO,cAAc,YACvB,cAAa;CAGf,MAAM,OAAO;AACb,KAAI,cAAc,KAChB,cAAa,0BAA0B;CAGzC,MAAM,WAAW,UAAU;AAC3B,MAAK,cAAc;AAGnB,MAAK,gBAAgB,yBAAyB,eAAe;EAC3D,OAFW,sBAAsB,SAAS;EAG1C,cAAc;EACd,UAAU;EACX,CAAC;AAEF,QAAO;;AAGT,SAAgB,2BAAiC;AAC/C,KAAI,OAAO,cAAc,YAAa;CACtC,MAAM,OAAO;AACb,KAAI,EAAE,cAAc,MAAO;CAE3B,MAAM,WAAW,KAAK;AACtB,KAAI,SAAU,0BAAyB,eAAe,SAAS;AAC/D,QAAO,KAAK;AACZ,QAAO,KAAK"}
@@ -1 +1 @@
1
- {"version":3,"file":"network.d.ts","names":[],"sources":["../../src/shims/network.ts"],"mappings":";;AAoIA;;;;;AAqGA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBArGgB,kBAAA,CAAA;AAAA,iBAqGA,oBAAA,CAAA"}
1
+ {"version":3,"file":"network.d.ts","names":[],"sources":["../../src/shims/network.ts"],"mappings":";;AA6IA;;;;;AAqFA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBArFgB,kBAAA,CAAA;AAAA,iBAqFA,oBAAA,CAAA"}
@@ -54,6 +54,54 @@ async function loadTossSdk() {
54
54
  }
55
55
  }
56
56
  //#endregion
57
+ //#region src/shims/_install-helpers.ts
58
+ /**
59
+ * Install `descriptor` at `navigator[prop]`. Prefer instance-level; if the
60
+ * browser refuses (property is non-configurable on the instance), install on
61
+ * `Navigator.prototype` instead.
62
+ *
63
+ * Returns a snapshot describing where the original value was, which
64
+ * `restoreNavigatorProperty` uses to undo the install.
65
+ */
66
+ function installNavigatorProperty(prop, descriptor) {
67
+ const nav = navigator;
68
+ const instanceDesc = Object.getOwnPropertyDescriptor(nav, prop);
69
+ const instanceHadOwn = instanceDesc !== void 0;
70
+ if (!instanceDesc || instanceDesc.configurable) try {
71
+ Object.defineProperty(nav, prop, descriptor);
72
+ return {
73
+ location: "instance",
74
+ originalDescriptor: instanceDesc,
75
+ instanceHadOwn
76
+ };
77
+ } catch {}
78
+ const proto = Object.getPrototypeOf(nav);
79
+ const protoDesc = Object.getOwnPropertyDescriptor(proto, prop);
80
+ if (instanceHadOwn) try {
81
+ delete nav[prop];
82
+ } catch {}
83
+ Object.defineProperty(proto, prop, descriptor);
84
+ return {
85
+ location: "prototype",
86
+ originalDescriptor: protoDesc,
87
+ instanceHadOwn
88
+ };
89
+ }
90
+ /**
91
+ * Reverse the install recorded in `snapshot`. If the original descriptor was
92
+ * `undefined` (property didn't exist before), delete the property instead of
93
+ * re-defining it.
94
+ */
95
+ function restoreNavigatorProperty(prop, snapshot) {
96
+ const target = snapshot.location === "instance" ? navigator : Object.getPrototypeOf(navigator);
97
+ if (snapshot.originalDescriptor) try {
98
+ Object.defineProperty(target, prop, snapshot.originalDescriptor);
99
+ } catch {}
100
+ else try {
101
+ delete target[prop];
102
+ } catch {}
103
+ }
104
+ //#endregion
57
105
  //#region src/shims/network.ts
58
106
  /**
59
107
  * `navigator.onLine` + `navigator.connection` shim.
@@ -97,6 +145,8 @@ async function loadTossSdk() {
97
145
  * reads may return the native object.
98
146
  */
99
147
  const INSTALLED_KEY = Symbol.for("@ait-co/polyfill/network.installed");
148
+ const ON_LINE_SNAPSHOT_KEY = Symbol.for("@ait-co/polyfill/network.onLine.snapshot");
149
+ const CONNECTION_SNAPSHOT_KEY = Symbol.for("@ait-co/polyfill/network.connection.snapshot");
100
150
  const REFRESH_THROTTLE_MS = 500;
101
151
  function statusToOnline(status) {
102
152
  return status !== "OFFLINE";
@@ -176,35 +226,22 @@ function installNetworkShim() {
176
226
  })();
177
227
  return inflight;
178
228
  }
229
+ const nativeOnLine = navigator.onLine;
230
+ const nativeConnection = navigator.connection;
179
231
  refresh();
180
- Object.defineProperty(navigator, "onLine", {
232
+ host[ON_LINE_SNAPSHOT_KEY] = installNavigatorProperty("onLine", {
181
233
  configurable: true,
182
234
  get() {
183
235
  refresh();
184
236
  if (cachedStatus !== null) return statusToOnline(cachedStatus);
185
- const desc = Object.getOwnPropertyDescriptor(navigator, "onLine");
186
- delete navigator.onLine;
187
- try {
188
- return navigator.onLine;
189
- } finally {
190
- if (desc) Object.defineProperty(navigator, "onLine", desc);
191
- }
237
+ return nativeOnLine ?? true;
192
238
  }
193
239
  });
194
- Object.defineProperty(navigator, "connection", {
240
+ host[CONNECTION_SNAPSHOT_KEY] = installNavigatorProperty("connection", {
195
241
  configurable: true,
196
242
  get() {
197
243
  refresh();
198
- if (cachedStatus === null) {
199
- const desc = Object.getOwnPropertyDescriptor(navigator, "connection");
200
- delete navigator.connection;
201
- try {
202
- const native = navigator.connection;
203
- if (native !== void 0) return native;
204
- } finally {
205
- if (desc) Object.defineProperty(navigator, "connection", desc);
206
- }
207
- }
244
+ if (cachedStatus === null && nativeConnection !== void 0) return nativeConnection;
208
245
  return connection;
209
246
  }
210
247
  });
@@ -214,9 +251,13 @@ function uninstallNetworkShim() {
214
251
  if (typeof navigator === "undefined") return;
215
252
  const host = navigator;
216
253
  if (!host[INSTALLED_KEY]) return;
217
- delete navigator.onLine;
218
- delete navigator.connection;
254
+ const onLineSnap = host[ON_LINE_SNAPSHOT_KEY];
255
+ if (onLineSnap) restoreNavigatorProperty("onLine", onLineSnap);
256
+ const connSnap = host[CONNECTION_SNAPSHOT_KEY];
257
+ if (connSnap) restoreNavigatorProperty("connection", connSnap);
219
258
  delete host[INSTALLED_KEY];
259
+ delete host[ON_LINE_SNAPSHOT_KEY];
260
+ delete host[CONNECTION_SNAPSHOT_KEY];
220
261
  }
221
262
  //#endregion
222
263
  export { installNetworkShim, uninstallNetworkShim };
@@ -1 +1 @@
1
- {"version":3,"file":"network.js","names":["#status"],"sources":["../../src/detect.ts","../../src/shims/network.ts"],"sourcesContent":["/**\n * Environment detection: are we running inside Apps in Toss, or a plain browser?\n *\n * Strategy: call the SDK's `getAppsInTossGlobals()` — a synchronous export\n * that returns the runtime's Toss globals (deploymentId, brand name, …)\n * inside the Apps in Toss runtime and throws (RN bridge unavailable)\n * anywhere else. The SDK itself is an **optional** peer dependency; if its\n * module can't be imported we are definitely not inside Toss.\n *\n * Just having the SDK module resolvable is not enough — apps can bundle it\n * and still run in a plain browser. We need the bridge probe to confirm.\n *\n * UA sniffing (spoofable) is avoided. We do call `getAppsInTossGlobals`, but\n * that's a constant read from the bridge — no permission dialogs, no\n * analytics fire. In a plain browser the bridge lookup fails fast (sync\n * throw, microsecond-scale), so the startup cost is negligible.\n */\n\nlet cached: boolean | undefined;\n\n/**\n * Reset the cached detection result. Primarily for tests.\n */\nexport function resetDetection(): void {\n cached = undefined;\n}\n\n/**\n * Synchronous read of the cached detection result. Returns:\n * - `true` / `false` if an override is active or the async detection has\n * already resolved\n * - `undefined` if detection hasn't run yet\n *\n * Used by spec-sync APIs (e.g. `navigator.canShare`) that can't `await`\n * detection.\n */\nexport function isTossEnvironmentCached(): boolean | undefined {\n const force = globalThis.__AIT_POLYFILL_FORCE__;\n if (force === 'toss') return true;\n if (force === 'browser') return false;\n return cached;\n}\n\n/**\n * Returns `true` iff we detect we are running in an environment where the\n * Apps in Toss SDK (`@apps-in-toss/web-framework`) is present and usable.\n *\n * Async because we use dynamic `import()` to probe the optional peer dep\n * without forcing it into the consumer's bundle.\n */\nexport async function isTossEnvironment(): Promise<boolean> {\n // Override check precedes cache so `devtools` / tests can flip the result\n // mid-session without a `resetDetection()` call.\n const force = globalThis.__AIT_POLYFILL_FORCE__;\n if (force === 'toss') return true;\n if (force === 'browser') return false;\n\n if (cached !== undefined) return cached;\n\n const mod = await loadTossSdk();\n if (typeof mod?.getAppsInTossGlobals !== 'function') {\n cached = false;\n return cached;\n }\n // Inside Toss the bridge returns a populated globals object. In a plain\n // browser the RN bridge isn't attached and the call throws — that's our\n // signal. Any non-throwing call with an object return is treated as Toss.\n try {\n const globals = mod.getAppsInTossGlobals();\n cached = Boolean(globals) && typeof globals === 'object';\n } catch {\n cached = false;\n }\n return cached;\n}\n\n/**\n * Lazy SDK accessor — returns the module if available, else `null`. Callers\n * are expected to `await` and null-check. Never throws.\n */\nexport async function loadTossSdk(): Promise<typeof import('@apps-in-toss/web-framework') | null> {\n try {\n return await import('@apps-in-toss/web-framework');\n } catch {\n return null;\n }\n}\n","/**\n * `navigator.onLine` + `navigator.connection` shim.\n *\n * Inside Apps in Toss → seeded from SDK `getNetworkStatus()` on install and\n * refreshed on read (throttled):\n * - `'OFFLINE'` → `onLine = false`\n * - `'WIFI'` → `onLine = true`, `effectiveType = '4g'` (no web wifi value)\n * - `'2G'/'3G'/'4G'/'5G'` → `onLine = true`, `effectiveType = <lowercased>`\n * - `'WWAN'/'UNKNOWN'` → `onLine = true`, `effectiveType = '4g'` (best guess)\n *\n * Outside Apps in Toss → both `navigator.onLine` and `navigator.connection`\n * read through to the native value. Install installs own-instance getters\n * that consult the Toss-seeded cache first; when the cache is empty (which\n * it always is in browser mode), the getter temporarily removes its own\n * shadow, reads the prototype value, and reinstates the shadow.\n *\n * Uninstall `delete`s the instance-level override so the prototype descriptor\n * (where `onLine` and `connection` actually live in real browsers) becomes\n * visible again. We never mutate the prototype — doing so would throw in\n * browsers where the descriptor is non-configurable.\n *\n * Caveat: the Web NetworkInformation API is evented (`change` fires on\n * transitions). The SDK exposes only a one-shot query, so listeners attached\n * to `navigator.connection` are accepted but never fire from a `change` event\n * unless the shim observes a real status transition. Synthesising richer\n * events via polling is tracked in TODO.md.\n *\n * Lifecycle: `navigator.connection` is a ShimConnection instance that lives in\n * the install closure. On uninstall the instance-level override is removed,\n * but listeners the consumer attached to the old instance stay bound to that\n * (now-orphan) object and will not see events from a subsequent install.\n * Consumers should re-attach listeners after each install.\n *\n * Seed-boundary race: in Toss mode, reads before the install-time SDK seed\n * completes fall through to the native `navigator.connection`. After the seed\n * lands, subsequent reads return the shim's ShimConnection. Consumers that\n * specifically need the ShimConnection instance (e.g., to attach `change`\n * listeners that fire on Toss network transitions) should wait a microtask\n * after `install()` before attaching listeners, or accept that pre-seed\n * reads may return the native object.\n */\n\nimport { isTossEnvironment, loadTossSdk } from '../detect.js';\n\nconst INSTALLED_KEY = Symbol.for('@ait-co/polyfill/network.installed');\n\ninterface BackupHost {\n [INSTALLED_KEY]?: boolean;\n}\n\ntype SdkNetworkStatus = 'OFFLINE' | 'WIFI' | '2G' | '3G' | '4G' | '5G' | 'WWAN' | 'UNKNOWN';\ntype EffectiveType = 'slow-2g' | '2g' | '3g' | '4g';\n\nconst REFRESH_THROTTLE_MS = 500;\n\nfunction statusToOnline(status: SdkNetworkStatus): boolean {\n return status !== 'OFFLINE';\n}\n\nfunction statusToEffectiveType(status: SdkNetworkStatus): EffectiveType {\n switch (status) {\n case '2G':\n return '2g';\n case '3G':\n return '3g';\n default:\n return '4g';\n }\n}\n\nfunction statusToConnectionType(status: SdkNetworkStatus): string {\n switch (status) {\n case 'WIFI':\n return 'wifi';\n case '2G':\n case '3G':\n case '4G':\n case '5G':\n case 'WWAN':\n return 'cellular';\n case 'OFFLINE':\n return 'none';\n default:\n return 'unknown';\n }\n}\n\n// Symbol-keyed setter: the install closure can mutate status without exposing\n// a `setStatus` name on `navigator.connection` (real NetworkInformation has\n// no mutator). `Object.getOwnPropertySymbols(navigator.connection)` returns\n// nothing, so casual enumeration can't find it. A determined caller walking\n// the prototype chain (`Object.getOwnPropertySymbols(Object.getPrototypeOf(...))`)\n// can still surface the symbol — there is no trust boundary between polyfill\n// and consumer code in the same realm, so this is a discouragement, not a\n// security control.\nconst SET_STATUS = Symbol('@ait-co/polyfill/network.setStatus');\n\nclass ShimConnection extends EventTarget {\n #status: SdkNetworkStatus | null = null;\n onchange: ((this: ShimConnection, ev: Event) => unknown) | null = null;\n\n constructor() {\n super();\n // Forward `change` events to the legacy `onchange` handler for parity with\n // the NetworkInformation API.\n this.addEventListener('change', (ev) => this.onchange?.call(this, ev));\n }\n\n [SET_STATUS](next: SdkNetworkStatus | null): void {\n this.#status = next;\n }\n\n get effectiveType(): EffectiveType {\n return statusToEffectiveType(this.#status ?? 'UNKNOWN');\n }\n // `downlink` / `rtt` / `saveData` are placeholders — the SDK does not expose\n // these. We return 0/false rather than fabricate plausible numbers. Noted\n // in CLAUDE.md.\n get downlink(): number {\n return 0;\n }\n get rtt(): number {\n return 0;\n }\n get saveData(): boolean {\n return false;\n }\n get type(): string {\n return statusToConnectionType(this.#status ?? 'UNKNOWN');\n }\n}\n\nexport function installNetworkShim(): () => void {\n if (typeof navigator === 'undefined') {\n return () => {};\n }\n\n const host = navigator as unknown as BackupHost;\n if (host[INSTALLED_KEY]) {\n return () => uninstallNetworkShim();\n }\n host[INSTALLED_KEY] = true;\n\n // Per-install state. Kept in closure so uninstall/reinstall cycles don't\n // leak state between instances (module-scope would leak across tests).\n let cachedStatus: SdkNetworkStatus | null = null;\n let lastRefresh = 0;\n let inflight: Promise<void> | null = null;\n const connection = new ShimConnection();\n\n async function refresh(): Promise<void> {\n // Coalesce concurrent refreshes — without this, rapid reads during an\n // in-flight SDK call each set `lastRefresh` and return early, without\n // anyone actually fetching fresh data.\n if (inflight) return inflight;\n const now = Date.now();\n if (now - lastRefresh < REFRESH_THROTTLE_MS) return;\n inflight = (async () => {\n try {\n if (!(await isTossEnvironment())) return;\n const sdk = await loadTossSdk();\n const fn = (sdk as { getNetworkStatus?: unknown } | null)?.getNetworkStatus;\n if (typeof fn !== 'function') return;\n const next = (await (fn as () => Promise<SdkNetworkStatus>)()) as SdkNetworkStatus;\n const prev = cachedStatus;\n cachedStatus = next;\n connection[SET_STATUS](next);\n // Only dispatch `change` on real transitions — the null → X seed on\n // first install is learning, not a transition, and would otherwise\n // mis-trigger consumer handlers.\n if (prev !== null && prev !== next) {\n connection.dispatchEvent(new Event('change'));\n }\n } catch {\n // Advisory — refresh failures keep the prior cache. `void refresh()`\n // callers would otherwise surface unhandled rejections if\n // isTossEnvironment / loadTossSdk / getNetworkStatus ever throw.\n } finally {\n lastRefresh = Date.now();\n inflight = null;\n }\n })();\n return inflight;\n }\n\n // Seed the cache on install so the first sync read is meaningful.\n void refresh();\n\n Object.defineProperty(navigator, 'onLine', {\n configurable: true,\n get() {\n void refresh();\n if (cachedStatus !== null) {\n return statusToOnline(cachedStatus);\n }\n // Fall back to whatever the prototype would have returned. Temporarily\n // delete our shadow to read through; the try/finally guarantees the\n // shadow is restored even if the prototype getter throws.\n const desc = Object.getOwnPropertyDescriptor(navigator, 'onLine');\n delete (navigator as unknown as { onLine?: boolean }).onLine;\n try {\n return navigator.onLine;\n } finally {\n if (desc) Object.defineProperty(navigator, 'onLine', desc);\n }\n },\n });\n\n Object.defineProperty(navigator, 'connection', {\n configurable: true,\n get() {\n void refresh();\n // Symmetric with `onLine`: when the SDK hasn't seeded us (either a\n // browser-mode install or pre-seed Toss), read through to the native\n // `navigator.connection` so consumers in plain browsers don't see a\n // hardcoded `effectiveType: '4g'` default.\n if (cachedStatus === null) {\n const desc = Object.getOwnPropertyDescriptor(navigator, 'connection');\n delete (navigator as unknown as { connection?: unknown }).connection;\n try {\n const native = (navigator as Navigator & { connection?: unknown }).connection;\n if (native !== undefined) return native;\n } finally {\n if (desc) Object.defineProperty(navigator, 'connection', desc);\n }\n }\n return connection;\n },\n });\n\n return uninstallNetworkShim;\n}\n\nexport function uninstallNetworkShim(): void {\n if (typeof navigator === 'undefined') return;\n const host = navigator as unknown as BackupHost;\n if (!host[INSTALLED_KEY]) return;\n\n // `delete` the instance-level property so the prototype descriptor (where\n // `onLine` and `connection` actually live in real browsers) is exposed\n // again. Redefining the prototype would throw on non-configurable getters.\n delete (navigator as unknown as { onLine?: boolean }).onLine;\n delete (navigator as unknown as { connection?: unknown }).connection;\n\n delete host[INSTALLED_KEY];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkBA,IAAI;;;;;;;;AAgCJ,eAAsB,oBAAsC;CAG1D,MAAM,QAAQ,WAAW;AACzB,KAAI,UAAU,OAAQ,QAAO;AAC7B,KAAI,UAAU,UAAW,QAAO;AAEhC,KAAI,WAAW,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AO;;EAEV,CAAC;AAEF,QAAO;;AAGT,SAAgB,uBAA6B;AAC3C,KAAI,OAAO,cAAc,YAAa;CACtC,MAAM,OAAO;AACb,KAAI,CAAC,KAAK,eAAgB;AAK1B,QAAQ,UAA8C;AACtD,QAAQ,UAAkD;AAE1D,QAAO,KAAK"}
1
+ {"version":3,"file":"network.js","names":["#status"],"sources":["../../src/detect.ts","../../src/shims/_install-helpers.ts","../../src/shims/network.ts"],"sourcesContent":["/**\n * Environment detection: are we running inside Apps in Toss, or a plain browser?\n *\n * Strategy: call the SDK's `getAppsInTossGlobals()` — a synchronous export\n * that returns the runtime's Toss globals (deploymentId, brand name, …)\n * inside the Apps in Toss runtime and throws (RN bridge unavailable)\n * anywhere else. The SDK itself is an **optional** peer dependency; if its\n * module can't be imported we are definitely not inside Toss.\n *\n * Just having the SDK module resolvable is not enough — apps can bundle it\n * and still run in a plain browser. We need the bridge probe to confirm.\n *\n * UA sniffing (spoofable) is avoided. We do call `getAppsInTossGlobals`, but\n * that's a constant read from the bridge — no permission dialogs, no\n * analytics fire. In a plain browser the bridge lookup fails fast (sync\n * throw, microsecond-scale), so the startup cost is negligible.\n */\n\nlet cached: boolean | undefined;\n\n/**\n * Reset the cached detection result. Primarily for tests.\n */\nexport function resetDetection(): void {\n cached = undefined;\n}\n\n/**\n * Synchronous read of the cached detection result. Returns:\n * - `true` / `false` if an override is active or the async detection has\n * already resolved\n * - `undefined` if detection hasn't run yet\n *\n * Used by spec-sync APIs (e.g. `navigator.canShare`) that can't `await`\n * detection.\n */\nexport function isTossEnvironmentCached(): boolean | undefined {\n const force = globalThis.__AIT_POLYFILL_FORCE__;\n if (force === 'toss') return true;\n if (force === 'browser') return false;\n return cached;\n}\n\n/**\n * Returns `true` iff we detect we are running in an environment where the\n * Apps in Toss SDK (`@apps-in-toss/web-framework`) is present and usable.\n *\n * Async because we use dynamic `import()` to probe the optional peer dep\n * without forcing it into the consumer's bundle.\n */\nexport async function isTossEnvironment(): Promise<boolean> {\n // Override check precedes cache so `devtools` / tests can flip the result\n // mid-session without a `resetDetection()` call.\n const force = globalThis.__AIT_POLYFILL_FORCE__;\n if (force === 'toss') return true;\n if (force === 'browser') return false;\n\n if (cached !== undefined) return cached;\n\n const mod = await loadTossSdk();\n if (typeof mod?.getAppsInTossGlobals !== 'function') {\n cached = false;\n return cached;\n }\n // Inside Toss the bridge returns a populated globals object. In a plain\n // browser the RN bridge isn't attached and the call throws — that's our\n // signal. Any non-throwing call with an object return is treated as Toss.\n try {\n const globals = mod.getAppsInTossGlobals();\n cached = Boolean(globals) && typeof globals === 'object';\n } catch {\n cached = false;\n }\n return cached;\n}\n\n/**\n * Lazy SDK accessor — returns the module if available, else `null`. Callers\n * are expected to `await` and null-check. Never throws.\n */\nexport async function loadTossSdk(): Promise<typeof import('@apps-in-toss/web-framework') | null> {\n try {\n return await import('@apps-in-toss/web-framework');\n } catch {\n return null;\n }\n}\n","/**\n * Shared helpers for installing shims on `navigator`.\n *\n * Chromium now marks a handful of `navigator` properties (e.g. `geolocation`,\n * `clipboard`) as non-configurable **own** properties on the instance. That\n * means a plain `Object.defineProperty(navigator, 'x', …)` throws\n * `TypeError: Cannot redefine property`.\n *\n * The workaround is to shim at the prototype level — `Navigator.prototype`\n * keeps these as configurable accessors, so we can swap them there and every\n * instance that falls through to the prototype (including `window.navigator`)\n * sees the shim. We only reach for the prototype when the instance-level\n * assignment refuses.\n *\n * For restoration we remember the descriptor chain (instance + prototype) so\n * `uninstall()` puts the browser back in its original state.\n */\n\ntype PropertyLocation = 'instance' | 'prototype';\n\nexport interface InstallSnapshot {\n /** Where we ended up writing the shim. */\n location: PropertyLocation;\n /** Original descriptor at that location (may be undefined if nothing was there). */\n originalDescriptor: PropertyDescriptor | undefined;\n /** `true` iff the original property lived on the instance before we touched it. */\n instanceHadOwn: boolean;\n}\n\n/**\n * Install `descriptor` at `navigator[prop]`. Prefer instance-level; if the\n * browser refuses (property is non-configurable on the instance), install on\n * `Navigator.prototype` instead.\n *\n * Returns a snapshot describing where the original value was, which\n * `restoreNavigatorProperty` uses to undo the install.\n */\nexport function installNavigatorProperty(\n prop: string,\n descriptor: PropertyDescriptor,\n): InstallSnapshot {\n const nav = navigator as unknown as Record<PropertyKey, unknown>;\n const instanceDesc = Object.getOwnPropertyDescriptor(nav, prop);\n const instanceHadOwn = instanceDesc !== undefined;\n\n // Fast path: instance-level property is missing or configurable.\n if (!instanceDesc || instanceDesc.configurable) {\n try {\n Object.defineProperty(nav, prop, descriptor);\n return { location: 'instance', originalDescriptor: instanceDesc, instanceHadOwn };\n } catch {\n // Fall through to prototype-level install.\n }\n }\n\n // Prototype-level install. Drop the instance-level shadow so the prototype\n // accessor is visible to readers on `navigator`.\n const proto = Object.getPrototypeOf(nav) as object;\n const protoDesc = Object.getOwnPropertyDescriptor(proto, prop);\n\n if (instanceHadOwn) {\n // Try to remove the instance-level shadow. On non-configurable it throws —\n // we deliberately ignore that; prototype-level install still wins because\n // the prototype accessor shows through when we read via `navigator[prop]`.\n try {\n delete nav[prop];\n } catch {\n /* non-configurable own — leave it; prototype install still useful */\n }\n }\n\n Object.defineProperty(proto, prop, descriptor);\n return { location: 'prototype', originalDescriptor: protoDesc, instanceHadOwn };\n}\n\n/**\n * Reverse the install recorded in `snapshot`. If the original descriptor was\n * `undefined` (property didn't exist before), delete the property instead of\n * re-defining it.\n */\nexport function restoreNavigatorProperty(prop: string, snapshot: InstallSnapshot): void {\n const target =\n snapshot.location === 'instance'\n ? (navigator as unknown as Record<PropertyKey, unknown>)\n : (Object.getPrototypeOf(navigator) as object);\n\n if (snapshot.originalDescriptor) {\n try {\n Object.defineProperty(target, prop, snapshot.originalDescriptor);\n } catch {\n /* descriptor was non-configurable upstream; we can't undo — rare. */\n }\n } else {\n try {\n // biome-ignore lint/performance/noDelete: property deletion is the uninstall intent\n delete (target as Record<PropertyKey, unknown>)[prop];\n } catch {\n /* non-configurable — rare. */\n }\n }\n\n // If our install pushed past an instance shadow, we leave the instance alone\n // — the descriptor we captured for `instanceHadOwn: true` lives on the\n // instance and was not modified at install time.\n}\n","/**\n * `navigator.onLine` + `navigator.connection` shim.\n *\n * Inside Apps in Toss → seeded from SDK `getNetworkStatus()` on install and\n * refreshed on read (throttled):\n * - `'OFFLINE'` → `onLine = false`\n * - `'WIFI'` → `onLine = true`, `effectiveType = '4g'` (no web wifi value)\n * - `'2G'/'3G'/'4G'/'5G'` → `onLine = true`, `effectiveType = <lowercased>`\n * - `'WWAN'/'UNKNOWN'` → `onLine = true`, `effectiveType = '4g'` (best guess)\n *\n * Outside Apps in Toss → both `navigator.onLine` and `navigator.connection`\n * read through to the native value. Install installs own-instance getters\n * that consult the Toss-seeded cache first; when the cache is empty (which\n * it always is in browser mode), the getter temporarily removes its own\n * shadow, reads the prototype value, and reinstates the shadow.\n *\n * Uninstall `delete`s the instance-level override so the prototype descriptor\n * (where `onLine` and `connection` actually live in real browsers) becomes\n * visible again. We never mutate the prototype — doing so would throw in\n * browsers where the descriptor is non-configurable.\n *\n * Caveat: the Web NetworkInformation API is evented (`change` fires on\n * transitions). The SDK exposes only a one-shot query, so listeners attached\n * to `navigator.connection` are accepted but never fire from a `change` event\n * unless the shim observes a real status transition. Synthesising richer\n * events via polling is tracked in TODO.md.\n *\n * Lifecycle: `navigator.connection` is a ShimConnection instance that lives in\n * the install closure. On uninstall the instance-level override is removed,\n * but listeners the consumer attached to the old instance stay bound to that\n * (now-orphan) object and will not see events from a subsequent install.\n * Consumers should re-attach listeners after each install.\n *\n * Seed-boundary race: in Toss mode, reads before the install-time SDK seed\n * completes fall through to the native `navigator.connection`. After the seed\n * lands, subsequent reads return the shim's ShimConnection. Consumers that\n * specifically need the ShimConnection instance (e.g., to attach `change`\n * listeners that fire on Toss network transitions) should wait a microtask\n * after `install()` before attaching listeners, or accept that pre-seed\n * reads may return the native object.\n */\n\nimport { isTossEnvironment, loadTossSdk } from '../detect.js';\nimport {\n type InstallSnapshot,\n installNavigatorProperty,\n restoreNavigatorProperty,\n} from './_install-helpers.js';\n\nconst INSTALLED_KEY = Symbol.for('@ait-co/polyfill/network.installed');\nconst ON_LINE_SNAPSHOT_KEY = Symbol.for('@ait-co/polyfill/network.onLine.snapshot');\nconst CONNECTION_SNAPSHOT_KEY = Symbol.for('@ait-co/polyfill/network.connection.snapshot');\n\ninterface BackupHost {\n [INSTALLED_KEY]?: boolean;\n [ON_LINE_SNAPSHOT_KEY]?: InstallSnapshot | undefined;\n [CONNECTION_SNAPSHOT_KEY]?: InstallSnapshot | undefined;\n}\n\ntype SdkNetworkStatus = 'OFFLINE' | 'WIFI' | '2G' | '3G' | '4G' | '5G' | 'WWAN' | 'UNKNOWN';\ntype EffectiveType = 'slow-2g' | '2g' | '3g' | '4g';\n\nconst REFRESH_THROTTLE_MS = 500;\n\nfunction statusToOnline(status: SdkNetworkStatus): boolean {\n return status !== 'OFFLINE';\n}\n\nfunction statusToEffectiveType(status: SdkNetworkStatus): EffectiveType {\n switch (status) {\n case '2G':\n return '2g';\n case '3G':\n return '3g';\n default:\n return '4g';\n }\n}\n\nfunction statusToConnectionType(status: SdkNetworkStatus): string {\n switch (status) {\n case 'WIFI':\n return 'wifi';\n case '2G':\n case '3G':\n case '4G':\n case '5G':\n case 'WWAN':\n return 'cellular';\n case 'OFFLINE':\n return 'none';\n default:\n return 'unknown';\n }\n}\n\n// Symbol-keyed setter: the install closure can mutate status without exposing\n// a `setStatus` name on `navigator.connection` (real NetworkInformation has\n// no mutator). `Object.getOwnPropertySymbols(navigator.connection)` returns\n// nothing, so casual enumeration can't find it. A determined caller walking\n// the prototype chain (`Object.getOwnPropertySymbols(Object.getPrototypeOf(...))`)\n// can still surface the symbol — there is no trust boundary between polyfill\n// and consumer code in the same realm, so this is a discouragement, not a\n// security control.\nconst SET_STATUS = Symbol('@ait-co/polyfill/network.setStatus');\n\nclass ShimConnection extends EventTarget {\n #status: SdkNetworkStatus | null = null;\n onchange: ((this: ShimConnection, ev: Event) => unknown) | null = null;\n\n constructor() {\n super();\n // Forward `change` events to the legacy `onchange` handler for parity with\n // the NetworkInformation API.\n this.addEventListener('change', (ev) => this.onchange?.call(this, ev));\n }\n\n [SET_STATUS](next: SdkNetworkStatus | null): void {\n this.#status = next;\n }\n\n get effectiveType(): EffectiveType {\n return statusToEffectiveType(this.#status ?? 'UNKNOWN');\n }\n // `downlink` / `rtt` / `saveData` are placeholders — the SDK does not expose\n // these. We return 0/false rather than fabricate plausible numbers. Noted\n // in CLAUDE.md.\n get downlink(): number {\n return 0;\n }\n get rtt(): number {\n return 0;\n }\n get saveData(): boolean {\n return false;\n }\n get type(): string {\n return statusToConnectionType(this.#status ?? 'UNKNOWN');\n }\n}\n\nexport function installNetworkShim(): () => void {\n if (typeof navigator === 'undefined') {\n return () => {};\n }\n\n const host = navigator as unknown as BackupHost;\n if (host[INSTALLED_KEY]) {\n return () => uninstallNetworkShim();\n }\n host[INSTALLED_KEY] = true;\n\n // Per-install state. Kept in closure so uninstall/reinstall cycles don't\n // leak state between instances (module-scope would leak across tests).\n let cachedStatus: SdkNetworkStatus | null = null;\n let lastRefresh = 0;\n let inflight: Promise<void> | null = null;\n const connection = new ShimConnection();\n\n async function refresh(): Promise<void> {\n // Coalesce concurrent refreshes — without this, rapid reads during an\n // in-flight SDK call each set `lastRefresh` and return early, without\n // anyone actually fetching fresh data.\n if (inflight) return inflight;\n const now = Date.now();\n if (now - lastRefresh < REFRESH_THROTTLE_MS) return;\n inflight = (async () => {\n try {\n if (!(await isTossEnvironment())) return;\n const sdk = await loadTossSdk();\n const fn = (sdk as { getNetworkStatus?: unknown } | null)?.getNetworkStatus;\n if (typeof fn !== 'function') return;\n const next = (await (fn as () => Promise<SdkNetworkStatus>)()) as SdkNetworkStatus;\n const prev = cachedStatus;\n cachedStatus = next;\n connection[SET_STATUS](next);\n // Only dispatch `change` on real transitions — the null → X seed on\n // first install is learning, not a transition, and would otherwise\n // mis-trigger consumer handlers.\n if (prev !== null && prev !== next) {\n connection.dispatchEvent(new Event('change'));\n }\n } catch {\n // Advisory — refresh failures keep the prior cache. `void refresh()`\n // callers would otherwise surface unhandled rejections if\n // isTossEnvironment / loadTossSdk / getNetworkStatus ever throw.\n } finally {\n lastRefresh = Date.now();\n inflight = null;\n }\n })();\n return inflight;\n }\n\n // Capture the native values **before** we install so the getters can fall\n // through without needing to temporarily remove their own shadow (which is\n // incompatible with prototype-level installs — Chromium keeps\n // `navigator.onLine` / `connection` non-configurable on the instance, so we\n // may end up installing on Navigator.prototype instead).\n const nativeOnLine = (navigator as Navigator & { onLine?: boolean }).onLine;\n const nativeConnection = (navigator as Navigator & { connection?: unknown }).connection;\n\n // Seed the cache on install so the first sync read is meaningful.\n void refresh();\n\n host[ON_LINE_SNAPSHOT_KEY] = installNavigatorProperty('onLine', {\n configurable: true,\n get() {\n void refresh();\n if (cachedStatus !== null) return statusToOnline(cachedStatus);\n return nativeOnLine ?? true;\n },\n });\n\n host[CONNECTION_SNAPSHOT_KEY] = installNavigatorProperty('connection', {\n configurable: true,\n get() {\n void refresh();\n if (cachedStatus === null && nativeConnection !== undefined) return nativeConnection;\n return connection;\n },\n });\n\n return uninstallNetworkShim;\n}\n\nexport function uninstallNetworkShim(): void {\n if (typeof navigator === 'undefined') return;\n const host = navigator as unknown as BackupHost;\n if (!host[INSTALLED_KEY]) return;\n\n const onLineSnap = host[ON_LINE_SNAPSHOT_KEY];\n if (onLineSnap) restoreNavigatorProperty('onLine', onLineSnap);\n const connSnap = host[CONNECTION_SNAPSHOT_KEY];\n if (connSnap) restoreNavigatorProperty('connection', connSnap);\n\n delete host[INSTALLED_KEY];\n delete host[ON_LINE_SNAPSHOT_KEY];\n delete host[CONNECTION_SNAPSHOT_KEY];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkBA,IAAI;;;;;;;;AAgCJ,eAAsB,oBAAsC;CAG1D,MAAM,QAAQ,WAAW;AACzB,KAAI,UAAU,OAAQ,QAAO;AAC7B,KAAI,UAAU,UAAW,QAAO;AAEhC,KAAI,WAAW,KAAA,EAAW,QAAO;C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,MAAO,IAAwC;IAC7D,MAAM,OAAO;AACb,mBAAe;AACf,eAAW,YAAY,KAAK;AAI5B,QAAI,SAAS,QAAQ,SAAS,KAC5B,YAAW,cAAc,IAAI,MAAM,SAAS,CAAC;WAEzC,WAIE;AACR,kBAAc,KAAK,KAAK;AACxB,eAAW;;MAEX;AACJ,SAAO;;CAQT,MAAM,eAAgB,UAA+C;CACrE,MAAM,mBAAoB,UAAmD;AAGxE,UAAS;AAEd,MAAK,wBAAwB,yBAAyB,UAAU;EAC9D,cAAc;EACd,MAAM;AACC,YAAS;AACd,OAAI,iBAAiB,KAAM,QAAO,eAAe,aAAa;AAC9D,UAAO,gBAAgB;;EAE1B,CAAC;AAEF,MAAK,2BAA2B,yBAAyB,cAAc;EACrE,cAAc;EACd,MAAM;AACC,YAAS;AACd,OAAI,iBAAiB,QAAQ,qBAAqB,KAAA,EAAW,QAAO;AACpE,UAAO;;EAEV,CAAC;AAEF,QAAO;;AAGT,SAAgB,uBAA6B;AAC3C,KAAI,OAAO,cAAc,YAAa;CACtC,MAAM,OAAO;AACb,KAAI,CAAC,KAAK,eAAgB;CAE1B,MAAM,aAAa,KAAK;AACxB,KAAI,WAAY,0BAAyB,UAAU,WAAW;CAC9D,MAAM,WAAW,KAAK;AACtB,KAAI,SAAU,0BAAyB,cAAc,SAAS;AAE9D,QAAO,KAAK;AACZ,QAAO,KAAK;AACZ,QAAO,KAAK"}
@@ -1 +1 @@
1
- {"version":3,"file":"share.d.ts","names":[],"sources":["../../src/shims/share.ts"],"mappings":";;AA2HA;;;;;AAsCA;;;;;;;;iBAtCgB,gBAAA,CAAA;AAAA,iBAsCA,kBAAA,CAAA"}
1
+ {"version":3,"file":"share.d.ts","names":[],"sources":["../../src/shims/share.ts"],"mappings":";;AAoIA;;;;;AAsCA;;;;;;;;iBAtCgB,gBAAA,CAAA;AAAA,iBAsCA,kBAAA,CAAA"}