Skip to content
14 changes: 14 additions & 0 deletions eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,13 @@ const USE_SEARCH_PARAMS_IMPORT_RESTRICTION = {
"Don't read query params with useSearchParams — use useQueryStates from 'nuqs' (typed parsers, URL as state). See CLAUDE.md 'URL as State'. DS 10 ratchet: existing files are allowlisted; new files must use nuqs.",
}

const REGISTER_PLUGIN_IMPORT_RESTRICTION = {
name: '@capacitor/core',
importNames: ['registerPlugin'],
Comment thread
innolope-dev marked this conversation as resolved.
message:
"Don't call registerPlugin directly — declare the plugin with nativeCapability() from '@/utils/native-capability' and reach it through .call(invoke, onUnavailable). This JS ships over the air onto binaries built months earlier, where the plugin simply does not exist and Capacitor answers a missing native method with a rejected promise, not a compile error: a forgotten try/catch is a crash on a user's device that no type and no test sees. The wrapper also gates on platform and keeps the proxy inside the closure, so it can never be returned across an await (the .then trap that shipped in 1.0.44 and 1.0.45–1.0.47).",
Comment thread
innolope-dev marked this conversation as resolved.
Outdated
Comment thread
innolope-dev marked this conversation as resolved.
Outdated
}

const QUERY_STRING_PUSH_MESSAGE =
"Don't build a query string by hand for router.push/replace — write URL state with useQueryStates from 'nuqs' (its setter updates the params in place; pathname-only navigation is fine). See CLAUDE.md 'URL as State'. DS 10 ratchet: existing files are allowlisted; new files must use nuqs."

Expand Down Expand Up @@ -225,6 +232,7 @@ module.exports = [
...RESTRICTED_IMPORT_PATHS,
USE_SEARCH_PARAMS_IMPORT_RESTRICTION,
TAILWIND_MERGE_IMPORT_RESTRICTION,
REGISTER_PLUGIN_IMPORT_RESTRICTION,
Comment thread
innolope-dev marked this conversation as resolved.
Outdated
Comment thread
innolope-dev marked this conversation as resolved.
Outdated
],
},
],
Expand Down Expand Up @@ -260,6 +268,12 @@ module.exports = [
files: ['src/utils/tw.ts', 'src/utils/__tests__/tw.test.ts'],
rules: { 'no-restricted-imports': 'off' },
},
{
// The wrapper itself is the one legal registerPlugin caller — it is
Comment thread
innolope-dev marked this conversation as resolved.
// what every other call site is required to go through.
files: ['src/utils/native-capability.ts'],
rules: { 'no-restricted-imports': 'off' },
},
{
// Capacitor hardware back: different bug class (canGoBack + minimizeApp).
files: ['src/hooks/useNativePlugins.ts'],
Expand Down
148 changes: 148 additions & 0 deletions src/utils/__tests__/native-capability.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
// nativeCapability is the single door to app-local Capacitor plugins, so its
// job is the failure paths: a plugin the running binary predates, a platform
// with no native half, and the registerPlugin proxy's thenable trap.
import { nativeCapability } from '../native-capability'
import { isAndroidNative, isIOSNative } from '../capacitor'
import { createPluginProxy, expectToSettle } from '../__mocks__/capacitor-plugin-proxy'

const pluginImplementation: Record<string, unknown> = {}

jest.mock('@capacitor/core', () => ({
// The real registerPlugin returns a Proxy, not a plain object. Mocking it
// as a plain object is what hides the thenable trap, so the house mock is
// used here too.
registerPlugin: jest.fn(() =>
jest.requireActual('../__mocks__/capacitor-plugin-proxy').createPluginProxy(pluginImplementation, 'TestPlugin')
),
}))

jest.mock('../capacitor', () => ({
isIOSNative: jest.fn(() => false),
isAndroidNative: jest.fn(() => false),
}))

const mockIsIOSNative = isIOSNative as jest.MockedFunction<typeof isIOSNative>
const mockIsAndroidNative = isAndroidNative as jest.MockedFunction<typeof isAndroidNative>

interface TestPlugin {
doThing(options?: undefined): Promise<{ value: string }>
}

describe('nativeCapability', () => {
beforeEach(() => {
jest.clearAllMocks()
for (const key of Object.keys(pluginImplementation)) delete pluginImplementation[key]
mockIsIOSNative.mockReturnValue(false)
mockIsAndroidNative.mockReturnValue(false)
})

it('returns the native answer on a supported platform', async () => {
mockIsIOSNative.mockReturnValue(true)
pluginImplementation.doThing = jest.fn(async () => ({ value: 'native' }))

const capability = nativeCapability<TestPlugin>('TestPlugin', { platforms: ['ios'] })

await expect(capability.call('doThing', undefined, () => ({ value: 'fallback' }))).resolves.toEqual({
value: 'native',
})
})

it('falls back without touching the plugin on an unsupported platform', async () => {
mockIsAndroidNative.mockReturnValue(true)
const doThing = jest.fn()
pluginImplementation.doThing = doThing

const capability = nativeCapability<TestPlugin>('TestPlugin', { platforms: ['ios'] })

await expect(capability.call('doThing', undefined, () => ({ value: 'fallback' }))).resolves.toEqual({
value: 'fallback',
})
// Not merely "answered fallback": on web the proxy exists and invoking
// it rejects, so the gate has to stop the call, not catch it.
expect(doThing).not.toHaveBeenCalled()
})

it('falls back when the running binary predates the plugin', async () => {
mockIsIOSNative.mockReturnValue(true)
// The method is simply absent — exactly an older binary running OTA'd
// JS. The proxy answers with an Unimplemented rejection, not undefined.

const capability = nativeCapability<TestPlugin>('TestPlugin', { platforms: ['ios'] })

await expect(capability.call('doThing', undefined, () => ({ value: 'fallback' }))).resolves.toEqual({
value: 'fallback',
})
})

it('hands the rejection to the fallback, for callers that report it', async () => {
mockIsIOSNative.mockReturnValue(true)
pluginImplementation.doThing = jest.fn(async () => {
throw new Error('user cancelled')
})

const capability = nativeCapability<TestPlugin>('TestPlugin', { platforms: ['ios'] })
const result = await capability.call('doThing', undefined, (error) => ({
value: error instanceof Error ? error.message : 'unknown',
}))

expect(result).toEqual({ value: 'user cancelled' })
})

it('settles rather than hanging, even though the plugin is a proxy', async () => {
mockIsIOSNative.mockReturnValue(true)
pluginImplementation.doThing = jest.fn(async () => ({ value: 'native' }))

const capability = nativeCapability<TestPlugin>('TestPlugin', { platforms: ['ios'] })

// The trap this closes: resolving a promise WITH the plugin makes the
// runtime probe proxy.then, which dispatches a native call that never
// invokes either callback — the promise stays pending forever.
await expect(
expectToSettle(capability.call('doThing', undefined, () => ({ value: 'fallback' })))
).resolves.toEqual({ value: 'native' })
})

it('gives callers no way to get the proxy back out', () => {
const capability = nativeCapability<TestPlugin>('TestPlugin', { platforms: ['ios'] })

// The reason `call` takes a method NAME. With a callback signature,
// `call(async (plugin) => plugin, fallback)` type-checks and then hangs
// forever: the async function assimilates the proxy's .then while
// resolving, so it never reaches the catch or the fallback. There is no
// runtime guard for it — the hang happens before any code of ours runs
// again — so the invariant has to hold at the type level, and typecheck
// is a CI job. If this stops erroring, the hole is back.
// @ts-expect-error a callback is not a method name

Check failure on line 115 in src/utils/__tests__/native-capability.test.ts

View workflow job for this annotation

GitHub Actions / typecheck

Unused '@ts-expect-error' directive.

Check failure on line 115 in src/utils/__tests__/native-capability.test.ts

View workflow job for this annotation

GitHub Actions / ds-shots

Unused '@ts-expect-error' directive.
expect(() =>
capability.call(

Check failure on line 117 in src/utils/__tests__/native-capability.test.ts

View workflow job for this annotation

GitHub Actions / typecheck

Expected 3 arguments, but got 2.

Check failure on line 117 in src/utils/__tests__/native-capability.test.ts

View workflow job for this annotation

GitHub Actions / ds-shots

Expected 3 arguments, but got 2.
async (plugin: TestPlugin) => plugin,
() => undefined
)
).toBeDefined()
Comment thread
innolope-dev marked this conversation as resolved.
Outdated
// @ts-expect-error 'notAMethod' is not on TestPlugin
expect(() => capability.call('notAMethod', undefined, () => undefined)).toBeDefined()
})

it('reports platform support from the declared platforms', () => {
const iosOnly = nativeCapability<TestPlugin>('TestPlugin', { platforms: ['ios'] })
const both = nativeCapability<TestPlugin>('TestPlugin', { platforms: ['ios', 'android'] })

expect(iosOnly.isSupportedPlatform()).toBe(false)

mockIsAndroidNative.mockReturnValue(true)
expect(iosOnly.isSupportedPlatform()).toBe(false)
expect(both.isSupportedPlatform()).toBe(true)

mockIsAndroidNative.mockReturnValue(false)
mockIsIOSNative.mockReturnValue(true)
expect(iosOnly.isSupportedPlatform()).toBe(true)
})

it('keeps the house proxy semantics the mock exists to enforce', async () => {
// Guards the guard: if createPluginProxy ever stopped rejecting for
// absent methods, every "older binary" test above would pass vacuously.
const proxy = createPluginProxy<Record<string, unknown>>({}, 'TestPlugin')

await expect((proxy as unknown as TestPlugin).doThing()).rejects.toThrow('is not implemented')
})
})
19 changes: 19 additions & 0 deletions src/utils/__tests__/push-provisioning.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,14 @@ describe('getPushProvisioningAvailability', () => {

describe('addCardToWallet', () => {
beforeEach(() => {
// Both platform answers reset AND a supported one enabled explicitly:
// clearAllMocks keeps mockReturnValue, so these tests used to pass only
// because the availability suite above happened to leave Android true.
// Run alone, each took the unsupported-platform fallback and never
// reached addCard at all.
jest.clearAllMocks()
mockIsIOSNative.mockReturnValue(false)
mockIsAndroidNative.mockReturnValue(true)
})

it('passes through the native result', async () => {
Expand All @@ -71,6 +78,7 @@ describe('addCardToWallet', () => {
added: true,
last4: '1234',
})
expect(addCard).toHaveBeenCalled()
})

it('never throws — plugin errors come back as { added: false, error }', async () => {
Expand All @@ -79,5 +87,16 @@ describe('addCardToWallet', () => {
added: false,
error: 'boom',
})
expect(addCard).toHaveBeenCalled()
})

it('is unavailable on web without touching the plugin', async () => {
mockIsAndroidNative.mockReturnValue(false)

await expect(addCardToWallet({ cardId: 'c', cardSecret: 's' })).resolves.toEqual({
added: false,
error: 'PushProvisioning is not available on this platform',
})
expect(addCard).not.toHaveBeenCalled()
})
})
25 changes: 6 additions & 19 deletions src/utils/clipboard-detect.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import { registerPlugin } from '@capacitor/core'
import { isIOSNative } from './capacitor'
import { nativeCapability } from './native-capability'

interface ClipboardDetectPlugin {
hasStrings(): Promise<{ value: boolean }>
hasProbableWebUrl(): Promise<{ value: boolean }>
hasStrings(options?: undefined): Promise<{ value: boolean }>
hasProbableWebUrl(options?: undefined): Promise<{ value: boolean }>
}

// App-local iOS plugin (ios/App/App/ClipboardDetectPlugin.swift); no web/Android
// implementation exists — callers must treat "unavailable" as false.
const ClipboardDetect = registerPlugin<ClipboardDetectPlugin>('ClipboardDetect')
const ClipboardDetect = nativeCapability<ClipboardDetectPlugin>('ClipboardDetect', { platforms: ['ios'] })

/**
* iOS-native only: prompt-free "is there text on the clipboard?" check via
Expand All @@ -18,13 +17,7 @@ const ClipboardDetect = registerPlugin<ClipboardDetectPlugin>('ClipboardDetect')
* (OTA'd JS), so the caller simply doesn't offer the paste shortcut there.
*/
export async function clipboardHasStrings(): Promise<boolean> {
if (!isIOSNative()) return false
try {
const { value } = await ClipboardDetect.hasStrings()
return value
} catch {
return false
}
return (await ClipboardDetect.call('hasStrings', undefined, () => ({ value: false }))).value
}

/**
Expand All @@ -35,11 +28,5 @@ export async function clipboardHasStrings(): Promise<boolean> {
* the prompt. False on other platforms and binaries without the method.
*/
export async function clipboardHasProbableWebUrl(): Promise<boolean> {
if (!isIOSNative()) return false
try {
const { value } = await ClipboardDetect.hasProbableWebUrl()
return value
} catch {
return false
}
return (await ClipboardDetect.call('hasProbableWebUrl', undefined, () => ({ value: false }))).value
}
21 changes: 10 additions & 11 deletions src/utils/deferred-link.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@
// native app. android rides the Play Install Referrer; iOS rides a clipboard
// hand-off written on the store-bounce tap and read once on first launch.
// TASK-20772 — the download modal (TASK-20769) is the eventual web consumer.
import { registerPlugin } from '@capacitor/core'
import posthog from 'posthog-js'
import { ANALYTICS_EVENTS, DEFERRED_LINK_OUTCOMES, type DeferredLinkOutcome } from '@/constants/analytics.consts'
import { PLAY_STORE_URL } from '@/constants/general.consts'
import { isValidLocale } from '@/i18n/config'
import { type AppLocale, resolveLocaleOrNull } from '@/i18n/app/config'
import { isAndroidNative, isIOSNative } from './capacitor'
import { nativeCapability } from './native-capability'
import { getFromCookie, saveToCookie, sanitizeRedirectURL } from './cookie-url.utils'
import { toInviteCode } from './invite-code.utils'
import { deepLinkToNativePath } from './native-routes'
Expand Down Expand Up @@ -52,19 +52,18 @@ export interface DeferredPayload {
dest?: string
}

// app-local android plugin (InstallReferrerPlugin.java); throws "not
// implemented" on iOS/web and on older binaries running OTA'd JS — callers
// catch and treat as null.
const InstallReferrer = registerPlugin<{ getReferrer(): Promise<{ referrer: string | null }> }>('InstallReferrer')
// app-local android plugin (InstallReferrerPlugin.java); absent on iOS/web and
// on older binaries running OTA'd JS, which the capability turns into null.
const InstallReferrer = nativeCapability<{ getReferrer(options?: undefined): Promise<{ referrer: string | null }> }>(
'InstallReferrer',
{ platforms: ['android'] }
)

/** raw play install referrer string, or null anywhere it can't be read. */
export async function readInstallReferrer(): Promise<string | null> {
try {
return (await InstallReferrer.getReferrer()).referrer ?? null
} catch {
// older binary without the plugin, iOS/web, or referrer service unavailable
return null
}
// null covers all of: older binary without the plugin, iOS/web, and the
// referrer service being unavailable on a busy first boot.
return (await InstallReferrer.call('getReferrer', undefined, () => ({ referrer: null }))).referrer ?? null
}

// ---------------------------------------------------------------------------
Expand Down
Loading
Loading