@ait-co/polyfill 0.1.1 → 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.
package/dist/auto.js ADDED
@@ -0,0 +1,789 @@
1
+ //#region src/detect.ts
2
+ /**
3
+ * Environment detection: are we running inside Apps in Toss, or a plain browser?
4
+ *
5
+ * Strategy: call the SDK's `getAppsInTossGlobals()` — a synchronous export
6
+ * that returns the runtime's Toss globals (deploymentId, brand name, …)
7
+ * inside the Apps in Toss runtime and throws (RN bridge unavailable)
8
+ * anywhere else. The SDK itself is an **optional** peer dependency; if its
9
+ * module can't be imported we are definitely not inside Toss.
10
+ *
11
+ * Just having the SDK module resolvable is not enough — apps can bundle it
12
+ * and still run in a plain browser. We need the bridge probe to confirm.
13
+ *
14
+ * UA sniffing (spoofable) is avoided. We do call `getAppsInTossGlobals`, but
15
+ * that's a constant read from the bridge — no permission dialogs, no
16
+ * analytics fire. In a plain browser the bridge lookup fails fast (sync
17
+ * throw, microsecond-scale), so the startup cost is negligible.
18
+ */
19
+ let cached;
20
+ /**
21
+ * Synchronous read of the cached detection result. Returns:
22
+ * - `true` / `false` if an override is active or the async detection has
23
+ * already resolved
24
+ * - `undefined` if detection hasn't run yet
25
+ *
26
+ * Used by spec-sync APIs (e.g. `navigator.canShare`) that can't `await`
27
+ * detection.
28
+ */
29
+ function isTossEnvironmentCached() {
30
+ const force = globalThis.__AIT_POLYFILL_FORCE__;
31
+ if (force === "toss") return true;
32
+ if (force === "browser") return false;
33
+ return cached;
34
+ }
35
+ /**
36
+ * Returns `true` iff we detect we are running in an environment where the
37
+ * Apps in Toss SDK (`@apps-in-toss/web-framework`) is present and usable.
38
+ *
39
+ * Async because we use dynamic `import()` to probe the optional peer dep
40
+ * without forcing it into the consumer's bundle.
41
+ */
42
+ async function isTossEnvironment() {
43
+ const force = globalThis.__AIT_POLYFILL_FORCE__;
44
+ if (force === "toss") return true;
45
+ if (force === "browser") return false;
46
+ if (cached !== void 0) return cached;
47
+ const mod = await loadTossSdk();
48
+ if (typeof mod?.getAppsInTossGlobals !== "function") {
49
+ cached = false;
50
+ return cached;
51
+ }
52
+ try {
53
+ const globals = mod.getAppsInTossGlobals();
54
+ cached = Boolean(globals) && typeof globals === "object";
55
+ } catch {
56
+ cached = false;
57
+ }
58
+ return cached;
59
+ }
60
+ /**
61
+ * Lazy SDK accessor — returns the module if available, else `null`. Callers
62
+ * are expected to `await` and null-check. Never throws.
63
+ */
64
+ async function loadTossSdk() {
65
+ try {
66
+ return await import("@apps-in-toss/web-framework");
67
+ } catch {
68
+ return null;
69
+ }
70
+ }
71
+ //#endregion
72
+ //#region src/shims/_install-helpers.ts
73
+ /**
74
+ * Install `descriptor` at `navigator[prop]`. Prefer instance-level; if the
75
+ * browser refuses (property is non-configurable on the instance), install on
76
+ * `Navigator.prototype` instead.
77
+ *
78
+ * Returns a snapshot describing where the original value was, which
79
+ * `restoreNavigatorProperty` uses to undo the install.
80
+ */
81
+ function installNavigatorProperty(prop, descriptor) {
82
+ const nav = navigator;
83
+ const instanceDesc = Object.getOwnPropertyDescriptor(nav, prop);
84
+ const instanceHadOwn = instanceDesc !== void 0;
85
+ if (!instanceDesc || instanceDesc.configurable) try {
86
+ Object.defineProperty(nav, prop, descriptor);
87
+ return {
88
+ location: "instance",
89
+ originalDescriptor: instanceDesc,
90
+ instanceHadOwn
91
+ };
92
+ } catch {}
93
+ const proto = Object.getPrototypeOf(nav);
94
+ const protoDesc = Object.getOwnPropertyDescriptor(proto, prop);
95
+ if (instanceHadOwn) try {
96
+ delete nav[prop];
97
+ } catch {}
98
+ Object.defineProperty(proto, prop, descriptor);
99
+ return {
100
+ location: "prototype",
101
+ originalDescriptor: protoDesc,
102
+ instanceHadOwn
103
+ };
104
+ }
105
+ /**
106
+ * Reverse the install recorded in `snapshot`. If the original descriptor was
107
+ * `undefined` (property didn't exist before), delete the property instead of
108
+ * re-defining it.
109
+ */
110
+ function restoreNavigatorProperty(prop, snapshot) {
111
+ const target = snapshot.location === "instance" ? navigator : Object.getPrototypeOf(navigator);
112
+ if (snapshot.originalDescriptor) try {
113
+ Object.defineProperty(target, prop, snapshot.originalDescriptor);
114
+ } catch {}
115
+ else try {
116
+ delete target[prop];
117
+ } catch {}
118
+ }
119
+ //#endregion
120
+ //#region src/shims/clipboard.ts
121
+ /**
122
+ * `navigator.clipboard` shim.
123
+ *
124
+ * Inside Apps in Toss → routes `readText` / `writeText` through the SDK
125
+ * (`getClipboardText` / `setClipboardText`).
126
+ *
127
+ * Outside Apps in Toss → defers to the browser's native `navigator.clipboard`.
128
+ * If the browser doesn't implement it, the standard `TypeError` / `DOMException`
129
+ * surfaces unchanged — we don't paper over missing support.
130
+ */
131
+ const BACKUP_KEY$2 = Symbol.for("@ait-co/polyfill/clipboard.original");
132
+ const SNAPSHOT_KEY$2 = Symbol.for("@ait-co/polyfill/clipboard.snapshot");
133
+ /**
134
+ * Produces a Clipboard-compatible object whose `readText` / `writeText` methods
135
+ * route to the SDK when in Toss, else fall through to the supplied `fallback`.
136
+ */
137
+ function createClipboardShim(fallback) {
138
+ return {
139
+ async readText() {
140
+ if (await isTossEnvironment()) {
141
+ const sdk = await loadTossSdk();
142
+ if (sdk?.getClipboardText) return sdk.getClipboardText();
143
+ }
144
+ if (!fallback) throw new DOMException("[@ait-co/polyfill] navigator.clipboard.readText is not available in this environment.", "NotSupportedError");
145
+ return fallback.readText();
146
+ },
147
+ async writeText(text) {
148
+ if (await isTossEnvironment()) {
149
+ const sdk = await loadTossSdk();
150
+ if (sdk?.setClipboardText) return sdk.setClipboardText(text);
151
+ }
152
+ if (!fallback) throw new DOMException("[@ait-co/polyfill] navigator.clipboard.writeText is not available in this environment.", "NotSupportedError");
153
+ return fallback.writeText(text);
154
+ },
155
+ async read() {
156
+ if (await isTossEnvironment()) throw new DOMException("[@ait-co/polyfill] navigator.clipboard.read (rich content) is not supported in the Apps in Toss environment. Use readText instead.", "NotSupportedError");
157
+ if (!fallback?.read) throw new DOMException("[@ait-co/polyfill] navigator.clipboard.read is not available.", "NotSupportedError");
158
+ return fallback.read();
159
+ },
160
+ async write(items) {
161
+ if (await isTossEnvironment()) throw new DOMException("[@ait-co/polyfill] navigator.clipboard.write (rich content) is not supported in the Apps in Toss environment. Use writeText instead.", "NotSupportedError");
162
+ if (!fallback?.write) throw new DOMException("[@ait-co/polyfill] navigator.clipboard.write is not available.", "NotSupportedError");
163
+ return fallback.write(items);
164
+ },
165
+ addEventListener: (...args) => fallback?.addEventListener(...args),
166
+ removeEventListener: (...args) => fallback?.removeEventListener(...args),
167
+ dispatchEvent: (event) => fallback?.dispatchEvent(event) ?? false
168
+ };
169
+ }
170
+ /**
171
+ * Install the `navigator.clipboard` shim.
172
+ *
173
+ * @returns an uninstall function that restores the original `navigator.clipboard`.
174
+ * Calling install twice without uninstalling is a no-op on the second call
175
+ * and returns the same uninstall function.
176
+ */
177
+ function installClipboardShim() {
178
+ if (typeof navigator === "undefined") return () => {};
179
+ const host = navigator;
180
+ if (BACKUP_KEY$2 in host) return () => uninstallClipboardShim();
181
+ const original = navigator.clipboard;
182
+ host[BACKUP_KEY$2] = original;
183
+ host[SNAPSHOT_KEY$2] = installNavigatorProperty("clipboard", {
184
+ value: createClipboardShim(original),
185
+ configurable: true,
186
+ writable: true
187
+ });
188
+ return uninstallClipboardShim;
189
+ }
190
+ /**
191
+ * Remove the shim and restore the pre-install shape.
192
+ */
193
+ function uninstallClipboardShim() {
194
+ if (typeof navigator === "undefined") return;
195
+ const host = navigator;
196
+ if (!(BACKUP_KEY$2 in host)) return;
197
+ const snapshot = host[SNAPSHOT_KEY$2];
198
+ if (snapshot) restoreNavigatorProperty("clipboard", snapshot);
199
+ delete host[BACKUP_KEY$2];
200
+ delete host[SNAPSHOT_KEY$2];
201
+ }
202
+ //#endregion
203
+ //#region src/shims/geolocation.ts
204
+ /**
205
+ * `navigator.geolocation` shim.
206
+ *
207
+ * Inside Apps in Toss → routes through the SDK:
208
+ * - `getCurrentPosition` → `getCurrentLocation({ accuracy })`
209
+ * - `watchPosition` / `clearWatch` → `startUpdateLocation({ onEvent, onError, options })`
210
+ *
211
+ * Outside Apps in Toss → defers to the browser's native `navigator.geolocation`.
212
+ * If neither is available, the error callback receives a `GeolocationPositionError`.
213
+ *
214
+ * SDK/Web shape mismatch handled here:
215
+ * - SDK `Accuracy` is a numeric enum (1 = Lowest … 6 = BestForNavigation); the
216
+ * standard `PositionOptions.enableHighAccuracy` is a boolean. We map
217
+ * `true → Accuracy.High (4, "~10m")` and `false → Accuracy.Balanced (3)`.
218
+ * `Highest (5)` / `BestForNavigation (6)` are available but carry a battery
219
+ * cost that's rarely what mini-apps want; consumers who need them should
220
+ * call the SDK directly.
221
+ * - SDK coords lack `speed`; we surface `null` (per the W3C spec when unknown).
222
+ * - SDK `startUpdateLocation` returns an `unsubscribe` fn; we wrap it behind
223
+ * a numeric watch id so `clearWatch(id)` behaves like the standard.
224
+ *
225
+ * Caveat: watch ids reset whenever the shim is uninstalled and reinstalled;
226
+ * they are not stable across such cycles. Ids obtained before uninstall
227
+ * cannot be cleared after uninstall — `clearWatch(id)` on the restored native
228
+ * `navigator.geolocation` uses a different id space, so the SDK subscription
229
+ * leaks. Consumers should `clearWatch` all outstanding ids before calling
230
+ * `uninstall()`.
231
+ */
232
+ const BACKUP_KEY$1 = Symbol.for("@ait-co/polyfill/geolocation.original");
233
+ const SNAPSHOT_KEY$1 = Symbol.for("@ait-co/polyfill/geolocation.snapshot");
234
+ const ACCURACY_BALANCED = 3;
235
+ const ACCURACY_HIGH = 4;
236
+ function toStandardPosition(sdk) {
237
+ const coordsData = {
238
+ latitude: sdk.coords.latitude,
239
+ longitude: sdk.coords.longitude,
240
+ altitude: sdk.coords.altitude,
241
+ accuracy: sdk.coords.accuracy,
242
+ altitudeAccuracy: sdk.coords.altitudeAccuracy,
243
+ heading: sdk.coords.heading,
244
+ speed: null
245
+ };
246
+ return {
247
+ coords: {
248
+ ...coordsData,
249
+ toJSON() {
250
+ return { ...coordsData };
251
+ }
252
+ },
253
+ timestamp: sdk.timestamp,
254
+ toJSON() {
255
+ return {
256
+ coords: { ...coordsData },
257
+ timestamp: sdk.timestamp
258
+ };
259
+ }
260
+ };
261
+ }
262
+ function toPositionError(code, message) {
263
+ const Ctor = globalThis.GeolocationPositionError;
264
+ if (typeof Ctor === "function") {
265
+ const proto = Ctor.prototype;
266
+ if (proto) {
267
+ const shape = {
268
+ code,
269
+ message
270
+ };
271
+ Object.setPrototypeOf(shape, proto);
272
+ return shape;
273
+ }
274
+ }
275
+ return {
276
+ code,
277
+ message,
278
+ PERMISSION_DENIED: 1,
279
+ POSITION_UNAVAILABLE: 2,
280
+ TIMEOUT: 3
281
+ };
282
+ }
283
+ function accuracyFromOptions(options) {
284
+ return options?.enableHighAccuracy ? ACCURACY_HIGH : ACCURACY_BALANCED;
285
+ }
286
+ function createGeolocationShim(fallback) {
287
+ let nextWatchId = 1;
288
+ const sdkWatches = /* @__PURE__ */ new Map();
289
+ const nativeWatches = /* @__PURE__ */ new Map();
290
+ const pendingWatches = /* @__PURE__ */ new Map();
291
+ return {
292
+ getCurrentPosition(success, error, options) {
293
+ (async () => {
294
+ if (await isTossEnvironment()) {
295
+ const fn = (await loadTossSdk())?.getCurrentLocation;
296
+ if (typeof fn === "function") {
297
+ try {
298
+ success(toStandardPosition(await fn({ accuracy: accuracyFromOptions(options) })));
299
+ } catch (e) {
300
+ error?.(toPositionError(2, e instanceof Error ? e.message : "[@ait-co/polyfill] getCurrentLocation failed."));
301
+ }
302
+ return;
303
+ }
304
+ }
305
+ if (!fallback) {
306
+ error?.(toPositionError(2, "[@ait-co/polyfill] navigator.geolocation is not available in this environment."));
307
+ return;
308
+ }
309
+ fallback.getCurrentPosition(success, error, options);
310
+ })();
311
+ },
312
+ watchPosition(success, error, options) {
313
+ const id = nextWatchId++;
314
+ const pending = { cancelled: false };
315
+ pendingWatches.set(id, pending);
316
+ (async () => {
317
+ if (await isTossEnvironment()) {
318
+ const fn = (await loadTossSdk())?.startUpdateLocation;
319
+ if (typeof fn === "function") {
320
+ if (pending.cancelled) {
321
+ pendingWatches.delete(id);
322
+ return;
323
+ }
324
+ const unsubscribe = fn({
325
+ onEvent: (loc) => success(toStandardPosition(loc)),
326
+ onError: (err) => error?.(toPositionError(2, err instanceof Error ? err.message : "[@ait-co/polyfill] startUpdateLocation failed.")),
327
+ options: {
328
+ accuracy: accuracyFromOptions(options),
329
+ timeInterval: 1e3,
330
+ distanceInterval: 0
331
+ }
332
+ });
333
+ if (pending.cancelled) {
334
+ unsubscribe();
335
+ pendingWatches.delete(id);
336
+ return;
337
+ }
338
+ sdkWatches.set(id, unsubscribe);
339
+ pendingWatches.delete(id);
340
+ return;
341
+ }
342
+ }
343
+ if (!fallback) {
344
+ pendingWatches.delete(id);
345
+ error?.(toPositionError(2, "[@ait-co/polyfill] navigator.geolocation is not available in this environment."));
346
+ return;
347
+ }
348
+ if (pending.cancelled) {
349
+ pendingWatches.delete(id);
350
+ return;
351
+ }
352
+ const nativeId = fallback.watchPosition(success, error, options);
353
+ if (pending.cancelled) {
354
+ fallback.clearWatch(nativeId);
355
+ pendingWatches.delete(id);
356
+ return;
357
+ }
358
+ nativeWatches.set(id, nativeId);
359
+ pendingWatches.delete(id);
360
+ })();
361
+ return id;
362
+ },
363
+ clearWatch(id) {
364
+ const pending = pendingWatches.get(id);
365
+ if (pending) {
366
+ pending.cancelled = true;
367
+ pendingWatches.delete(id);
368
+ return;
369
+ }
370
+ const unsubscribe = sdkWatches.get(id);
371
+ if (unsubscribe) {
372
+ unsubscribe();
373
+ sdkWatches.delete(id);
374
+ return;
375
+ }
376
+ const nativeId = nativeWatches.get(id);
377
+ if (nativeId !== void 0 && fallback) {
378
+ fallback.clearWatch(nativeId);
379
+ nativeWatches.delete(id);
380
+ }
381
+ }
382
+ };
383
+ }
384
+ function installGeolocationShim() {
385
+ if (typeof navigator === "undefined") return () => {};
386
+ const host = navigator;
387
+ if (BACKUP_KEY$1 in host) return () => uninstallGeolocationShim();
388
+ const original = navigator.geolocation;
389
+ host[BACKUP_KEY$1] = original;
390
+ host[SNAPSHOT_KEY$1] = installNavigatorProperty("geolocation", {
391
+ value: createGeolocationShim(original),
392
+ configurable: true,
393
+ writable: true
394
+ });
395
+ return uninstallGeolocationShim;
396
+ }
397
+ function uninstallGeolocationShim() {
398
+ if (typeof navigator === "undefined") return;
399
+ const host = navigator;
400
+ if (!(BACKUP_KEY$1 in host)) return;
401
+ const snapshot = host[SNAPSHOT_KEY$1];
402
+ if (snapshot) restoreNavigatorProperty("geolocation", snapshot);
403
+ delete host[BACKUP_KEY$1];
404
+ delete host[SNAPSHOT_KEY$1];
405
+ }
406
+ //#endregion
407
+ //#region src/shims/network.ts
408
+ /**
409
+ * `navigator.onLine` + `navigator.connection` shim.
410
+ *
411
+ * Inside Apps in Toss → seeded from SDK `getNetworkStatus()` on install and
412
+ * refreshed on read (throttled):
413
+ * - `'OFFLINE'` → `onLine = false`
414
+ * - `'WIFI'` → `onLine = true`, `effectiveType = '4g'` (no web wifi value)
415
+ * - `'2G'/'3G'/'4G'/'5G'` → `onLine = true`, `effectiveType = <lowercased>`
416
+ * - `'WWAN'/'UNKNOWN'` → `onLine = true`, `effectiveType = '4g'` (best guess)
417
+ *
418
+ * Outside Apps in Toss → both `navigator.onLine` and `navigator.connection`
419
+ * read through to the native value. Install installs own-instance getters
420
+ * that consult the Toss-seeded cache first; when the cache is empty (which
421
+ * it always is in browser mode), the getter temporarily removes its own
422
+ * shadow, reads the prototype value, and reinstates the shadow.
423
+ *
424
+ * Uninstall `delete`s the instance-level override so the prototype descriptor
425
+ * (where `onLine` and `connection` actually live in real browsers) becomes
426
+ * visible again. We never mutate the prototype — doing so would throw in
427
+ * browsers where the descriptor is non-configurable.
428
+ *
429
+ * Caveat: the Web NetworkInformation API is evented (`change` fires on
430
+ * transitions). The SDK exposes only a one-shot query, so listeners attached
431
+ * to `navigator.connection` are accepted but never fire from a `change` event
432
+ * unless the shim observes a real status transition. Synthesising richer
433
+ * events via polling is tracked in TODO.md.
434
+ *
435
+ * Lifecycle: `navigator.connection` is a ShimConnection instance that lives in
436
+ * the install closure. On uninstall the instance-level override is removed,
437
+ * but listeners the consumer attached to the old instance stay bound to that
438
+ * (now-orphan) object and will not see events from a subsequent install.
439
+ * Consumers should re-attach listeners after each install.
440
+ *
441
+ * Seed-boundary race: in Toss mode, reads before the install-time SDK seed
442
+ * completes fall through to the native `navigator.connection`. After the seed
443
+ * lands, subsequent reads return the shim's ShimConnection. Consumers that
444
+ * specifically need the ShimConnection instance (e.g., to attach `change`
445
+ * listeners that fire on Toss network transitions) should wait a microtask
446
+ * after `install()` before attaching listeners, or accept that pre-seed
447
+ * reads may return the native object.
448
+ */
449
+ const INSTALLED_KEY = Symbol.for("@ait-co/polyfill/network.installed");
450
+ const ON_LINE_SNAPSHOT_KEY = Symbol.for("@ait-co/polyfill/network.onLine.snapshot");
451
+ const CONNECTION_SNAPSHOT_KEY = Symbol.for("@ait-co/polyfill/network.connection.snapshot");
452
+ const REFRESH_THROTTLE_MS = 500;
453
+ function statusToOnline(status) {
454
+ return status !== "OFFLINE";
455
+ }
456
+ function statusToEffectiveType(status) {
457
+ switch (status) {
458
+ case "2G": return "2g";
459
+ case "3G": return "3g";
460
+ default: return "4g";
461
+ }
462
+ }
463
+ function statusToConnectionType(status) {
464
+ switch (status) {
465
+ case "WIFI": return "wifi";
466
+ case "2G":
467
+ case "3G":
468
+ case "4G":
469
+ case "5G":
470
+ case "WWAN": return "cellular";
471
+ case "OFFLINE": return "none";
472
+ default: return "unknown";
473
+ }
474
+ }
475
+ const SET_STATUS = Symbol("@ait-co/polyfill/network.setStatus");
476
+ var ShimConnection = class extends EventTarget {
477
+ #status = null;
478
+ onchange = null;
479
+ constructor() {
480
+ super();
481
+ this.addEventListener("change", (ev) => this.onchange?.call(this, ev));
482
+ }
483
+ [SET_STATUS](next) {
484
+ this.#status = next;
485
+ }
486
+ get effectiveType() {
487
+ return statusToEffectiveType(this.#status ?? "UNKNOWN");
488
+ }
489
+ get downlink() {
490
+ return 0;
491
+ }
492
+ get rtt() {
493
+ return 0;
494
+ }
495
+ get saveData() {
496
+ return false;
497
+ }
498
+ get type() {
499
+ return statusToConnectionType(this.#status ?? "UNKNOWN");
500
+ }
501
+ };
502
+ function installNetworkShim() {
503
+ if (typeof navigator === "undefined") return () => {};
504
+ const host = navigator;
505
+ if (host[INSTALLED_KEY]) return () => uninstallNetworkShim();
506
+ host[INSTALLED_KEY] = true;
507
+ let cachedStatus = null;
508
+ let lastRefresh = 0;
509
+ let inflight = null;
510
+ const connection = new ShimConnection();
511
+ async function refresh() {
512
+ if (inflight) return inflight;
513
+ if (Date.now() - lastRefresh < REFRESH_THROTTLE_MS) return;
514
+ inflight = (async () => {
515
+ try {
516
+ if (!await isTossEnvironment()) return;
517
+ const fn = (await loadTossSdk())?.getNetworkStatus;
518
+ if (typeof fn !== "function") return;
519
+ const next = await fn();
520
+ const prev = cachedStatus;
521
+ cachedStatus = next;
522
+ connection[SET_STATUS](next);
523
+ if (prev !== null && prev !== next) connection.dispatchEvent(new Event("change"));
524
+ } catch {} finally {
525
+ lastRefresh = Date.now();
526
+ inflight = null;
527
+ }
528
+ })();
529
+ return inflight;
530
+ }
531
+ const nativeOnLine = navigator.onLine;
532
+ const nativeConnection = navigator.connection;
533
+ refresh();
534
+ host[ON_LINE_SNAPSHOT_KEY] = installNavigatorProperty("onLine", {
535
+ configurable: true,
536
+ get() {
537
+ refresh();
538
+ if (cachedStatus !== null) return statusToOnline(cachedStatus);
539
+ return nativeOnLine ?? true;
540
+ }
541
+ });
542
+ host[CONNECTION_SNAPSHOT_KEY] = installNavigatorProperty("connection", {
543
+ configurable: true,
544
+ get() {
545
+ refresh();
546
+ if (cachedStatus === null && nativeConnection !== void 0) return nativeConnection;
547
+ return connection;
548
+ }
549
+ });
550
+ return uninstallNetworkShim;
551
+ }
552
+ function uninstallNetworkShim() {
553
+ if (typeof navigator === "undefined") return;
554
+ const host = navigator;
555
+ if (!host[INSTALLED_KEY]) return;
556
+ const onLineSnap = host[ON_LINE_SNAPSHOT_KEY];
557
+ if (onLineSnap) restoreNavigatorProperty("onLine", onLineSnap);
558
+ const connSnap = host[CONNECTION_SNAPSHOT_KEY];
559
+ if (connSnap) restoreNavigatorProperty("connection", connSnap);
560
+ delete host[INSTALLED_KEY];
561
+ delete host[ON_LINE_SNAPSHOT_KEY];
562
+ delete host[CONNECTION_SNAPSHOT_KEY];
563
+ }
564
+ //#endregion
565
+ //#region src/shims/share.ts
566
+ /**
567
+ * `navigator.share` shim.
568
+ *
569
+ * Inside Apps in Toss → routes through SDK `share({ message })`. The SDK only
570
+ * accepts a single `message` string, so we concatenate `title`, `text`, and
571
+ * `url` with newline separators (skipping missing/empty values).
572
+ *
573
+ * Outside Apps in Toss → defers to the browser's native `navigator.share`, or
574
+ * throws `NotSupportedError` if unavailable.
575
+ *
576
+ * Caveat: the SDK's share has no counterpart for `files` (Web Share Level 2).
577
+ * `canShare({ files })` returns `false` whenever the sync-accessible detection
578
+ * says Toss is active (or is being forced via the test override).
579
+ */
580
+ const SHARE_BACKUP_KEY = Symbol.for("@ait-co/polyfill/share.original");
581
+ const SHARE_SNAPSHOT_KEY = Symbol.for("@ait-co/polyfill/share.snapshot");
582
+ const CAN_SHARE_SNAPSHOT_KEY = Symbol.for("@ait-co/polyfill/canShare.snapshot");
583
+ function buildSdkMessage(data) {
584
+ const parts = [];
585
+ if (data?.title != null && data.title !== "") parts.push(data.title);
586
+ if (data?.text != null && data.text !== "") parts.push(data.text);
587
+ if (data?.url != null && data.url !== "") parts.push(data.url);
588
+ return parts.join("\n");
589
+ }
590
+ async function shareShim(data) {
591
+ if (await isTossEnvironment()) {
592
+ const fn = (await loadTossSdk())?.share;
593
+ if (typeof fn === "function") {
594
+ const message = buildSdkMessage(data);
595
+ if (!message) throw new TypeError("[@ait-co/polyfill] navigator.share requires at least one of title, text, or url.");
596
+ try {
597
+ await fn({ message });
598
+ } catch (e) {
599
+ const message_ = e instanceof Error ? e.message : String(e);
600
+ const wrapped = new DOMException(message_, "AbortError");
601
+ if (e instanceof Error) wrapped.cause = e;
602
+ throw wrapped;
603
+ }
604
+ return;
605
+ }
606
+ }
607
+ const original = navigator[SHARE_BACKUP_KEY]?.share;
608
+ if (!original) throw new DOMException("[@ait-co/polyfill] navigator.share is not available in this environment.", "NotSupportedError");
609
+ return original.call(navigator, data);
610
+ }
611
+ function canShareShim(data) {
612
+ const hasFiles = Boolean(data?.files && data.files.length > 0);
613
+ const toss = isTossEnvironmentCached();
614
+ if (hasFiles) {
615
+ if (toss === true) return false;
616
+ if (toss === void 0) return false;
617
+ }
618
+ if (toss === true) return Boolean(data?.title != null && data.title !== "" || data?.text != null && data.text !== "" || data?.url != null && data.url !== "");
619
+ const originalCanShare = navigator[SHARE_BACKUP_KEY]?.canShare;
620
+ if (originalCanShare) return originalCanShare.call(navigator, data);
621
+ return Boolean(data?.title != null && data.title !== "" || data?.text != null && data.text !== "" || data?.url != null && data.url !== "");
622
+ }
623
+ function installShareShim() {
624
+ if (typeof navigator === "undefined") return () => {};
625
+ const host = navigator;
626
+ if (SHARE_BACKUP_KEY in host) return () => uninstallShareShim();
627
+ const nav = navigator;
628
+ host[SHARE_BACKUP_KEY] = {
629
+ share: nav.share,
630
+ canShare: nav.canShare,
631
+ hadShare: "share" in nav,
632
+ hadCanShare: "canShare" in nav
633
+ };
634
+ host[SHARE_SNAPSHOT_KEY] = installNavigatorProperty("share", {
635
+ value: shareShim,
636
+ configurable: true,
637
+ writable: true
638
+ });
639
+ host[CAN_SHARE_SNAPSHOT_KEY] = installNavigatorProperty("canShare", {
640
+ value: canShareShim,
641
+ configurable: true,
642
+ writable: true
643
+ });
644
+ return uninstallShareShim;
645
+ }
646
+ function uninstallShareShim() {
647
+ if (typeof navigator === "undefined") return;
648
+ const host = navigator;
649
+ if (!(SHARE_BACKUP_KEY in host)) return;
650
+ const shareSnap = host[SHARE_SNAPSHOT_KEY];
651
+ if (shareSnap) restoreNavigatorProperty("share", shareSnap);
652
+ const canShareSnap = host[CAN_SHARE_SNAPSHOT_KEY];
653
+ if (canShareSnap) restoreNavigatorProperty("canShare", canShareSnap);
654
+ delete host[SHARE_BACKUP_KEY];
655
+ delete host[SHARE_SNAPSHOT_KEY];
656
+ delete host[CAN_SHARE_SNAPSHOT_KEY];
657
+ }
658
+ //#endregion
659
+ //#region src/shims/vibrate.ts
660
+ /**
661
+ * `navigator.vibrate` shim.
662
+ *
663
+ * Inside Apps in Toss → best-effort mapping to SDK `generateHapticFeedback`:
664
+ * - `vibrate(0)` → no-op (web standard: cancels pending vibration)
665
+ * - `vibrate(number)`: short (< 40ms) → `tickWeak`, long (≥ 40ms) → `basicMedium`
666
+ * - `vibrate(number[])`: iterate "on" segments (even indices) as `tap` pulses
667
+ *
668
+ * Outside Apps in Toss → defers to the browser's native `navigator.vibrate`,
669
+ * or returns `false` when unavailable (matches the spec — browsers that don't
670
+ * support vibration simply return `false`).
671
+ *
672
+ * Caveats (documented in CLAUDE.md as the known lossy trade-off):
673
+ * - SDK haptics are qualitative ("tickWeak", "basicMedium"), not millisecond
674
+ * durations. The shim approximates intensity from duration but cannot
675
+ * reproduce exact patterns.
676
+ * - Arrays are fired sequentially via `setTimeout`; gaps between pulses are
677
+ * honoured only as "time until the next tap", not as silent-vs-vibrating.
678
+ * - `vibrate` is spec'd as **synchronous**; the SDK call is async. We return
679
+ * `true` immediately (fire-and-forget). Errors from the SDK are swallowed.
680
+ */
681
+ const BACKUP_KEY = Symbol.for("@ait-co/polyfill/vibrate.original");
682
+ const SNAPSHOT_KEY = Symbol.for("@ait-co/polyfill/vibrate.snapshot");
683
+ const SHORT_VIBRATION_MS = 40;
684
+ async function haptic(type) {
685
+ const fn = (await loadTossSdk())?.generateHapticFeedback;
686
+ if (typeof fn === "function") try {
687
+ await fn({ type });
688
+ } catch {}
689
+ }
690
+ function durationToHaptic(duration) {
691
+ return duration < SHORT_VIBRATION_MS ? "tickWeak" : "basicMedium";
692
+ }
693
+ function vibrateShim(pattern) {
694
+ const arr = Array.isArray(pattern) ? pattern : [pattern];
695
+ if (arr.length === 0 || arr.every((n) => n === 0)) {
696
+ (async () => {
697
+ if (!await isTossEnvironment()) navigator[BACKUP_KEY]?.call(navigator, pattern);
698
+ })();
699
+ return true;
700
+ }
701
+ (async () => {
702
+ if (await isTossEnvironment()) {
703
+ if (!Array.isArray(pattern)) {
704
+ await haptic(durationToHaptic(pattern));
705
+ return;
706
+ }
707
+ for (let i = 0; i < pattern.length; i += 2) {
708
+ const on = pattern[i];
709
+ if (on === void 0) break;
710
+ if (on > 0) await haptic("tap");
711
+ const pause = pattern[i + 1];
712
+ if (typeof pause === "number" && pause > 0) await new Promise((r) => setTimeout(r, pause));
713
+ }
714
+ return;
715
+ }
716
+ navigator[BACKUP_KEY]?.call(navigator, pattern);
717
+ })();
718
+ return true;
719
+ }
720
+ function installVibrateShim() {
721
+ if (typeof navigator === "undefined") return () => {};
722
+ const host = navigator;
723
+ if (BACKUP_KEY in host) return () => uninstallVibrateShim();
724
+ host[BACKUP_KEY] = navigator.vibrate?.bind(navigator);
725
+ host[SNAPSHOT_KEY] = installNavigatorProperty("vibrate", {
726
+ value: vibrateShim,
727
+ configurable: true,
728
+ writable: true
729
+ });
730
+ return uninstallVibrateShim;
731
+ }
732
+ function uninstallVibrateShim() {
733
+ if (typeof navigator === "undefined") return;
734
+ const host = navigator;
735
+ if (!(BACKUP_KEY in host)) return;
736
+ const snapshot = host[SNAPSHOT_KEY];
737
+ if (snapshot) restoreNavigatorProperty("vibrate", snapshot);
738
+ delete host[BACKUP_KEY];
739
+ delete host[SNAPSHOT_KEY];
740
+ }
741
+ //#endregion
742
+ //#region src/index.ts
743
+ const NOOP = () => {};
744
+ /**
745
+ * Install every shim this library ships, but only if we detect an Apps in
746
+ * Toss runtime. In a plain browser `install()` is a no-op — the browser's
747
+ * native APIs stay untouched.
748
+ *
749
+ * Returns a promise that resolves with an uninstall function. If the
750
+ * environment turns out not to be Toss, the uninstall function is a no-op.
751
+ *
752
+ * Install order (when active): clipboard → geolocation → share → vibrate →
753
+ * network. Not atomic on failure — if a per-shim install throws (e.g., a
754
+ * consumer pinned a target navigator property as non-configurable), earlier
755
+ * shims are already in place. Callers should catch and invoke the returned
756
+ * uninstall to roll back.
757
+ */
758
+ async function install() {
759
+ if (!await isTossEnvironment()) return NOOP;
760
+ const uninstalls = [
761
+ installClipboardShim(),
762
+ installGeolocationShim(),
763
+ installShareShim(),
764
+ installVibrateShim(),
765
+ installNetworkShim()
766
+ ];
767
+ return () => {
768
+ for (const fn of uninstalls) fn();
769
+ };
770
+ }
771
+ //#endregion
772
+ //#region src/auto.ts
773
+ /**
774
+ * Side-effect entry point: `import '@ait-co/polyfill/auto'`
775
+ *
776
+ * Kicks off detection and, if we're inside Apps in Toss, installs every shim
777
+ * this library ships. In a plain browser this is a no-op — browser native
778
+ * APIs stay untouched. No-op idempotent: importing the entry more than once
779
+ * doesn't re-install.
780
+ *
781
+ * Use this when you want the "just add the dep" experience. If you need to
782
+ * observe when the polyfill actually attached (to gate init logic) or to tear
783
+ * it down, import `install` / `uninstall` from `@ait-co/polyfill` directly.
784
+ */
785
+ install();
786
+ //#endregion
787
+ export {};
788
+
789
+ //# sourceMappingURL=auto.js.map