@ait-co/polyfill 0.1.3 → 0.1.5
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 +176 -57
- package/dist/auto.js.map +1 -1
- package/dist/index.d.ts +27 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +177 -58
- package/dist/index.js.map +1 -1
- package/dist/shims/clipboard.js.map +1 -1
- package/dist/shims/geolocation.d.ts +7 -0
- package/dist/shims/geolocation.d.ts.map +1 -1
- package/dist/shims/geolocation.js +90 -47
- package/dist/shims/geolocation.js.map +1 -1
- package/dist/shims/network.d.ts +9 -0
- package/dist/shims/network.d.ts.map +1 -1
- package/dist/shims/network.js +39 -16
- package/dist/shims/network.js.map +1 -1
- package/dist/shims/share.d.ts +6 -0
- package/dist/shims/share.d.ts.map +1 -1
- package/dist/shims/share.js +78 -57
- package/dist/shims/share.js.map +1 -1
- package/dist/shims/vibrate.d.ts +5 -0
- package/dist/shims/vibrate.d.ts.map +1 -1
- package/dist/shims/vibrate.js +75 -45
- package/dist/shims/vibrate.js.map +1 -1
- package/package.json +11 -12
package/dist/shims/share.js
CHANGED
|
@@ -71,50 +71,72 @@ async function loadTossSdk() {
|
|
|
71
71
|
//#endregion
|
|
72
72
|
//#region src/shims/_install-helpers.ts
|
|
73
73
|
/**
|
|
74
|
-
*
|
|
75
|
-
*
|
|
76
|
-
* `
|
|
74
|
+
* Mutate methods on an existing object rather than replacing the object
|
|
75
|
+
* itself. This is the path we take for `navigator.geolocation`, `navigator.share`,
|
|
76
|
+
* and `navigator.vibrate` in Chromium, where the slot on `navigator` is a
|
|
77
|
+
* non-configurable own property that we cannot replace — but the methods
|
|
78
|
+
* themselves (or the methods on the referenced object) are still
|
|
79
|
+
* `configurable: true, writable: true`.
|
|
77
80
|
*
|
|
78
|
-
*
|
|
79
|
-
*
|
|
81
|
+
* Each replacement is installed via plain assignment. If any slot is not
|
|
82
|
+
* writable (e.g. frozen object), install is aborted and previously-applied
|
|
83
|
+
* replacements are rolled back, so the caller observes an atomic "all or
|
|
84
|
+
* nothing" failure as `null`. The caller is expected to degrade gracefully
|
|
85
|
+
* (e.g. log a one-time `console.warn`) when that happens.
|
|
80
86
|
*/
|
|
81
|
-
function
|
|
82
|
-
const
|
|
83
|
-
const
|
|
84
|
-
const
|
|
85
|
-
|
|
86
|
-
Object.
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
87
|
+
function installObjectMethods(target, replacements) {
|
|
88
|
+
const methods = {};
|
|
89
|
+
const applied = [];
|
|
90
|
+
const bag = target;
|
|
91
|
+
for (const key of Object.keys(replacements)) {
|
|
92
|
+
const hadOwn = Object.hasOwn(target, key);
|
|
93
|
+
const original = bag[key];
|
|
94
|
+
try {
|
|
95
|
+
bag[key] = replacements[key];
|
|
96
|
+
} catch {
|
|
97
|
+
for (const applieKey of applied) {
|
|
98
|
+
const prev = methods[applieKey];
|
|
99
|
+
if (!prev) continue;
|
|
100
|
+
if (prev.hadOwn) bag[applieKey] = prev.original;
|
|
101
|
+
else delete bag[applieKey];
|
|
102
|
+
}
|
|
103
|
+
return null;
|
|
104
|
+
}
|
|
105
|
+
if (bag[key] !== replacements[key]) {
|
|
106
|
+
for (const applieKey of applied) {
|
|
107
|
+
const prev = methods[applieKey];
|
|
108
|
+
if (!prev) continue;
|
|
109
|
+
if (prev.hadOwn) bag[applieKey] = prev.original;
|
|
110
|
+
else delete bag[applieKey];
|
|
111
|
+
}
|
|
112
|
+
return null;
|
|
113
|
+
}
|
|
114
|
+
methods[key] = {
|
|
115
|
+
hadOwn,
|
|
116
|
+
original
|
|
91
117
|
};
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
const protoDesc = Object.getOwnPropertyDescriptor(proto, prop);
|
|
95
|
-
if (instanceHadOwn) try {
|
|
96
|
-
delete nav[prop];
|
|
97
|
-
} catch {}
|
|
98
|
-
Object.defineProperty(proto, prop, descriptor);
|
|
118
|
+
applied.push(key);
|
|
119
|
+
}
|
|
99
120
|
return {
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
instanceHadOwn
|
|
121
|
+
target,
|
|
122
|
+
methods
|
|
103
123
|
};
|
|
104
124
|
}
|
|
105
125
|
/**
|
|
106
|
-
* Reverse
|
|
107
|
-
*
|
|
108
|
-
*
|
|
126
|
+
* Reverse an `installObjectMethods` snapshot. Reassigns originals for slots
|
|
127
|
+
* that were own properties before install; deletes the override for slots
|
|
128
|
+
* that were inherited (so the prototype method surfaces again).
|
|
109
129
|
*/
|
|
110
|
-
function
|
|
111
|
-
const
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
130
|
+
function restoreObjectMethods(snapshot) {
|
|
131
|
+
const bag = snapshot.target;
|
|
132
|
+
for (const key of Object.keys(snapshot.methods)) {
|
|
133
|
+
const entry = snapshot.methods[key];
|
|
134
|
+
if (!entry) continue;
|
|
135
|
+
try {
|
|
136
|
+
if (entry.hadOwn) bag[key] = entry.original;
|
|
137
|
+
else delete bag[key];
|
|
138
|
+
} catch {}
|
|
139
|
+
}
|
|
118
140
|
}
|
|
119
141
|
//#endregion
|
|
120
142
|
//#region src/shims/share.ts
|
|
@@ -128,13 +150,18 @@ function restoreNavigatorProperty(prop, snapshot) {
|
|
|
128
150
|
* Outside Apps in Toss → defers to the browser's native `navigator.share`, or
|
|
129
151
|
* throws `NotSupportedError` if unavailable.
|
|
130
152
|
*
|
|
153
|
+
* Install strategy: **method-level** on `navigator`. Assigning
|
|
154
|
+
* `navigator.share = fn` creates an own property that shadows the prototype
|
|
155
|
+
* method. Uninstall deletes the own shadow so the prototype method surfaces
|
|
156
|
+
* again. We do not mutate `Navigator.prototype` — in real browsers its
|
|
157
|
+
* descriptor may be non-configurable, which would throw on reassignment.
|
|
158
|
+
*
|
|
131
159
|
* Caveat: the SDK's share has no counterpart for `files` (Web Share Level 2).
|
|
132
160
|
* `canShare({ files })` returns `false` whenever the sync-accessible detection
|
|
133
161
|
* says Toss is active (or is being forced via the test override).
|
|
134
162
|
*/
|
|
135
163
|
const SHARE_BACKUP_KEY = Symbol.for("@ait-co/polyfill/share.original");
|
|
136
164
|
const SHARE_SNAPSHOT_KEY = Symbol.for("@ait-co/polyfill/share.snapshot");
|
|
137
|
-
const CAN_SHARE_SNAPSHOT_KEY = Symbol.for("@ait-co/polyfill/canShare.snapshot");
|
|
138
165
|
function buildSdkMessage(data) {
|
|
139
166
|
const parts = [];
|
|
140
167
|
if (data?.title != null && data.title !== "") parts.push(data.title);
|
|
@@ -161,7 +188,7 @@ async function shareShim(data) {
|
|
|
161
188
|
}
|
|
162
189
|
const original = navigator[SHARE_BACKUP_KEY]?.share;
|
|
163
190
|
if (!original) throw new DOMException("[@ait-co/polyfill] navigator.share is not available in this environment.", "NotSupportedError");
|
|
164
|
-
return original
|
|
191
|
+
return original(data);
|
|
165
192
|
}
|
|
166
193
|
function canShareShim(data) {
|
|
167
194
|
const hasFiles = Boolean(data?.files && data.files.length > 0);
|
|
@@ -172,7 +199,7 @@ function canShareShim(data) {
|
|
|
172
199
|
}
|
|
173
200
|
if (toss === true) return Boolean(data?.title != null && data.title !== "" || data?.text != null && data.text !== "" || data?.url != null && data.url !== "");
|
|
174
201
|
const originalCanShare = navigator[SHARE_BACKUP_KEY]?.canShare;
|
|
175
|
-
if (originalCanShare) return originalCanShare
|
|
202
|
+
if (originalCanShare) return originalCanShare(data);
|
|
176
203
|
return Boolean(data?.title != null && data.title !== "" || data?.text != null && data.text !== "" || data?.url != null && data.url !== "");
|
|
177
204
|
}
|
|
178
205
|
function installShareShim() {
|
|
@@ -181,34 +208,28 @@ function installShareShim() {
|
|
|
181
208
|
if (SHARE_BACKUP_KEY in host) return () => uninstallShareShim();
|
|
182
209
|
const nav = navigator;
|
|
183
210
|
host[SHARE_BACKUP_KEY] = {
|
|
184
|
-
share: nav.share,
|
|
185
|
-
canShare: nav.canShare
|
|
186
|
-
hadShare: "share" in nav,
|
|
187
|
-
hadCanShare: "canShare" in nav
|
|
211
|
+
share: nav.share ? nav.share.bind(navigator) : void 0,
|
|
212
|
+
canShare: nav.canShare ? nav.canShare.bind(navigator) : void 0
|
|
188
213
|
};
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
writable: true
|
|
193
|
-
});
|
|
194
|
-
host[CAN_SHARE_SNAPSHOT_KEY] = installNavigatorProperty("canShare", {
|
|
195
|
-
value: canShareShim,
|
|
196
|
-
configurable: true,
|
|
197
|
-
writable: true
|
|
214
|
+
const snapshot = installObjectMethods(navigator, {
|
|
215
|
+
share: shareShim,
|
|
216
|
+
canShare: canShareShim
|
|
198
217
|
});
|
|
218
|
+
if (!snapshot) {
|
|
219
|
+
delete host[SHARE_BACKUP_KEY];
|
|
220
|
+
return () => uninstallShareShim();
|
|
221
|
+
}
|
|
222
|
+
host[SHARE_SNAPSHOT_KEY] = snapshot;
|
|
199
223
|
return uninstallShareShim;
|
|
200
224
|
}
|
|
201
225
|
function uninstallShareShim() {
|
|
202
226
|
if (typeof navigator === "undefined") return;
|
|
203
227
|
const host = navigator;
|
|
204
228
|
if (!(SHARE_BACKUP_KEY in host)) return;
|
|
205
|
-
const
|
|
206
|
-
if (
|
|
207
|
-
const canShareSnap = host[CAN_SHARE_SNAPSHOT_KEY];
|
|
208
|
-
if (canShareSnap) restoreNavigatorProperty("canShare", canShareSnap);
|
|
229
|
+
const snapshot = host[SHARE_SNAPSHOT_KEY];
|
|
230
|
+
if (snapshot) restoreObjectMethods(snapshot);
|
|
209
231
|
delete host[SHARE_BACKUP_KEY];
|
|
210
232
|
delete host[SHARE_SNAPSHOT_KEY];
|
|
211
|
-
delete host[CAN_SHARE_SNAPSHOT_KEY];
|
|
212
233
|
}
|
|
213
234
|
//#endregion
|
|
214
235
|
export { installShareShim, uninstallShareShim };
|
package/dist/shims/share.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"share.js","names":[],"sources":["../../src/detect.ts","../../src/shims/_install-helpers.ts","../../src/shims/share.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.share` shim.\n *\n * Inside Apps in Toss → routes through SDK `share({ message })`. The SDK only\n * accepts a single `message` string, so we concatenate `title`, `text`, and\n * `url` with newline separators (skipping missing/empty values).\n *\n * Outside Apps in Toss → defers to the browser's native `navigator.share`, or\n * throws `NotSupportedError` if unavailable.\n *\n * Caveat: the SDK's share has no counterpart for `files` (Web Share Level 2).\n * `canShare({ files })` returns `false` whenever the sync-accessible detection\n * says Toss is active (or is being forced via the test override).\n */\n\nimport { isTossEnvironment, isTossEnvironmentCached, loadTossSdk } from '../detect.js';\nimport {\n type InstallSnapshot,\n installNavigatorProperty,\n restoreNavigatorProperty,\n} from './_install-helpers.js';\n\nconst SHARE_BACKUP_KEY = Symbol.for('@ait-co/polyfill/share.original');\nconst SHARE_SNAPSHOT_KEY = Symbol.for('@ait-co/polyfill/share.snapshot');\nconst CAN_SHARE_SNAPSHOT_KEY = Symbol.for('@ait-co/polyfill/canShare.snapshot');\n\ntype ShareFn = (data?: ShareData) => Promise<void>;\ntype CanShareFn = (data?: ShareData) => boolean;\n\ninterface Backup {\n share?: ShareFn | undefined;\n canShare?: CanShareFn | undefined;\n hadShare: boolean;\n hadCanShare: boolean;\n}\n\ninterface BackupHost {\n [SHARE_BACKUP_KEY]?: Backup | undefined;\n [SHARE_SNAPSHOT_KEY]?: InstallSnapshot | undefined;\n [CAN_SHARE_SNAPSHOT_KEY]?: InstallSnapshot | undefined;\n}\n\nfunction buildSdkMessage(data: ShareData | undefined): string {\n // Use presence checks rather than truthiness so an intentionally empty\n // string in one field is handled correctly alongside a non-empty sibling.\n const parts: string[] = [];\n if (data?.title != null && data.title !== '') parts.push(data.title);\n if (data?.text != null && data.text !== '') parts.push(data.text);\n if (data?.url != null && data.url !== '') parts.push(data.url);\n return parts.join('\\n');\n}\n\nasync function shareShim(data?: ShareData): Promise<void> {\n if (await isTossEnvironment()) {\n const sdk = await loadTossSdk();\n const fn = (sdk as { share?: unknown } | null)?.share;\n if (typeof fn === 'function') {\n const message = buildSdkMessage(data);\n if (!message) {\n throw new TypeError(\n '[@ait-co/polyfill] navigator.share requires at least one of title, text, or url.',\n );\n }\n try {\n await (fn as (o: { message: string }) => Promise<void>)({ message });\n } catch (e) {\n // Spec says navigator.share rejects with a DOMException. Wrap SDK\n // errors as AbortError (the most common cause is user cancellation),\n // attaching the original as `.cause` for Sentry-style telemetry.\n const message_ = e instanceof Error ? e.message : String(e);\n const wrapped = new DOMException(message_, 'AbortError');\n if (e instanceof Error) {\n (wrapped as Error).cause = e;\n }\n throw wrapped;\n }\n return;\n }\n }\n const host = navigator as unknown as BackupHost;\n const backup = host[SHARE_BACKUP_KEY];\n const original = backup?.share;\n if (!original) {\n throw new DOMException(\n '[@ait-co/polyfill] navigator.share is not available in this environment.',\n 'NotSupportedError',\n );\n }\n return original.call(navigator, data);\n}\n\nfunction canShareShim(data?: ShareData): boolean {\n const hasFiles = Boolean(data?.files && data.files.length > 0);\n const toss = isTossEnvironmentCached();\n\n if (hasFiles) {\n // SDK does not share files. If we know we're in Toss (or it's being\n // forced), say so honestly. If detection hasn't resolved yet, be\n // pessimistic — a false negative is safer than promising a capability\n // we'll turn around and deny.\n if (toss === true) return false;\n if (toss === undefined) return false;\n }\n\n // Toss with non-file payloads: true iff there's at least one field.\n if (toss === true) {\n return Boolean(\n (data?.title != null && data.title !== '') ||\n (data?.text != null && data.text !== '') ||\n (data?.url != null && data.url !== ''),\n );\n }\n\n // `toss === undefined` (detection not resolved) with non-file payload falls\n // through to the browser-native answer. Rationale: `canShare` is rarely\n // load-bearing — consumers care about `share()` itself, which awaits the\n // async detection correctly. A false-negative here would needlessly hide a\n // Share button while detection settles.\n // Browser path: delegate to native when present.\n const host = navigator as unknown as BackupHost;\n const backup = host[SHARE_BACKUP_KEY];\n const originalCanShare = backup?.canShare;\n if (originalCanShare) {\n return originalCanShare.call(navigator, data);\n }\n return Boolean(\n (data?.title != null && data.title !== '') ||\n (data?.text != null && data.text !== '') ||\n (data?.url != null && data.url !== ''),\n );\n}\n\nexport function installShareShim(): () => void {\n if (typeof navigator === 'undefined') {\n return () => {};\n }\n\n const host = navigator as unknown as BackupHost;\n if (SHARE_BACKUP_KEY in host) {\n // Already installed. Use `in` so the absence of `share` / `canShare` on\n // the pre-install navigator (legitimately stored as `undefined`) doesn't\n // re-trigger install.\n return () => uninstallShareShim();\n }\n\n const nav = navigator as Navigator & {\n share?: ShareFn;\n canShare?: CanShareFn;\n };\n host[SHARE_BACKUP_KEY] = {\n share: nav.share,\n canShare: nav.canShare,\n hadShare: 'share' in nav,\n hadCanShare: 'canShare' in nav,\n };\n\n host[SHARE_SNAPSHOT_KEY] = installNavigatorProperty('share', {\n value: shareShim,\n configurable: true,\n writable: true,\n });\n host[CAN_SHARE_SNAPSHOT_KEY] = installNavigatorProperty('canShare', {\n value: canShareShim,\n configurable: true,\n writable: true,\n });\n\n return uninstallShareShim;\n}\n\nexport function uninstallShareShim(): void {\n if (typeof navigator === 'undefined') return;\n const host = navigator as unknown as BackupHost;\n if (!(SHARE_BACKUP_KEY in host)) return;\n\n const shareSnap = host[SHARE_SNAPSHOT_KEY];\n if (shareSnap) restoreNavigatorProperty('share', shareSnap);\n const canShareSnap = host[CAN_SHARE_SNAPSHOT_KEY];\n if (canShareSnap) restoreNavigatorProperty('canShare', canShareSnap);\n\n delete host[SHARE_BACKUP_KEY];\n delete host[SHARE_SNAPSHOT_KEY];\n delete host[CAN_SHARE_SNAPSHOT_KEY];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkBA,IAAI;;;;;;;;;;AAkBJ,SAAgB,0BAA+C;CAC7D,MAAM,QAAQ,WAAW;AACzB,KAAI,UAAU,OAAQ,QAAO;AAC7B,KAAI,UAAU,UAAW,QAAO;AAChC,QAAO;;;;;;;;;AAUT,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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AAM,OAAO;AACb,KAAI,oBAAoB,KAItB,cAAa,oBAAoB;CAGnC,MAAM,MAAM;AAIZ,MAAK,oBAAoB;EACvB,OAAO,IAAI;EACX,UAAU,IAAI;EACd,UAAU,WAAW;EACrB,aAAa,cAAc;EAC5B;AAED,MAAK,sBAAsB,yBAAyB,SAAS;EAC3D,OAAO;EACP,cAAc;EACd,UAAU;EACX,CAAC;AACF,MAAK,0BAA0B,yBAAyB,YAAY;EAClE,OAAO;EACP,cAAc;EACd,UAAU;EACX,CAAC;AAEF,QAAO;;AAGT,SAAgB,qBAA2B;AACzC,KAAI,OAAO,cAAc,YAAa;CACtC,MAAM,OAAO;AACb,KAAI,EAAE,oBAAoB,MAAO;CAEjC,MAAM,YAAY,KAAK;AACvB,KAAI,UAAW,0BAAyB,SAAS,UAAU;CAC3D,MAAM,eAAe,KAAK;AAC1B,KAAI,aAAc,0BAAyB,YAAY,aAAa;AAEpE,QAAO,KAAK;AACZ,QAAO,KAAK;AACZ,QAAO,KAAK"}
|
|
1
|
+
{"version":3,"file":"share.js","names":[],"sources":["../../src/detect.ts","../../src/shims/_install-helpers.ts","../../src/shims/share.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 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/**\n * Method-level install snapshot. Captured per-key so `restoreObjectMethods`\n * can distinguish \"was an own property, reassign it\" from \"was inherited,\n * delete the override so the prototype method surfaces again\".\n */\nexport interface MethodInstallSnapshot {\n target: object;\n methods: Record<string, { hadOwn: boolean; original: unknown }>;\n}\n\n/**\n * Mutate methods on an existing object rather than replacing the object\n * itself. This is the path we take for `navigator.geolocation`, `navigator.share`,\n * and `navigator.vibrate` in Chromium, where the slot on `navigator` is a\n * non-configurable own property that we cannot replace — but the methods\n * themselves (or the methods on the referenced object) are still\n * `configurable: true, writable: true`.\n *\n * Each replacement is installed via plain assignment. If any slot is not\n * writable (e.g. frozen object), install is aborted and previously-applied\n * replacements are rolled back, so the caller observes an atomic \"all or\n * nothing\" failure as `null`. The caller is expected to degrade gracefully\n * (e.g. log a one-time `console.warn`) when that happens.\n */\nexport function installObjectMethods(\n target: object,\n replacements: Record<string, (...args: never[]) => unknown>,\n): MethodInstallSnapshot | null {\n const methods: Record<string, { hadOwn: boolean; original: unknown }> = {};\n const applied: string[] = [];\n const bag = target as Record<string, unknown>;\n\n for (const key of Object.keys(replacements)) {\n const hadOwn = Object.hasOwn(target, key);\n const original = bag[key];\n try {\n bag[key] = replacements[key] as unknown;\n } catch {\n // Non-writable / frozen. Roll back and return null.\n for (const applieKey of applied) {\n const prev = methods[applieKey];\n if (!prev) continue;\n if (prev.hadOwn) {\n bag[applieKey] = prev.original;\n } else {\n delete bag[applieKey];\n }\n }\n return null;\n }\n // Verify the assignment actually stuck — silent-failure descriptors (e.g.\n // `writable: false` without strict mode) can skip the throw and leave the\n // original value in place. Treat that the same as a throw.\n if (bag[key] !== (replacements[key] as unknown)) {\n for (const applieKey of applied) {\n const prev = methods[applieKey];\n if (!prev) continue;\n if (prev.hadOwn) {\n bag[applieKey] = prev.original;\n } else {\n delete bag[applieKey];\n }\n }\n return null;\n }\n methods[key] = { hadOwn, original };\n applied.push(key);\n }\n\n return { target, methods };\n}\n\n/**\n * Reverse an `installObjectMethods` snapshot. Reassigns originals for slots\n * that were own properties before install; deletes the override for slots\n * that were inherited (so the prototype method surfaces again).\n */\nexport function restoreObjectMethods(snapshot: MethodInstallSnapshot): void {\n const bag = snapshot.target as Record<string, unknown>;\n for (const key of Object.keys(snapshot.methods)) {\n const entry = snapshot.methods[key];\n if (!entry) continue;\n try {\n if (entry.hadOwn) {\n bag[key] = entry.original;\n } else {\n delete bag[key];\n }\n } catch {\n /* frozen between install and restore — rare. */\n }\n }\n}\n","/**\n * `navigator.share` shim.\n *\n * Inside Apps in Toss → routes through SDK `share({ message })`. The SDK only\n * accepts a single `message` string, so we concatenate `title`, `text`, and\n * `url` with newline separators (skipping missing/empty values).\n *\n * Outside Apps in Toss → defers to the browser's native `navigator.share`, or\n * throws `NotSupportedError` if unavailable.\n *\n * Install strategy: **method-level** on `navigator`. Assigning\n * `navigator.share = fn` creates an own property that shadows the prototype\n * method. Uninstall deletes the own shadow so the prototype method surfaces\n * again. We do not mutate `Navigator.prototype` — in real browsers its\n * descriptor may be non-configurable, which would throw on reassignment.\n *\n * Caveat: the SDK's share has no counterpart for `files` (Web Share Level 2).\n * `canShare({ files })` returns `false` whenever the sync-accessible detection\n * says Toss is active (or is being forced via the test override).\n */\n\nimport { isTossEnvironment, isTossEnvironmentCached, loadTossSdk } from '../detect.js';\nimport {\n installObjectMethods,\n type MethodInstallSnapshot,\n restoreObjectMethods,\n} from './_install-helpers.js';\n\nconst SHARE_BACKUP_KEY = Symbol.for('@ait-co/polyfill/share.original');\nconst SHARE_SNAPSHOT_KEY = Symbol.for('@ait-co/polyfill/share.snapshot');\n\ntype ShareFn = (data?: ShareData) => Promise<void>;\ntype CanShareFn = (data?: ShareData) => boolean;\n\ninterface Backup {\n share: ShareFn | undefined;\n canShare: CanShareFn | undefined;\n}\n\ninterface BackupHost {\n [SHARE_BACKUP_KEY]?: Backup | undefined;\n [SHARE_SNAPSHOT_KEY]?: MethodInstallSnapshot | undefined;\n}\n\nfunction buildSdkMessage(data: ShareData | undefined): string {\n // Use presence checks rather than truthiness so an intentionally empty\n // string in one field is handled correctly alongside a non-empty sibling.\n const parts: string[] = [];\n if (data?.title != null && data.title !== '') parts.push(data.title);\n if (data?.text != null && data.text !== '') parts.push(data.text);\n if (data?.url != null && data.url !== '') parts.push(data.url);\n return parts.join('\\n');\n}\n\nasync function shareShim(data?: ShareData): Promise<void> {\n if (await isTossEnvironment()) {\n const sdk = await loadTossSdk();\n const fn = (sdk as { share?: unknown } | null)?.share;\n if (typeof fn === 'function') {\n const message = buildSdkMessage(data);\n if (!message) {\n throw new TypeError(\n '[@ait-co/polyfill] navigator.share requires at least one of title, text, or url.',\n );\n }\n try {\n await (fn as (o: { message: string }) => Promise<void>)({ message });\n } catch (e) {\n // Spec says navigator.share rejects with a DOMException. Wrap SDK\n // errors as AbortError (the most common cause is user cancellation),\n // attaching the original as `.cause` for Sentry-style telemetry.\n const message_ = e instanceof Error ? e.message : String(e);\n const wrapped = new DOMException(message_, 'AbortError');\n if (e instanceof Error) {\n (wrapped as Error).cause = e;\n }\n throw wrapped;\n }\n return;\n }\n }\n const host = navigator as unknown as BackupHost;\n const backup = host[SHARE_BACKUP_KEY];\n const original = backup?.share;\n if (!original) {\n throw new DOMException(\n '[@ait-co/polyfill] navigator.share is not available in this environment.',\n 'NotSupportedError',\n );\n }\n return original(data);\n}\n\nfunction canShareShim(data?: ShareData): boolean {\n const hasFiles = Boolean(data?.files && data.files.length > 0);\n const toss = isTossEnvironmentCached();\n\n if (hasFiles) {\n // SDK does not share files. If we know we're in Toss (or it's being\n // forced), say so honestly. If detection hasn't resolved yet, be\n // pessimistic — a false negative is safer than promising a capability\n // we'll turn around and deny.\n if (toss === true) return false;\n if (toss === undefined) return false;\n }\n\n // Toss with non-file payloads: true iff there's at least one field.\n if (toss === true) {\n return Boolean(\n (data?.title != null && data.title !== '') ||\n (data?.text != null && data.text !== '') ||\n (data?.url != null && data.url !== ''),\n );\n }\n\n // `toss === undefined` (detection not resolved) with non-file payload falls\n // through to the browser-native answer. Rationale: `canShare` is rarely\n // load-bearing — consumers care about `share()` itself, which awaits the\n // async detection correctly. A false-negative here would needlessly hide a\n // Share button while detection settles.\n // Browser path: delegate to native when present.\n const host = navigator as unknown as BackupHost;\n const backup = host[SHARE_BACKUP_KEY];\n const originalCanShare = backup?.canShare;\n if (originalCanShare) {\n return originalCanShare(data);\n }\n return Boolean(\n (data?.title != null && data.title !== '') ||\n (data?.text != null && data.text !== '') ||\n (data?.url != null && data.url !== ''),\n );\n}\n\nexport function installShareShim(): () => void {\n if (typeof navigator === 'undefined') {\n return () => {};\n }\n\n const host = navigator as unknown as BackupHost;\n if (SHARE_BACKUP_KEY in host) {\n // Already installed. Use `in` so the absence of `share` / `canShare` on\n // the pre-install navigator (legitimately stored as `undefined`) doesn't\n // re-trigger install.\n return () => uninstallShareShim();\n }\n\n const nav = navigator as Navigator & {\n share?: ShareFn;\n canShare?: CanShareFn;\n };\n // Capture the native methods BEFORE patching, bound to `navigator` so that\n // fallback calls keep the correct `this` and never recurse through our shim.\n host[SHARE_BACKUP_KEY] = {\n share: nav.share ? nav.share.bind(navigator) : undefined,\n canShare: nav.canShare ? nav.canShare.bind(navigator) : undefined,\n };\n\n const snapshot = installObjectMethods(navigator, {\n share: shareShim as (...args: never[]) => unknown,\n canShare: canShareShim as (...args: never[]) => unknown,\n });\n\n if (!snapshot) {\n // Slots frozen. Back out the backup bookkeeping so a later install can retry.\n delete host[SHARE_BACKUP_KEY];\n return () => uninstallShareShim();\n }\n\n host[SHARE_SNAPSHOT_KEY] = snapshot;\n return uninstallShareShim;\n}\n\nexport function uninstallShareShim(): void {\n if (typeof navigator === 'undefined') return;\n const host = navigator as unknown as BackupHost;\n if (!(SHARE_BACKUP_KEY in host)) return;\n\n const snapshot = host[SHARE_SNAPSHOT_KEY];\n if (snapshot) restoreObjectMethods(snapshot);\n\n delete host[SHARE_BACKUP_KEY];\n delete host[SHARE_SNAPSHOT_KEY];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkBA,IAAI;;;;;;;;;;AAkBJ,SAAgB,0BAA+C;CAC7D,MAAM,QAAQ,WAAW;AACzB,KAAI,UAAU,OAAQ,QAAO;AAC7B,KAAI,UAAU,UAAW,QAAO;AAChC,QAAO;;;;;;;;;AAUT,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;;;;;;;;;;;;;;;;;;;AC6CX,SAAgB,qBACd,QACA,cAC8B;CAC9B,MAAM,UAAkE,EAAE;CAC1E,MAAM,UAAoB,EAAE;CAC5B,MAAM,MAAM;AAEZ,MAAK,MAAM,OAAO,OAAO,KAAK,aAAa,EAAE;EAC3C,MAAM,SAAS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B,OAAO,IAAI,QAAQ,IAAI,MAAM,KAAK,UAAU,GAAG,KAAA;EAC/C,UAAU,IAAI,WAAW,IAAI,SAAS,KAAK,UAAU,GAAG,KAAA;EACzD;CAED,MAAM,WAAW,qBAAqB,WAAW;EAC/C,OAAO;EACP,UAAU;EACX,CAAC;AAEF,KAAI,CAAC,UAAU;AAEb,SAAO,KAAK;AACZ,eAAa,oBAAoB;;AAGnC,MAAK,sBAAsB;AAC3B,QAAO;;AAGT,SAAgB,qBAA2B;AACzC,KAAI,OAAO,cAAc,YAAa;CACtC,MAAM,OAAO;AACb,KAAI,EAAE,oBAAoB,MAAO;CAEjC,MAAM,WAAW,KAAK;AACtB,KAAI,SAAU,sBAAqB,SAAS;AAE5C,QAAO,KAAK;AACZ,QAAO,KAAK"}
|
package/dist/shims/vibrate.d.ts
CHANGED
|
@@ -11,6 +11,11 @@
|
|
|
11
11
|
* or returns `false` when unavailable (matches the spec — browsers that don't
|
|
12
12
|
* support vibration simply return `false`).
|
|
13
13
|
*
|
|
14
|
+
* Install strategy: **method-level** on `navigator`. We assign our wrapper to
|
|
15
|
+
* `navigator.vibrate` (creating an own shadow over the prototype method) and
|
|
16
|
+
* delete it on uninstall so the prototype re-surfaces. We do not mutate
|
|
17
|
+
* `Navigator.prototype` itself — browsers may mark it non-configurable.
|
|
18
|
+
*
|
|
14
19
|
* Caveats (documented in CLAUDE.md as the known lossy trade-off):
|
|
15
20
|
* - SDK haptics are qualitative ("tickWeak", "basicMedium"), not millisecond
|
|
16
21
|
* durations. The shim approximates intensity from duration but cannot
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vibrate.d.ts","names":[],"sources":["../../src/shims/vibrate.ts"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"vibrate.d.ts","names":[],"sources":["../../src/shims/vibrate.ts"],"mappings":";;AAuHA;;;;;AA4BA;;;;;;;;;;;;;;;;;;;;iBA5BgB,kBAAA,CAAA;AAAA,iBA4BA,oBAAA,CAAA"}
|
package/dist/shims/vibrate.js
CHANGED
|
@@ -56,50 +56,72 @@ async function loadTossSdk() {
|
|
|
56
56
|
//#endregion
|
|
57
57
|
//#region src/shims/_install-helpers.ts
|
|
58
58
|
/**
|
|
59
|
-
*
|
|
60
|
-
*
|
|
61
|
-
* `
|
|
59
|
+
* Mutate methods on an existing object rather than replacing the object
|
|
60
|
+
* itself. This is the path we take for `navigator.geolocation`, `navigator.share`,
|
|
61
|
+
* and `navigator.vibrate` in Chromium, where the slot on `navigator` is a
|
|
62
|
+
* non-configurable own property that we cannot replace — but the methods
|
|
63
|
+
* themselves (or the methods on the referenced object) are still
|
|
64
|
+
* `configurable: true, writable: true`.
|
|
62
65
|
*
|
|
63
|
-
*
|
|
64
|
-
*
|
|
66
|
+
* Each replacement is installed via plain assignment. If any slot is not
|
|
67
|
+
* writable (e.g. frozen object), install is aborted and previously-applied
|
|
68
|
+
* replacements are rolled back, so the caller observes an atomic "all or
|
|
69
|
+
* nothing" failure as `null`. The caller is expected to degrade gracefully
|
|
70
|
+
* (e.g. log a one-time `console.warn`) when that happens.
|
|
65
71
|
*/
|
|
66
|
-
function
|
|
67
|
-
const
|
|
68
|
-
const
|
|
69
|
-
const
|
|
70
|
-
|
|
71
|
-
Object.
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
72
|
+
function installObjectMethods(target, replacements) {
|
|
73
|
+
const methods = {};
|
|
74
|
+
const applied = [];
|
|
75
|
+
const bag = target;
|
|
76
|
+
for (const key of Object.keys(replacements)) {
|
|
77
|
+
const hadOwn = Object.hasOwn(target, key);
|
|
78
|
+
const original = bag[key];
|
|
79
|
+
try {
|
|
80
|
+
bag[key] = replacements[key];
|
|
81
|
+
} catch {
|
|
82
|
+
for (const applieKey of applied) {
|
|
83
|
+
const prev = methods[applieKey];
|
|
84
|
+
if (!prev) continue;
|
|
85
|
+
if (prev.hadOwn) bag[applieKey] = prev.original;
|
|
86
|
+
else delete bag[applieKey];
|
|
87
|
+
}
|
|
88
|
+
return null;
|
|
89
|
+
}
|
|
90
|
+
if (bag[key] !== replacements[key]) {
|
|
91
|
+
for (const applieKey of applied) {
|
|
92
|
+
const prev = methods[applieKey];
|
|
93
|
+
if (!prev) continue;
|
|
94
|
+
if (prev.hadOwn) bag[applieKey] = prev.original;
|
|
95
|
+
else delete bag[applieKey];
|
|
96
|
+
}
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
methods[key] = {
|
|
100
|
+
hadOwn,
|
|
101
|
+
original
|
|
76
102
|
};
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
const protoDesc = Object.getOwnPropertyDescriptor(proto, prop);
|
|
80
|
-
if (instanceHadOwn) try {
|
|
81
|
-
delete nav[prop];
|
|
82
|
-
} catch {}
|
|
83
|
-
Object.defineProperty(proto, prop, descriptor);
|
|
103
|
+
applied.push(key);
|
|
104
|
+
}
|
|
84
105
|
return {
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
instanceHadOwn
|
|
106
|
+
target,
|
|
107
|
+
methods
|
|
88
108
|
};
|
|
89
109
|
}
|
|
90
110
|
/**
|
|
91
|
-
* Reverse
|
|
92
|
-
*
|
|
93
|
-
*
|
|
111
|
+
* Reverse an `installObjectMethods` snapshot. Reassigns originals for slots
|
|
112
|
+
* that were own properties before install; deletes the override for slots
|
|
113
|
+
* that were inherited (so the prototype method surfaces again).
|
|
94
114
|
*/
|
|
95
|
-
function
|
|
96
|
-
const
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
115
|
+
function restoreObjectMethods(snapshot) {
|
|
116
|
+
const bag = snapshot.target;
|
|
117
|
+
for (const key of Object.keys(snapshot.methods)) {
|
|
118
|
+
const entry = snapshot.methods[key];
|
|
119
|
+
if (!entry) continue;
|
|
120
|
+
try {
|
|
121
|
+
if (entry.hadOwn) bag[key] = entry.original;
|
|
122
|
+
else delete bag[key];
|
|
123
|
+
} catch {}
|
|
124
|
+
}
|
|
103
125
|
}
|
|
104
126
|
//#endregion
|
|
105
127
|
//#region src/shims/vibrate.ts
|
|
@@ -115,6 +137,11 @@ function restoreNavigatorProperty(prop, snapshot) {
|
|
|
115
137
|
* or returns `false` when unavailable (matches the spec — browsers that don't
|
|
116
138
|
* support vibration simply return `false`).
|
|
117
139
|
*
|
|
140
|
+
* Install strategy: **method-level** on `navigator`. We assign our wrapper to
|
|
141
|
+
* `navigator.vibrate` (creating an own shadow over the prototype method) and
|
|
142
|
+
* delete it on uninstall so the prototype re-surfaces. We do not mutate
|
|
143
|
+
* `Navigator.prototype` itself — browsers may mark it non-configurable.
|
|
144
|
+
*
|
|
118
145
|
* Caveats (documented in CLAUDE.md as the known lossy trade-off):
|
|
119
146
|
* - SDK haptics are qualitative ("tickWeak", "basicMedium"), not millisecond
|
|
120
147
|
* durations. The shim approximates intensity from duration but cannot
|
|
@@ -140,7 +167,7 @@ function vibrateShim(pattern) {
|
|
|
140
167
|
const arr = Array.isArray(pattern) ? pattern : [pattern];
|
|
141
168
|
if (arr.length === 0 || arr.every((n) => n === 0)) {
|
|
142
169
|
(async () => {
|
|
143
|
-
if (!await isTossEnvironment()) navigator[BACKUP_KEY]?.
|
|
170
|
+
if (!await isTossEnvironment()) navigator[BACKUP_KEY]?.(pattern);
|
|
144
171
|
})();
|
|
145
172
|
return true;
|
|
146
173
|
}
|
|
@@ -159,7 +186,8 @@ function vibrateShim(pattern) {
|
|
|
159
186
|
}
|
|
160
187
|
return;
|
|
161
188
|
}
|
|
162
|
-
navigator[BACKUP_KEY]
|
|
189
|
+
const original = navigator[BACKUP_KEY];
|
|
190
|
+
original?.(pattern);
|
|
163
191
|
})();
|
|
164
192
|
return true;
|
|
165
193
|
}
|
|
@@ -167,12 +195,14 @@ function installVibrateShim() {
|
|
|
167
195
|
if (typeof navigator === "undefined") return () => {};
|
|
168
196
|
const host = navigator;
|
|
169
197
|
if (BACKUP_KEY in host) return () => uninstallVibrateShim();
|
|
170
|
-
|
|
171
|
-
host[
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
198
|
+
const nav = navigator;
|
|
199
|
+
host[BACKUP_KEY] = nav.vibrate ? nav.vibrate.bind(navigator) : void 0;
|
|
200
|
+
const snapshot = installObjectMethods(navigator, { vibrate: vibrateShim });
|
|
201
|
+
if (!snapshot) {
|
|
202
|
+
delete host[BACKUP_KEY];
|
|
203
|
+
return () => uninstallVibrateShim();
|
|
204
|
+
}
|
|
205
|
+
host[SNAPSHOT_KEY] = snapshot;
|
|
176
206
|
return uninstallVibrateShim;
|
|
177
207
|
}
|
|
178
208
|
function uninstallVibrateShim() {
|
|
@@ -180,7 +210,7 @@ function uninstallVibrateShim() {
|
|
|
180
210
|
const host = navigator;
|
|
181
211
|
if (!(BACKUP_KEY in host)) return;
|
|
182
212
|
const snapshot = host[SNAPSHOT_KEY];
|
|
183
|
-
if (snapshot)
|
|
213
|
+
if (snapshot) restoreObjectMethods(snapshot);
|
|
184
214
|
delete host[BACKUP_KEY];
|
|
185
215
|
delete host[SNAPSHOT_KEY];
|
|
186
216
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vibrate.js","names":[],"sources":["../../src/detect.ts","../../src/shims/_install-helpers.ts","../../src/shims/vibrate.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.vibrate` shim.\n *\n * Inside Apps in Toss → best-effort mapping to SDK `generateHapticFeedback`:\n * - `vibrate(0)` → no-op (web standard: cancels pending vibration)\n * - `vibrate(number)`: short (< 40ms) → `tickWeak`, long (≥ 40ms) → `basicMedium`\n * - `vibrate(number[])`: iterate \"on\" segments (even indices) as `tap` pulses\n *\n * Outside Apps in Toss → defers to the browser's native `navigator.vibrate`,\n * or returns `false` when unavailable (matches the spec — browsers that don't\n * support vibration simply return `false`).\n *\n * Caveats (documented in CLAUDE.md as the known lossy trade-off):\n * - SDK haptics are qualitative (\"tickWeak\", \"basicMedium\"), not millisecond\n * durations. The shim approximates intensity from duration but cannot\n * reproduce exact patterns.\n * - Arrays are fired sequentially via `setTimeout`; gaps between pulses are\n * honoured only as \"time until the next tap\", not as silent-vs-vibrating.\n * - `vibrate` is spec'd as **synchronous**; the SDK call is async. We return\n * `true` immediately (fire-and-forget). Errors from the SDK are swallowed.\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/vibrate.original');\nconst SNAPSHOT_KEY = Symbol.for('@ait-co/polyfill/vibrate.snapshot');\n\ninterface BackupHost {\n [BACKUP_KEY]?: ((pattern: VibratePattern) => boolean) | undefined;\n [SNAPSHOT_KEY]?: InstallSnapshot | undefined;\n}\n\nconst SHORT_VIBRATION_MS = 40;\n\ntype HapticType =\n | 'tickWeak'\n | 'tap'\n | 'tickMedium'\n | 'softMedium'\n | 'basicWeak'\n | 'basicMedium'\n | 'success'\n | 'error'\n | 'wiggle'\n | 'confetti';\n\nasync function haptic(type: HapticType): Promise<void> {\n const sdk = await loadTossSdk();\n const fn = (sdk as { generateHapticFeedback?: unknown } | null)?.generateHapticFeedback;\n if (typeof fn === 'function') {\n try {\n await (fn as (o: { type: HapticType }) => Promise<void>)({ type });\n } catch {\n // Best-effort; spec-level `vibrate` cannot surface errors.\n }\n }\n}\n\nfunction durationToHaptic(duration: number): HapticType {\n return duration < SHORT_VIBRATION_MS ? 'tickWeak' : 'basicMedium';\n}\n\nfunction vibrateShim(pattern: VibratePattern): boolean {\n // Matches the spec: `vibrate(0)` or `vibrate([])` cancels pending vibration.\n // We can't cancel an in-flight SDK haptic (no cancel API), but we still\n // forward the cancel to the browser fallback so native vibration stops.\n const arr = Array.isArray(pattern) ? pattern : [pattern];\n if (arr.length === 0 || arr.every((n) => n === 0)) {\n void (async () => {\n if (!(await isTossEnvironment())) {\n const host = navigator as unknown as BackupHost;\n host[BACKUP_KEY]?.call(navigator, pattern);\n }\n })();\n return true;\n }\n\n void (async () => {\n if (await isTossEnvironment()) {\n if (!Array.isArray(pattern)) {\n await haptic(durationToHaptic(pattern));\n return;\n }\n // Even indices = \"on\" durations, odd indices = pauses. `pattern[i]` is\n // `number | undefined` under `noUncheckedIndexedAccess`; the `undefined`\n // case only arises on out-of-bounds, which our length bound prevents.\n for (let i = 0; i < pattern.length; i += 2) {\n const on = pattern[i];\n if (on === undefined) break;\n if (on > 0) {\n await haptic('tap');\n }\n const pause = pattern[i + 1];\n if (typeof pause === 'number' && pause > 0) {\n await new Promise<void>((r) => setTimeout(r, pause));\n }\n }\n return;\n }\n const host = navigator as unknown as BackupHost;\n const original = host[BACKUP_KEY];\n original?.call(navigator, pattern);\n })();\n\n return true;\n}\n\nexport function installVibrateShim(): () => 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 () => uninstallVibrateShim();\n }\n\n const nav = navigator as Navigator & { vibrate?: (p: VibratePattern) => boolean };\n host[BACKUP_KEY] = nav.vibrate?.bind(navigator);\n\n host[SNAPSHOT_KEY] = installNavigatorProperty('vibrate', {\n value: vibrateShim,\n configurable: true,\n writable: true,\n });\n\n return uninstallVibrateShim;\n}\n\nexport function uninstallVibrateShim(): 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('vibrate', 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,eAAsB,cAA4E;AAChG,KAAI;AACF,SAAO,MAAM,OAAO;SACd;AACN,S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AAM,YAAY;AAChB,OAAI,CAAE,MAAM,mBAAmB,CAChB,WACR,aAAa,KAAK,WAAW,QAAQ;MAE1C;AACJ,SAAO;;AAGT,EAAM,YAAY;AAChB,MAAI,MAAM,mBAAmB,EAAE;AAC7B,OAAI,CAAC,MAAM,QAAQ,QAAQ,EAAE;AAC3B,UAAM,OAAO,iBAAiB,QAAQ,CAAC;AACvC;;AAKF,QAAK,IAAI,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK,GAAG;IAC1C,MAAM,KAAK,QAAQ;AACnB,QAAI,OAAO,KAAA,EAAW;AACtB,QAAI,KAAK,EACP,OAAM,OAAO,MAAM;IAErB,MAAM,QAAQ,QAAQ,IAAI;AAC1B,QAAI,OAAO,UAAU,YAAY,QAAQ,EACvC,OAAM,IAAI,SAAe,MAAM,WAAW,GAAG,MAAM,CAAC;;AAGxD;;AAEW,YACS,aACZ,KAAK,WAAW,QAAQ;KAChC;AAEJ,QAAO;;AAGT,SAAgB,qBAAiC;AAC/C,KAAI,OAAO,cAAc,YACvB,cAAa;CAGf,MAAM,OAAO;AACb,KAAI,cAAc,KAChB,cAAa,sBAAsB;AAIrC,MAAK,cADO,UACW,SAAS,KAAK,UAAU;AAE/C,MAAK,gBAAgB,yBAAyB,WAAW;EACvD,OAAO;EACP,cAAc;EACd,UAAU;EACX,CAAC;AAEF,QAAO;;AAGT,SAAgB,uBAA6B;AAC3C,KAAI,OAAO,cAAc,YAAa;CACtC,MAAM,OAAO;AACb,KAAI,EAAE,cAAc,MAAO;CAE3B,MAAM,WAAW,KAAK;AACtB,KAAI,SAAU,0BAAyB,WAAW,SAAS;AAC3D,QAAO,KAAK;AACZ,QAAO,KAAK"}
|
|
1
|
+
{"version":3,"file":"vibrate.js","names":[],"sources":["../../src/detect.ts","../../src/shims/_install-helpers.ts","../../src/shims/vibrate.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 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/**\n * Method-level install snapshot. Captured per-key so `restoreObjectMethods`\n * can distinguish \"was an own property, reassign it\" from \"was inherited,\n * delete the override so the prototype method surfaces again\".\n */\nexport interface MethodInstallSnapshot {\n target: object;\n methods: Record<string, { hadOwn: boolean; original: unknown }>;\n}\n\n/**\n * Mutate methods on an existing object rather than replacing the object\n * itself. This is the path we take for `navigator.geolocation`, `navigator.share`,\n * and `navigator.vibrate` in Chromium, where the slot on `navigator` is a\n * non-configurable own property that we cannot replace — but the methods\n * themselves (or the methods on the referenced object) are still\n * `configurable: true, writable: true`.\n *\n * Each replacement is installed via plain assignment. If any slot is not\n * writable (e.g. frozen object), install is aborted and previously-applied\n * replacements are rolled back, so the caller observes an atomic \"all or\n * nothing\" failure as `null`. The caller is expected to degrade gracefully\n * (e.g. log a one-time `console.warn`) when that happens.\n */\nexport function installObjectMethods(\n target: object,\n replacements: Record<string, (...args: never[]) => unknown>,\n): MethodInstallSnapshot | null {\n const methods: Record<string, { hadOwn: boolean; original: unknown }> = {};\n const applied: string[] = [];\n const bag = target as Record<string, unknown>;\n\n for (const key of Object.keys(replacements)) {\n const hadOwn = Object.hasOwn(target, key);\n const original = bag[key];\n try {\n bag[key] = replacements[key] as unknown;\n } catch {\n // Non-writable / frozen. Roll back and return null.\n for (const applieKey of applied) {\n const prev = methods[applieKey];\n if (!prev) continue;\n if (prev.hadOwn) {\n bag[applieKey] = prev.original;\n } else {\n delete bag[applieKey];\n }\n }\n return null;\n }\n // Verify the assignment actually stuck — silent-failure descriptors (e.g.\n // `writable: false` without strict mode) can skip the throw and leave the\n // original value in place. Treat that the same as a throw.\n if (bag[key] !== (replacements[key] as unknown)) {\n for (const applieKey of applied) {\n const prev = methods[applieKey];\n if (!prev) continue;\n if (prev.hadOwn) {\n bag[applieKey] = prev.original;\n } else {\n delete bag[applieKey];\n }\n }\n return null;\n }\n methods[key] = { hadOwn, original };\n applied.push(key);\n }\n\n return { target, methods };\n}\n\n/**\n * Reverse an `installObjectMethods` snapshot. Reassigns originals for slots\n * that were own properties before install; deletes the override for slots\n * that were inherited (so the prototype method surfaces again).\n */\nexport function restoreObjectMethods(snapshot: MethodInstallSnapshot): void {\n const bag = snapshot.target as Record<string, unknown>;\n for (const key of Object.keys(snapshot.methods)) {\n const entry = snapshot.methods[key];\n if (!entry) continue;\n try {\n if (entry.hadOwn) {\n bag[key] = entry.original;\n } else {\n delete bag[key];\n }\n } catch {\n /* frozen between install and restore — rare. */\n }\n }\n}\n","/**\n * `navigator.vibrate` shim.\n *\n * Inside Apps in Toss → best-effort mapping to SDK `generateHapticFeedback`:\n * - `vibrate(0)` → no-op (web standard: cancels pending vibration)\n * - `vibrate(number)`: short (< 40ms) → `tickWeak`, long (≥ 40ms) → `basicMedium`\n * - `vibrate(number[])`: iterate \"on\" segments (even indices) as `tap` pulses\n *\n * Outside Apps in Toss → defers to the browser's native `navigator.vibrate`,\n * or returns `false` when unavailable (matches the spec — browsers that don't\n * support vibration simply return `false`).\n *\n * Install strategy: **method-level** on `navigator`. We assign our wrapper to\n * `navigator.vibrate` (creating an own shadow over the prototype method) and\n * delete it on uninstall so the prototype re-surfaces. We do not mutate\n * `Navigator.prototype` itself — browsers may mark it non-configurable.\n *\n * Caveats (documented in CLAUDE.md as the known lossy trade-off):\n * - SDK haptics are qualitative (\"tickWeak\", \"basicMedium\"), not millisecond\n * durations. The shim approximates intensity from duration but cannot\n * reproduce exact patterns.\n * - Arrays are fired sequentially via `setTimeout`; gaps between pulses are\n * honoured only as \"time until the next tap\", not as silent-vs-vibrating.\n * - `vibrate` is spec'd as **synchronous**; the SDK call is async. We return\n * `true` immediately (fire-and-forget). Errors from the SDK are swallowed.\n */\n\nimport { isTossEnvironment, loadTossSdk } from '../detect.js';\nimport {\n installObjectMethods,\n type MethodInstallSnapshot,\n restoreObjectMethods,\n} from './_install-helpers.js';\n\nconst BACKUP_KEY = Symbol.for('@ait-co/polyfill/vibrate.original');\nconst SNAPSHOT_KEY = Symbol.for('@ait-co/polyfill/vibrate.snapshot');\n\ntype VibrateFn = (pattern: VibratePattern) => boolean;\n\ninterface BackupHost {\n [BACKUP_KEY]?: VibrateFn | undefined;\n [SNAPSHOT_KEY]?: MethodInstallSnapshot | undefined;\n}\n\nconst SHORT_VIBRATION_MS = 40;\n\ntype HapticType =\n | 'tickWeak'\n | 'tap'\n | 'tickMedium'\n | 'softMedium'\n | 'basicWeak'\n | 'basicMedium'\n | 'success'\n | 'error'\n | 'wiggle'\n | 'confetti';\n\nasync function haptic(type: HapticType): Promise<void> {\n const sdk = await loadTossSdk();\n const fn = (sdk as { generateHapticFeedback?: unknown } | null)?.generateHapticFeedback;\n if (typeof fn === 'function') {\n try {\n await (fn as (o: { type: HapticType }) => Promise<void>)({ type });\n } catch {\n // Best-effort; spec-level `vibrate` cannot surface errors.\n }\n }\n}\n\nfunction durationToHaptic(duration: number): HapticType {\n return duration < SHORT_VIBRATION_MS ? 'tickWeak' : 'basicMedium';\n}\n\nfunction vibrateShim(pattern: VibratePattern): boolean {\n // Matches the spec: `vibrate(0)` or `vibrate([])` cancels pending vibration.\n // We can't cancel an in-flight SDK haptic (no cancel API), but we still\n // forward the cancel to the browser fallback so native vibration stops.\n const arr = Array.isArray(pattern) ? pattern : [pattern];\n if (arr.length === 0 || arr.every((n) => n === 0)) {\n void (async () => {\n if (!(await isTossEnvironment())) {\n const host = navigator as unknown as BackupHost;\n host[BACKUP_KEY]?.(pattern);\n }\n })();\n return true;\n }\n\n void (async () => {\n if (await isTossEnvironment()) {\n if (!Array.isArray(pattern)) {\n await haptic(durationToHaptic(pattern));\n return;\n }\n // Even indices = \"on\" durations, odd indices = pauses. `pattern[i]` is\n // `number | undefined` under `noUncheckedIndexedAccess`; the `undefined`\n // case only arises on out-of-bounds, which our length bound prevents.\n for (let i = 0; i < pattern.length; i += 2) {\n const on = pattern[i];\n if (on === undefined) break;\n if (on > 0) {\n await haptic('tap');\n }\n const pause = pattern[i + 1];\n if (typeof pause === 'number' && pause > 0) {\n await new Promise<void>((r) => setTimeout(r, pause));\n }\n }\n return;\n }\n const host = navigator as unknown as BackupHost;\n const original = host[BACKUP_KEY];\n original?.(pattern);\n })();\n\n return true;\n}\n\nexport function installVibrateShim(): () => 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 () => uninstallVibrateShim();\n }\n\n const nav = navigator as Navigator & { vibrate?: VibrateFn };\n // Capture the native method BEFORE we patch, bound to `navigator` so our\n // fallback call keeps the correct `this` and never recurses into our shim.\n host[BACKUP_KEY] = nav.vibrate ? nav.vibrate.bind(navigator) : undefined;\n\n const snapshot = installObjectMethods(navigator, {\n vibrate: vibrateShim as (...args: never[]) => unknown,\n });\n\n if (!snapshot) {\n delete host[BACKUP_KEY];\n return () => uninstallVibrateShim();\n }\n\n host[SNAPSHOT_KEY] = snapshot;\n return uninstallVibrateShim;\n}\n\nexport function uninstallVibrateShim(): 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) restoreObjectMethods(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,eAAsB,cAA4E;AAChG,KAAI;AACF,SAAO,MAAM,OAAO;SACd;AACN,SAAO;;;;;;;;;;;;;;;;;;;AC6CX,SAAgB,qBACd,QACA,cAC8B;CAC9B,MAAM,UAAkE,EAAE;CAC1E,MAAM,UAAoB,EAAE;CAC5B,MAAM,MAAM;AAEZ,MAAK,MAAM,OAAO,OAAO,KAAK,aAAa,EAAE;EAC3C,MAAM,SAAS,OAAO,OAAO,QAAQ,IAAI;EACzC,MAAM,WAAW,IAAI;AACrB,MAAI;AACF,OAAI,OAAO,aAAa;UAClB;AAEN,QAAK,MAAM,aAAa,SAAS;IAC/B,MAAM,OAAO,QAAQ;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apps with standard Web APIs (navigator.clipboard, navigator.geolocation, ...) instead of the proprietary SDK",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"engines": {
|
|
@@ -48,15 +48,6 @@
|
|
|
48
48
|
"sideEffects": [
|
|
49
49
|
"./dist/auto.js"
|
|
50
50
|
],
|
|
51
|
-
"scripts": {
|
|
52
|
-
"build": "tsdown",
|
|
53
|
-
"dev": "tsdown --watch",
|
|
54
|
-
"typecheck": "tsc --noEmit",
|
|
55
|
-
"test": "vitest run",
|
|
56
|
-
"lint": "biome check .",
|
|
57
|
-
"lint:fix": "biome check --write .",
|
|
58
|
-
"format": "biome format --write ."
|
|
59
|
-
},
|
|
60
51
|
"peerDependencies": {
|
|
61
52
|
"@apps-in-toss/web-framework": ">=2.4.0 <3.0.0"
|
|
62
53
|
},
|
|
@@ -82,7 +73,6 @@
|
|
|
82
73
|
"polyfill",
|
|
83
74
|
"web-api"
|
|
84
75
|
],
|
|
85
|
-
"packageManager": "pnpm@10.33.0",
|
|
86
76
|
"license": "BSD-3-Clause",
|
|
87
77
|
"publishConfig": {
|
|
88
78
|
"access": "public"
|
|
@@ -94,5 +84,14 @@
|
|
|
94
84
|
"homepage": "https://www.npmjs.com/package/@ait-co/polyfill",
|
|
95
85
|
"bugs": {
|
|
96
86
|
"url": "https://github.com/apps-in-toss-community/polyfill/issues"
|
|
87
|
+
},
|
|
88
|
+
"scripts": {
|
|
89
|
+
"build": "tsdown",
|
|
90
|
+
"dev": "tsdown --watch",
|
|
91
|
+
"typecheck": "tsc --noEmit",
|
|
92
|
+
"test": "vitest run",
|
|
93
|
+
"lint": "biome check .",
|
|
94
|
+
"lint:fix": "biome check --write .",
|
|
95
|
+
"format": "biome format --write ."
|
|
97
96
|
}
|
|
98
|
-
}
|
|
97
|
+
}
|