Repository navigation
Expand file tree
/
Copy pathsettings.ts
More file actions
436 lines (400 loc) · 16 KB
/
Copy pathsettings.ts
File metadata and controls
436 lines (400 loc) · 16 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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
import { AppError, appNotInstalledDetails, discloseDispatch } from '@agent-device/kernel/errors';
import {
APPEARANCE_ACTIONS,
MOBILE_PERMISSION_TARGETS,
PERMISSION_ACTIONS,
PERMISSION_MODES,
SETTINGS,
settingDefinition,
SETTING_NAMES,
TEXT_SIZE_CATEGORIES,
type AppearanceAction,
type MobilePermissionTarget,
type PermissionAction,
type SettingDefinition,
type SettingForm,
type SettingName,
type SettingsAppScope,
type SettingsTargetFamily,
type TextSizeCategory,
} from './settings-catalog.ts';
/**
* What `text-size` answers with. The ladder is shared across platforms, so a read names the
* category the ladder calls the device's value *and* the value the platform itself reported: an
* Apple content-size name, or an Android `font_scale` multiplier. The ladder is coarser than any
* one platform's own scale, and `platformValue` is what keeps a normalized answer auditable.
*/
export type TextSizeSettingPayload = Readonly<{
setting: 'text-size';
category: TextSizeCategory;
platformValue: string;
}>;
/**
* The payload a readable setting answers with, keyed by the setting that answered. Each readable
* setting has its own shape — a category and a multiplier are not the same observation — so the
* discriminant is what lets a response be composed, recorded, and printed from one place without
* assuming every setting is a ladder rung. A second readable setting joins this union and supplies
* its own sentence in `describeSettingRead`, which is where the compiler then asks for it.
*/
export type ReadSettingResult = TextSizeSettingPayload;
/** Builds the ladder's read payload, so no owner renames its keys or drops the platform value. */
export function textSizeSettingPayload(
category: TextSizeCategory,
platformValue: string,
): TextSizeSettingPayload {
return Object.freeze({ setting: 'text-size', category, platformValue });
}
/** The one sentence a settings read answers with, per payload shape rather than per call site. */
export function describeSettingRead(result: ReadSettingResult): string {
return `Text size is ${result.category}`;
}
/**
* The sentence a settings mutation answers with. It belongs to the vocabulary rather than the daemon
* because it is a claim about the setting: `clear-app-state` names the app it cleared and `text-size`
* names the rung it applied, and both are the same words whoever performs the write.
*/
export function describeSettingWrite(
setting: string,
state: string,
appBundleId: string | undefined,
): string {
if (setting === 'clear-app-state') return `Cleared user data for ${appBundleId}`;
if (setting === 'text-size') return `Text size set to ${state}`;
return `Updated setting: ${setting}`;
}
export type SettingOptions = {
permissionTarget?: string;
permissionMode?: string;
latitude?: number;
longitude?: number;
};
/** The settings a simulator changes through `simctl` alone, whichever host runs that `simctl`. */
type SimctlSetting = 'appearance' | 'permission' | 'location';
/**
* Runs one `simctl` argv on the simulator. It resolves with the output when `simctl` exits 0 and
* rejects with a `COMMAND_FAILED` AppError whose `details.stderr` is the `simctl` stderr otherwise.
*/
type SimctlSettingRunner = (
args: string[],
) => Promise<{ readonly stdout: string; readonly stderr: string }>;
/** One simulator setting the Apple `simctl` plan changes, whichever host runs that `simctl`. */
export type SimctlSettingRequest = {
runSimctl: SimctlSettingRunner;
/** The simulator UDID `simctl` addresses, or `booted` where the runner reaches one simulator. */
udid: string;
/** The device id a refusal reports to the caller, which `udid` is not on every runner. */
deviceId: string;
setting: SimctlSetting;
state: string;
appBundleId?: string;
/** Resolves the app a privacy change names to the bundle id `simctl privacy` writes. */
resolveApp: (app: string) => Promise<string>;
options?: SettingOptions;
};
/**
* Whether naming an app on one mutation can mean anything on one target family, read from the
* matched form's `appScope`, then the setting's own.
*/
export function settingsAppScope(
family: SettingsTargetFamily,
setting: string,
state: string | undefined,
): SettingsAppScope {
const definition = settingDefinition(setting);
if (definition === undefined) return 'unknown';
const form =
definition.forms.length === 1
? definition.forms[0]
: definition.forms.find((candidate) => formAcceptsState(candidate, state));
const scope = (form && 'appScope' in form ? form.appScope : undefined) ?? definition.appScope;
return scope?.[family] ?? 'unknown';
}
/**
* The reason a request is told its app names nothing: what a caller does about it — drop the app or
* move to a target whose mutation is app-scoped — is the reason's meaning, so a driver can branch
* on `error.details.reason` instead of the prose. Paired with `dispatched: no`, because the
* refusal runs before a device is touched.
*/
export const SETTINGS_APP_NOT_CONSUMED_REASON = 'setting_app_not_consumed';
/**
* The refusal a mutation answers with when its target consumes no app: the code, sentence, typed
* details, and hint as data, so the daemon can answer with it through its own response builder
* rather than by unwrapping an error the CLI would then re-normalize. The `app` that named nothing
* stays in `details` — the caller asked about that bundle id and the answer should quote it back.
*/
export function settingsAppNotConsumedRefusal(
setting: string,
state: string | undefined,
app: string,
): {
code: 'INVALID_ARGS';
message: string;
details: Record<string, unknown>;
hint: string;
} {
const described = state === undefined ? setting : `${setting} ${state}`;
return {
code: 'INVALID_ARGS',
message: `settings ${described} applies to the target itself, not to an app: ${app} names nothing it can grant or revoke.`,
details: {
reason: SETTINGS_APP_NOT_CONSUMED_REASON,
dispatched: 'no',
setting: described,
app,
},
hint: `Drop the --app option and run \`settings ${described}\`, or aim the app at an app-scoped setting such as \`settings permission grant location --app ${app}\`.`,
};
}
const SETTINGS_APP_NOT_INSTALLED_HINT =
'Run apps --all for the exact bundle id or package name, or install the app, then retry with that id in --app.';
/**
* The reason an Android app-scoped mutation refuses an app that resolves to an intent rather than a
* package: a permission or app-data change needs a package, so the recovery is naming one.
*/
export const SETTINGS_APP_NOT_PACKAGE_REASON = 'setting_app_not_package';
/**
* Resolves the app an app-scoped mutation lands on through the owner's own app resolution, ahead of
* anything that reaches the device. A failed resolution therefore dispatched nothing, and an app that
* resolves to no installed app answers `app_not_installed` rather than reaching the device as a
* literal id.
*/
export async function resolveSettingsApp<Resolved>(
app: string,
resolve: (app: string) => Promise<Resolved>,
): Promise<Resolved> {
try {
return await resolve(app);
} catch (error) {
if (!(error instanceof AppError)) throw error;
if (error.code === 'APP_NOT_INSTALLED') {
error.details = {
...error.details,
...appNotInstalledDetails(),
app,
hint: SETTINGS_APP_NOT_INSTALLED_HINT,
};
}
throw discloseDispatch(error, 'no');
}
}
/** The positionals after `settings` one form accepts, as help prints them. */
function formUsage(form: SettingForm, readable: boolean): string {
switch (form.kind) {
case 'on-off':
return '<on|off>';
case 'choice': {
const states = form.states.join('|');
if (readable) return `[${states}]`;
return form.states.length === 1 ? states : `<${states}>`;
}
case 'coordinates':
return 'set <lat> <lon>';
case 'permission': {
const modes = form.modes ? ` [${form.modes.join('|')}]` : '';
return `<${form.actions.join('|')}> <${form.targets.join('|')}>${modes}`;
}
case 'app-id':
return '[app-id]';
}
}
/** Every settings form, with settings that share a form folded into one `<a|b> <form>` line. */
function settingsUsageForms(): string[] {
const namesByForm = new Map<string, string[]>();
for (const name of SETTING_NAMES) {
const definition: SettingDefinition = SETTINGS[name];
for (const form of definition.forms) {
const usage = formUsage(form, definition.readable === true);
namesByForm.set(usage, [...(namesByForm.get(usage) ?? []), name]);
}
}
return [...namesByForm].map(([usage, names]) =>
names.length === 1 ? `${names[0]} ${usage}` : `<${names.join('|')}> ${usage}`,
);
}
export const SETTINGS_USAGE_OVERRIDE = settingsUsageForms()
.map((form) => `settings ${form}`)
.join(' | ');
export const SETTINGS_INVALID_ARGS_MESSAGE = `settings requires ${settingsUsageForms()
.join(', ')
.replace(/, (?!.*, )/, ', or ')}`;
/** One line per setting: its name and its help. */
export function settingsHelpLines(): string[] {
return SETTING_NAMES.map((name) => `${name}: ${SETTINGS[name].help}`);
}
/**
* One validated mutation. Names and states are normalized; the app, mode, and coordinates are kept
* as written, because the app is an id and coordinates are typed where the caller needs them.
*/
export type SettingsMutation = Readonly<{
setting: SettingName;
state: string;
app?: string;
permission?: string;
mode?: string;
latitude?: string;
longitude?: string;
}>;
/**
* Parses `settings <setting> <state> …` against the catalog. A lone readable setting is the read
* leg, which `resolveSettingsRuntimePlan` decides before this runs.
*/
export function parseSettingsMutation(positionals: readonly string[]): SettingsMutation {
const definition = settingDefinition(positionals[0]);
if (definition === undefined) throw invalidSettingsArgs();
const setting = normalizeName(positionals[0]) as SettingName;
const state = normalizeName(positionals[1]);
if (definition.forms.some((form) => form.kind === 'app-id')) {
if (positionals.length > 3) throw invalidSettingsArgs();
const app = state === 'clear' ? positionals[2] : positionals[1];
return { setting, state: 'clear', ...(app === undefined ? {} : { app }) };
}
const form = definition.forms.find((candidate) => formAcceptsState(candidate, state));
if (form === undefined || state === undefined)
throw invalidSettingState(setting, definition, state);
return parseFormPositionals(setting, state, form, definition, positionals);
}
function parseFormPositionals(
setting: SettingName,
state: string,
form: SettingForm,
definition: SettingDefinition,
positionals: readonly string[],
): SettingsMutation {
switch (form.kind) {
case 'coordinates':
if (positionals.length !== 4) throw invalidSettingsArgs();
return { setting, state, latitude: positionals[2], longitude: positionals[3] };
case 'permission':
return { setting, state, ...parsePermissionPositionals(definition, positionals) };
case 'on-off':
if (positionals.length !== 2) throw invalidSettingsArgs();
return { setting, state: readSettingState(state) ? 'on' : 'off' };
default:
if (positionals.length !== 2) throw invalidSettingsArgs();
return { setting, state };
}
}
function parsePermissionPositionals(
definition: SettingDefinition,
positionals: readonly string[],
): { permission: string; mode?: string } {
const targets = definition.forms.flatMap((form) =>
form.kind === 'permission' ? form.targets : [],
);
const permission = findVocabularyName(targets, positionals[2]);
if (permission === undefined) {
throw new AppError(
'INVALID_ARGS',
`settings permission requires a target: ${targets.join('|')}`,
);
}
if (positionals[3] === undefined) return { permission };
const mode = findVocabularyName(PERMISSION_MODES, positionals[3]);
if (mode === undefined || positionals.length > 4) {
throw new AppError(
'INVALID_ARGS',
`settings permission mode must be ${PERMISSION_MODES.join('|')}.`,
);
}
return { permission, mode };
}
function invalidSettingsArgs(): AppError {
return new AppError('INVALID_ARGS', SETTINGS_INVALID_ARGS_MESSAGE);
}
function invalidSettingState(
setting: SettingName,
definition: SettingDefinition,
state: string | undefined,
): AppError {
const accepted = definition.forms
.map((form) => (form.kind === 'choice' ? form.states.join('|') : formUsage(form, false)))
.join(' | ')
.replace('<on|off>', 'on|off');
return new AppError(
'INVALID_ARGS',
state === undefined
? `settings ${setting} requires a state: ${accepted}.`
: `Invalid ${setting} state: ${state}. Use ${accepted}.`,
);
}
function formAcceptsState(form: SettingForm, state: string | undefined): boolean {
switch (form.kind) {
case 'on-off':
return readSettingState(normalizeName(state)) !== undefined;
case 'choice':
return findVocabularyName(form.states, state) !== undefined;
case 'coordinates':
return normalizeName(state) === 'set';
case 'permission':
return findVocabularyName(form.actions, state) !== undefined;
case 'app-id':
return true;
}
}
function normalizeName(value: string | undefined): string | undefined {
return value?.trim().toLowerCase();
}
/**
* The category a caller asked for. `simctl` exits 0 with `Invalid argument` for a category it does
* not know, so a write never hands validation to the tool.
*/
export function parseTextSizeCategory(value: string | undefined): TextSizeCategory {
const parsed = readTextSizeCategory(value);
if (parsed !== undefined) return parsed;
throw invalidSettingState('text-size', SETTINGS['text-size'], value);
}
/** The category an owner reads back, or `undefined` for a value the ladder does not name. */
export function readTextSizeCategory(value: string | undefined): TextSizeCategory | undefined {
return findVocabularyName(TEXT_SIZE_CATEGORIES, value);
}
function findVocabularyName<const TNames extends readonly string[]>(
names: TNames,
value: string | undefined,
): TNames[number] | undefined {
const normalized = normalizeName(value);
return normalized === undefined ? undefined : names.find((name) => name === normalized);
}
export function parsePermissionAction(action: string): PermissionAction {
const parsed = findVocabularyName(PERMISSION_ACTIONS, action);
if (parsed !== undefined) return parsed;
throw new AppError(
'INVALID_ARGS',
`Invalid permission action: ${action}. Use ${PERMISSION_ACTIONS.join('|')}.`,
);
}
export function parsePermissionTarget(value: string | undefined): MobilePermissionTarget {
const parsed = findVocabularyName(MOBILE_PERMISSION_TARGETS, value);
if (parsed !== undefined) return parsed;
throw new AppError(
'INVALID_ARGS',
`permission setting requires a target: ${MOBILE_PERMISSION_TARGETS.join('|')}`,
);
}
/**
* `simctl` and `adb` answer a bad appearance with a tool-specific error or a silent no-op, so an
* owner parses here before a device is touched.
*/
export function parseAppearanceAction(state: string): AppearanceAction {
const parsed = findVocabularyName(APPEARANCE_ACTIONS, state);
if (parsed !== undefined) return parsed;
throw new AppError(
'INVALID_ARGS',
`Invalid appearance state: ${state}. Use ${APPEARANCE_ACTIONS.join('|')}.`,
);
}
/**
* On/off spellings alias a boolean rather than name a value the device echoes back, so padding
* stays rejected: an `adb shell settings put` argument with a stray space is a caller bug.
*/
function readSettingState(state: string | undefined): boolean | undefined {
const normalized = state?.toLowerCase();
if (normalized === 'on' || normalized === 'true' || normalized === '1') return true;
if (normalized === 'off' || normalized === 'false' || normalized === '0') return false;
return undefined;
}
/** The boolean a `settings <setting> <state>` positional spells, in any casing. */
export function parseSettingState(state: string): boolean {
const parsed = readSettingState(state);
if (parsed !== undefined) return parsed;
throw new AppError('INVALID_ARGS', `Invalid setting state: ${state}`);
}