Repository navigation
Expand file tree
/
Copy pathadb-host.ts
More file actions
175 lines (161 loc) · 7.13 KB
/
Copy pathadb-host.ts
File metadata and controls
175 lines (161 loc) · 7.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
import { AsyncLocalStorage } from 'node:async_hooks';
import type { AndroidHelperInstallDecision, AndroidImeHelperArtifact } from './helper-artifacts.ts';
import type {
AndroidAdbInvocation,
AndroidAdbExecutor,
AndroidAdbExecutorOptions,
AndroidAdbExecutorResult,
AndroidAdbProcess,
AndroidAdbProvider,
AndroidAdbSpawnOptions,
} from './adb-transport.ts';
export type AndroidAdbCommandExecutorOverride = (
cmd: string,
args: readonly string[],
options: AndroidAdbExecutorOptions,
) => Promise<AndroidAdbExecutorResult> | undefined;
export type AndroidAdbDiagnosticEvent = {
level?: 'info' | 'warn' | 'error' | 'debug';
phase: string;
durationMs?: number;
data?: Record<string, unknown>;
};
export type AndroidAdbFileHost = Readonly<{
access(path: string): Promise<void>;
ensureDirectory(path: string): Promise<void>;
isExecutable(path: string): Promise<boolean>;
makeTempDirectory(prefix: string): Promise<string>;
readBytes(path: string): Promise<Buffer>;
readDirectory(path: string): Promise<string[]>;
readText(path: string): Promise<string>;
remove(path: string, options?: Readonly<{ force?: boolean; recursive?: boolean }>): Promise<void>;
sha256(value: Buffer): string;
stat(path: string): Promise<Readonly<{ isFile: boolean; size: number }>>;
writeAtomicText(path: string, value: string, mode?: number): Promise<void>;
writeBytes(path: string, value: Buffer): Promise<void>;
}>;
export type AndroidAdbEnvironment = Record<string, string | undefined>;
export type AndroidAdbHost = Readonly<{
/**
* One piece of helper state the current daemon runtime owns (warm sessions, failed starts,
* pending retirements, shell-protocol probes), created on first use. The root binds the daemon's
* runtime slots here, so a close tears down only its own runtime's helper.
*/
runtimeSlot<T>(key: symbol, create: () => T, dispose?: (value: T) => void): T;
/** Explicit process environment captured by the root composition boundary. */
environment: AndroidAdbEnvironment;
/** Narrow filesystem authority used by Android helper, SDK, and artifact mechanics. */
files: AndroidAdbFileHost;
/**
* Local adb execution for one addressing decision, visible to an installed command-executor
* override so a scoped transport can answer for it. A caller that must not be captured — the
* device-scoped executor a provider would otherwise re-enter — wraps this in
* `withoutAdbCommandExecutorOverride`. The invocation's command is appended verbatim; only
* `target` is lowered into adb global options.
*/
execAdb(
invocation: AndroidAdbInvocation,
options?: AndroidAdbExecutorOptions,
): Promise<AndroidAdbExecutorResult>;
/** Local adb background spawn for one addressing decision; the host owns stream wiring. */
spawnAdb(invocation: AndroidAdbInvocation, options?: AndroidAdbSpawnOptions): AndroidAdbProcess;
/** Installs `override` as the host command-executor override for the duration of `fn`. */
withAdbCommandExecutorOverride<T>(
override: AndroidAdbCommandExecutorOverride,
fn: () => Promise<T>,
): Promise<T>;
/** Escapes any active command-executor override for the duration of `fn`. */
withoutAdbCommandExecutorOverride<T>(fn: () => Promise<T>): Promise<T>;
/** Normalizes a result that crossed an unchecked SDK/provider boundary. */
coerceAdbResult<T extends Pick<AndroidAdbExecutorResult, 'stdout' | 'stderr' | 'exitCode'>>(
result: T,
): T;
/** COMMAND_FAILED details for a non-zero result, flagged for stderr-excerpt enrichment. */
execFailureDetails(
result: Pick<AndroidAdbExecutorResult, 'stdout' | 'stderr' | 'exitCode'>,
extra?: Record<string, unknown>,
): Record<string, unknown>;
emitDiagnostic(event: AndroidAdbDiagnosticEvent): void;
/** Durable per-state-dir test-IME recovery markers (host-side files). */
imeRecoveryMarkers: Readonly<{
write(stateDir: string, serial: string): Promise<boolean>;
clear(stateDir: string, serial: string): Promise<void>;
read(stateDir: string): Promise<string[]>;
}>;
/** Resolves an npm-bundled helper artifact from the packaged install tree. */
resolveHelperArtifact<Manifest extends { assetName: string }>(options: {
helperDirName: string;
manifestFileName: (version: string) => string;
parseManifest: (value: unknown) => Manifest;
unavailableMessage: string;
}): Promise<{ apkPath: string; manifest: Manifest }>;
/** Shared helper APK install/version-check/checksum lifecycle. */
ensureHelperInstalled(
config: Readonly<{ cache: Set<string>; installTimeoutMs: number; helperLabel: string }>,
request: Readonly<{
adb: AndroidAdbExecutor;
adbProvider: AndroidAdbProvider;
artifact: AndroidImeHelperArtifact;
deviceKey: string;
}>,
): Promise<AndroidHelperInstallDecision>;
}>;
let boundHost: AndroidAdbHost | undefined;
/** Scoped override for host-global and explicitly serial-qualified adb invocations. */
export type AndroidAdbHostTransport = (
invocation: AndroidAdbInvocation,
options?: AndroidAdbExecutorOptions,
) => Promise<AndroidAdbExecutorResult>;
const androidAdbHostTransportScope = new AsyncLocalStorage<AndroidAdbHostTransport>();
/** Composition-time wiring; the last bind wins so test harnesses can rebind. */
export function bindAndroidAdbHost(host: AndroidAdbHost): void {
boundHost = host;
}
/** One piece of helper state the current daemon runtime owns, created on first use. */
export function helperRuntimeSlot<T>(key: symbol, create: () => T): T {
return requireAndroidAdbHost().runtimeSlot(key, create);
}
export function requireAndroidAdbHost(): AndroidAdbHost {
if (!boundHost) {
throw new Error(
'Android adb host port is not bound; import the platform composition wiring ' +
'(src/platform-runtime-android-adb-host.ts) before using the adb/IME cluster.',
);
}
return boundHost;
}
/**
* Runs host-level adb through one package-owned failure contract. A scoped
* transport wins over the injected local host port; nested scopes are
* innermost-first and restore automatically.
*/
export async function runAndroidHostAdb(
invocation: AndroidAdbInvocation,
options?: AndroidAdbExecutorOptions,
): Promise<AndroidAdbExecutorResult> {
const host = requireAndroidAdbHost();
const transport = androidAdbHostTransportScope.getStore();
const result = host.coerceAdbResult(
transport
? await transport(invocation, options)
: await host.execAdb(invocation, { ...options, allowFailure: true }),
);
if (!options?.allowFailure && result.exitCode !== 0) {
const { androidAdbResultError } = await import('./adb-failure.ts');
const { serializeAndroidAdbInvocation } = await import('./adb-transport.ts');
throw androidAdbResultError(
`adb ${serializeAndroidAdbInvocation(invocation).join(' ')} exited with code ${result.exitCode}`,
result,
);
}
return result;
}
export async function withAndroidHostAdbTransport<T>(
transport: AndroidAdbHostTransport,
fn: () => Promise<T>,
): Promise<T> {
return await androidAdbHostTransportScope.run(transport, fn);
}
export function emitAndroidAdbDiagnostic(event: AndroidAdbDiagnosticEvent): void {
requireAndroidAdbHost().emitDiagnostic(event);
}