@swipt/cli 0.1.0-nightly.77 → 0.1.0-nightly.79

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.
Files changed (68) hide show
  1. package/dist/availability.d.ts +5 -0
  2. package/dist/availability.js +349 -0
  3. package/dist/availability.js.map +1 -0
  4. package/dist/client.d.ts +25 -0
  5. package/dist/client.js +248 -0
  6. package/dist/client.js.map +1 -0
  7. package/dist/connection.d.ts +24 -0
  8. package/dist/connection.js +293 -0
  9. package/dist/connection.js.map +1 -0
  10. package/dist/coredevice.d.ts +22 -0
  11. package/dist/coredevice.js +329 -0
  12. package/dist/coredevice.js.map +1 -0
  13. package/dist/device.d.ts +130 -0
  14. package/dist/device.js +539 -0
  15. package/dist/device.js.map +1 -0
  16. package/dist/i18n.d.ts +2 -0
  17. package/dist/i18n.js +57 -0
  18. package/dist/i18n.js.map +1 -0
  19. package/dist/ignore.d.ts +8 -0
  20. package/dist/ignore.js +112 -0
  21. package/dist/ignore.js.map +1 -0
  22. package/dist/metro.d.ts +10 -0
  23. package/dist/metro.js +349 -0
  24. package/dist/metro.js.map +1 -0
  25. package/dist/output.d.ts +20 -0
  26. package/dist/output.js +116 -0
  27. package/dist/output.js.map +1 -0
  28. package/dist/project.d.ts +18 -0
  29. package/dist/project.js +696 -0
  30. package/dist/project.js.map +1 -0
  31. package/dist/proto/common_pb.js +34 -0
  32. package/dist/proto/common_pb.js.map +1 -0
  33. package/dist/proto/logs_pb.js +15 -0
  34. package/dist/proto/logs_pb.js.map +1 -0
  35. package/dist/proto/repl_pb.js +15 -0
  36. package/dist/proto/repl_pb.js.map +1 -0
  37. package/dist/proto/swiplets_pb.js +28 -0
  38. package/dist/proto/swiplets_pb.js.map +1 -0
  39. package/dist/proto/system_pb.js +15 -0
  40. package/dist/proto/system_pb.js.map +1 -0
  41. package/dist/sideload.d.ts +17 -0
  42. package/dist/sideload.js +1098 -0
  43. package/dist/sideload.js.map +1 -0
  44. package/dist/swipt.d.ts +1 -0
  45. package/dist/swipt.js +631 -0
  46. package/dist/swipt.js.map +1 -0
  47. package/dist/version.d.ts +2 -0
  48. package/dist/version.js +15 -0
  49. package/dist/version.js.map +1 -0
  50. package/package.json +21 -7
  51. package/availability.mjs +0 -642
  52. package/client.mjs +0 -375
  53. package/connection.mjs +0 -450
  54. package/coredevice.mjs +0 -478
  55. package/device.mjs +0 -837
  56. package/i18n.mjs +0 -71
  57. package/ignore.mjs +0 -149
  58. package/metro.mjs +0 -432
  59. package/output.mjs +0 -177
  60. package/project.mjs +0 -1013
  61. package/proto/common_pb.js +0 -98
  62. package/proto/logs_pb.js +0 -34
  63. package/proto/repl_pb.js +0 -55
  64. package/proto/swiplets_pb.js +0 -179
  65. package/proto/system_pb.js +0 -27
  66. package/sideload.mjs +0 -1696
  67. package/swipt.mjs +0 -726
  68. package/version.mjs +0 -16
@@ -0,0 +1,1098 @@
1
+ import { UsageError, open } from "./client.js";
2
+ import { findPublished, runningSwipt, tryUnlock, withToken } from "./connection.js";
3
+ import { apps, configureGuest, containerHasFile, coreDevice, devicectl, installApp, launchApp, lockedError, provisioningProfiles, pullFromContainer, pushToContainer, serverHint, serverPath, terminateApp, uninstallApp } from "./coredevice.js";
4
+ import { language, tr } from "./i18n.js";
5
+ import { choose, columns, interactive, printScriptError, selectTheme, step } from "./output.js";
6
+ import { LogLevel } from "./proto/common_pb.js";
7
+ import fs from "node:fs";
8
+ import path from "node:path";
9
+ import { execFile, execFileSync, spawn } from "node:child_process";
10
+ import os from "node:os";
11
+ import { promisify } from "node:util";
12
+ import select from "@inquirer/select";
13
+ import { X509Certificate, createHash } from "node:crypto";
14
+ import readline from "node:readline";
15
+ import { Readable } from "node:stream";
16
+ import { pipeline } from "node:stream/promises";
17
+ import password from "@inquirer/password";
18
+ // src/sideload.ts
19
+ const exec = promisify(execFile);
20
+ const bundleId = "io.nekohasekai.swipt";
21
+ const bundleTeam = "P8XK3KHB48";
22
+ const repository = "swipt-automation/swipt";
23
+ const teamPattern = /^[A-Z0-9]{10}$/;
24
+ const sideloadedPattern = new RegExp(`^${bundleId.replaceAll(".", "\\.")}(?:\\.([A-Z0-9]{10}))?$`);
25
+ const guestTeam = "SWIPTLOCAL";
26
+ const guestEntitlements = (id) => `<?xml version="1.0" encoding="UTF-8"?>
27
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
28
+ <plist version="1.0">
29
+ <dict>
30
+ <key>application-identifier</key>
31
+ <string>${guestTeam}.${id}</string>
32
+ <key>com.apple.developer.team-identifier</key>
33
+ <string>${guestTeam}</string>
34
+ <key>com.apple.security.application-groups</key>
35
+ <array>
36
+ <string>${guestTeam}.${id}</string>
37
+ </array>
38
+ <key>get-task-allow</key>
39
+ <true/>
40
+ <key>keychain-access-groups</key>
41
+ <array>
42
+ <string>${guestTeam}.${id}</string>
43
+ </array>
44
+ </dict>
45
+ </plist>
46
+ `;
47
+ const accountsHint = "Xcode › Settings › Accounts";
48
+ const xcodeProfiles = "Library/Developer/Xcode/UserData/Provisioning Profiles";
49
+ const downloads = path.join(process.env.XDG_CACHE_HOME || path.join(os.homedir(), ".cache"), "swipt", "sideload");
50
+ const expiresSoon = ({ creation, expiration }) => expiration - Date.now() < (expiration - creation) / 2;
51
+ const passcodeTypes = [
52
+ "pin",
53
+ "numeric",
54
+ "alphanumeric"
55
+ ];
56
+ const plistValueMissing = /No value at that key path/;
57
+ function passcodeOf(options) {
58
+ const type = options["passcode-type"] ?? "pin";
59
+ if (!passcodeTypes.includes(type)) throw new UsageError(tr("invalid argument {value} for --passcode-type: it is {types}", {
60
+ value: JSON.stringify(type),
61
+ types: passcodeTypes.join(", ")
62
+ }));
63
+ const passcode = options.passcode;
64
+ if (!passcode) return;
65
+ const digits = /^\d+$/.test(passcode);
66
+ if (type === "pin" && !(digits && [4, 6].includes(passcode.length))) throw new UsageError(tr("a pin passcode is 4 or 6 digits; a custom one needs --passcode-type numeric or alphanumeric"));
67
+ if (type === "numeric" && !digits) throw new UsageError(tr("a numeric passcode is digits only"));
68
+ if (!/^[\x20-\x7e]{1,64}$/.test(passcode)) throw new UsageError(tr("a passcode is up to 64 printable ASCII characters"));
69
+ return {
70
+ passcode,
71
+ type
72
+ };
73
+ }
74
+ function headers(accept) {
75
+ const token = process.env.GITHUB_TOKEN;
76
+ return {
77
+ Accept: accept,
78
+ "X-GitHub-Api-Version": "2022-11-28",
79
+ "User-Agent": "swipt-cli",
80
+ ...token ? { Authorization: `Bearer ${token}` } : {}
81
+ };
82
+ }
83
+ async function github(url, accept, signal) {
84
+ let response = await fetch(url, {
85
+ headers: headers(accept),
86
+ signal,
87
+ redirect: "manual"
88
+ });
89
+ if (response.status >= 300 && response.status < 400) response = await fetch(response.headers.get("location"), { signal });
90
+ if (!response.ok) {
91
+ let message = `GitHub answered ${response.status} for ${url}`;
92
+ if ([
93
+ 401,
94
+ 403,
95
+ 429
96
+ ].includes(response.status)) message += `; ${process.env.GITHUB_TOKEN ? "GITHUB_TOKEN" : "set GITHUB_TOKEN to a token that"} must read the repository and stay under the rate limit`;
97
+ const error = new Error(message);
98
+ error.status = response.status;
99
+ throw error;
100
+ }
101
+ return response;
102
+ }
103
+ async function findRelease(nightly, signal) {
104
+ const read = async (name) => (await github(`https://api.github.com/repos/${repository}/releases/${name}`, "application/vnd.github+json", signal)).json();
105
+ const release = nightly ? await read("tags/nightly") : await read("latest").catch((error) => {
106
+ if (error.status !== 404) throw error;
107
+ return read("tags/nightly");
108
+ });
109
+ const asset = (name) => {
110
+ const found = release.assets.find((it) => it.name === name);
111
+ if (!found) throw new Error(`release ${release.tag_name} has no ${name}`);
112
+ return found;
113
+ };
114
+ const metadata = await (await github(asset("metadata.json").url, "application/octet-stream", signal)).json();
115
+ return {
116
+ tag: release.tag_name,
117
+ version: metadata.version,
118
+ build: Number(metadata.build),
119
+ ipa: asset("Swipt.ipa")
120
+ };
121
+ }
122
+ async function download(url, file, signal, update) {
123
+ const response = await github(url, "application/octet-stream", signal);
124
+ const total = Number(response.headers.get("content-length"));
125
+ const megabytes = (bytes) => (bytes / 1e6).toFixed(1);
126
+ let received = 0;
127
+ await pipeline(Readable.fromWeb(response.body), async function* (source) {
128
+ for await (const chunk of source) {
129
+ received += chunk.length;
130
+ update(total > 0 ? `${megabytes(received)} / ${megabytes(total)} MB ${Math.floor(received / total * 100)}%` : `${megabytes(received)} MB`);
131
+ yield chunk;
132
+ }
133
+ }, fs.createWriteStream(file), { signal });
134
+ }
135
+ async function unpack(ipa, directory) {
136
+ await exec("unzip", [
137
+ "-q",
138
+ ipa,
139
+ "-d",
140
+ directory
141
+ ]);
142
+ const payload = path.join(directory, "Payload");
143
+ const app = fs.readdirSync(payload).find((name) => name.endsWith(".app"));
144
+ if (app === void 0) throw new Error("the IPA has no app in Payload");
145
+ return path.join(payload, app);
146
+ }
147
+ const pbxproj = (id, team) => `// !$*UTF8*$!
148
+ {
149
+ archiveVersion = 1;
150
+ classes = {
151
+ };
152
+ objectVersion = 56;
153
+ objects = {
154
+ A1 = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = main.c; sourceTree = "<group>"; };
155
+ A2 = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Stub.app; sourceTree = BUILT_PRODUCTS_DIR; };
156
+ A3 = {isa = PBXBuildFile; fileRef = A1; };
157
+ B1 = {isa = PBXGroup; children = (B2, B3); sourceTree = "<group>"; };
158
+ B2 = {isa = PBXGroup; children = (A1); path = Stub; sourceTree = "<group>"; };
159
+ B3 = {isa = PBXGroup; children = (A2); name = Products; sourceTree = "<group>"; };
160
+ C1 = {isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = (A3); runOnlyForDeploymentPostprocessing = 0; };
161
+ D1 = {
162
+ isa = PBXNativeTarget;
163
+ buildConfigurationList = E1;
164
+ buildPhases = (C1);
165
+ buildRules = ();
166
+ dependencies = ();
167
+ name = Stub;
168
+ productName = Stub;
169
+ productReference = A2;
170
+ productType = "com.apple.product-type.application";
171
+ };
172
+ E1 = {isa = XCConfigurationList; buildConfigurations = (F1); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; };
173
+ E2 = {isa = XCConfigurationList; buildConfigurations = (F2); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; };
174
+ F1 = {
175
+ isa = XCBuildConfiguration;
176
+ buildSettings = {
177
+ CODE_SIGN_STYLE = Automatic;
178
+ DEVELOPMENT_TEAM = "${team}";
179
+ GENERATE_INFOPLIST_FILE = YES;
180
+ IPHONEOS_DEPLOYMENT_TARGET = 16.4;
181
+ PRODUCT_BUNDLE_IDENTIFIER = "${id}";
182
+ PRODUCT_NAME = Stub;
183
+ SDKROOT = iphoneos;
184
+ TARGETED_DEVICE_FAMILY = "1,2";
185
+ };
186
+ name = Release;
187
+ };
188
+ F2 = {isa = XCBuildConfiguration; buildSettings = {}; name = Release; };
189
+ G1 = {
190
+ isa = PBXProject;
191
+ buildConfigurationList = E2;
192
+ compatibilityVersion = "Xcode 14.0";
193
+ mainGroup = B1;
194
+ productRefGroup = B3;
195
+ projectDirPath = "";
196
+ projectRoot = "";
197
+ targets = (D1);
198
+ };
199
+ };
200
+ rootObject = G1;
201
+ }
202
+ `;
203
+ function explain(output, team) {
204
+ const errors = [...new Set(output.split("\n").filter((line) => /^(xcodebuild: )?error: /.test(line)).map((line) => line.replace(/^(xcodebuild: )?error: /, "")))].join("; ");
205
+ if (/No Accounts?\b/.test(output)) return tr("Xcode has no account for team {team}; sign in with its Apple Account at {accounts}", {
206
+ team,
207
+ accounts: accountsHint
208
+ });
209
+ if (/signing certificate|certificateType/i.test(output)) return tr("Xcode could not make a development certificate for team {team}; add one at {accounts} › Manage Certificates ({errors})", {
210
+ team,
211
+ accounts: accountsHint,
212
+ errors
213
+ });
214
+ if (/requires Xcode|xcode-select/.test(output)) return tr("xcodebuild needs Xcode; install it and select it with xcode-select");
215
+ return errors || output.trim();
216
+ }
217
+ function profileField(file, key) {
218
+ return execFileSync("plutil", [
219
+ "-extract",
220
+ key,
221
+ "raw",
222
+ "-o",
223
+ "-",
224
+ "-"
225
+ ], {
226
+ input: execFileSync("security", [
227
+ "cms",
228
+ "-D",
229
+ "-i",
230
+ file
231
+ ], { stdio: [
232
+ "ignore",
233
+ "pipe",
234
+ "ignore"
235
+ ] }),
236
+ encoding: "utf8"
237
+ }).trim();
238
+ }
239
+ function revoked(certificates) {
240
+ const [leaf, issuer] = [0, 1].map((index) => new X509Certificate(fs.readFileSync(`${certificates}${index}`)));
241
+ const url = /^OCSP - URI:(.+)$/m.exec(leaf.infoAccess ?? "")?.[1];
242
+ if (url === void 0) return false;
243
+ fs.writeFileSync(`${certificates}0.pem`, leaf.toString());
244
+ fs.writeFileSync(`${certificates}1.pem`, issuer.toString());
245
+ try {
246
+ return /: revoked$/m.test(execFileSync("openssl", [
247
+ "ocsp",
248
+ "-issuer",
249
+ `${certificates}1.pem`,
250
+ "-cert",
251
+ `${certificates}0.pem`,
252
+ "-url",
253
+ url,
254
+ "-noverify"
255
+ ], {
256
+ encoding: "utf8",
257
+ stdio: [
258
+ "ignore",
259
+ "pipe",
260
+ "ignore"
261
+ ],
262
+ timeout: 1e4
263
+ }));
264
+ } catch {
265
+ return false;
266
+ }
267
+ }
268
+ async function provision(work, id, team, device, update) {
269
+ const stub = path.join(work, "Stub");
270
+ const products = path.join(stub, "Products");
271
+ const app = path.join(products, "Stub.app");
272
+ const profile = path.join(app, "embedded.mobileprovision");
273
+ fs.mkdirSync(path.join(stub, "Stub.xcodeproj"), { recursive: true });
274
+ fs.mkdirSync(path.join(stub, "Stub"));
275
+ fs.writeFileSync(path.join(stub, "Stub/main.c"), "int main(void) { return 0; }\n");
276
+ fs.writeFileSync(path.join(stub, "Stub.xcodeproj/project.pbxproj"), pbxproj(id, team));
277
+ const build = async () => {
278
+ const running = exec("xcodebuild", [
279
+ "build",
280
+ "-project",
281
+ path.join(stub, "Stub.xcodeproj"),
282
+ "-scheme",
283
+ "Stub",
284
+ "-configuration",
285
+ "Release",
286
+ "-destination",
287
+ `id=${device.udid}`,
288
+ `CONFIGURATION_BUILD_DIR=${products}`,
289
+ `OBJROOT=${path.join(stub, "Objects")}`,
290
+ "-allowProvisioningUpdates",
291
+ "-allowProvisioningDeviceRegistration"
292
+ ], { maxBuffer: Infinity });
293
+ running.child.stdout.on("data", (chunk) => {
294
+ const line = String(chunk).split("\n").findLast((it) => /^[A-Z]\w* /.test(it));
295
+ if (line) update(line.split(" ")[0]);
296
+ });
297
+ try {
298
+ await running;
299
+ } catch (error) {
300
+ if (error.code === "ENOENT") throw new Error(tr("xcodebuild is missing; install Xcode"));
301
+ if (typeof error.code !== "number") throw error;
302
+ throw new Error(explain(`${error.stdout}${error.stderr}`, team));
303
+ }
304
+ };
305
+ const certificates = path.join(work, "certificate");
306
+ const stdio = [
307
+ "ignore",
308
+ "pipe",
309
+ "ignore"
310
+ ];
311
+ const extract = () => execFileSync("codesign", [
312
+ "-d",
313
+ `--extract-certificates=${certificates}`,
314
+ app
315
+ ], { stdio });
316
+ await build();
317
+ extract();
318
+ if (expiresSoon({
319
+ creation: Date.parse(profileField(profile, "CreationDate")),
320
+ expiration: Date.parse(profileField(profile, "ExpirationDate"))
321
+ }) || revoked(certificates)) {
322
+ fs.rmSync(path.join(os.homedir(), xcodeProfiles, `${profileField(profile, "UUID")}.mobileprovision`), { force: true });
323
+ await build();
324
+ extract();
325
+ }
326
+ const entitlements = path.join(work, "entitlements.plist");
327
+ fs.writeFileSync(entitlements, execFileSync("codesign", [
328
+ "-d",
329
+ "--entitlements",
330
+ "-",
331
+ "--xml",
332
+ app
333
+ ], { stdio }));
334
+ return {
335
+ identity: createHash("sha1").update(fs.readFileSync(`${certificates}0`)).digest("hex").toUpperCase(),
336
+ entitlements,
337
+ profile
338
+ };
339
+ }
340
+ async function resign(app, id, signing, update) {
341
+ const info = path.join(app, "Info.plist");
342
+ execFileSync("plutil", [
343
+ "-replace",
344
+ "CFBundleIdentifier",
345
+ "-string",
346
+ id,
347
+ info
348
+ ]);
349
+ let permitted;
350
+ try {
351
+ permitted = JSON.parse(execFileSync("plutil", [
352
+ "-extract",
353
+ "BGTaskSchedulerPermittedIdentifiers",
354
+ "json",
355
+ "-o",
356
+ "-",
357
+ info
358
+ ], { stdio: "pipe" }));
359
+ } catch (error) {
360
+ if (!plistValueMissing.test(error.stderr)) throw error;
361
+ }
362
+ if (permitted !== void 0) execFileSync("plutil", [
363
+ "-replace",
364
+ "BGTaskSchedulerPermittedIdentifiers",
365
+ "-json",
366
+ JSON.stringify(permitted.map((it) => it.startsWith(`io.nekohasekai.swipt.`) ? id + it.slice(20) : it)),
367
+ info
368
+ ]);
369
+ const profile = path.join(app, "embedded.mobileprovision");
370
+ if (signing.profile === void 0) fs.rmSync(profile, { force: true });
371
+ else fs.copyFileSync(signing.profile, profile);
372
+ const codesign = [
373
+ "--force",
374
+ "--sign",
375
+ signing.identity,
376
+ "--timestamp=none"
377
+ ];
378
+ const frameworks = path.join(app, "Frameworks");
379
+ const nested = [...fs.readdirSync(app).filter((name) => name.endsWith(".dylib")).map((name) => path.join(app, name)), ...fs.existsSync(frameworks) ? fs.readdirSync(frameworks).map((name) => path.join(frameworks, name)) : []];
380
+ for (const file of nested) {
381
+ update(path.basename(file));
382
+ await exec("codesign", [...codesign, file]);
383
+ }
384
+ update(path.basename(app));
385
+ await exec("codesign", [
386
+ ...codesign,
387
+ "--entitlements",
388
+ signing.entitlements,
389
+ app
390
+ ]);
391
+ }
392
+ function xcodeTeams() {
393
+ const valid = new Set([...execFileSync("security", [
394
+ "find-identity",
395
+ "-v",
396
+ "-p",
397
+ "codesigning"
398
+ ], { encoding: "utf8" }).matchAll(/\) ([0-9A-F]{40}) "Apple Development: /g)].map((match) => match[1]));
399
+ const certificates = execFileSync("security", [
400
+ "find-certificate",
401
+ "-a",
402
+ "-Z",
403
+ "-p",
404
+ "-c",
405
+ "Apple Development"
406
+ ], { encoding: "utf8" }).matchAll(/SHA-1 hash: ([0-9A-F]{40})[\s\S]*?(-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----)/g);
407
+ const teams = /* @__PURE__ */ new Map();
408
+ for (const [, hash, pem] of certificates) {
409
+ if (!valid.has(hash)) continue;
410
+ const subject = new X509Certificate(pem).subject;
411
+ const id = /^OU=(.+)$/m.exec(subject)?.[1];
412
+ if (id !== void 0 && teamPattern.test(id)) teams.set(id, /^O=(.+)$/m.exec(subject)?.[1].replaceAll("\\", ""));
413
+ }
414
+ return [...teams].map(([id, name]) => ({
415
+ id,
416
+ name
417
+ }));
418
+ }
419
+ function xcodeSignedIn() {
420
+ try {
421
+ const lists = JSON.parse(execFileSync("plutil", [
422
+ "-extract",
423
+ "DVTDeveloperAccountManagerAppleIDLists",
424
+ "json",
425
+ "-o",
426
+ "-",
427
+ "-"
428
+ ], {
429
+ input: execFileSync("defaults", [
430
+ "export",
431
+ "com.apple.dt.Xcode",
432
+ "-"
433
+ ]),
434
+ stdio: "pipe",
435
+ encoding: "utf8"
436
+ }));
437
+ return Object.values(lists).some((accounts) => accounts.length > 0);
438
+ } catch (error) {
439
+ if (plistValueMissing.test(error.stderr)) return false;
440
+ throw error;
441
+ }
442
+ }
443
+ const teamList = (teams) => teams.map((team) => ` ${team.id}${team.name ? ` ${team.name}` : ""}`).join("\n");
444
+ const teamChoice = ({ id, name }) => ({
445
+ name: name ? `${name} ${id}` : id,
446
+ short: name ?? id,
447
+ value: id
448
+ });
449
+ async function sideloadedDevices(devices, missing = tr("Swipt is not sideloaded on any online iOS device")) {
450
+ const sideloaded = await step(tr("looking for Swipt on the devices"), () => Promise.all(devices.map((device) => apps(device).then((listed) => listed.some((app) => sideloadedPattern.test(app.bundleIdentifier)), () => true))), { transient: true });
451
+ const found = devices.filter((_, index) => sideloaded[index]);
452
+ if (found.length === 0) throw new Error(missing);
453
+ return found;
454
+ }
455
+ async function locate(context, device, fresh = false) {
456
+ const { options } = context;
457
+ const listed = await step(tr("checking Swipt on {device}", { device: device.name }), () => apps(device), { transient: true });
458
+ if (device.virtual) return { current: listed.find((app) => app.bundleIdentifier === bundleId) };
459
+ const found = listed.map((app) => {
460
+ const match = sideloadedPattern.exec(app.bundleIdentifier);
461
+ return {
462
+ ...app,
463
+ team: match && (match[1] ?? bundleTeam)
464
+ };
465
+ }).filter((app) => app.team !== null);
466
+ if (options.team !== void 0) {
467
+ if (!teamPattern.test(options.team)) throw new UsageError(tr("invalid argument {value} for --team: it is the 10-character team ID shown in {accounts}", {
468
+ value: JSON.stringify(options.team),
469
+ accounts: accountsHint
470
+ }));
471
+ return {
472
+ team: options.team,
473
+ current: found.find((app) => app.team === options.team)
474
+ };
475
+ }
476
+ if (found.length > 1) {
477
+ const known = xcodeTeams();
478
+ const teams = found.map((app) => ({
479
+ id: app.team,
480
+ name: known.find((team) => team.id === app.team)?.name
481
+ }));
482
+ const team = await choose(context, tr("Choose a team"), teams.map(teamChoice), /* @__PURE__ */ new Error(`${tr("Swipt is sideloaded on {device} by more than one team; choose one with --team ID:", { device: device.name })}\n${teamList(teams)}`));
483
+ return {
484
+ team,
485
+ current: found.find((app) => app.team === team)
486
+ };
487
+ }
488
+ if (found.length === 0 && fresh) {
489
+ const teams = xcodeTeams();
490
+ if (teams.length === 0) throw new Error(xcodeSignedIn() ? tr("Xcode has no development certificate; add one at {accounts} › Manage Certificates, or choose a team with --team ID", { accounts: accountsHint }) : tr("Xcode has no account; sign in at {accounts}, or choose a team with --team ID", { accounts: accountsHint }));
491
+ return {
492
+ team: teams.some((it) => it.id === bundleTeam) ? bundleTeam : teams.length === 1 ? teams[0].id : await choose(context, tr("Choose a team"), teams.map(teamChoice), /* @__PURE__ */ new Error(`${tr("choose a team with --team ID:")}\n${teamList(teams)}`)),
493
+ current: void 0
494
+ };
495
+ }
496
+ return {
497
+ team: found[0]?.team,
498
+ current: found[0]
499
+ };
500
+ }
501
+ const buildText = (app) => `Swipt ${app.version} (${app.bundleVersion})`;
502
+ async function signingPeriod(device, id, team) {
503
+ const names = [id, "*"].map((it) => `iOS Team Provisioning Profile: ${it}`);
504
+ return (await step(tr("checking Swipt on {device}", { device: device.name }), () => provisioningProfiles(device.udid), { transient: true })).filter((profile) => profile.teamIdentifier === team && names.includes(profile.name)).map((profile) => ({
505
+ creation: Date.parse(profile.creationDate),
506
+ expiration: Date.parse(profile.expirationDate)
507
+ })).reduce((latest, it) => it.expiration > latest.expiration ? it : latest, {
508
+ creation: 0,
509
+ expiration: 0
510
+ });
511
+ }
512
+ function expirationText(time) {
513
+ const hours = (time - Date.now()) / 36e5;
514
+ const days = Math.round(hours / 24);
515
+ const [value, unit] = hours < 24 ? [Math.max(Math.round(hours), 1), "hour"] : days < 7 ? [days, "day"] : days < 30 ? [Math.round(days / 7), "week"] : days < 365 ? [Math.round(days / 30), "month"] : [Math.round(days / 365), "year"];
516
+ return new Intl.RelativeTimeFormat(language).format(value, unit).replace(/(\d)(\p{Script=Han})/gu, "$1 $2");
517
+ }
518
+ async function askPasscode(context) {
519
+ const type = await select({
520
+ message: tr("Set up auto-unlock? Swipt can then unlock this device by itself"),
521
+ theme: selectTheme,
522
+ choices: [
523
+ {
524
+ name: tr("4 or 6 digit passcode"),
525
+ short: tr("4 or 6 digits"),
526
+ value: "pin"
527
+ },
528
+ {
529
+ name: tr("Custom numeric passcode"),
530
+ short: tr("numeric"),
531
+ value: "numeric"
532
+ },
533
+ {
534
+ name: tr("Custom alphanumeric passcode"),
535
+ short: tr("alphanumeric"),
536
+ value: "alphanumeric"
537
+ },
538
+ {
539
+ name: tr("No Thanks"),
540
+ value: null
541
+ }
542
+ ]
543
+ }, {
544
+ output: process.stderr,
545
+ signal: context.signal
546
+ });
547
+ if (type === null) return;
548
+ const options = (passcode) => ({
549
+ passcode,
550
+ "passcode-type": type
551
+ });
552
+ return passcodeOf(options(await password({
553
+ message: tr("Device passcode"),
554
+ theme: { i18n: { maskedText: tr("[input is masked]") } },
555
+ validate(passcode) {
556
+ try {
557
+ passcodeOf(options(passcode));
558
+ return passcode !== "" || tr("enter the passcode");
559
+ } catch (error) {
560
+ return error.message;
561
+ }
562
+ }
563
+ }, {
564
+ output: process.stderr,
565
+ signal: context.signal
566
+ })));
567
+ }
568
+ async function installPasscode(context, device, current) {
569
+ return current === void 0 && !device.virtual && interactive(context) && context.options.passcode === void 0 && context.options["passcode-type"] === void 0 && !context.options["no-setup"] ? askPasscode(context) : passcodeOf(context.options);
570
+ }
571
+ async function findInstalled(context) {
572
+ const device = await coreDevice(context, { filter: (devices) => sideloadedDevices(devices, tr("Swipt is not sideloaded on any online iOS device; install it with \"swipt sideload install\"")) });
573
+ const { team, current } = await locate(context, device);
574
+ if (current === void 0) throw new Error(team === void 0 ? tr("Swipt is not sideloaded on {device}; install it with \"swipt sideload install\"", { device: device.name }) : tr("Swipt is not sideloaded on {device} by team {team}; install it with \"swipt sideload install\"", {
575
+ device: device.name,
576
+ team
577
+ }));
578
+ return {
579
+ device,
580
+ team,
581
+ current
582
+ };
583
+ }
584
+ async function downloadIPA(context, release) {
585
+ const name = `Swipt-${release.ipa.id}.ipa`;
586
+ const ipa = path.join(downloads, name);
587
+ if (fs.existsSync(ipa)) return ipa;
588
+ fs.mkdirSync(downloads, { recursive: true });
589
+ const partial = `${ipa}.download`;
590
+ await step(tr("downloading Swipt {version} ({build}) from {release}", {
591
+ version: release.version,
592
+ build: release.build,
593
+ release: release.tag
594
+ }), (update) => download(release.ipa.url, partial, context.signal, update));
595
+ fs.renameSync(partial, ipa);
596
+ for (const entry of fs.readdirSync(downloads)) if (entry !== name) fs.rmSync(path.join(downloads, entry), { force: true });
597
+ return ipa;
598
+ }
599
+ async function localIPA(context) {
600
+ const cached = fs.existsSync(downloads) ? fs.readdirSync(downloads).find((entry) => entry.endsWith(".ipa")) : void 0;
601
+ return cached === void 0 ? downloadIPA(context, await step(tr("checking the latest release"), () => findRelease(context.options.nightly, context.signal), { transient: true })) : path.join(downloads, cached);
602
+ }
603
+ async function withLocalApp(context, device, run) {
604
+ if (device.virtual) return run(void 0);
605
+ const work = fs.mkdtempSync(path.join(os.tmpdir(), "swipt-app-"));
606
+ try {
607
+ return await run(await unpack(await localIPA(context), work));
608
+ } finally {
609
+ fs.rmSync(work, {
610
+ recursive: true,
611
+ force: true
612
+ });
613
+ }
614
+ }
615
+ async function mountDiskImage(context, device, app) {
616
+ if (device.virtual) return;
617
+ try {
618
+ await step(tr("preparing the Developer Disk Image on {device}", { device: device.name }), async () => {
619
+ try {
620
+ await exec(serverPath(), [
621
+ "mount",
622
+ "-d",
623
+ device.udid,
624
+ "--disk-image",
625
+ path.join(app, "DeveloperDiskImage")
626
+ ]);
627
+ } catch (error) {
628
+ if (error.code !== "ENOENT") throw error;
629
+ }
630
+ }, { transient: true });
631
+ } catch (error) {
632
+ if (context.signal.aborted) throw error;
633
+ console.error(tr("could not prepare the Developer Disk Image on {device}: {error}", {
634
+ device: device.name,
635
+ error: /^Error: (.*)$/m.exec(error.stderr ?? "")?.[1] ?? error.message
636
+ }));
637
+ }
638
+ }
639
+ async function deploy(context, { device, team, current }, updateOnly) {
640
+ const passcode = await installPasscode(context, device, current);
641
+ const release = await step(tr("checking the latest release"), () => findRelease(context.options.nightly, context.signal), { transient: true });
642
+ const id = device.virtual || team === bundleTeam ? bundleId : `${bundleId}.${team}`;
643
+ if (current !== void 0) {
644
+ const installed = Number(current.bundleVersion);
645
+ const signing = device.virtual ? void 0 : await signingPeriod(device, id, team);
646
+ if (installed >= release.build && (signing === void 0 || !expiresSoon(signing))) {
647
+ const parameters = {
648
+ build: buildText(current),
649
+ device: device.name,
650
+ release: release.tag,
651
+ releaseBuild: release.build
652
+ };
653
+ console.log(installed === release.build ? tr("{build} on {device} is already {release}", parameters) : tr("{build} on {device} is newer than {release} ({releaseBuild})", parameters));
654
+ if (signing !== void 0) console.log(tr("its signing expires {expiration}", { expiration: expirationText(signing.expiration) }));
655
+ const saves = !updateOnly && passcode !== void 0;
656
+ const pairs = !context.options["no-setup"] && !context.options["no-setup-pair"] && !await step(tr("checking Swipt on {device}", { device: device.name }), () => containerHasFile(device, id, pairingPath), { transient: true });
657
+ if (!saves && !pairs) return;
658
+ await withLocalApp(context, device, async (app) => {
659
+ await mountDiskImage(context, device, app);
660
+ if (saves) await step(tr("setting up auto-unlock"), () => setUpAutoUnlock(device, id, passcode));
661
+ if (context.options["no-setup"]) {
662
+ await launch(device, id);
663
+ return;
664
+ }
665
+ const paired = pairs && await pair(device, id, true);
666
+ if (saves || paired) await openConfigured(context, device, id, passcode, void 0, app);
667
+ });
668
+ return;
669
+ }
670
+ if (installed > release.build && updateOnly) throw new Error(tr("{build} on {device} needs new signing, but {release} ({releaseBuild}) is older; use --nightly, or downgrade with \"swipt sideload install\"", {
671
+ build: buildText(current),
672
+ device: device.name,
673
+ release: release.tag,
674
+ releaseBuild: release.build
675
+ }));
676
+ }
677
+ const work = fs.mkdtempSync(path.join(os.tmpdir(), "swipt-sideload-"));
678
+ try {
679
+ const signing = device.virtual ? void 0 : await step(tr("preparing signing for Swipt with team {team} through Xcode", { team: xcodeTeams().find((it) => it.id === team)?.name ?? team }), (update) => provision(work, id, team, device, update));
680
+ const ipa = await downloadIPA(context, release);
681
+ const app = signing === void 0 ? await unpack(ipa, work) : await step(tr("re-signing Swipt"), async (update) => {
682
+ const unpacked = await unpack(ipa, work);
683
+ await resign(unpacked, id, signing, update);
684
+ return unpacked;
685
+ });
686
+ await installAndOpen(context, {
687
+ device,
688
+ id,
689
+ current
690
+ }, app, release.build, {
691
+ passcode,
692
+ saves: !updateOnly
693
+ });
694
+ } finally {
695
+ fs.rmSync(work, {
696
+ recursive: true,
697
+ force: true
698
+ });
699
+ }
700
+ }
701
+ async function installOnGuest(device, id, app) {
702
+ const work = fs.mkdtempSync(path.join(os.tmpdir(), "swipt-guest-"));
703
+ try {
704
+ const signed = path.join(work, "Payload", path.basename(app));
705
+ await exec("ditto", [app, signed]);
706
+ await step(tr("re-signing Swipt"), async (update) => {
707
+ const entitlements = path.join(work, "entitlements.plist");
708
+ fs.writeFileSync(entitlements, guestEntitlements(id));
709
+ execFileSync("plutil", [
710
+ "-replace",
711
+ "AppGroupIdentifier",
712
+ "-string",
713
+ `${guestTeam}.${id}`,
714
+ path.join(signed, "Info.plist")
715
+ ]);
716
+ await resign(signed, id, {
717
+ identity: "-",
718
+ entitlements
719
+ }, update);
720
+ });
721
+ const archive = path.join(work, "Swipt.ipa");
722
+ await exec("zip", [
723
+ "-qry1",
724
+ archive,
725
+ "Payload"
726
+ ], { cwd: work });
727
+ await step(tr("installing on {device}", { device: device.name }), () => installApp(device, archive, id));
728
+ } finally {
729
+ fs.rmSync(work, {
730
+ recursive: true,
731
+ force: true
732
+ });
733
+ }
734
+ }
735
+ async function installAndOpen(context, { device, id, current }, app, build, { passcode, saves = true }) {
736
+ if (current !== void 0) {
737
+ const running = await step(tr("checking Swipt on {device}", { device: device.name }), () => runningSwipt(device.name, context.signal), { transient: true });
738
+ if (running !== void 0) await step(tr("unlocking the device"), () => tryUnlock(running, context.signal), { transient: true });
739
+ }
740
+ await mountDiskImage(context, device, app);
741
+ if (device.virtual) await installOnGuest(device, id, app);
742
+ else await step(tr("installing on {device}", { device: device.name }), () => installApp(device, app, id));
743
+ if (saves && passcode !== void 0) await step(tr("setting up auto-unlock"), () => setUpAutoUnlock(device, id, passcode));
744
+ const result = (await step(tr("checking Swipt on {device}", { device: device.name }), () => apps(device), { transient: true })).find((it) => it.bundleIdentifier === id);
745
+ if (result === void 0 || Number(result.bundleVersion) !== build) throw new Error(result === void 0 ? `${device.name} does not list ${id} after the install` : `${device.name} has ${buildText(result)} after the install`);
746
+ const parameters = {
747
+ build: buildText(result),
748
+ device: device.name
749
+ };
750
+ console.log(current === void 0 ? tr("{build} is installed on {device}", parameters) : Number(current.bundleVersion) === build ? tr("{build} is re-signed on {device}", parameters) : tr("{build} is updated on {device}", parameters));
751
+ if (!device.virtual) console.log(tr("its signing expires {expiration}", { expiration: expirationText(Date.parse(profileField(path.join(app, "embedded.mobileprovision"), "ExpirationDate"))) }));
752
+ if (context.options["no-setup"]) {
753
+ await launch(device, id);
754
+ return;
755
+ }
756
+ const paired = !context.options["no-setup-pair"] && await pair(device, id);
757
+ await openConfigured(context, device, id, passcode, current !== void 0 && !paired, app);
758
+ }
759
+ const publishArgument = "--publish-local-network";
760
+ const setupArgument = "--setup";
761
+ async function printAPI(context, device) {
762
+ const found = await step(tr("checking Swipt on {device}", { device: device.name }), () => findPublished(device.name, context.signal), { transient: true });
763
+ if (found === void 0) {
764
+ console.error(tr("{device} was not found on the local network; find its API URLs in Swipt › Developer › Local Network", { device: device.name }));
765
+ return;
766
+ }
767
+ const url = found.authenticates ? withToken(found.url) : found.url;
768
+ console.log(columns([["CLI", url], ["MCP", `${url}/mcp`]]));
769
+ }
770
+ async function openConfigured(context, device, id, passcode, updated, app) {
771
+ const publishes = !context.options["no-setup-api"];
772
+ if (device.virtual) await step(tr("opening Swipt on {device}", { device: device.name }), async () => {
773
+ await savePreferences(device, id, {
774
+ autoUnlockSetUp: true,
775
+ developerLocalNetworkEnabled: publishes
776
+ });
777
+ await configureGuest(device, id, "Swipt");
778
+ await launchApp(device, id);
779
+ });
780
+ else try {
781
+ await trustAndOpen(context, device, id, passcode, updated, path.join(app, "DeveloperDiskImage"));
782
+ } catch (error) {
783
+ if (error.message !== serverHint) throw error;
784
+ console.error(tr("{hint}; its developer is not trusted automatically", { hint: serverHint }));
785
+ if (!await launch(device, id, publishes ? [publishArgument] : [])) return;
786
+ }
787
+ if (publishes) await printAPI(context, device);
788
+ }
789
+ async function launch(device, id, args) {
790
+ try {
791
+ await step(tr("opening Swipt on {device}", { device: device.name }), () => launchApp(device, id, args));
792
+ return true;
793
+ } catch (error) {
794
+ if (/trusted by the user/.test(error.message)) {
795
+ await step(tr("opening Settings on {device}", { device: device.name }), () => devicectl([
796
+ "device",
797
+ "process",
798
+ "launch",
799
+ "--device",
800
+ device.udid,
801
+ "--payload-url",
802
+ "prefs:root=General&path=ManagedConfigurationList",
803
+ "com.apple.Preferences"
804
+ ]));
805
+ console.log(tr("its developer is not trusted yet; trust it in the Settings page opened on {device}, then open Swipt", { device: device.name }));
806
+ } else if (lockedError.test(error.message)) console.log(tr("it opens once {device} is unlocked", { device: device.name }));
807
+ else throw error;
808
+ return false;
809
+ }
810
+ }
811
+ async function install(context) {
812
+ const device = await coreDevice(context);
813
+ await deploy(context, {
814
+ device,
815
+ ...await locate(context, device, true)
816
+ }, false);
817
+ }
818
+ async function update(context) {
819
+ await deploy(context, await findInstalled(context), true);
820
+ }
821
+ async function setup(context) {
822
+ const given = passcodeOf(context.options);
823
+ const { device, current } = await findInstalled(context);
824
+ const id = current.bundleIdentifier;
825
+ const passcode = given ?? (interactive(context) && !device.virtual ? await askPasscode(context) : void 0);
826
+ await withLocalApp(context, device, async (app) => {
827
+ await mountDiskImage(context, device, app);
828
+ if (passcode !== void 0) await step(tr("setting up auto-unlock"), () => setUpAutoUnlock(device, id, passcode));
829
+ if (!context.options["no-setup-pair"]) await pair(device, id, true);
830
+ await openConfigured(context, device, id, passcode, void 0, app);
831
+ });
832
+ }
833
+ const trustMessages = JSON.stringify({
834
+ unlockToContinue: tr("unlock the device to continue"),
835
+ unlocking: tr("unlocking the device"),
836
+ trusting: tr("trusting {developer} in Settings", { developer: "{developer}" }),
837
+ running: tr("{app} is running", { app: "{app}" }),
838
+ trusted: tr("{developer} is trusted", { developer: "{developer}" })
839
+ });
840
+ const deviceNotListedExit = 3;
841
+ const schema = [
842
+ "CREATE TABLE grdb_migrations (identifier TEXT NOT NULL PRIMARY KEY)",
843
+ "CREATE TABLE \"preferences\" (\"name\" TEXT PRIMARY KEY NOT NULL, \"data\" BLOB NOT NULL)",
844
+ "CREATE TABLE \"swiplets\" (\"id\" TEXT PRIMARY KEY NOT NULL, \"position\" INTEGER NOT NULL, \"etag\" TEXT NOT NULL)",
845
+ "CREATE TABLE \"repositories\" (\"url\" TEXT PRIMARY KEY NOT NULL, \"position\" INTEGER NOT NULL, \"name\" TEXT NOT NULL, \"localizedNames\" TEXT, \"iconColor\" TEXT, \"iconSymbol\" TEXT, \"image\" BLOB, \"etag\" TEXT NOT NULL)",
846
+ "CREATE TABLE \"repositorySwiplets\" (\"repository\" TEXT NOT NULL REFERENCES \"repositories\"(\"url\") ON DELETE CASCADE, \"position\" INTEGER NOT NULL, \"id\" TEXT NOT NULL, \"name\" TEXT NOT NULL, \"localizedNames\" TEXT NOT NULL, \"description\" TEXT NOT NULL, \"version\" TEXT NOT NULL, \"versionCode\" INTEGER NOT NULL, \"iconColor\" TEXT, \"iconSymbol\" TEXT, \"url\" TEXT NOT NULL, \"sha256\" TEXT NOT NULL, PRIMARY KEY (\"repository\", \"id\"))",
847
+ "INSERT INTO grdb_migrations VALUES ('0.1.0')"
848
+ ];
849
+ const databasePath = "Library/Application Support/Swipt.sqlite";
850
+ async function savePreferences(device, id, preferences) {
851
+ const work = fs.mkdtempSync(path.join(os.tmpdir(), "swipt-database-"));
852
+ try {
853
+ const database = path.join(work, "Swipt.sqlite");
854
+ const exists = await containerHasFile(device, id, databasePath);
855
+ if (exists) {
856
+ await terminateApp(device, id);
857
+ await pullFromContainer(device, id, databasePath, database);
858
+ }
859
+ const quote = (text) => `'${text.replaceAll("'", "''")}'`;
860
+ execFileSync("sqlite3", [database], { input: [...exists ? [] : schema, ...Object.entries(preferences).map(([name, value]) => `INSERT OR REPLACE INTO preferences VALUES (${quote(name)}, CAST(${quote(JSON.stringify(value))} AS BLOB))`)].map((statement) => `${statement};\n`).join("") });
861
+ await pushToContainer(device, id, database, databasePath);
862
+ } finally {
863
+ fs.rmSync(work, {
864
+ recursive: true,
865
+ force: true
866
+ });
867
+ }
868
+ }
869
+ const setUpAutoUnlock = (device, id, passcode) => savePreferences(device, id, {
870
+ serverAutoUnlocks: true,
871
+ serverAutoUnlockPasscodeType: passcodeTypes.indexOf(passcode.type),
872
+ serverAutoUnlockPasscode: passcode.passcode,
873
+ autoUnlockSetUp: true
874
+ });
875
+ const pairingFile = "PairingRecord.plist";
876
+ const pairingPath = `Library/Application Support/${pairingFile}`;
877
+ async function savedPasscode(device, id) {
878
+ if (!await containerHasFile(device, id, databasePath)) return;
879
+ const work = fs.mkdtempSync(path.join(os.tmpdir(), "swipt-database-"));
880
+ try {
881
+ const database = path.join(work, "Swipt.sqlite");
882
+ await pullFromContainer(device, id, databasePath, database);
883
+ const rows = execFileSync("sqlite3", [
884
+ "-json",
885
+ database,
886
+ "SELECT name, CAST(data AS TEXT) AS value FROM preferences WHERE name LIKE 'serverAutoUnlock%'"
887
+ ], { encoding: "utf8" });
888
+ const saved = Object.fromEntries(JSON.parse(rows || "[]").map(({ name, value }) => [name, JSON.parse(value)]));
889
+ return saved.serverAutoUnlocks && saved.serverAutoUnlockPasscode ? {
890
+ passcode: saved.serverAutoUnlockPasscode,
891
+ type: passcodeTypes[saved.serverAutoUnlockPasscodeType ?? 0]
892
+ } : void 0;
893
+ } finally {
894
+ fs.rmSync(work, {
895
+ recursive: true,
896
+ force: true
897
+ });
898
+ }
899
+ }
900
+ async function pair(device, id, overwrite = false) {
901
+ if (!overwrite && await step(tr("checking Swipt on {device}", { device: device.name }), () => containerHasFile(device, id, pairingPath), { transient: true })) return false;
902
+ const work = fs.mkdtempSync(path.join(os.tmpdir(), "swipt-pairing-"));
903
+ let warning;
904
+ try {
905
+ await step(tr("pairing with {device}", { device: device.name }), async () => {
906
+ const record = path.join(work, pairingFile);
907
+ try {
908
+ await exec(serverPath(), [
909
+ "pair",
910
+ "-d",
911
+ device.udid,
912
+ "-o",
913
+ record
914
+ ]);
915
+ } catch (error) {
916
+ if (typeof error.code === "number") warning = tr("pairing failed, so Swipt pairs in Settings instead: {error}", { error: error.stderr.trim() });
917
+ else if (error.code === "ENOENT") warning = tr("{hint}; Swipt pairs in Settings instead", { hint: serverHint });
918
+ throw error;
919
+ }
920
+ await pushToContainer(device, id, record, pairingPath);
921
+ });
922
+ } catch (error) {
923
+ if (warning === void 0) throw error;
924
+ console.error(warning);
925
+ return false;
926
+ } finally {
927
+ fs.rmSync(work, {
928
+ recursive: true,
929
+ force: true
930
+ });
931
+ }
932
+ return true;
933
+ }
934
+ async function serve(udid, passcode, signal, diskImage) {
935
+ const server = spawn(serverPath(), [
936
+ "-d",
937
+ udid,
938
+ ...passcode ? [
939
+ "--passcode",
940
+ passcode.passcode,
941
+ "--passcode-type",
942
+ passcode.type
943
+ ] : [],
944
+ "--disk-image",
945
+ diskImage
946
+ ], {
947
+ stdio: [
948
+ "ignore",
949
+ "pipe",
950
+ "pipe"
951
+ ],
952
+ signal
953
+ });
954
+ let logs = "";
955
+ server.stderr.on("data", (chunk) => {
956
+ logs += chunk;
957
+ });
958
+ const exited = new Promise((resolve) => server.once("close", resolve));
959
+ return {
960
+ url: new Promise((resolve, reject) => {
961
+ server.once("error", (error) => reject(error.code === "ENOENT" ? new Error(serverHint) : error));
962
+ exited.then((code) => reject(Object.assign(/* @__PURE__ */ new Error(`swipt-server exited with ${code ?? "a signal"}${logs.trim() === "" ? "" : `: ${logs.trim()}`}`), { exitCode: code })));
963
+ readline.createInterface({ input: server.stdout }).on("line", (line) => {
964
+ const found = /^Swipt API: (\S+)/.exec(line);
965
+ if (found) {
966
+ const parsed = new URL(found[1]);
967
+ parsed.hostname = "127.0.0.1";
968
+ resolve(parsed.origin);
969
+ }
970
+ });
971
+ }),
972
+ stop() {
973
+ server.kill("SIGTERM");
974
+ return exited;
975
+ }
976
+ };
977
+ }
978
+ async function launchUnlocking(device, id, args, signal, diskImage) {
979
+ try {
980
+ await launchApp(device, id, args);
981
+ return;
982
+ } catch (error) {
983
+ if (!lockedError.test(error.message)) throw error;
984
+ const passcode = await savedPasscode(device, id);
985
+ if (passcode === void 0) throw error;
986
+ const server = await serve(device.udid, passcode, signal, diskImage);
987
+ try {
988
+ const failure = await tryUnlock(open({
989
+ url: await server.url,
990
+ token: ""
991
+ }), signal);
992
+ if (failure !== void 0) throw new Error(failure);
993
+ } finally {
994
+ await server.stop();
995
+ }
996
+ }
997
+ await launchApp(device, id, args);
998
+ }
999
+ async function trustAndOpen(context, device, id, given, updated, diskImage) {
1000
+ const lines = [];
1001
+ let failure;
1002
+ let passcode = given;
1003
+ try {
1004
+ await step(tr("opening Swipt on {device}", { device: device.name }), async (update) => {
1005
+ if (updated) try {
1006
+ await launchUnlocking(device, id, context.options["no-setup-api"] ? [] : [publishArgument], context.signal, diskImage);
1007
+ return;
1008
+ } catch (error) {
1009
+ if (!/trusted by the user/.test(error.message) && !lockedError.test(error.message)) throw error;
1010
+ }
1011
+ passcode ??= await savedPasscode(device, id);
1012
+ const unlock = passcode !== void 0 ? "passcode" : process.stderr.isTTY ? "wait" : "";
1013
+ let server;
1014
+ let url;
1015
+ while (url === void 0) {
1016
+ server = await serve(device.udid, passcode, context.signal, diskImage);
1017
+ try {
1018
+ url = await server.url;
1019
+ } catch (error) {
1020
+ if (error.exitCode !== deviceNotListedExit || unlock !== "wait") throw error;
1021
+ update(tr("waiting for {device}", { device: device.name }));
1022
+ }
1023
+ }
1024
+ try {
1025
+ const client = open({
1026
+ url,
1027
+ token: ""
1028
+ });
1029
+ const run = async (args) => {
1030
+ for await (const response of client.repl.execute({
1031
+ code: fs.readFileSync(new URL("../sideload/trust.js", import.meta.url), "utf8"),
1032
+ args: [trustMessages, ...args],
1033
+ program: true
1034
+ }, { signal: context.signal })) switch (response.part.case) {
1035
+ case "console": {
1036
+ const output = response.part.value;
1037
+ if (output.level === LogLevel.DEBUG) update(output.text);
1038
+ else lines.push(output);
1039
+ break;
1040
+ }
1041
+ case "error": failure = response.part.value;
1042
+ }
1043
+ if (failure) throw new Error(failure.message);
1044
+ };
1045
+ const args = [setupArgument, ...context.options["no-setup-api"] ? [] : [publishArgument]];
1046
+ await run([
1047
+ id,
1048
+ "unlock",
1049
+ unlock
1050
+ ]);
1051
+ update("");
1052
+ try {
1053
+ await launchApp(device, id, args);
1054
+ } catch (error) {
1055
+ if (!/trusted by the user/.test(error.message)) throw error;
1056
+ await run([
1057
+ id,
1058
+ "trust",
1059
+ "",
1060
+ error.message
1061
+ ]);
1062
+ update("");
1063
+ await launchApp(device, id, args);
1064
+ }
1065
+ await run([id, "prompts"]);
1066
+ } finally {
1067
+ await server.stop();
1068
+ }
1069
+ });
1070
+ } catch (error) {
1071
+ if (failure === void 0) throw error;
1072
+ } finally {
1073
+ for (const output of lines) (output.level === LogLevel.ERROR || output.level === LogLevel.WARN ? console.error : console.log)(output.text);
1074
+ }
1075
+ if (failure) {
1076
+ if (passcode === void 0 && failure.name === "UnavailableError" && /\bdevice is locked\b/.test(failure.message)) throw new Error(tr("{device}: {message}; unlock it or pass --passcode, then run this again", {
1077
+ device: device.name,
1078
+ message: failure.message
1079
+ }));
1080
+ throw printScriptError(failure);
1081
+ }
1082
+ }
1083
+ async function uninstall(context) {
1084
+ const device = await coreDevice(context, { filter: sideloadedDevices });
1085
+ const { team, current } = await locate(context, device);
1086
+ if (current === void 0) throw new Error(team === void 0 ? tr("Swipt is not sideloaded on {device}", { device: device.name }) : tr("Swipt is not sideloaded on {device} by team {team}", {
1087
+ device: device.name,
1088
+ team
1089
+ }));
1090
+ await step(tr("removing Swipt from {device}", { device: device.name }), () => uninstallApp(device, current.bundleIdentifier));
1091
+ console.log(tr("removed {build} from {device}", {
1092
+ build: buildText(current),
1093
+ device: device.name
1094
+ }));
1095
+ }
1096
+ export { bundleId, install, installAndOpen, installPasscode, setup, uninstall, update };
1097
+
1098
+ //# sourceMappingURL=sideload.js.map