From f8451ed148dece75490389fbe20834ba7e970170 Mon Sep 17 00:00:00 2001 From: Jason Olinger <72224982+jolinger-godaddy@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:08:30 -0500 Subject: [PATCH] Let a dom-bundle UI extension request host actions The mount input carries an optional requestAction. Target and UiExtensionRuntimeHost take an onActionRequest handler; without one, requests reject with action_rejected. --- .changeset/ui-extension-action-requests.md | 7 + .../react/src/ui-extensions/discovery.test.ts | 37 ++ packages/react/src/ui-extensions/discovery.ts | 29 + packages/react/src/ui-extensions/index.ts | 2 + .../runtime/dom-bundle-runtime.test.ts | 569 +++++++++++++++++- .../runtime/dom-bundle-runtime.ts | 274 ++++++++- .../react/src/ui-extensions/runtime/index.ts | 1 + .../runtime/runtime-host.test.tsx | 95 +++ .../ui-extensions/runtime/runtime-host.tsx | 42 +- .../react/src/ui-extensions/runtime/types.ts | 46 +- .../react/src/ui-extensions/target.test.tsx | 67 ++- packages/react/src/ui-extensions/target.tsx | 2 + packages/react/src/ui-extensions/types.ts | 13 + 13 files changed, 1165 insertions(+), 19 deletions(-) create mode 100644 .changeset/ui-extension-action-requests.md create mode 100644 packages/react/src/ui-extensions/discovery.test.ts create mode 100644 packages/react/src/ui-extensions/discovery.ts create mode 100644 packages/react/src/ui-extensions/runtime/runtime-host.test.tsx diff --git a/.changeset/ui-extension-action-requests.md b/.changeset/ui-extension-action-requests.md new file mode 100644 index 000000000..8a7d7dd02 --- /dev/null +++ b/.changeset/ui-extension-action-requests.md @@ -0,0 +1,7 @@ +--- +'@godaddy/react': minor +--- + +A `dom-bundle` UI extension can ask its host to run an action. The mount input now carries an optional `requestAction({ action, input })`, which resolves with the host's result. Hosts handle requests with a new optional `onActionRequest` prop on `Target` and `UiExtensionRuntimeHost`, or through the runtime's existing `onActionRequest` mount option, which now also receives an optional second argument. The handler gets a structured clone of the request and the metadata of the extension that sent it, built from the host's own record, and the extension gets a structured clone of the result. Without a handler, when the host rejects, when a value can't be cloned, without an action name (or with one that is blank or has spaces around it), or when the extension unmounts (including while a request is still waiting on the host), the request rejects with an `action_rejected` runtime error; the host's own reason isn't passed to the extension. The function stays the same for the life of the mount, and under `Target` and `UiExtensionRuntimeHost` it always reaches the host's current committed handler. A request rejected at unmount may still have run on the host. A runtime mounted again before its earlier mount finishes now unmounts the replaced bundle, and that bundle's requests are refused. Existing bundles and hosts work unchanged. + +Hosts that pick a target's extensions before rendering can call the new `getEnabledStoreUiExtensions({ storeId, target, apiHost })`, the same discovery request `useEnabledStoreUiExtensions` sends, outside React. diff --git a/packages/react/src/ui-extensions/discovery.test.ts b/packages/react/src/ui-extensions/discovery.test.ts new file mode 100644 index 000000000..c62ef2912 --- /dev/null +++ b/packages/react/src/ui-extensions/discovery.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, it, vi } from 'vitest'; +import { getEnabledStoreUiExtensions as requestEnabledStoreUiExtensions } from '@/lib/godaddy/godaddy'; +import { getEnabledStoreUiExtensions } from './discovery'; + +vi.mock('@/lib/godaddy/godaddy', () => ({ + getEnabledStoreUiExtensions: vi.fn().mockResolvedValue([{ id: 'app-1' }]), +})); + +describe('getEnabledStoreUiExtensions', () => { + it('sends the same discovery request as the hook, outside React', async () => { + await expect( + getEnabledStoreUiExtensions({ + storeId: 'store-1', + target: 'some.target', + apiHost: 'api.ote-godaddy.com', + }) + ).resolves.toEqual([{ id: 'app-1' }]); + + expect(requestEnabledStoreUiExtensions).toHaveBeenCalledWith( + { storeId: 'store-1', target: 'some.target' }, + 'api.ote-godaddy.com' + ); + }); + + it('sends nothing without a store id or a target, like the hook', async () => { + vi.mocked(requestEnabledStoreUiExtensions).mockClear(); + + await expect( + getEnabledStoreUiExtensions({ storeId: '', target: 'some.target' }) + ).resolves.toEqual([]); + await expect( + getEnabledStoreUiExtensions({ storeId: 'store-1', target: '' }) + ).resolves.toEqual([]); + + expect(requestEnabledStoreUiExtensions).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/react/src/ui-extensions/discovery.ts b/packages/react/src/ui-extensions/discovery.ts new file mode 100644 index 000000000..b8a6076ee --- /dev/null +++ b/packages/react/src/ui-extensions/discovery.ts @@ -0,0 +1,29 @@ +import { getEnabledStoreUiExtensions as requestEnabledStoreUiExtensions } from '@/lib/godaddy/godaddy'; +import type { UiExtensionTargetId } from './types'; + +export interface GetEnabledStoreUiExtensionsInput { + storeId: string; + target: UiExtensionTargetId; + /** The environment's API host, as `GoDaddyProvider` takes it. */ + apiHost?: string; +} + +/** + * Reads the UI extensions enabled for a target on a store, outside React. It + * sends the same Checkout API query as `useEnabledStoreUiExtensions`, for a + * host that has to know a target's extensions before it renders. Like the hook, + * it sends nothing without a store id and a target; it then answers an empty + * list. + */ +export function getEnabledStoreUiExtensions({ + storeId, + target, + apiHost, +}: GetEnabledStoreUiExtensionsInput): ReturnType< + typeof requestEnabledStoreUiExtensions +> { + if (!storeId || !target) { + return Promise.resolve([]); + } + return requestEnabledStoreUiExtensions({ storeId, target }, apiHost); +} diff --git a/packages/react/src/ui-extensions/index.ts b/packages/react/src/ui-extensions/index.ts index 03a50f3c8..64d118742 100644 --- a/packages/react/src/ui-extensions/index.ts +++ b/packages/react/src/ui-extensions/index.ts @@ -1,3 +1,5 @@ +export type { GetEnabledStoreUiExtensionsInput } from './discovery'; +export { getEnabledStoreUiExtensions } from './discovery'; export * from './hooks'; export * from './runtime'; export { Target } from './target'; diff --git a/packages/react/src/ui-extensions/runtime/dom-bundle-runtime.test.ts b/packages/react/src/ui-extensions/runtime/dom-bundle-runtime.test.ts index 1af6928a8..fdc177003 100644 --- a/packages/react/src/ui-extensions/runtime/dom-bundle-runtime.test.ts +++ b/packages/react/src/ui-extensions/runtime/dom-bundle-runtime.test.ts @@ -1,7 +1,13 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import type { UiExtension } from '../types'; import { DomBundleUiExtensionRuntime } from './dom-bundle-runtime'; -import type { UiExtensionRuntimeError } from './types'; +import type { + DomExtensionContract, + DomExtensionMountInput, + UiExtensionActionRequest, + UiExtensionRuntimeError, + UiExtensionRuntimeMountInput, +} from './types'; function createExtension(overrides: Partial = {}): UiExtension { return { @@ -163,6 +169,567 @@ describe('DomBundleUiExtensionRuntime', () => { expect(mount).not.toHaveBeenCalled(); }); + async function mountWithContract( + contract: ( + capture: (input: DomExtensionMountInput) => void + ) => DomExtensionContract, + onActionRequest?: UiExtensionRuntimeMountInput['onActionRequest'] + ) { + const runtime = new DomBundleUiExtensionRuntime({ timeoutMs: 50 }); + let mountInput: DomExtensionMountInput | undefined; + const mountPromise = runtime.mount({ + extension: createExtension(), + context: { target: 'checkout.test-target' }, + container: document.createElement('div'), + onError: () => undefined, + onActionRequest, + }); + + const script = await getLastScript(); + window.GoDaddyUiExtensions?.register( + contract(input => { + mountInput = input; + }) + ); + script.dispatchEvent(new Event('load')); + await mountPromise; + + if (!mountInput?.requestAction) { + throw new Error('mount input has no requestAction'); + } + + return { runtime, mountInput, requestAction: mountInput.requestAction }; + } + + function mountWithActions( + onActionRequest?: UiExtensionRuntimeMountInput['onActionRequest'] + ) { + return mountWithContract( + capture => ({ + mount: capture, + }), + onActionRequest + ); + } + + const extensionMetadata = { + id: 'extension-1', + applicationId: 'app-1', + releaseId: 'release-1', + target: 'checkout.test-target', + }; + + it('passes action requests to the host handler with the extension that sent them', async () => { + const onActionRequest = vi.fn().mockResolvedValue({ saved: true }); + const { requestAction } = await mountWithActions(onActionRequest); + + await expect( + requestAction({ action: 'settings.open', input: { section: 'tax' } }) + ).resolves.toEqual({ saved: true }); + expect(onActionRequest).toHaveBeenCalledWith( + { action: 'settings.open', input: { section: 'tax' } }, + { extension: extensionMetadata } + ); + }); + + it('names the extension from the host record, whatever the bundle changes', async () => { + const onActionRequest = vi.fn().mockResolvedValue(undefined); + const { mountInput, requestAction } = + await mountWithActions(onActionRequest); + + mountInput.extension.id = 'trusted-extension'; + mountInput.extension.applicationId = 'trusted-app'; + await requestAction({ action: 'settings.open' }); + + const [, source] = onActionRequest.mock.calls[0] ?? []; + expect(source).toEqual({ extension: extensionMetadata }); + expect(Object.isFrozen(source.extension)).toBe(true); + }); + + it('passes the host a clone of the request, read once', async () => { + const onActionRequest = vi.fn().mockResolvedValue(undefined); + const { requestAction } = await mountWithActions(onActionRequest); + let reads = 0; + const input = { amount: 1 }; + const request = { + get action() { + reads += 1; + return reads === 1 ? 'settings.open' : 'payments.refund'; + }, + input, + extra: 'ignored', + }; + + const pending = requestAction(request); + input.amount = 10000; + await pending; + + // Counted before the assertions below, which read the getter themselves. + expect(reads).toBe(1); + const [received] = onActionRequest.mock.calls[0] ?? []; + expect(received).toEqual({ action: 'settings.open', input: { amount: 1 } }); + expect(received).not.toBe(request); + }); + + it('rejects a request whose input cannot be cloned, without calling the host', async () => { + const onActionRequest = vi.fn(); + const { requestAction } = await mountWithActions(onActionRequest); + + await expect( + requestAction({ action: 'settings.open', input: { run: () => 1 } }) + ).rejects.toMatchObject({ code: 'action_rejected' }); + expect(onActionRequest).not.toHaveBeenCalled(); + }); + + it('gives the extension a clone of the host result', async () => { + const hostState = { rate: 7 }; + const { requestAction } = await mountWithActions(() => + Promise.resolve(hostState) + ); + + const result = (await requestAction({ action: 'settings.get' })) as { + rate: number; + }; + result.rate = 0; + + expect(result).not.toBe(hostState); + expect(hostState.rate).toBe(7); + }); + + it('rejects with action_rejected when the host result cannot be cloned', async () => { + const { requestAction } = await mountWithActions(() => + Promise.resolve({ format: () => 'x' }) + ); + + await expect( + requestAction({ action: 'settings.get' }) + ).rejects.toMatchObject({ code: 'action_rejected' }); + }); + + it('rejects with action_rejected when the host handler rejects, without its reason', async () => { + const { requestAction } = await mountWithActions(() => + Promise.reject({ + code: 'action_rejected', + runtimeType: 'dom-bundle', + extensionId: 'other-extension', + message: 'internal detail', + cause: 'secret', + }) + ); + + const rejection = await requestAction({ action: 'settings.open' }).catch( + (error: unknown) => error + ); + expect(rejection).toMatchObject({ + code: 'action_rejected', + message: 'The host rejected the action.', + extensionId: 'extension-1', + }); + expect(rejection).not.toHaveProperty('cause'); + }); + + it('rejects action requests when the host has no handler', async () => { + const { requestAction } = await mountWithActions(); + + await expect( + requestAction({ action: 'settings.open' }) + ).rejects.toMatchObject({ + code: 'action_rejected', + runtimeType: 'dom-bundle', + extensionId: 'extension-1', + }); + }); + + it('rejects action requests without an action name', async () => { + const onActionRequest = vi.fn(); + const { requestAction } = await mountWithActions(onActionRequest); + + await expect( + requestAction({ action: '' } as UiExtensionActionRequest) + ).rejects.toMatchObject({ code: 'action_rejected' }); + await expect(requestAction({ action: ' ' })).rejects.toMatchObject({ + code: 'action_rejected', + }); + await expect( + requestAction({ action: ' settings.open ' }) + ).rejects.toMatchObject({ code: 'action_rejected' }); + expect(onActionRequest).not.toHaveBeenCalled(); + }); + + it('rejects action requests after unmount', async () => { + const onActionRequest = vi.fn(); + const { runtime, requestAction } = await mountWithActions(onActionRequest); + + await runtime.unmount(); + + await expect( + requestAction({ action: 'settings.open' }) + ).rejects.toMatchObject({ code: 'action_rejected' }); + expect(onActionRequest).not.toHaveBeenCalled(); + }); + + it('rejects a request still waiting on the host when the extension unmounts', async () => { + const { runtime, requestAction } = await mountWithActions( + () => new Promise(() => undefined) + ); + + const pending = requestAction({ action: 'settings.open' }); + await runtime.unmount(); + + await expect(pending).rejects.toMatchObject({ + code: 'action_rejected', + message: 'UI extension is no longer mounted.', + }); + }); + + it('keeps requests from a failed mount away from the host', async () => { + const onActionRequest = vi.fn().mockResolvedValue(undefined); + let duringCleanup: Promise | undefined; + let requestAction: DomExtensionMountInput['requestAction']; + const runtime = new DomBundleUiExtensionRuntime({ timeoutMs: 50 }); + const mountPromise = runtime.mount({ + extension: createExtension(), + context: { target: 'checkout.test-target' }, + container: document.createElement('div'), + onError: () => undefined, + onActionRequest, + }); + const script = await getLastScript(); + window.GoDaddyUiExtensions?.register({ + mount(input: DomExtensionMountInput) { + requestAction = input.requestAction; + throw new Error('bundle broke'); + }, + unmount() { + duringCleanup = requestAction?.({ action: 'settings.save' }); + }, + }); + script.dispatchEvent(new Event('load')); + await mountPromise; + + await expect(duringCleanup).rejects.toMatchObject({ + code: 'action_rejected', + }); + expect(onActionRequest).not.toHaveBeenCalled(); + }); + + it('reports a request whose action cannot be read as missing its name', async () => { + const onActionRequest = vi.fn(); + const { requestAction } = await mountWithActions(onActionRequest); + const request = { + get action(): string { + throw new Error('no'); + }, + }; + + await expect(requestAction(request)).rejects.toMatchObject({ + message: 'UI extension action requests need an action name.', + }); + expect(onActionRequest).not.toHaveBeenCalled(); + }); + + it('keeps the source taken at mount when the host record changes later', async () => { + const onActionRequest = vi.fn().mockResolvedValue(undefined); + const extension = createExtension(); + const runtime = new DomBundleUiExtensionRuntime(); + let requestAction: DomExtensionMountInput['requestAction']; + const mountPromise = runtime.mount({ + extension, + context: { target: 'checkout.test-target' }, + container: document.createElement('div'), + onError: () => undefined, + onActionRequest, + }); + const script = await getLastScript(); + window.GoDaddyUiExtensions?.register({ + mount(input: DomExtensionMountInput) { + requestAction = input.requestAction; + }, + }); + script.dispatchEvent(new Event('load')); + await mountPromise; + + extension.id = 'trusted-extension'; + await requestAction?.({ action: 'settings.open' }); + + expect(onActionRequest.mock.calls[0]?.[1]).toEqual({ + extension: extensionMetadata, + }); + }); + + it('hands the runtime to a newer mount and unmounts the older bundle', async () => { + const runtime = new DomBundleUiExtensionRuntime(); + const container = document.createElement('div'); + const onActionRequest = vi.fn().mockResolvedValue(undefined); + const mountInput = (id: string) => ({ + extension: createExtension({ id }), + context: { target: 'checkout.test-target' }, + container, + onError: () => undefined, + onActionRequest, + }); + const olderUnmount = vi.fn(); + const newerUnmount = vi.fn(); + let finishOlderMount: (() => void) | undefined; + let olderRequestAction: DomExtensionMountInput['requestAction']; + + const older = runtime.mount(mountInput('extension-old')); + const olderScript = await getLastScript(); + window.GoDaddyUiExtensions?.register({ + mount: input => + new Promise(resolve => { + olderRequestAction = input.requestAction; + finishOlderMount = resolve; + }), + unmount: olderUnmount, + }); + olderScript.dispatchEvent(new Event('load')); + await vi.waitFor(() => expect(finishOlderMount).toBeDefined()); + + const newer = runtime.mount(mountInput('extension-new')); + await expect( + olderRequestAction?.({ action: 'settings.open' }) + ).rejects.toMatchObject({ code: 'action_rejected' }); + finishOlderMount?.(); + await older; + expect(olderUnmount).toHaveBeenCalledTimes(1); + expect(onActionRequest).not.toHaveBeenCalled(); + + await vi.waitFor(() => + expect(document.querySelector('script')).not.toBeNull() + ); + const newerScript = await getLastScript(); + window.GoDaddyUiExtensions?.register({ + mount: vi.fn(), + unmount: newerUnmount, + }); + newerScript.dispatchEvent(new Event('load')); + await newer; + + await runtime.unmount(); + expect(newerUnmount).toHaveBeenCalledTimes(1); + expect(olderUnmount).toHaveBeenCalledTimes(1); + }); + + async function mountNewer( + runtime: DomBundleUiExtensionRuntime, + input: UiExtensionRuntimeMountInput + ) { + let requestAction: DomExtensionMountInput['requestAction']; + const mounted = runtime.mount(input); + await vi.waitFor(() => + expect(document.querySelector('script')).not.toBeNull() + ); + const script = await getLastScript(); + window.GoDaddyUiExtensions?.register({ + mount: mountInput => { + requestAction = mountInput.requestAction; + }, + }); + script.dispatchEvent(new Event('load')); + await mounted; + return requestAction; + } + + it('leaves a newer mount alone when a failed mount finishes cleaning up', async () => { + const runtime = new DomBundleUiExtensionRuntime(); + const container = document.createElement('div'); + const olderErrors: UiExtensionRuntimeError[] = []; + const onActionRequest = vi.fn().mockResolvedValue({ saved: true }); + let finishOlderCleanup: (() => void) | undefined; + + const older = runtime.mount({ + extension: createExtension({ id: 'extension-old' }), + context: { target: 'checkout.test-target' }, + container, + onError: error => olderErrors.push(error), + }); + const olderScript = await getLastScript(); + window.GoDaddyUiExtensions?.register({ + mount() { + throw new Error('mount failed'); + }, + unmount: () => + new Promise(resolve => { + finishOlderCleanup = resolve; + }), + }); + olderScript.dispatchEvent(new Event('load')); + await vi.waitFor(() => expect(finishOlderCleanup).toBeDefined()); + + const newer = mountNewer(runtime, { + extension: createExtension({ id: 'extension-new' }), + context: { target: 'checkout.test-target' }, + container, + onError: () => undefined, + onActionRequest, + }); + finishOlderCleanup?.(); + await older; + const requestAction = await newer; + + expect(olderErrors).toEqual([]); + await expect(requestAction?.({ action: 'settings.open' })).resolves.toEqual( + { saved: true } + ); + }); + + it('keeps a newer mount when an earlier unmount finishes after it starts', async () => { + const onActionRequest = vi.fn().mockResolvedValue({ saved: true }); + let finishUnmount: (() => void) | undefined; + const { runtime } = await mountWithContract(capture => ({ + mount: capture, + unmount: () => + new Promise(resolve => { + finishUnmount = resolve; + }), + })); + + const unmounted = runtime.unmount(); + const newer = mountNewer(runtime, { + extension: createExtension({ id: 'extension-new' }), + context: { target: 'checkout.test-target' }, + container: document.createElement('div'), + onError: () => undefined, + onActionRequest, + }); + finishUnmount?.(); + await unmounted; + const requestAction = await newer; + + await expect(requestAction?.({ action: 'settings.open' })).resolves.toEqual( + { saved: true } + ); + }); + + it('unmounts a bundle replaced while it applies a queued update', async () => { + const runtime = new DomBundleUiExtensionRuntime(); + const container = document.createElement('div'); + const olderUnmount = vi.fn(); + let finishOlderMount: (() => void) | undefined; + let finishOlderUpdate: (() => void) | undefined; + + const older = runtime.mount({ + extension: createExtension({ id: 'extension-old' }), + context: { target: 'checkout.test-target' }, + container, + onError: () => undefined, + }); + const olderScript = await getLastScript(); + window.GoDaddyUiExtensions?.register({ + mount: () => + new Promise(resolve => { + finishOlderMount = resolve; + }), + update: () => + new Promise(resolve => { + finishOlderUpdate = resolve; + }), + unmount: olderUnmount, + }); + olderScript.dispatchEvent(new Event('load')); + await vi.waitFor(() => expect(finishOlderMount).toBeDefined()); + await runtime.update({ + context: { target: 'checkout.test-target', orderId: 'order-1' }, + }); + finishOlderMount?.(); + await vi.waitFor(() => expect(finishOlderUpdate).toBeDefined()); + + const newer = mountNewer(runtime, { + extension: createExtension({ id: 'extension-new' }), + context: { target: 'checkout.test-target' }, + container, + onError: () => undefined, + }); + finishOlderUpdate?.(); + await older; + await newer; + + expect(olderUnmount).toHaveBeenCalledTimes(1); + }); + + it('unmounts the bundle once when the host unmounts during a queued update that fails', async () => { + const runtime = new DomBundleUiExtensionRuntime(); + const unmount = vi.fn(); + const errors: UiExtensionRuntimeError[] = []; + let finishMount: (() => void) | undefined; + let failUpdate: (() => void) | undefined; + + const mounted = runtime.mount({ + extension: createExtension(), + context: { target: 'checkout.test-target' }, + container: document.createElement('div'), + onError: error => errors.push(error), + }); + const script = await getLastScript(); + window.GoDaddyUiExtensions?.register({ + mount: () => + new Promise(resolve => { + finishMount = resolve; + }), + update: () => + new Promise((_, reject) => { + failUpdate = () => reject(new Error('update failed')); + }), + unmount, + }); + script.dispatchEvent(new Event('load')); + await vi.waitFor(() => expect(finishMount).toBeDefined()); + await runtime.update({ + context: { target: 'checkout.test-target', orderId: 'order-1' }, + }); + finishMount?.(); + await vi.waitFor(() => expect(failUpdate).toBeDefined()); + + await runtime.unmount(); + failUpdate?.(); + await mounted; + + expect(unmount).toHaveBeenCalledTimes(1); + expect(errors).toEqual([]); + }); + + it('unmounts the bundle once when the host unmounts while a failed update cleans up', async () => { + const runtime = new DomBundleUiExtensionRuntime(); + let finishCleanup: (() => void) | undefined; + const unmount = vi.fn( + () => + new Promise(resolve => { + finishCleanup = resolve; + }) + ); + const mounted = runtime.mount({ + extension: createExtension(), + context: { target: 'checkout.test-target' }, + container: document.createElement('div'), + onError: () => undefined, + }); + const script = await getLastScript(); + let finishMount: (() => void) | undefined; + window.GoDaddyUiExtensions?.register({ + mount: () => + new Promise(resolve => { + finishMount = resolve; + }), + update: () => Promise.reject(new Error('update failed')), + unmount, + }); + script.dispatchEvent(new Event('load')); + await vi.waitFor(() => expect(finishMount).toBeDefined()); + await runtime.update({ + context: { target: 'checkout.test-target', orderId: 'order-1' }, + }); + finishMount?.(); + await vi.waitFor(() => expect(finishCleanup).toBeDefined()); + + await runtime.unmount(); + await runtime.unmount(); + finishCleanup?.(); + await mounted; + + expect(unmount).toHaveBeenCalledTimes(1); + }); + it('applies queued updates after mount finishes', async () => { const runtime = new DomBundleUiExtensionRuntime(); const update = vi.fn(); diff --git a/packages/react/src/ui-extensions/runtime/dom-bundle-runtime.ts b/packages/react/src/ui-extensions/runtime/dom-bundle-runtime.ts index 32bfd2553..6020a1328 100644 --- a/packages/react/src/ui-extensions/runtime/dom-bundle-runtime.ts +++ b/packages/react/src/ui-extensions/runtime/dom-bundle-runtime.ts @@ -2,6 +2,8 @@ import type { UiExtension } from '../types'; import { getUiExtensionScriptUrl } from './script-url'; import type { DomExtensionContract, + UiExtensionActionRequest, + UiExtensionActionSource, UiExtensionMetadata, UiExtensionRuntime, UiExtensionRuntimeError, @@ -11,6 +13,17 @@ import type { const DEFAULT_TIMEOUT_MS = 5000; +const NOT_MOUNTED = 'UI extension is no longer mounted.'; +const NO_HANDLER = 'The host does not handle UI extension actions.'; + +/** + * What `UiExtensionRuntimeHost` rejects with when no handler is passed, so the + * runtime can tell it from a host's own rejection. Not part of the public API. + */ +export const NO_ACTION_HANDLER: unique symbol = Symbol( + 'no UI extension action handler' +); + let scriptLoadQueue = Promise.resolve(); function enqueueScriptLoad(task: () => Promise): Promise { @@ -57,7 +70,9 @@ function createRuntimeError( }; } -function getExtensionMetadata(extension: UiExtension): UiExtensionMetadata { +export function getExtensionMetadata( + extension: UiExtension +): UiExtensionMetadata { return { id: extension.id, applicationId: extension.applicationId || '', @@ -170,14 +185,21 @@ function loadRegisteredContract( } export class DomBundleUiExtensionRuntime implements UiExtensionRuntime { + private acceptsActions = false; private contract: DomExtensionContract | undefined; private extension: UiExtension | undefined; private hasMounted = false; private isDisposed = false; private isMounting = false; + private actionSource: UiExtensionActionSource | undefined; private metadata: UiExtensionMetadata | undefined; + private mountId = 0; + private onActionRequest: UiExtensionRuntimeMountInput['onActionRequest']; + private pendingActions = new Set<() => void>(); private pendingUpdate: UiExtensionRuntimeUpdateInput | undefined; private timeoutMs: number; + // Bundles already unmounted, so a mount's own cleanup never unmounts one again. + private unmountedBundles = new WeakSet(); constructor(options: { timeoutMs?: number } = {}) { this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS; @@ -189,6 +211,9 @@ export class DomBundleUiExtensionRuntime implements UiExtensionRuntime { this.clearRuntimeState(); this.isDisposed = false; this.extension = extension; + this.onActionRequest = input.onActionRequest; + this.mountId += 1; + const mountId = this.mountId; if (!container) { onError( @@ -201,6 +226,9 @@ export class DomBundleUiExtensionRuntime implements UiExtensionRuntime { } this.metadata = getExtensionMetadata(extension); + this.actionSource = Object.freeze({ + extension: Object.freeze(getExtensionMetadata(extension)), + }); const scriptUrlResult = getUiExtensionScriptUrl(extension, apiHost); if (!scriptUrlResult.success) { @@ -208,6 +236,7 @@ export class DomBundleUiExtensionRuntime implements UiExtensionRuntime { return; } + let loaded: DomExtensionContract | undefined; try { const contract = await loadRegisteredContract( scriptUrlResult.url, @@ -215,13 +244,22 @@ export class DomBundleUiExtensionRuntime implements UiExtensionRuntime { this.timeoutMs ); + if (mountId !== this.mountId) { + // A newer mount started while this one loaded; it owns the runtime. + return; + } + if (this.isDisposed) { this.clearRuntimeState(); return; } + loaded = contract; + // A bundle may register the same contract object on every load. + this.unmountedBundles.delete(contract); this.contract = contract; this.isMounting = true; + this.acceptsActions = true; await withTimeout( Promise.resolve( @@ -230,6 +268,8 @@ export class DomBundleUiExtensionRuntime implements UiExtensionRuntime { context, initialProps, extension: this.metadata, + requestAction: request => + this.requestAction(extension, mountId, request), }) ), this.timeoutMs, @@ -240,6 +280,11 @@ export class DomBundleUiExtensionRuntime implements UiExtensionRuntime { }) ); + if (mountId !== this.mountId) { + await this.unmountSuperseded(extension, contract); + return; + } + this.isMounting = false; this.hasMounted = true; @@ -255,10 +300,28 @@ export class DomBundleUiExtensionRuntime implements UiExtensionRuntime { pendingUpdate.initialProps !== initialProps) ) { await this.update(pendingUpdate); + if (mountId !== this.mountId) { + await this.unmountSuperseded(extension, contract); + } } } catch (cause) { + if (mountId !== this.mountId) { + // A newer mount owns the runtime now, its contract and its action + // channel included, so a superseded mount's failure leaves them alone + // and only cleans up its own bundle. + await this.unmountSuperseded(extension, loaded); + return; + } this.isMounting = false; - await this.cleanupFailedMount(); + // The host is told the mount failed, so nothing the extension asks for + // while it is cleaned up reaches the host. + this.stopActions(); + await this.cleanupFailedMount(extension, loaded); + + if (mountId !== this.mountId) { + // A newer mount started while this one cleaned up; the runtime is its. + return; + } if (this.isDisposed) { this.clearRuntimeState(); @@ -291,6 +354,8 @@ export class DomBundleUiExtensionRuntime implements UiExtensionRuntime { return; } + // Read before the wait: a remount may replace them while the bundle updates. + const extension = this.extension; try { await withTimeout( Promise.resolve( @@ -302,13 +367,13 @@ export class DomBundleUiExtensionRuntime implements UiExtensionRuntime { ), this.timeoutMs, () => - createRuntimeError(this.extension as UiExtension, { + createRuntimeError(extension, { code: 'update_failed', message: 'UI extension update timed out.', }) ); } catch (cause) { - throw createRuntimeError(this.extension, { + throw createRuntimeError(extension, { code: 'update_failed', message: 'Failed to update UI extension.', cause, @@ -317,7 +382,11 @@ export class DomBundleUiExtensionRuntime implements UiExtensionRuntime { } async unmount() { + // A mount started while this unmount waits on the bundle owns the runtime + // by the time it finishes, so only the mount this call ended is cleared. + const mountId = this.mountId; this.isDisposed = true; + this.stopActions(); if (this.isMounting && !this.hasMounted) { return; @@ -328,62 +397,237 @@ export class DomBundleUiExtensionRuntime implements UiExtensionRuntime { return; } - if (!this.contract?.unmount || !this.extension) { + const { contract, extension } = this; + if ( + !contract?.unmount || + !extension || + // Already unmounted, by an earlier call or a failed mount's cleanup. + this.unmountedBundles.has(contract) + ) { this.clearRuntimeState(); return; } + this.unmountedBundles.add(contract); try { await withTimeout( - Promise.resolve(this.contract.unmount()), + Promise.resolve(contract.unmount()), this.timeoutMs, () => - createRuntimeError(this.extension as UiExtension, { + createRuntimeError(extension, { code: 'unmount_failed', message: 'UI extension unmount timed out.', }) ); } catch (cause) { - throw createRuntimeError(this.extension, { + throw createRuntimeError(extension, { code: 'unmount_failed', message: 'Failed to unmount UI extension.', cause, }); } finally { - this.clearRuntimeState(); + if (mountId === this.mountId) { + this.clearRuntimeState(); + } } } - private async cleanupFailedMount() { - if (!this.contract?.unmount || !this.extension) { + // Unmounts the bundle of a mount a newer one replaced, leaving the runtime's + // state, which belongs to the newer mount, alone. + private unmountSuperseded( + extension: UiExtension, + contract: DomExtensionContract | undefined + ) { + // Nothing to report: the host has already moved on to the newer mount. + return this.unmountQuietly( + extension, + contract, + 'Superseded UI extension cleanup timed out.' + ); + } + + private cleanupFailedMount( + extension: UiExtension, + contract: DomExtensionContract | undefined + ) { + // Failures are ignored so the original mount error is reported. + return this.unmountQuietly( + extension, + contract, + 'UI extension cleanup timed out after mount failure.' + ); + } + + // Unmounts a bundle the runtime is done with, unless the host's unmount + // already did, and swallows what goes wrong. + private async unmountQuietly( + extension: UiExtension, + contract: DomExtensionContract | undefined, + timeoutMessage: string + ) { + if (!contract?.unmount || this.unmountedBundles.has(contract)) { return; } + this.unmountedBundles.add(contract); try { await withTimeout( - Promise.resolve(this.contract.unmount()), + Promise.resolve().then(() => contract.unmount?.()), this.timeoutMs, () => - createRuntimeError(this.extension as UiExtension, { + createRuntimeError(extension, { code: 'unmount_failed', - message: 'UI extension cleanup timed out after mount failure.', + message: timeoutMessage, }) ); } catch { - // Ignore cleanup failures so the original mount error is reported. + // See the callers. + } + } + + private requestAction( + extension: UiExtension, + mountId: number, + request: unknown + ): Promise { + const rejection = (message: string) => + createRuntimeError(extension, { code: 'action_rejected', message }); + const isCurrent = () => + this.acceptsActions && !this.isDisposed && mountId === this.mountId; + + if (!isCurrent()) { + return Promise.reject(rejection(NOT_MOUNTED)); + } + + if (typeof structuredClone !== 'function') { + return Promise.reject( + rejection('This browser cannot pass UI extension action values.') + ); + } + + // A structured clone, read once: a getter, a proxy or a later change on the + // extension's object can't alter what the host checked. + const action = cloneActionRequest(request); + if (action === 'invalid') { + return Promise.reject( + rejection('UI extension action requests need an action name.') + ); + } + if (action === 'uncloneable') { + return Promise.reject( + rejection('UI extension action input must be structured-cloneable.') + ); + } + + const handler = this.onActionRequest; + if (!handler) { + return Promise.reject(rejection(NO_HANDLER)); + } + + // Taken from the host's record at mount and frozen, so neither the + // extension nor a later change to that record can pass a request off as + // another extension's. + const source = this.actionSource; + if (!source) { + return Promise.reject(rejection(NOT_MOUNTED)); + } + + return new Promise((resolve, reject) => { + const cancel = () => reject(rejection(NOT_MOUNTED)); + this.pendingActions.add(cancel); + const settle = (answer: () => void) => { + if (!this.pendingActions.delete(cancel)) { + return; + } + if (!isCurrent()) { + reject(rejection(NOT_MOUNTED)); + return; + } + answer(); + }; + + new Promise(run => run(handler(action, source))).then( + result => + settle(() => { + try { + resolve(structuredClone(result)); + } catch { + reject( + rejection( + 'The host answered with a value that cannot be cloned.' + ) + ); + } + }), + cause => + settle(() => + // The host's reason stays with the host; the extension learns only + // that the action was rejected. + reject( + rejection( + cause === NO_ACTION_HANDLER + ? NO_HANDLER + : 'The host rejected the action.' + ) + ) + ) + ); + }); + } + + private stopActions() { + this.acceptsActions = false; + const pending = [...this.pendingActions]; + this.pendingActions.clear(); + for (const cancel of pending) { + cancel(); } } private clearRuntimeState() { + this.stopActions(); this.contract = undefined; this.extension = undefined; this.hasMounted = false; this.isMounting = false; + this.actionSource = undefined; this.metadata = undefined; + this.onActionRequest = undefined; this.pendingUpdate = undefined; } } +function cloneActionRequest( + value: unknown +): UiExtensionActionRequest | 'invalid' | 'uncloneable' { + if (!value || typeof value !== 'object') { + return 'invalid'; + } + let action: unknown; + try { + action = (value as UiExtensionActionRequest).action; + } catch { + return 'invalid'; + } + // A blank name, or one with spaces around it, would never match a host's + // action exactly. + if ( + typeof action !== 'string' || + action.length === 0 || + action !== action.trim() + ) { + return 'invalid'; + } + let input: unknown; + try { + input = (value as UiExtensionActionRequest).input; + input = input === undefined ? undefined : structuredClone(input); + } catch { + return 'uncloneable'; + } + return input === undefined ? { action } : { action, input }; +} + function isRuntimeError(value: unknown): value is UiExtensionRuntimeError { return Boolean( value && diff --git a/packages/react/src/ui-extensions/runtime/index.ts b/packages/react/src/ui-extensions/runtime/index.ts index 221584b5c..e3d22ab3d 100644 --- a/packages/react/src/ui-extensions/runtime/index.ts +++ b/packages/react/src/ui-extensions/runtime/index.ts @@ -8,6 +8,7 @@ export type { DomExtensionMountInput, DomExtensionUpdateInput, UiExtensionActionRequest, + UiExtensionActionSource, UiExtensionCapabilities, UiExtensionComponentNode, UiExtensionComponentTree, diff --git a/packages/react/src/ui-extensions/runtime/runtime-host.test.tsx b/packages/react/src/ui-extensions/runtime/runtime-host.test.tsx new file mode 100644 index 000000000..32028a441 --- /dev/null +++ b/packages/react/src/ui-extensions/runtime/runtime-host.test.tsx @@ -0,0 +1,95 @@ +import { act, render } from '@testing-library/react'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import type { UiExtension } from '../types'; +import { UiExtensionRuntimeHost } from './runtime-host'; +import type { DomExtensionMountInput, UiExtensionContext } from './types'; + +const extension: UiExtension = { + id: 'extension-1', + applicationId: 'app-1', + releaseId: 'release-1', + type: 'checkout', + target: 'checkout.test-target', +}; + +const context: UiExtensionContext = { target: 'checkout.test-target' }; + +async function loadFakeBundle() { + let mountInput: DomExtensionMountInput | undefined; + const mount = vi.fn((input: DomExtensionMountInput) => { + mountInput = input; + }); + + await act(async () => { + await Promise.resolve(); + }); + const scripts = document.querySelectorAll('script'); + const script = scripts[scripts.length - 1] as HTMLScriptElement; + window.GoDaddyUiExtensions?.register({ mount }); + + await act(async () => { + script.dispatchEvent(new Event('load')); + await Promise.resolve(); + }); + + if (!mountInput?.requestAction) { + throw new Error('mount input has no requestAction'); + } + + return { mount, requestAction: mountInput.requestAction }; +} + +describe('UiExtensionRuntimeHost', () => { + afterEach(() => { + document.head.innerHTML = ''; + delete window.GoDaddyUiExtensions; + }); + + it('sends action requests to the current handler without remounting', async () => { + const first = vi.fn().mockResolvedValue('first'); + const second = vi.fn().mockResolvedValue('second'); + const { rerender } = render( + + ); + const { mount, requestAction } = await loadFakeBundle(); + + await expect(requestAction({ action: 'settings.open' })).resolves.toBe( + 'first' + ); + + rerender( + + ); + + await expect(requestAction({ action: 'settings.open' })).resolves.toBe( + 'second' + ); + expect(first).toHaveBeenCalledTimes(1); + expect(second).toHaveBeenCalledWith( + { action: 'settings.open' }, + { extension: expect.objectContaining({ id: 'extension-1' }) } + ); + expect(mount).toHaveBeenCalledTimes(1); + }); + + it('rejects action requests when no handler is passed', async () => { + render(); + const { requestAction } = await loadFakeBundle(); + + await expect( + requestAction({ action: 'settings.open' }) + ).rejects.toMatchObject({ + code: 'action_rejected', + extensionId: 'extension-1', + message: 'The host does not handle UI extension actions.', + }); + }); +}); diff --git a/packages/react/src/ui-extensions/runtime/runtime-host.tsx b/packages/react/src/ui-extensions/runtime/runtime-host.tsx index 68b42cd6d..a13195590 100644 --- a/packages/react/src/ui-extensions/runtime/runtime-host.tsx +++ b/packages/react/src/ui-extensions/runtime/runtime-host.tsx @@ -1,9 +1,16 @@ 'use client'; import { Component, type ReactNode, useEffect, useMemo, useRef } from 'react'; +import { useIsomorphicLayoutEffect } from '@/hooks/use-isomorphic-layout-effect'; import type { UiExtension } from '../types'; -import { DomBundleUiExtensionRuntime } from './dom-bundle-runtime'; +import { + DomBundleUiExtensionRuntime, + getExtensionMetadata, + NO_ACTION_HANDLER, +} from './dom-bundle-runtime'; import type { + UiExtensionActionRequest, + UiExtensionActionSource, UiExtensionContext, UiExtensionInitialProps, UiExtensionRuntime, @@ -18,6 +25,18 @@ export interface UiExtensionRuntimeHostProps { initialProps?: UiExtensionInitialProps; runtimeType?: Extract; onError?(error: UiExtensionRuntimeError): void; + /** + * Runs an action the extension requests, with the extension that sent it. + * Changing it doesn't remount the extension; the next request reaches the + * new handler. Without it, requests reject with an `action_rejected` runtime + * error. A handler's failure goes only to the extension, as a generic + * rejection, not to `onError`, so catch inside the handler to log it, and + * resolve with structured-cloneable values. + */ + onActionRequest?( + request: UiExtensionActionRequest, + source: UiExtensionActionSource + ): Promise; } interface UiExtensionErrorBoundaryProps { @@ -102,16 +121,24 @@ function UiExtensionRuntimeHostContainer({ initialProps, runtimeType = 'dom-bundle', onError, + onActionRequest, }: UiExtensionRuntimeHostProps) { const containerRef = useRef(null); const runtimeRef = useRef(undefined); const onErrorRef = useRef(onError); + const onActionRequestRef = useRef(onActionRequest); const extensionKey = useMemo(() => getExtensionKey(extension), [extension]); useEffect(() => { onErrorRef.current = onError; }, [onError]); + // A layout effect, so only a committed handler is used, and it is in place + // before the browser paints the render that passed it. + useIsomorphicLayoutEffect(() => { + onActionRequestRef.current = onActionRequest; + }, [onActionRequest]); + useEffect(() => { const runtime = createUiExtensionRuntime(runtimeType); runtimeRef.current = runtime; @@ -123,6 +150,19 @@ function UiExtensionRuntimeHostContainer({ initialProps, container: containerRef.current || undefined, onError: error => onErrorRef.current?.(error), + onActionRequest: (request, source) => { + const handler = onActionRequestRef.current; + if (!handler) { + return Promise.reject(NO_ACTION_HANDLER); + } + // A runtime that passes no source still names the extension it runs. + return handler( + request, + source ?? { + extension: Object.freeze(getExtensionMetadata(extension)), + } + ); + }, }); return () => { diff --git a/packages/react/src/ui-extensions/runtime/types.ts b/packages/react/src/ui-extensions/runtime/types.ts index 262c829ef..9a82692d7 100644 --- a/packages/react/src/ui-extensions/runtime/types.ts +++ b/packages/react/src/ui-extensions/runtime/types.ts @@ -28,6 +28,27 @@ export interface DomExtensionMountInput { context: UiExtensionContext; initialProps?: UiExtensionInitialProps; extension: UiExtensionMetadata; + /** + * Asks the host to run an action, such as opening a page or saving a value. + * The request and the host's result are structured-cloned on the way, so + * neither side keeps a live reference to the other's objects. It resolves + * with the host's result. It rejects with an `action_rejected` runtime error + * when the host has no action handler, when the host rejects the action, + * when the action name is missing, blank or has spaces around it, when + * either value can't be cloned, or when the extension unmounts before + * the host answers. A request rejected at unmount may still have run on the + * host. Requests stop when unmount starts, so an `unmount` hook can't send + * one, and a request awaited inside `mount` counts against the mount + * timeout. Catch every call, including fire-and-forget ones, or a rejection + * goes unhandled. The rejection value is a plain `UiExtensionRuntimeError` + * object, not an `Error`. + * + * Optional because older hosts don't pass it, so check for it before + * calling. The same function stays valid until unmount. Under `Target` and + * `UiExtensionRuntimeHost` it always reaches the host's current committed + * handler; the runtime alone keeps the handler it was mounted with. + */ + requestAction?(request: UiExtensionActionRequest): Promise; } export interface DomExtensionUpdateInput { @@ -88,6 +109,15 @@ export interface UiExtensionActionRequest { input?: unknown; } +/** + * Which extension sent an action request, so a host can scope or audit it. + * The runtime builds it from the host's record of the extension, never from + * anything the extension can change. + */ +export interface UiExtensionActionSource { + extension: UiExtensionMetadata; +} + export interface UiExtensionRuntimeMountInput { extension: UiExtension; context: UiExtensionContext; @@ -98,7 +128,21 @@ export interface UiExtensionRuntimeMountInput { onRender?(tree: UiExtensionComponentTree): void; onResize?(size: { height?: number; width?: number }): void; onError(error: UiExtensionRuntimeError): void; - onActionRequest?(request: UiExtensionActionRequest): Promise; + /** + * Runs an action the extension requests through `requestAction`. The + * `dom-bundle` runtime always passes `source`, built from the host's own + * record of the extension; it is optional so runtimes that call this with + * the request alone still compile. Without it, requests reject with an + * `action_rejected` runtime error. + * + * A handler's failure goes only to the extension, as a generic rejection, so + * a host that wants to log one catches it inside its handler. Resolve with + * structured-cloneable values. + */ + onActionRequest?( + request: UiExtensionActionRequest, + source?: UiExtensionActionSource + ): Promise; } export interface UiExtensionRuntimeUpdateInput { diff --git a/packages/react/src/ui-extensions/target.test.tsx b/packages/react/src/ui-extensions/target.test.tsx index 297cf5403..08a45dd25 100644 --- a/packages/react/src/ui-extensions/target.test.tsx +++ b/packages/react/src/ui-extensions/target.test.tsx @@ -1,7 +1,9 @@ +import { act, render } from '@testing-library/react'; import { renderToStaticMarkup } from 'react-dom/server'; -import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { useGoDaddyContext } from '@/godaddy-provider'; import { useEnabledStoreUiExtensions } from './hooks'; +import type { DomExtensionMountInput } from './runtime'; import { Target } from './target'; import type { EnabledStoreUiExtensionApp, @@ -40,6 +42,11 @@ describe('Target', () => { mockHookResult(); }); + afterEach(() => { + document.head.innerHTML = ''; + delete window.GoDaddyUiExtensions; + }); + it('does not require token and keeps orderId out of extension discovery', () => { renderToStaticMarkup( @@ -131,6 +138,64 @@ describe('Target', () => { expect(output).toContain('extension-1'); }); + it('passes action requests to onActionRequest', async () => { + const onActionRequest = vi.fn().mockResolvedValue('done'); + let mountInput: DomExtensionMountInput | undefined; + const apps: EnabledStoreUiExtensionApp[] = [ + { + id: 'app-1', + name: 'app-1', + release: null, + uiExtensions: [ + { + id: 'extension-1', + applicationId: 'app-1', + releaseId: 'release-1', + type: 'CHECKOUT', + target: 'some.target', + }, + ], + }, + ]; + + render( + + ); + await act(async () => { + await Promise.resolve(); + }); + const script = document.head.querySelector('script') as HTMLScriptElement; + window.GoDaddyUiExtensions?.register({ + mount(input: DomExtensionMountInput) { + mountInput = input; + }, + }); + await act(async () => { + script.dispatchEvent(new Event('load')); + await Promise.resolve(); + }); + + await expect( + mountInput?.requestAction?.({ action: 'settings.open' }) + ).resolves.toBe('done'); + expect(onActionRequest).toHaveBeenCalledWith( + { action: 'settings.open' }, + { + extension: { + id: 'extension-1', + applicationId: 'app-1', + releaseId: 'release-1', + target: 'some.target', + }, + } + ); + }); + it('does not render hook errors to shoppers', () => { mockHookResult({ error: new Error('Failed to load extensions') }); diff --git a/packages/react/src/ui-extensions/target.tsx b/packages/react/src/ui-extensions/target.tsx index 711e8079b..5147036ce 100644 --- a/packages/react/src/ui-extensions/target.tsx +++ b/packages/react/src/ui-extensions/target.tsx @@ -53,6 +53,7 @@ export function Target({ currencyCode, theme, onExtensionError, + onActionRequest, }: TargetProps) { const { apiHost, debug } = useGoDaddyContext(); const lastDebugLogSignatureRef = useRef(undefined); @@ -141,6 +142,7 @@ export function Target({ extension={extension} initialProps={initialProps} key={extension.id} + onActionRequest={onActionRequest} onError={onExtensionError} runtimeType={runtime} /> diff --git a/packages/react/src/ui-extensions/types.ts b/packages/react/src/ui-extensions/types.ts index a5e2147b8..7d58137d3 100644 --- a/packages/react/src/ui-extensions/types.ts +++ b/packages/react/src/ui-extensions/types.ts @@ -1,6 +1,8 @@ import type { ResultOf } from 'gql.tada'; import { GetEnabledStoreUiExtensionsQuery } from '@/lib/godaddy/checkout-queries'; import type { + UiExtensionActionRequest, + UiExtensionActionSource, UiExtensionContext, UiExtensionInitialProps, UiExtensionRuntimeError, @@ -47,6 +49,17 @@ export interface TargetProps { currencyCode?: string; theme?: UiExtensionContext['theme']; onExtensionError?(error: UiExtensionRuntimeError): void; + /** + * Runs an action an extension on this target requests, with the extension + * that sent it. Without it, requests reject with an `action_rejected` + * runtime error. A handler's failure goes only to the extension, not to + * `onExtensionError`, so catch inside the handler to log it, and resolve + * with structured-cloneable values. + */ + onActionRequest?( + request: UiExtensionActionRequest, + source: UiExtensionActionSource + ): Promise; } export interface UseEnabledStoreUiExtensionsOptions {