@appthen/host-sdk 0.0.0-stage → 1.0.0
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/client.d.ts +24 -0
- package/dist/client.js +70 -0
- package/dist/contract.d.ts +92 -0
- package/dist/contract.js +14 -0
- package/dist/desktop.d.ts +152 -0
- package/dist/desktop.js +102 -0
- package/dist/dispatcher.d.ts +55 -0
- package/dist/dispatcher.js +121 -0
- package/dist/host-mode.d.ts +26 -0
- package/dist/host-mode.js +62 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.js +36 -0
- package/dist/index.mjs +565 -0
- package/dist/injectedScript.d.ts +17 -0
- package/dist/injectedScript.js +82 -0
- package/dist/web-providers.d.ts +21 -0
- package/dist/web-providers.js +247 -0
- package/package.json +23 -3
- package/src/client.ts +87 -0
- package/src/contract.ts +109 -0
- package/src/desktop.ts +209 -0
- package/src/dispatcher.ts +167 -0
- package/src/host-mode.ts +62 -0
- package/src/index.ts +16 -0
- package/src/injectedScript.ts +79 -0
- package/src/web-providers.ts +278 -0
- package/tsconfig.build.json +12 -0
- package/tsconfig.json +16 -0
- package/README.md +0 -3
package/src/desktop.ts
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* appthenHost 桌面端(Electron)RPC 契约。
|
|
3
|
+
*
|
|
4
|
+
* 这份契约是「SDK 作为两端对齐依据」的桌面侧部分:桌面 main 进程按这里的
|
|
5
|
+
* 方法名注册能力,桌面 Console 与 Workbench / 扩展用 `desktopClient` 调用,
|
|
6
|
+
* 移动端不注册这些方法(请求时得到 `method_not_found` / `host_unavailable`),
|
|
7
|
+
* 因此移动端页面通过 `hasHostCapability` / 握手 capabilities 感知宿主能力差异。
|
|
8
|
+
*
|
|
9
|
+
* 事件名 / 方法名 / DTO 都以本模块为准,别在别处再造一套。
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { appthenRequest, appthenSubscribe } from './client';
|
|
13
|
+
|
|
14
|
+
// ---- DTO(与桌面 main 内部类型保持结构一致,此处为对外契约) ----
|
|
15
|
+
|
|
16
|
+
export type DaemonConnectionState =
|
|
17
|
+
| 'idle' | 'starting' | 'connecting' | 'connected' | 'disconnected' | 'errored';
|
|
18
|
+
|
|
19
|
+
export interface DaemonStatus {
|
|
20
|
+
state: 'stopped' | 'starting' | 'running' | 'errored';
|
|
21
|
+
connection: DaemonConnectionState;
|
|
22
|
+
pid: number | null;
|
|
23
|
+
command: string | null;
|
|
24
|
+
error: string | null;
|
|
25
|
+
exitCode: number | null;
|
|
26
|
+
logPath: string | null;
|
|
27
|
+
lastMessage: string | null;
|
|
28
|
+
recentLogs: string[];
|
|
29
|
+
startedAt: string | null;
|
|
30
|
+
connectedAt: string | null;
|
|
31
|
+
nodeId: string | null;
|
|
32
|
+
projectId?: string;
|
|
33
|
+
workspaceId?: string;
|
|
34
|
+
workspaceName?: string;
|
|
35
|
+
cwd?: string;
|
|
36
|
+
serverUrl?: string;
|
|
37
|
+
recentEvents?: DaemonLogEntry[];
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export type DaemonLogCategory = 'connection' | 'message' | 'task' | 'error' | 'process' | 'log';
|
|
41
|
+
|
|
42
|
+
export interface DaemonLogEntry {
|
|
43
|
+
id: string;
|
|
44
|
+
timestamp: string;
|
|
45
|
+
source: 'stdout' | 'stderr' | 'desktop';
|
|
46
|
+
level: 'info' | 'warn' | 'error';
|
|
47
|
+
category: DaemonLogCategory;
|
|
48
|
+
message: string;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** 定位某个 daemon 的最小维度(`daemon.status` / `daemon.stop` / `daemon.logs` 入参)。 */
|
|
52
|
+
export interface DaemonTarget {
|
|
53
|
+
projectId?: string;
|
|
54
|
+
workspaceId?: string;
|
|
55
|
+
cwd?: string;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export type DaemonStartReason =
|
|
59
|
+
| 'manual_start' | 'manual_restart' | 'environment_created'
|
|
60
|
+
| 'conversation_ensure' | 'runtime_ensure';
|
|
61
|
+
|
|
62
|
+
/** `daemon.start` / `daemon.restart` 入参。 */
|
|
63
|
+
export interface DaemonStartParams extends DaemonTarget {
|
|
64
|
+
serverUrl: string;
|
|
65
|
+
projectId: string;
|
|
66
|
+
token: string;
|
|
67
|
+
workspaceId?: string;
|
|
68
|
+
workspaceName?: string;
|
|
69
|
+
cwd?: string;
|
|
70
|
+
reason?: DaemonStartReason;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** `dialog.chooseDirectory` 出参。 */
|
|
74
|
+
export interface DirectoryPickerResult {
|
|
75
|
+
canceled: boolean;
|
|
76
|
+
path?: string;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** 桌面端稳定的设备身份(`device.identity` 出参)。 */
|
|
80
|
+
export interface DesktopDeviceIdentity {
|
|
81
|
+
nodeId: string;
|
|
82
|
+
machineId: string;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** `notifications.show` / `events.publish` 入参。 */
|
|
86
|
+
export interface DesktopNotification {
|
|
87
|
+
title: string;
|
|
88
|
+
body?: string;
|
|
89
|
+
route?: string;
|
|
90
|
+
tag?: string;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** `updater.*` 状态(`updater:state` 事件载荷)。 */
|
|
94
|
+
export interface UpdateState {
|
|
95
|
+
status:
|
|
96
|
+
| 'idle' | 'checking' | 'available' | 'downloading' | 'downloaded'
|
|
97
|
+
| 'not-available' | 'error';
|
|
98
|
+
version?: string;
|
|
99
|
+
percent?: number;
|
|
100
|
+
message?: string;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// ---- 方法名 / 事件名约定(一份,别在别处再造) ----
|
|
104
|
+
|
|
105
|
+
export const desktopRpcMethods = {
|
|
106
|
+
appVersion: 'app.version',
|
|
107
|
+
serverGetUrl: 'server.getUrl',
|
|
108
|
+
dialogChooseDirectory: 'dialog.chooseDirectory',
|
|
109
|
+
daemonStatus: 'daemon.status',
|
|
110
|
+
daemonStatusAll: 'daemon.statusAll',
|
|
111
|
+
daemonStart: 'daemon.start',
|
|
112
|
+
daemonStop: 'daemon.stop',
|
|
113
|
+
daemonRestart: 'daemon.restart',
|
|
114
|
+
daemonLogs: 'daemon.logs',
|
|
115
|
+
logsOpenDirectory: 'logs.openDirectory',
|
|
116
|
+
notificationsShow: 'notifications.show',
|
|
117
|
+
eventsPublish: 'events.publish',
|
|
118
|
+
updaterCheck: 'updater.check',
|
|
119
|
+
updaterDownload: 'updater.download',
|
|
120
|
+
updaterInstall: 'updater.install',
|
|
121
|
+
navigationOpenExternal: 'navigation.openExternal',
|
|
122
|
+
} as const;
|
|
123
|
+
|
|
124
|
+
export const desktopRpcEvents = {
|
|
125
|
+
daemonStatus: 'daemon:status',
|
|
126
|
+
notification: 'events:notification',
|
|
127
|
+
updaterState: 'updater:state',
|
|
128
|
+
} as const;
|
|
129
|
+
|
|
130
|
+
/** SDK 声明的桌面能力清单(握手 capabilities 下发,供页面探测宿主能力差异)。 */
|
|
131
|
+
export const desktopHostCapabilities = [
|
|
132
|
+
desktopRpcMethods.appVersion,
|
|
133
|
+
desktopRpcMethods.serverGetUrl,
|
|
134
|
+
desktopRpcMethods.dialogChooseDirectory,
|
|
135
|
+
desktopRpcMethods.daemonStatus,
|
|
136
|
+
desktopRpcMethods.daemonStatusAll,
|
|
137
|
+
desktopRpcMethods.daemonStart,
|
|
138
|
+
desktopRpcMethods.daemonStop,
|
|
139
|
+
desktopRpcMethods.daemonRestart,
|
|
140
|
+
desktopRpcMethods.daemonLogs,
|
|
141
|
+
desktopRpcMethods.logsOpenDirectory,
|
|
142
|
+
desktopRpcMethods.notificationsShow,
|
|
143
|
+
desktopRpcMethods.eventsPublish,
|
|
144
|
+
desktopRpcMethods.updaterCheck,
|
|
145
|
+
desktopRpcMethods.updaterDownload,
|
|
146
|
+
desktopRpcMethods.updaterInstall,
|
|
147
|
+
desktopRpcMethods.navigationOpenExternal,
|
|
148
|
+
] as const;
|
|
149
|
+
|
|
150
|
+
export type DesktopRpcMethod = (typeof desktopHostCapabilities)[number];
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* 类型化桌面客户端:Console / Workbench / 扩展统一从这里调用,替代旧
|
|
154
|
+
* `window.appthenDesktop`。底层走 `window.appthenHost.request / subscribe`,
|
|
155
|
+
* 纯浏览器无宿主时按「无此能力」处理(thrown `host_unavailable`)。
|
|
156
|
+
*/
|
|
157
|
+
export const desktopClient = {
|
|
158
|
+
getVersion: (): Promise<string> => appthenRequest(desktopRpcMethods.appVersion),
|
|
159
|
+
server: {
|
|
160
|
+
getUrl: (): Promise<string> => appthenRequest(desktopRpcMethods.serverGetUrl),
|
|
161
|
+
},
|
|
162
|
+
device: {
|
|
163
|
+
identity: (): Promise<DesktopDeviceIdentity> => appthenRequest('device.identity'),
|
|
164
|
+
},
|
|
165
|
+
dialog: {
|
|
166
|
+
chooseDirectory: (): Promise<DirectoryPickerResult> =>
|
|
167
|
+
appthenRequest(desktopRpcMethods.dialogChooseDirectory),
|
|
168
|
+
},
|
|
169
|
+
daemon: {
|
|
170
|
+
status: (target?: DaemonTarget): Promise<DaemonStatus> =>
|
|
171
|
+
appthenRequest(desktopRpcMethods.daemonStatus, target),
|
|
172
|
+
statusAll: (): Promise<DaemonStatus[]> =>
|
|
173
|
+
appthenRequest(desktopRpcMethods.daemonStatusAll),
|
|
174
|
+
start: (config: DaemonStartParams): Promise<DaemonStatus> =>
|
|
175
|
+
appthenRequest(desktopRpcMethods.daemonStart, config),
|
|
176
|
+
stop: (target?: DaemonTarget): Promise<DaemonStatus> =>
|
|
177
|
+
appthenRequest(desktopRpcMethods.daemonStop, target),
|
|
178
|
+
restart: (config: DaemonStartParams): Promise<DaemonStatus> =>
|
|
179
|
+
appthenRequest(desktopRpcMethods.daemonRestart, config),
|
|
180
|
+
logs: (target: DaemonTarget, limit?: number): Promise<string[]> =>
|
|
181
|
+
appthenRequest(desktopRpcMethods.daemonLogs, { target, limit }),
|
|
182
|
+
/** 订阅 daemon 状态事件,返回取消函数。 */
|
|
183
|
+
onStatus: (listener: (status: DaemonStatus) => void): (() => void) =>
|
|
184
|
+
appthenSubscribe(desktopRpcEvents.daemonStatus, listener),
|
|
185
|
+
},
|
|
186
|
+
logs: {
|
|
187
|
+
openDirectory: (): Promise<string> =>
|
|
188
|
+
appthenRequest(desktopRpcMethods.logsOpenDirectory),
|
|
189
|
+
},
|
|
190
|
+
notifications: {
|
|
191
|
+
show: (payload: DesktopNotification): Promise<void> =>
|
|
192
|
+
appthenRequest(desktopRpcMethods.notificationsShow, payload),
|
|
193
|
+
},
|
|
194
|
+
events: {
|
|
195
|
+
publish: (payload: DesktopNotification): Promise<void> =>
|
|
196
|
+
appthenRequest(desktopRpcMethods.eventsPublish, payload),
|
|
197
|
+
/** 订阅应用内事件通知,返回取消函数。 */
|
|
198
|
+
onNotification: (listener: (payload: DesktopNotification) => void): (() => void) =>
|
|
199
|
+
appthenSubscribe(desktopRpcEvents.notification, listener),
|
|
200
|
+
},
|
|
201
|
+
updater: {
|
|
202
|
+
check: (): Promise<void> => appthenRequest(desktopRpcMethods.updaterCheck),
|
|
203
|
+
download: (): Promise<void> => appthenRequest(desktopRpcMethods.updaterDownload),
|
|
204
|
+
install: (): Promise<void> => appthenRequest(desktopRpcMethods.updaterInstall),
|
|
205
|
+
/** 订阅更新状态,返回取消函数。 */
|
|
206
|
+
onState: (listener: (state: UpdateState) => void): (() => void) =>
|
|
207
|
+
appthenSubscribe(desktopRpcEvents.updaterState, listener),
|
|
208
|
+
},
|
|
209
|
+
};
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
AppthenHostContext,
|
|
3
|
+
AppthenHostEvent,
|
|
4
|
+
AppthenHostHandshakeResponse,
|
|
5
|
+
AppthenHostRequest,
|
|
6
|
+
AppthenHostResponse,
|
|
7
|
+
} from './contract';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Native 侧可以回写给 Web 的通道。
|
|
11
|
+
* - 移动端:App 用 WebView ref 的 `injectJavaScript`
|
|
12
|
+
* - 桌面端:main 进程用 `webContents.executeJavaScript`
|
|
13
|
+
*/
|
|
14
|
+
export interface WebViewHostSink {
|
|
15
|
+
injectJavaScript(js: string): void;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export type MethodHandler = (
|
|
19
|
+
params: unknown,
|
|
20
|
+
context: AppthenHostContext,
|
|
21
|
+
) => unknown | Promise<unknown>;
|
|
22
|
+
|
|
23
|
+
export interface AppthenHostOptions {
|
|
24
|
+
hostKind: 'ios' | 'android' | 'desktop';
|
|
25
|
+
appVersion: string;
|
|
26
|
+
/** 稳定设备 id。移动端用 native 生成,桌面端用自己的 identity —— SDK 不负责生成。 */
|
|
27
|
+
deviceId: string;
|
|
28
|
+
/** 本端实装并对外声明的能力(handshake 下发)。 */
|
|
29
|
+
capabilities: string[];
|
|
30
|
+
/** 契约已声明、但 native 尚未接的能力:返回明确「未可用」诊断而非静默成功。 */
|
|
31
|
+
notYetImplemented: string[];
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const mkError = (id: string, code: string, message: string, retryable = false): AppthenHostResponse => ({
|
|
35
|
+
id,
|
|
36
|
+
ok: false,
|
|
37
|
+
error: { code, message, retryable },
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
const mkOk = (id: string, result: unknown): AppthenHostResponse => ({ id, ok: true, result });
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* 宿主 bridge 的统一分发逻辑(桌面端 / 移动端共用一份)。
|
|
44
|
+
*
|
|
45
|
+
* - 解释 `appthen:request` 来信、按 method 路由到能力、把响应回写
|
|
46
|
+
* - 只做「能力分派」与「授权边界」,不持有会话 / 模型 / Workspace 状态
|
|
47
|
+
* - 能力由个端通过 `registerMethod` 挂入;`host.*` / `device.identity` 默认方法内建
|
|
48
|
+
* - `notYetImplemented` 里的能力返回明确诊断
|
|
49
|
+
*/
|
|
50
|
+
export class AppthenHost {
|
|
51
|
+
private readonly hostKind: AppthenHostOptions['hostKind'];
|
|
52
|
+
private readonly appVersion: string;
|
|
53
|
+
private readonly deviceId: string;
|
|
54
|
+
private readonly capabilities: readonly string[];
|
|
55
|
+
|
|
56
|
+
private sink: WebViewHostSink | null = null;
|
|
57
|
+
private readonly handlers = new Map<string, MethodHandler>();
|
|
58
|
+
|
|
59
|
+
constructor(options: AppthenHostOptions) {
|
|
60
|
+
this.hostKind = options.hostKind;
|
|
61
|
+
this.appVersion = options.appVersion;
|
|
62
|
+
this.deviceId = options.deviceId;
|
|
63
|
+
this.capabilities = [...options.capabilities];
|
|
64
|
+
this.registerDefaults(options.notYetImplemented);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** 绑定回写 sink(App / main 进程在拿到 WebView/WebContents 后调用)。 */
|
|
68
|
+
attach(sink: WebViewHostSink): void {
|
|
69
|
+
this.sink = sink;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** 供各端能力注册专用方法(调用方自行保证 method 在 capabilities 里)。 */
|
|
73
|
+
registerMethod(method: string, handler: MethodHandler): void {
|
|
74
|
+
this.handlers.set(method, handler);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* 处理收到的原文消息。
|
|
79
|
+
* 移动端:`react-native-webview` onMessage 的 `event.nativeEvent.data`。
|
|
80
|
+
* 桌面端:preload `ipcRenderer.send('appthen:toMain', raw)` 的 raw。
|
|
81
|
+
*/
|
|
82
|
+
handleIncoming(raw: string): void {
|
|
83
|
+
let payload: { type?: string; req?: AppthenHostRequest };
|
|
84
|
+
try {
|
|
85
|
+
payload = JSON.parse(raw);
|
|
86
|
+
} catch {
|
|
87
|
+
return; // 非 JSON / 注入之外的消息,忽略
|
|
88
|
+
}
|
|
89
|
+
if (payload?.type !== 'appthen:request' || !payload.req) return;
|
|
90
|
+
void this.handleRequest(payload.req);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Native → Web 事件(通知点击、语音转写/播报、daemon 状态等)。
|
|
95
|
+
* 业务用 `window.appthenHost.subscribe(eventType, listener)` 订阅。
|
|
96
|
+
*/
|
|
97
|
+
emit(eventType: string, payload: unknown, correlationId?: string): void {
|
|
98
|
+
if (!this.sink) return;
|
|
99
|
+
const event: AppthenHostEvent = {
|
|
100
|
+
eventType,
|
|
101
|
+
eventId: Math.random().toString(36).slice(2),
|
|
102
|
+
correlationId,
|
|
103
|
+
timestamp: Date.now(),
|
|
104
|
+
payload,
|
|
105
|
+
};
|
|
106
|
+
this.sink.injectJavaScript(
|
|
107
|
+
`window.appthenHost && window.appthenHost.__dispatchEvent(${JSON.stringify(event)});`,
|
|
108
|
+
);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
private registerDefaults(notYetImplemented: string[]): void {
|
|
112
|
+
this.handlers.set('host.handshake', () => this.makeHandshake());
|
|
113
|
+
this.handlers.set('host.info', () => ({
|
|
114
|
+
hostKind: this.hostKind,
|
|
115
|
+
appVersion: this.appVersion,
|
|
116
|
+
deviceId: this.deviceId,
|
|
117
|
+
capabilities: this.capabilities,
|
|
118
|
+
}));
|
|
119
|
+
this.handlers.set('device.identity', () => ({ deviceId: this.deviceId }));
|
|
120
|
+
this.handlers.set('device.registerPresence', (params) => params ?? { ok: true });
|
|
121
|
+
|
|
122
|
+
for (const method of notYetImplemented) {
|
|
123
|
+
this.handlers.set(method, () => {
|
|
124
|
+
throw {
|
|
125
|
+
code: 'not_yet_implemented',
|
|
126
|
+
message: `能力「${method}」的原生模块尚未接入(协同工作台后续版本提供)。`,
|
|
127
|
+
retryable: false,
|
|
128
|
+
};
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
private makeHandshake(): AppthenHostHandshakeResponse {
|
|
134
|
+
return {
|
|
135
|
+
protocolVersion: 1,
|
|
136
|
+
hostKind: this.hostKind,
|
|
137
|
+
appVersion: this.appVersion,
|
|
138
|
+
capabilities: [...this.capabilities],
|
|
139
|
+
deviceId: this.deviceId,
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
private async handleRequest(req: AppthenHostRequest): Promise<void> {
|
|
144
|
+
const respond = (resp: AppthenHostResponse) => {
|
|
145
|
+
this.sink?.injectJavaScript(
|
|
146
|
+
`window.appthenHost && window.appthenHost.__dispatchResponse(${JSON.stringify(resp)});`,
|
|
147
|
+
);
|
|
148
|
+
};
|
|
149
|
+
|
|
150
|
+
if (req.version !== 1) {
|
|
151
|
+
respond(mkError(req.id, 'unsupported_protocol', '不支持的协议版本。'));
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
const handler = this.handlers.get(req.method);
|
|
155
|
+
if (!handler) {
|
|
156
|
+
respond(mkError(req.id, 'method_not_found', `未知方法 ${req.method}。`));
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
try {
|
|
160
|
+
const result = await handler(req.params, req.context);
|
|
161
|
+
respond(mkOk(req.id, result));
|
|
162
|
+
} catch (err) {
|
|
163
|
+
const e = (err ?? {}) as { code?: string; message?: string; retryable?: boolean };
|
|
164
|
+
respond(mkError(req.id, e.code ?? 'internal_error', e.message ?? '能力执行失败。', Boolean(e.retryable)));
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
package/src/host-mode.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 主机模式(host mode):决定一次能力调用「优先走 native 宿主还是 web 降级」。
|
|
3
|
+
*
|
|
4
|
+
* 背景:同一份 `appthenHost` 契约,桌面端(Electron)+ 移动端(RN WebView)由
|
|
5
|
+
* native 宿主提供能力;纯浏览器没有 `window.appthenHost`,但部分能力(剪贴板、
|
|
6
|
+
* 通知、外链、TTS/STT、选目录等)可以用浏览器原生 API「将就着用」。
|
|
7
|
+
* 这份模块统一这套切换逻辑,避免各个消费点自己判 `window.appthenHost`。
|
|
8
|
+
*
|
|
9
|
+
* 优先级(高 → 低):
|
|
10
|
+
* 1. 运行时 `setHostMode(mode)` 覆盖;
|
|
11
|
+
* 2. 环境变量 `APPTHEN_HOST_MODE`(Node):取值 auto | native | web;
|
|
12
|
+
* 3. `globalThis.APPTHEN_HOST_MODE`(Vite 可用 `define` 注入 / 页面自设);
|
|
13
|
+
* 4. 默认 `'auto'`。
|
|
14
|
+
*
|
|
15
|
+
* Vite 的 `VITE_` 变量不会进入预编译的 CommonJS dist,web 侧如有需要请用
|
|
16
|
+
* `define` 注入 `globalThis.APPTHEN_HOST_MODE`,或直接调用 `setHostMode`。
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
export type HostMode = 'auto' | 'native' | 'web';
|
|
20
|
+
|
|
21
|
+
let runtimeMode: HostMode | undefined;
|
|
22
|
+
|
|
23
|
+
/** 运行时强制覆盖主机模式(例如在桌面里临时切到 web 路径做回归测试)。 */
|
|
24
|
+
export function setHostMode(mode: HostMode): void {
|
|
25
|
+
runtimeMode = mode;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function normalize(value: unknown): HostMode | undefined {
|
|
29
|
+
if (typeof value !== 'string') return undefined;
|
|
30
|
+
const v = value.trim().toLowerCase();
|
|
31
|
+
if (v === 'auto' || v === 'native' || v === 'web') return v;
|
|
32
|
+
return undefined;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** 当前生效的主机模式(调用时读取,允许运行时切换)。 */
|
|
36
|
+
export function getHostMode(): HostMode {
|
|
37
|
+
if (runtimeMode) return runtimeMode;
|
|
38
|
+
|
|
39
|
+
// Node 侧 `process.env`(SDK 开启 `types:[]`,故经 globalThis 取,避免静态引用 process)
|
|
40
|
+
const nodeProc = (globalThis as { process?: { env?: { APPTHEN_HOST_MODE?: string } } }).process;
|
|
41
|
+
if (nodeProc?.env?.APPTHEN_HOST_MODE) {
|
|
42
|
+
const fromEnv = normalize(nodeProc.env.APPTHEN_HOST_MODE);
|
|
43
|
+
if (fromEnv) return fromEnv;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
if (typeof globalThis !== 'undefined') {
|
|
47
|
+
const onGlobal = normalize((globalThis as { APPTHEN_HOST_MODE?: unknown }).APPTHEN_HOST_MODE);
|
|
48
|
+
if (onGlobal) return onGlobal;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
return 'auto';
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** web 降级是否在该模式下可用(`native` 模式返回 false)。 */
|
|
55
|
+
export function hostModeAllowsWebFallback(): boolean {
|
|
56
|
+
return getHostMode() !== 'native';
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** 当前是否允许优先使用 native 宿主(`web` 模式返回 false)。 */
|
|
60
|
+
export function hostModeAllowsNative(): boolean {
|
|
61
|
+
return getHostMode() !== 'web';
|
|
62
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @appthen/host-sdk —— appthenHost 统一桥共享 SDK
|
|
3
|
+
*
|
|
4
|
+
* 桌面端(Electron)与移动端(RN WebView)围绕这份包对齐:
|
|
5
|
+
* - `contract`:契约类型(request/response/event/handshake/voice + window.appthenHost)
|
|
6
|
+
* - `injectedScript`:注入页面的 Web JSSDK(transport 无关,两端同一份脚本)
|
|
7
|
+
* - `dispatcher`:native 侧统一分发逻辑(host.* / device.* 内建)
|
|
8
|
+
* - `client`:Web 侧统一客户端助手(appthenRequest / appthenSubscribe)
|
|
9
|
+
*/
|
|
10
|
+
export * from './contract';
|
|
11
|
+
export * from './host-mode';
|
|
12
|
+
export { webCapabilityProviders, type WebCapabilityProvider } from './web-providers';
|
|
13
|
+
export * from './client';
|
|
14
|
+
export * from './desktop';
|
|
15
|
+
export { AppthenHost, type MethodHandler, type AppthenHostOptions, type WebViewHostSink } from './dispatcher';
|
|
16
|
+
export { appthenHostInjectedScript } from './injectedScript';
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 注入 WebView / 页面的脚本(移动端经 `injectedJavaScriptBeforeContentLoaded`,
|
|
3
|
+
* 桌面端由 preload 在页面脚本运行前注入到主 world)。
|
|
4
|
+
*
|
|
5
|
+
* 在页面加载早期装好 `window.appthenHost`,业务代码只认它;这里不暴露任何
|
|
6
|
+
* RN / iOS / Android / Electron 专属对象。
|
|
7
|
+
*
|
|
8
|
+
* 通信通道(两端各喂一个 `post` 即可,脚本本体完全通用):
|
|
9
|
+
* - Web → Native:
|
|
10
|
+
* `window.__appthenHostTx.post(JSON.stringify({type:'appthen:request', req}))`
|
|
11
|
+
* - 移动端:RN WebView 里脚本找不到 `window.__appthenHostTx` 时,回落到
|
|
12
|
+
* `window.ReactNativeWebView.postMessage(...)`(保持向后兼容)。
|
|
13
|
+
* - 桌面端:preload 通过 contextBridge 暴露 `window.__appthenHostTx = { post }`,
|
|
14
|
+
* 底层走 `ipcRenderer.send('appthen:toMain', raw)`。
|
|
15
|
+
* - Native → Web:native 侧统一调 `window.appthenHost.__dispatchResponse/_dispatchEvent`。
|
|
16
|
+
*/
|
|
17
|
+
export const appthenHostInjectedScript = String.raw`
|
|
18
|
+
(function () {
|
|
19
|
+
if (window.__appthenHostInstalled) return;
|
|
20
|
+
window.__appthenHostInstalled = true;
|
|
21
|
+
|
|
22
|
+
var pending = Object.create(null);
|
|
23
|
+
var listeners = Object.create(null);
|
|
24
|
+
var seed = 0;
|
|
25
|
+
var seq = function () { seed += 1; return Date.now().toString(36) + '-' + seed; };
|
|
26
|
+
|
|
27
|
+
var post = function (payload) {
|
|
28
|
+
var raw = JSON.stringify(payload);
|
|
29
|
+
if (window.__appthenHostTx && window.__appthenHostTx.post) {
|
|
30
|
+
window.__appthenHostTx.post(raw);
|
|
31
|
+
} else if (window.ReactNativeWebView && window.ReactNativeWebView.postMessage) {
|
|
32
|
+
window.ReactNativeWebView.postMessage(raw);
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
function request(req) {
|
|
37
|
+
return new Promise(function (resolve) {
|
|
38
|
+
var id = req && req.id ? req.id : seq();
|
|
39
|
+
var envelope = {
|
|
40
|
+
type: 'appthen:request',
|
|
41
|
+
req: {
|
|
42
|
+
id: id,
|
|
43
|
+
version: 1,
|
|
44
|
+
method: req.method,
|
|
45
|
+
params: req.params,
|
|
46
|
+
context: req.context || {}
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
pending[id] = resolve;
|
|
50
|
+
post(envelope);
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function subscribe(eventType, listener) {
|
|
55
|
+
(listeners[eventType] = listeners[eventType] || []).push(listener);
|
|
56
|
+
return function unsubscribe() {
|
|
57
|
+
var arr = listeners[eventType] || [];
|
|
58
|
+
var idx = arr.indexOf(listener);
|
|
59
|
+
if (idx >= 0) arr.splice(idx, 1);
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
window.appthenHost = { request: request, subscribe: subscribe };
|
|
64
|
+
|
|
65
|
+
window.appthenHost.__dispatchResponse = function (resp) {
|
|
66
|
+
var r = typeof resp === 'string' ? JSON.parse(resp) : resp;
|
|
67
|
+
var cb = pending[r.id];
|
|
68
|
+
if (cb) { delete pending[r.id]; cb(r); }
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
window.appthenHost.__dispatchEvent = function (ev) {
|
|
72
|
+
var e = typeof ev === 'string' ? JSON.parse(ev) : ev;
|
|
73
|
+
var arr = listeners[e.eventType] || [];
|
|
74
|
+
for (var i = 0; i < arr.length; i++) {
|
|
75
|
+
try { arr[i](e); } catch (err) { }
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
})();
|
|
79
|
+
`;
|