回读宿主运行态能力
HostBridge 启动时通过真实 host.getRuntime 回读并缓存宿主能力 主 App 订阅宿主能力变化并在回读后刷新能力入口 补充宿主 runtime 回读测试和 App 能力刷新测试 更新 Expo/Tauri 壳方案、HostBridge 协议文档和共享决策记录
This commit is contained in:
@@ -16,14 +16,17 @@ import {
|
||||
openHostShareGrid,
|
||||
openWechatMiniProgramShareGridPage,
|
||||
postWechatMiniProgramMessage,
|
||||
refreshNativeAppHostRuntime,
|
||||
requestHostHapticsImpact,
|
||||
requestHostLogin,
|
||||
requestHostPayment,
|
||||
requestWechatMiniProgramPayment,
|
||||
requestWechatMiniProgramPhoneLogin,
|
||||
resetHostRuntimeCacheForTest,
|
||||
resolveHostRuntime,
|
||||
setHostAppTitle,
|
||||
setHostShareTarget,
|
||||
subscribeHostRuntimeChange,
|
||||
writeHostClipboardText,
|
||||
} from './hostBridge';
|
||||
import { resetNativeAppHostBridgeForTest } from './nativeAppHostBridge';
|
||||
@@ -57,6 +60,7 @@ afterEach(() => {
|
||||
delete window.ReactNativeWebView;
|
||||
delete window.__TAURI__;
|
||||
resetNativeAppHostBridgeForTest();
|
||||
resetHostRuntimeCacheForTest();
|
||||
});
|
||||
|
||||
describe('hostBridge', () => {
|
||||
@@ -133,6 +137,103 @@ describe('hostBridge', () => {
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test('从真实宿主 runtime 回读能力并通知订阅者', async () => {
|
||||
const listener = vi.fn();
|
||||
const unsubscribe = subscribeHostRuntimeChange(listener);
|
||||
const invoke = vi.fn(
|
||||
async (_command: string, args?: Record<string, unknown>) => {
|
||||
const request = (args as { request: { id: string; method: string } })
|
||||
.request;
|
||||
return {
|
||||
bridge: 'GenarrativeHostBridge',
|
||||
version: 1,
|
||||
id: request.id,
|
||||
ok: true,
|
||||
result: {
|
||||
shell: 'tauri_desktop',
|
||||
platform: 'linux',
|
||||
hostVersion: '0.1.0',
|
||||
bridgeVersion: 1,
|
||||
capabilities: [
|
||||
'host.getRuntime',
|
||||
'share.open',
|
||||
'clipboard.writeText',
|
||||
'unknown.capability',
|
||||
],
|
||||
},
|
||||
};
|
||||
},
|
||||
);
|
||||
window.history.replaceState(
|
||||
null,
|
||||
'',
|
||||
'/?clientRuntime=native_app&hostShell=tauri_desktop',
|
||||
);
|
||||
window.__TAURI__ = {
|
||||
core: {
|
||||
invoke: asTauriInvoke(invoke),
|
||||
},
|
||||
};
|
||||
|
||||
expect(canUseNativeHostCapability('share.open')).toBe(false);
|
||||
await expect(refreshNativeAppHostRuntime()).resolves.toMatchObject({
|
||||
shell: 'tauri_desktop',
|
||||
capabilities: ['host.getRuntime', 'share.open', 'clipboard.writeText'],
|
||||
});
|
||||
|
||||
expect(canUseNativeHostCapability('share.open')).toBe(true);
|
||||
expect(canUseNativeHostCapability('clipboard.writeText')).toBe(true);
|
||||
expect(canUseNativeHostCapability('file.exportText')).toBe(false);
|
||||
expect(getHostRuntime().hostCapabilities).toEqual([
|
||||
'host.getRuntime',
|
||||
'share.open',
|
||||
'clipboard.writeText',
|
||||
]);
|
||||
expect(listener).toHaveBeenCalledTimes(1);
|
||||
expect(invoke).toHaveBeenCalledTimes(1);
|
||||
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
test('普通浏览器不混入缓存的原生宿主能力', async () => {
|
||||
const invoke = vi.fn(
|
||||
async (_command: string, args?: Record<string, unknown>) => {
|
||||
const request = (args as { request: { id: string } }).request;
|
||||
return {
|
||||
bridge: 'GenarrativeHostBridge',
|
||||
version: 1,
|
||||
id: request.id,
|
||||
ok: true,
|
||||
result: {
|
||||
shell: 'tauri_desktop',
|
||||
platform: 'linux',
|
||||
hostVersion: '0.1.0',
|
||||
bridgeVersion: 1,
|
||||
capabilities: ['share.open'],
|
||||
},
|
||||
};
|
||||
},
|
||||
);
|
||||
window.history.replaceState(
|
||||
null,
|
||||
'',
|
||||
'/?clientRuntime=native_app&hostShell=tauri_desktop',
|
||||
);
|
||||
window.__TAURI__ = {
|
||||
core: {
|
||||
invoke: asTauriInvoke(invoke),
|
||||
},
|
||||
};
|
||||
|
||||
await refreshNativeAppHostRuntime();
|
||||
delete window.__TAURI__;
|
||||
window.history.replaceState(null, '', '/?clientRuntime=browser');
|
||||
|
||||
expect(getHostRuntime().kind).toBe('browser');
|
||||
expect(getHostRuntime().hostCapabilities).toEqual([]);
|
||||
expect(canUseNativeHostCapability('share.open')).toBe(false);
|
||||
});
|
||||
|
||||
test('通过微信小程序原生页请求登录', async () => {
|
||||
const navigateTo = vi.fn((options) => {
|
||||
options.success?.();
|
||||
|
||||
@@ -16,7 +16,10 @@ import type {
|
||||
WechatMiniProgramPayParams,
|
||||
WechatMiniProgramVirtualPayParams,
|
||||
} from '../../../packages/shared/src/contracts/runtime';
|
||||
import { requestNativeAppHostBridge } from './nativeAppHostBridge';
|
||||
import {
|
||||
canUseNativeAppHostBridge,
|
||||
requestNativeAppHostBridge,
|
||||
} from './nativeAppHostBridge';
|
||||
|
||||
const WECHAT_JS_SDK_URL = 'https://res.wx.qq.com/open/js/jweixin-1.6.0.js';
|
||||
const MINI_PROGRAM_AUTH_PAGE_URL =
|
||||
@@ -84,6 +87,13 @@ export type HostShareOpenRequest = ShareOpenPayload;
|
||||
|
||||
export type HostExternalUrlRequest = OpenExternalUrlPayload;
|
||||
|
||||
const HOST_RUNTIME_REFRESH_TIMEOUT_MS = 3000;
|
||||
|
||||
let cachedNativeHostRuntime: HostBridgeRuntimeResult | null = null;
|
||||
let nativeHostRuntimeRefreshPromise: Promise<HostBridgeRuntimeResult | null> | null =
|
||||
null;
|
||||
const hostRuntimeChangeListeners = new Set<() => void>();
|
||||
|
||||
function isUnsupportedHostBridgeError(error: unknown) {
|
||||
return (
|
||||
error instanceof Error &&
|
||||
@@ -92,6 +102,56 @@ function isUnsupportedHostBridgeError(error: unknown) {
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeHostCapabilities(values: unknown): HostBridgeCapability[] {
|
||||
if (!Array.isArray(values)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return values.filter(isHostBridgeCapability);
|
||||
}
|
||||
|
||||
function mergeHostCapabilities(
|
||||
...capabilityLists: Array<HostBridgeCapability[] | null | undefined>
|
||||
) {
|
||||
return Array.from(
|
||||
new Set(capabilityLists.flatMap((capabilities) => capabilities ?? [])),
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeNativeHostRuntimeResult(
|
||||
runtime: HostBridgeRuntimeResult | null | undefined,
|
||||
) {
|
||||
if (!runtime || typeof runtime !== 'object') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
...runtime,
|
||||
capabilities: normalizeHostCapabilities(runtime.capabilities),
|
||||
} satisfies HostBridgeRuntimeResult;
|
||||
}
|
||||
|
||||
function updateCachedNativeHostRuntime(
|
||||
runtime: HostBridgeRuntimeResult | null,
|
||||
) {
|
||||
const normalizedRuntime = normalizeNativeHostRuntimeResult(runtime);
|
||||
if (!normalizedRuntime) {
|
||||
return null;
|
||||
}
|
||||
|
||||
cachedNativeHostRuntime = normalizedRuntime;
|
||||
hostRuntimeChangeListeners.forEach((listener) => listener());
|
||||
return normalizedRuntime;
|
||||
}
|
||||
|
||||
export function subscribeHostRuntimeChange(listener: () => void) {
|
||||
hostRuntimeChangeListeners.add(listener);
|
||||
|
||||
return () => {
|
||||
hostRuntimeChangeListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
async function requestNativeHostBoolean(
|
||||
method: HostBridgeMethod,
|
||||
payload?: unknown,
|
||||
@@ -106,17 +166,6 @@ async function requestNativeHostBoolean(
|
||||
}
|
||||
}
|
||||
|
||||
function runtimeHasNativeCapability(
|
||||
capability: HostBridgeCapability,
|
||||
context: HostRuntimeContext = {},
|
||||
) {
|
||||
const runtime = getHostRuntime(context);
|
||||
return (
|
||||
runtime.kind === 'native_app' &&
|
||||
runtime.hostCapabilities.includes(capability)
|
||||
);
|
||||
}
|
||||
|
||||
function resolveLocation(context: HostRuntimeContext) {
|
||||
return (
|
||||
context.location ?? (typeof window !== 'undefined' ? window.location : null)
|
||||
@@ -171,7 +220,7 @@ export function resolveHostRuntime(
|
||||
const hostShell = params.get('hostShell');
|
||||
const hostPlatform = params.get('hostPlatform');
|
||||
const hostVersion = params.get('hostVersion');
|
||||
const hostCapabilities = (params.get('hostCapabilities') ?? '')
|
||||
const queryHostCapabilities = (params.get('hostCapabilities') ?? '')
|
||||
.split(',')
|
||||
.map((capability) => capability.trim())
|
||||
.filter(isHostBridgeCapability);
|
||||
@@ -180,6 +229,10 @@ export function resolveHostRuntime(
|
||||
const wxBridge = resolveWxBridge(context);
|
||||
const tauriBridge = resolveTauriBridge(context);
|
||||
const reactNativeWebView = resolveReactNativeWebView(context);
|
||||
const nativeHostCapabilities = mergeHostCapabilities(
|
||||
queryHostCapabilities,
|
||||
cachedNativeHostRuntime?.capabilities,
|
||||
);
|
||||
|
||||
if (
|
||||
clientRuntime === 'wechat_mini_program' ||
|
||||
@@ -194,7 +247,7 @@ export function resolveHostRuntime(
|
||||
hostShell,
|
||||
hostPlatform,
|
||||
hostVersion,
|
||||
hostCapabilities,
|
||||
hostCapabilities: queryHostCapabilities,
|
||||
miniProgramEnv,
|
||||
};
|
||||
}
|
||||
@@ -212,7 +265,7 @@ export function resolveHostRuntime(
|
||||
hostShell,
|
||||
hostPlatform,
|
||||
hostVersion,
|
||||
hostCapabilities,
|
||||
hostCapabilities: nativeHostCapabilities,
|
||||
miniProgramEnv,
|
||||
};
|
||||
}
|
||||
@@ -224,7 +277,7 @@ export function resolveHostRuntime(
|
||||
hostShell,
|
||||
hostPlatform,
|
||||
hostVersion,
|
||||
hostCapabilities,
|
||||
hostCapabilities: queryHostCapabilities,
|
||||
miniProgramEnv,
|
||||
};
|
||||
}
|
||||
@@ -247,7 +300,11 @@ export function canUseNativeHostCapability(
|
||||
capability: HostBridgeCapability,
|
||||
context: HostRuntimeContext = {},
|
||||
) {
|
||||
return runtimeHasNativeCapability(capability, context);
|
||||
const runtime = getHostRuntime(context);
|
||||
return (
|
||||
runtime.kind === 'native_app' &&
|
||||
runtime.hostCapabilities.includes(capability)
|
||||
);
|
||||
}
|
||||
|
||||
export function loadWechatMiniProgramBridge(
|
||||
@@ -550,13 +607,49 @@ export function postWechatMiniProgramMessage(message: unknown) {
|
||||
}
|
||||
|
||||
export async function getNativeAppHostRuntime() {
|
||||
if (!canUseNativeHostCapability('host.getRuntime')) {
|
||||
const runtime = getHostRuntime();
|
||||
if (
|
||||
runtime.kind !== 'native_app' ||
|
||||
(!runtime.hostCapabilities.includes('host.getRuntime') &&
|
||||
!canUseNativeAppHostBridge())
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return await requestNativeAppHostBridge<HostBridgeRuntimeResult>(
|
||||
'host.getRuntime',
|
||||
);
|
||||
try {
|
||||
return updateCachedNativeHostRuntime(
|
||||
await requestNativeAppHostBridge<HostBridgeRuntimeResult>(
|
||||
'host.getRuntime',
|
||||
undefined,
|
||||
{ timeoutMs: HOST_RUNTIME_REFRESH_TIMEOUT_MS },
|
||||
),
|
||||
);
|
||||
} catch (error) {
|
||||
if (isUnsupportedHostBridgeError(error)) {
|
||||
return null;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export function refreshNativeAppHostRuntime() {
|
||||
if (nativeHostRuntimeRefreshPromise) {
|
||||
return nativeHostRuntimeRefreshPromise;
|
||||
}
|
||||
|
||||
nativeHostRuntimeRefreshPromise = getNativeAppHostRuntime()
|
||||
.catch(() => null)
|
||||
.finally(() => {
|
||||
nativeHostRuntimeRefreshPromise = null;
|
||||
});
|
||||
|
||||
return nativeHostRuntimeRefreshPromise;
|
||||
}
|
||||
|
||||
export function resetHostRuntimeCacheForTest() {
|
||||
cachedNativeHostRuntime = null;
|
||||
nativeHostRuntimeRefreshPromise = null;
|
||||
hostRuntimeChangeListeners.clear();
|
||||
}
|
||||
|
||||
export async function writeHostClipboardText({
|
||||
|
||||
Reference in New Issue
Block a user