@swipt/cli 0.1.0-nightly.94 → 0.1.0-nightly.97

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 (106) hide show
  1. package/dist/cli/cli.js +1 -1
  2. package/dist/cli/cli.js.map +1 -1
  3. package/dist/cli/commands/data/read.js +4 -6
  4. package/dist/cli/commands/data/read.js.map +1 -1
  5. package/dist/cli/commands/device/stop.js +3 -3
  6. package/dist/cli/commands/device/stop.js.map +1 -1
  7. package/dist/cli/commands/driver/driver.js +28 -0
  8. package/dist/cli/commands/driver/driver.js.map +1 -0
  9. package/dist/cli/commands/driver/index.js +1 -0
  10. package/dist/cli/commands/flags.js +8 -7
  11. package/dist/cli/commands/flags.js.map +1 -1
  12. package/dist/cli/commands/index.js +3 -0
  13. package/dist/cli/commands/index.js.map +1 -1
  14. package/dist/cli/commands/project/create.js +2 -2
  15. package/dist/cli/commands/project/create.js.map +1 -1
  16. package/dist/cli/commands/project/source.js +10 -9
  17. package/dist/cli/commands/project/source.js.map +1 -1
  18. package/dist/cli/commands/swiplet/remove.js +1 -1
  19. package/dist/cli/commands/swiplet/remove.js.map +1 -1
  20. package/dist/client.js +27 -6
  21. package/dist/client.js.map +1 -1
  22. package/dist/connection.d.ts +3 -1
  23. package/dist/connection.js +41 -52
  24. package/dist/connection.js.map +1 -1
  25. package/dist/directories.d.ts +2 -0
  26. package/dist/directories.js +9 -0
  27. package/dist/directories.js.map +1 -0
  28. package/dist/driver.d.ts +39 -0
  29. package/dist/driver.js +199 -0
  30. package/dist/driver.js.map +1 -0
  31. package/dist/i18n.d.ts +1 -1
  32. package/dist/i18n.js +43 -7
  33. package/dist/i18n.js.map +1 -1
  34. package/dist/mdns.d.ts +7 -0
  35. package/dist/mdns.js +44 -0
  36. package/dist/mdns.js.map +1 -0
  37. package/dist/output.js +6 -6
  38. package/dist/output.js.map +1 -1
  39. package/dist/passcode.d.ts +9 -0
  40. package/dist/passcode.js +81 -0
  41. package/dist/passcode.js.map +1 -0
  42. package/dist/project.js +38 -32
  43. package/dist/project.js.map +1 -1
  44. package/dist/serve.d.ts +1 -0
  45. package/dist/serve.js +124 -0
  46. package/dist/serve.js.map +1 -0
  47. package/dist/sideload.d.ts +0 -1
  48. package/dist/sideload.js +82 -340
  49. package/dist/sideload.js.map +1 -1
  50. package/dist/swipt-app.d.ts +14 -0
  51. package/dist/swipt-app.js +51 -0
  52. package/dist/swipt-app.js.map +1 -0
  53. package/locales/ar.json +52 -28
  54. package/locales/bg.json +58 -34
  55. package/locales/bn.json +49 -25
  56. package/locales/ca.json +55 -31
  57. package/locales/cs.json +55 -31
  58. package/locales/da.json +50 -26
  59. package/locales/de.json +50 -26
  60. package/locales/el.json +60 -36
  61. package/locales/es-419.json +51 -27
  62. package/locales/es.json +51 -27
  63. package/locales/fi.json +51 -27
  64. package/locales/fr-CA.json +53 -29
  65. package/locales/fr.json +56 -32
  66. package/locales/gu.json +69 -45
  67. package/locales/he.json +51 -27
  68. package/locales/hi.json +50 -26
  69. package/locales/hr.json +51 -27
  70. package/locales/hu.json +62 -38
  71. package/locales/id.json +50 -26
  72. package/locales/it.json +69 -45
  73. package/locales/ja.json +50 -26
  74. package/locales/kk.json +49 -25
  75. package/locales/kn.json +49 -25
  76. package/locales/ko.json +79 -55
  77. package/locales/lt.json +50 -26
  78. package/locales/ml.json +49 -25
  79. package/locales/mr.json +56 -32
  80. package/locales/ms.json +50 -26
  81. package/locales/nb.json +50 -26
  82. package/locales/nl.json +56 -32
  83. package/locales/or.json +50 -26
  84. package/locales/pa.json +49 -25
  85. package/locales/pl.json +68 -44
  86. package/locales/pt-BR.json +51 -27
  87. package/locales/pt-PT.json +52 -28
  88. package/locales/ro.json +52 -28
  89. package/locales/ru.json +54 -30
  90. package/locales/sk.json +80 -56
  91. package/locales/sl.json +50 -26
  92. package/locales/sv.json +52 -28
  93. package/locales/ta.json +49 -25
  94. package/locales/te.json +49 -25
  95. package/locales/th.json +54 -30
  96. package/locales/tr.json +50 -26
  97. package/locales/uk.json +53 -29
  98. package/locales/ur.json +49 -25
  99. package/locales/vi.json +49 -25
  100. package/locales/zh-HK.json +54 -30
  101. package/locales/zh-Hans.json +54 -30
  102. package/locales/zh-Hant.json +60 -36
  103. package/package.json +13 -4
  104. package/dist/coredevice.d.ts +0 -22
  105. package/dist/coredevice.js +0 -329
  106. package/dist/coredevice.js.map +0 -1
package/dist/sideload.js CHANGED
@@ -1,28 +1,25 @@
1
1
  import { UsageError, open } from "./client.js";
2
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";
3
+ import { cacheDirectory } from "./directories.js";
4
+ import { apps, configureVirtual, failures, installApp, launchApp, mountDiskImage, openSettings, provisioningProfiles, randomToken, serve, terminateApp, trustedDevice, uninstallApp } from "./driver.js";
4
5
  import { language, tr } from "./i18n.js";
5
6
  import { choose, columns, interactive, printScriptError, selectTheme, step } from "./output.js";
7
+ import { askPasscode, passcodeOf } from "./passcode.js";
6
8
  import "./proto/common_pb.js";
9
+ import { bundleId, bundleTeam, hasPairing, publishArgument, savePairing, savePreferences, savedPasscode, setUpAutoUnlock, setupArgument, swiptApps, teamPattern } from "./swipt-app.js";
7
10
  import fs from "node:fs";
8
11
  import path from "node:path";
9
- import { execFile, execFileSync, spawn } from "node:child_process";
12
+ import { execFile, execFileSync } from "node:child_process";
10
13
  import os from "node:os";
11
14
  import { setTimeout } from "node:timers/promises";
12
15
  import { promisify } from "node:util";
13
16
  import select from "@inquirer/select";
14
17
  import { X509Certificate, createHash } from "node:crypto";
15
- import readline from "node:readline";
16
18
  import { Readable } from "node:stream";
17
19
  import { pipeline } from "node:stream/promises";
18
- import password from "@inquirer/password";
19
20
  // src/sideload.ts
20
21
  const exec = promisify(execFile);
21
- const bundleId = "io.nekohasekai.swipt";
22
- const bundleTeam = "P8XK3KHB48";
23
22
  const repository = "swipt-automation/swipt";
24
- const teamPattern = /^[A-Z0-9]{10}$/;
25
- const sideloadedPattern = new RegExp(`^${bundleId.replaceAll(".", "\\.")}(?:\\.([A-Z0-9]{10}))?$`);
26
23
  const guestTeam = "SWIPTLOCAL";
27
24
  const guestEntitlements = (id) => `<?xml version="1.0" encoding="UTF-8"?>
28
25
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
@@ -47,31 +44,10 @@ const guestEntitlements = (id) => `<?xml version="1.0" encoding="UTF-8"?>
47
44
  `;
48
45
  const accountsHint = "Xcode › Settings › Accounts";
49
46
  const xcodeProfiles = "Library/Developer/Xcode/UserData/Provisioning Profiles";
50
- const downloads = path.join(process.env.XDG_CACHE_HOME || path.join(os.homedir(), ".cache"), "swipt", "sideload");
47
+ const downloads = path.join(cacheDirectory, "sideload");
48
+ const signingNeedsMac = tr("Installing or updating Swipt needs macOS; install it from a Mac, then set it up here with \"swipt sideload setup\".");
51
49
  const expiresSoon = ({ creation, expiration }) => expiration - Date.now() < (expiration - creation) / 2;
52
- const passcodeTypes = [
53
- "pin",
54
- "numeric",
55
- "alphanumeric"
56
- ];
57
50
  const plistValueMissing = /No value at that key path/;
58
- function passcodeOf(options) {
59
- const type = options["passcode-type"] ?? "pin";
60
- if (!passcodeTypes.includes(type)) throw new UsageError(tr("invalid argument {value} for --passcode-type: it's {types}", {
61
- value: JSON.stringify(type),
62
- types: passcodeTypes.join(", ")
63
- }));
64
- const passcode = options.passcode;
65
- if (!passcode) return;
66
- const digits = /^\d+$/.test(passcode);
67
- 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"));
68
- if (type === "numeric" && !digits) throw new UsageError(tr("A numeric passcode is digits only."));
69
- if (!/^[\x20-\x7e]{1,64}$/.test(passcode)) throw new UsageError(tr("A passcode is up to 64 printable ASCII characters."));
70
- return {
71
- passcode,
72
- type
73
- };
74
- }
75
51
  function headers(accept) {
76
52
  const token = process.env.GITHUB_TOKEN;
77
53
  return {
@@ -134,10 +110,10 @@ async function download(url, file, signal, update) {
134
110
  }, fs.createWriteStream(file), { signal });
135
111
  }
136
112
  async function unpack(ipa, directory) {
137
- await exec("unzip", [
138
- "-q",
113
+ await exec("ditto", [
114
+ "-x",
115
+ "-k",
139
116
  ipa,
140
- "-d",
141
117
  directory
142
118
  ]);
143
119
  const payload = path.join(directory, "Payload");
@@ -364,7 +340,7 @@ async function resign(app, id, signing, update) {
364
340
  "-replace",
365
341
  "BGTaskSchedulerPermittedIdentifiers",
366
342
  "-json",
367
- JSON.stringify(permitted.map((it) => it.startsWith(`io.nekohasekai.swipt.`) ? id + it.slice(20) : it)),
343
+ JSON.stringify(permitted.map((it) => it.startsWith(`io.nekohasekai.swipt.`) ? id + it.slice(bundleId.length) : it)),
368
344
  info
369
345
  ]);
370
346
  const profile = path.join(app, "embedded.mobileprovision");
@@ -447,23 +423,16 @@ const teamChoice = ({ id, name }) => ({
447
423
  short: name ?? id,
448
424
  value: id
449
425
  });
450
- async function sideloadedDevices(devices, missing = tr("Swipt isn't sideloaded on any online iPhone or iPad.")) {
451
- 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 });
426
+ async function sideloadedDevices(devices, missing = tr("Swipt isn't sideloaded on any iPhone or iPad.")) {
427
+ const sideloaded = await step(tr("looking for Swipt on the devices"), () => Promise.all(devices.map((device) => swiptApps(device).then((found) => found.length > 0, () => true))), { transient: true });
452
428
  const found = devices.filter((_, index) => sideloaded[index]);
453
429
  if (found.length === 0) throw new Error(missing);
454
430
  return found;
455
431
  }
456
432
  async function locate(context, device, fresh = false) {
457
433
  const { options } = context;
458
- const listed = await step(tr("checking Swipt on {device}", { device: device.name }), () => apps(device), { transient: true });
459
- if (device.virtual) return { current: listed.find((app) => app.bundleIdentifier === bundleId) };
460
- const found = listed.map((app) => {
461
- const match = sideloadedPattern.exec(app.bundleIdentifier);
462
- return {
463
- ...app,
464
- team: match && (match[1] ?? bundleTeam)
465
- };
466
- }).filter((app) => app.team !== null);
434
+ const found = await step(tr("checking Swipt on {device}", { device: device.name }), () => swiptApps(device), { transient: true });
435
+ if (device.virtual) return { current: found.find((app) => app.bundleIdentifier === bundleId) };
467
436
  if (options.team !== void 0) {
468
437
  if (!teamPattern.test(options.team)) throw new UsageError(tr("invalid argument {value} for --team: it's the 10-character team ID shown in {accounts}", {
469
438
  value: JSON.stringify(options.team),
@@ -475,7 +444,7 @@ async function locate(context, device, fresh = false) {
475
444
  };
476
445
  }
477
446
  if (found.length > 1) {
478
- const known = xcodeTeams();
447
+ const known = process.platform === "darwin" ? xcodeTeams() : [];
479
448
  const teams = found.map((app) => ({
480
449
  id: app.team,
481
450
  name: known.find((team) => team.id === app.team)?.name
@@ -487,10 +456,11 @@ async function locate(context, device, fresh = false) {
487
456
  };
488
457
  }
489
458
  if (found.length === 0 && fresh) {
459
+ if (process.platform !== "darwin") throw new Error(signingNeedsMac);
490
460
  const teams = xcodeTeams();
491
461
  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 }));
492
462
  return {
493
- 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)}`)),
463
+ team: teams.some((it) => it.id === "P8XK3KHB48") ? 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)}`)),
494
464
  current: void 0
495
465
  };
496
466
  }
@@ -502,7 +472,7 @@ async function locate(context, device, fresh = false) {
502
472
  const buildText = (app) => `Swipt ${app.version} (${app.bundleVersion})`;
503
473
  async function signingPeriod(device, id, team) {
504
474
  const names = [id, "*"].map((it) => `iOS Team Provisioning Profile: ${it}`);
505
- 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) => ({
475
+ return (await step(tr("checking Swipt on {device}", { device: device.name }), () => provisioningProfiles(device), { transient: true })).filter((profile) => profile.teamIdentifier === team && names.includes(profile.name)).map((profile) => ({
506
476
  creation: Date.parse(profile.creationDate),
507
477
  expiration: Date.parse(profile.expirationDate)
508
478
  })).reduce((latest, it) => it.expiration > latest.expiration ? it : latest, {
@@ -516,61 +486,11 @@ function expirationText(time) {
516
486
  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"];
517
487
  return new Intl.RelativeTimeFormat(language).format(value, unit).replace(/(\d)(\p{Script=Han})/gu, "$1 $2");
518
488
  }
519
- async function askPasscode(context) {
520
- const type = await select({
521
- message: tr("Set up auto-unlock? Swipt can then unlock this device by itself."),
522
- theme: selectTheme,
523
- choices: [
524
- {
525
- name: tr("4 or 6 digit passcode"),
526
- short: tr("4 or 6 digits"),
527
- value: "pin"
528
- },
529
- {
530
- name: tr("Custom numeric passcode"),
531
- short: tr("numeric"),
532
- value: "numeric"
533
- },
534
- {
535
- name: tr("Custom alphanumeric passcode"),
536
- short: tr("alphanumeric"),
537
- value: "alphanumeric"
538
- },
539
- {
540
- name: tr("No Thanks"),
541
- value: null
542
- }
543
- ]
544
- }, {
545
- output: process.stderr,
546
- signal: context.signal
547
- });
548
- if (type === null) return;
549
- const options = (passcode) => ({
550
- passcode,
551
- "passcode-type": type
552
- });
553
- return passcodeOf(options(await password({
554
- message: tr("Device passcode"),
555
- theme: { i18n: { maskedText: tr("[input is masked]") } },
556
- validate(passcode) {
557
- try {
558
- passcodeOf(options(passcode));
559
- return passcode !== "" || tr("Enter the passcode.");
560
- } catch (error) {
561
- return error.message;
562
- }
563
- }
564
- }, {
565
- output: process.stderr,
566
- signal: context.signal
567
- })));
568
- }
569
489
  async function installPasscode(context, device, current) {
570
490
  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);
571
491
  }
572
492
  async function findInstalled(context) {
573
- const device = await coreDevice(context, { filter: (devices) => sideloadedDevices(devices, tr("Swipt isn't sideloaded on any online iPhone or iPad; install it with \"swipt sideload install\".")) });
493
+ const device = await trustedDevice(context, { filter: (devices) => sideloadedDevices(devices, tr("Swipt isn't sideloaded on any iPhone or iPad; install it with \"swipt sideload install\".")) });
574
494
  const { team, current } = await locate(context, device);
575
495
  if (current === void 0) throw new Error(team === void 0 ? tr("Swipt isn't sideloaded on {device}; install it with \"swipt sideload install\".", { device: device.name }) : tr("Swipt isn't sideloaded on {device} by team {team}; install it with \"swipt sideload install\".", {
576
496
  device: device.name,
@@ -597,50 +517,22 @@ async function downloadIPA(context, release) {
597
517
  for (const entry of fs.readdirSync(downloads)) if (entry !== name) fs.rmSync(path.join(downloads, entry), { force: true });
598
518
  return ipa;
599
519
  }
600
- async function localIPA(context) {
601
- const cached = fs.existsSync(downloads) ? fs.readdirSync(downloads).find((entry) => entry.endsWith(".ipa")) : void 0;
602
- 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);
603
- }
604
- async function withLocalApp(context, device, run) {
605
- if (device.virtual) return run(void 0);
606
- const work = fs.mkdtempSync(path.join(os.tmpdir(), "swipt-app-"));
607
- try {
608
- return await run(await unpack(await localIPA(context), work));
609
- } finally {
610
- fs.rmSync(work, {
611
- recursive: true,
612
- force: true
613
- });
614
- }
615
- }
616
- async function mountDiskImage(context, device, app) {
520
+ async function prepareDiskImage(context, device) {
617
521
  if (device.virtual) return;
618
522
  try {
619
- await step(tr("preparing the Developer Disk Image on {device}", { device: device.name }), async () => {
620
- try {
621
- await exec(serverPath(), [
622
- "mount",
623
- "-d",
624
- device.udid,
625
- "--disk-image",
626
- path.join(app, "DeveloperDiskImage")
627
- ]);
628
- } catch (error) {
629
- if (error.code !== "ENOENT") throw error;
630
- }
631
- }, { transient: true });
523
+ await step(tr("preparing the Developer Disk Image on {device}", { device: device.name }), () => mountDiskImage(device), { transient: true });
632
524
  } catch (error) {
633
525
  if (context.signal.aborted) throw error;
634
526
  console.error(tr("couldn't prepare the Developer Disk Image on {device}: {error}", {
635
527
  device: device.name,
636
- error: /^Error: (.*)$/m.exec(error.stderr ?? "")?.[1] ?? error.message
528
+ error: error.message
637
529
  }));
638
530
  }
639
531
  }
640
532
  async function deploy(context, { device, team, current }, updateOnly) {
641
533
  const passcode = await installPasscode(context, device, current);
642
534
  const release = await step(tr("checking the latest release"), () => findRelease(context.options.nightly, context.signal), { transient: true });
643
- const id = device.virtual || team === bundleTeam ? bundleId : `${bundleId}.${team}`;
535
+ const id = device.virtual || team === "P8XK3KHB48" ? bundleId : `${bundleId}.${team}`;
644
536
  if (current !== void 0) {
645
537
  const installed = Number(current.bundleVersion);
646
538
  const signing = device.virtual ? void 0 : await signingPeriod(device, id, team);
@@ -674,22 +566,21 @@ async function deploy(context, { device, team, current }, updateOnly) {
674
566
  if (!replaces && installed >= release.build && (signing === void 0 || !expiresSoon(signing))) {
675
567
  if (signing !== void 0) console.log(tr("Its signing expires {expiration}.", { expiration: expirationText(signing.expiration) }));
676
568
  const saves = !updateOnly && passcode !== void 0;
677
- 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 });
569
+ const pairs = !context.options["no-setup"] && !context.options["no-setup-pair"] && !await step(tr("checking Swipt on {device}", { device: device.name }), () => hasPairing(device, id), { transient: true });
678
570
  if (!saves && !pairs) return;
679
- await withLocalApp(context, device, async (app) => {
680
- await mountDiskImage(context, device, app);
681
- if (saves) await step(tr("setting up auto-unlock"), () => setUpAutoUnlock(device, id, passcode));
682
- if (context.options["no-setup"]) {
683
- await launch(device, id);
684
- return;
685
- }
686
- const paired = pairs && await pair(device, id, true);
687
- if (saves || paired) await openConfigured(context, device, id, passcode, void 0, app);
688
- });
571
+ await prepareDiskImage(context, device);
572
+ if (saves) await step(tr("setting up auto-unlock"), () => setUpAutoUnlock(device, id, passcode));
573
+ if (context.options["no-setup"]) {
574
+ await launch(device, id);
575
+ return;
576
+ }
577
+ const paired = pairs && await pair(context, device, id, true);
578
+ if (saves || paired) await openConfigured(context, device, id, passcode);
689
579
  return;
690
580
  }
691
581
  if (!replaces && installed > release.build) throw new Error(tr("{build} on {device} needs new signing, but {release} ({releaseBuild}) is earlier; use --nightly, or downgrade with \"swipt sideload install --force\".", parameters));
692
582
  }
583
+ if (!device.virtual && process.platform !== "darwin") throw new Error(signingNeedsMac);
693
584
  const work = fs.mkdtempSync(path.join(os.tmpdir(), "swipt-sideload-"));
694
585
  try {
695
586
  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));
@@ -734,13 +625,7 @@ async function installOnGuest(device, id, app) {
734
625
  entitlements
735
626
  }, update);
736
627
  });
737
- const archive = path.join(work, "Swipt.ipa");
738
- await exec("zip", [
739
- "-qry1",
740
- archive,
741
- "Payload"
742
- ], { cwd: work });
743
- await step(tr("installing on {device}", { device: device.name }), () => installApp(device, archive, id));
628
+ await step(tr("installing on {device}", { device: device.name }), () => installApp(device, signed, id));
744
629
  } finally {
745
630
  fs.rmSync(work, {
746
631
  recursive: true,
@@ -753,7 +638,7 @@ async function installAndOpen(context, { device, id, current }, app, build, { pa
753
638
  const running = await step(tr("checking Swipt on {device}", { device: device.name }), () => runningSwipt(device.name, context.signal), { transient: true });
754
639
  if (running !== void 0) await step(tr("unlocking the device"), () => tryUnlock(running, context.signal), { transient: true });
755
640
  }
756
- await mountDiskImage(context, device, app);
641
+ await prepareDiskImage(context, device);
757
642
  if (device.virtual) await installOnGuest(device, id, app);
758
643
  else await step(tr("installing on {device}", { device: device.name }), () => installApp(device, app, id));
759
644
  if (saves && passcode !== void 0) await step(tr("setting up auto-unlock"), () => setUpAutoUnlock(device, id, passcode));
@@ -769,11 +654,9 @@ async function installAndOpen(context, { device, id, current }, app, build, { pa
769
654
  await launch(device, id);
770
655
  return;
771
656
  }
772
- const paired = !context.options["no-setup-pair"] && await pair(device, id);
773
- await openConfigured(context, device, id, passcode, current !== void 0 && !paired, app);
657
+ const paired = !context.options["no-setup-pair"] && await pair(context, device, id);
658
+ await openConfigured(context, device, id, passcode, current !== void 0 && !paired);
774
659
  }
775
- const publishArgument = "--publish-local-network";
776
- const setupArgument = "--setup";
777
660
  async function printAPI(context, device) {
778
661
  const found = await step(tr("checking Swipt on {device}", { device: device.name }), () => findPublished(device.name, context.signal), { transient: true });
779
662
  if (found === void 0) {
@@ -783,23 +666,17 @@ async function printAPI(context, device) {
783
666
  const url = found.authenticates ? withToken(found.url) : found.url;
784
667
  console.log(columns([["CLI", url], ["MCP", `${url}/mcp`]]));
785
668
  }
786
- async function openConfigured(context, device, id, passcode, updated, app) {
669
+ async function openConfigured(context, device, id, passcode, updated) {
787
670
  const publishes = !context.options["no-setup-api"];
788
671
  if (device.virtual) await step(tr("opening Swipt on {device}", { device: device.name }), async () => {
789
672
  await savePreferences(device, id, {
790
673
  autoUnlockSetUp: true,
791
674
  developerLocalNetworkEnabled: publishes
792
675
  });
793
- await configureGuest(device, id, "Swipt");
676
+ await configureVirtual(device, id, "Swipt");
794
677
  await launchApp(device, id);
795
678
  });
796
- else try {
797
- await trustAndOpen(context, device, id, passcode, updated, path.join(app, "DeveloperDiskImage"));
798
- } catch (error) {
799
- if (error.message !== serverHint) throw error;
800
- console.error(tr("{hint}; its developer isn't trusted automatically.", { hint: serverHint }));
801
- if (!await launch(device, id, publishes ? [publishArgument] : [])) return;
802
- }
679
+ else await trustAndOpen(context, device, id, passcode, updated);
803
680
  if (publishes) await printAPI(context, device);
804
681
  }
805
682
  async function launch(device, id, args) {
@@ -807,25 +684,16 @@ async function launch(device, id, args) {
807
684
  await step(tr("opening Swipt on {device}", { device: device.name }), () => launchApp(device, id, args));
808
685
  return true;
809
686
  } catch (error) {
810
- if (/trusted by the user/.test(error.message)) {
811
- await step(tr("opening Settings on {device}", { device: device.name }), () => devicectl([
812
- "device",
813
- "process",
814
- "launch",
815
- "--device",
816
- device.udid,
817
- "--payload-url",
818
- "prefs:root=General&path=ManagedConfigurationList",
819
- "com.apple.Preferences"
820
- ]));
687
+ if (error.code === failures.untrusted) {
688
+ await step(tr("opening Settings on {device}", { device: device.name }), () => openSettings(device, "prefs:root=General&path=ManagedConfigurationList"));
821
689
  console.log(tr("Its developer isn't trusted yet; trust it in the Settings page opened on {device}, then open Swipt.", { device: device.name }));
822
- } else if (lockedError.test(error.message)) console.log(tr("It opens after {device} is unlocked.", { device: device.name }));
690
+ } else if (error.code === failures.locked) console.log(tr("It opens after {device} is unlocked.", { device: device.name }));
823
691
  else throw error;
824
692
  return false;
825
693
  }
826
694
  }
827
695
  async function install(context) {
828
- const device = await coreDevice(context);
696
+ const device = await trustedDevice(context);
829
697
  await deploy(context, {
830
698
  device,
831
699
  ...await locate(context, device, true)
@@ -839,12 +707,10 @@ async function setup(context) {
839
707
  const { device, current } = await findInstalled(context);
840
708
  const id = current.bundleIdentifier;
841
709
  const passcode = given ?? (interactive(context) && !device.virtual ? await askPasscode(context) : void 0);
842
- await withLocalApp(context, device, async (app) => {
843
- await mountDiskImage(context, device, app);
844
- if (passcode !== void 0) await step(tr("setting up auto-unlock"), () => setUpAutoUnlock(device, id, passcode));
845
- if (!context.options["no-setup-pair"]) await pair(device, id, true);
846
- await openConfigured(context, device, id, passcode, void 0, app);
847
- });
710
+ await prepareDiskImage(context, device);
711
+ if (passcode !== void 0) await step(tr("setting up auto-unlock"), () => setUpAutoUnlock(device, id, passcode));
712
+ if (!context.options["no-setup-pair"]) await pair(context, device, id, true);
713
+ await openConfigured(context, device, id, passcode);
848
714
  }
849
715
  const trustMessages = JSON.stringify({
850
716
  unlockToContinue: tr("Unlock the device to continue."),
@@ -853,196 +719,72 @@ const trustMessages = JSON.stringify({
853
719
  running: tr("{app} is running.", { app: "{app}" }),
854
720
  trusted: tr("{developer} is trusted.", { developer: "{developer}" })
855
721
  });
856
- const deviceNotListedExit = 3;
857
- const schema = [
858
- "CREATE TABLE grdb_migrations (identifier TEXT NOT NULL PRIMARY KEY)",
859
- "CREATE TABLE \"preferences\" (\"name\" TEXT PRIMARY KEY NOT NULL, \"data\" BLOB NOT NULL)",
860
- "CREATE TABLE \"swiplets\" (\"id\" TEXT PRIMARY KEY NOT NULL, \"position\" INTEGER NOT NULL, \"etag\" TEXT NOT NULL)",
861
- "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)",
862
- "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\"))",
863
- "INSERT INTO grdb_migrations VALUES ('0.1.0')"
864
- ];
865
- const databasePath = "Library/Application Support/Swipt.sqlite";
866
- async function savePreferences(device, id, preferences) {
867
- const work = fs.mkdtempSync(path.join(os.tmpdir(), "swipt-database-"));
722
+ async function pair(context, device, id, overwrite = false) {
723
+ if (!overwrite && await step(tr("checking Swipt on {device}", { device: device.name }), () => hasPairing(device, id), { transient: true })) return false;
868
724
  try {
869
- const database = path.join(work, "Swipt.sqlite");
870
- const exists = await containerHasFile(device, id, databasePath);
871
- if (exists) {
872
- await terminateApp(device, id);
873
- await pullFromContainer(device, id, databasePath, database);
874
- }
875
- const quote = (text) => `'${text.replaceAll("'", "''")}'`;
876
- 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("") });
877
- await pushToContainer(device, id, database, databasePath);
878
- } finally {
879
- fs.rmSync(work, {
880
- recursive: true,
881
- force: true
882
- });
883
- }
884
- }
885
- const setUpAutoUnlock = (device, id, passcode) => savePreferences(device, id, {
886
- autoUnlocks: true,
887
- autoUnlockPasscodeType: passcodeTypes.indexOf(passcode.type),
888
- autoUnlockPasscode: passcode.passcode,
889
- autoUnlockSetUp: true
890
- });
891
- const pairingFile = "PairingRecord.plist";
892
- const pairingPath = `Library/Application Support/${pairingFile}`;
893
- async function savedPasscode(device, id) {
894
- if (!await containerHasFile(device, id, databasePath)) return;
895
- const work = fs.mkdtempSync(path.join(os.tmpdir(), "swipt-database-"));
896
- try {
897
- const database = path.join(work, "Swipt.sqlite");
898
- await pullFromContainer(device, id, databasePath, database);
899
- const rows = execFileSync("sqlite3", [
900
- "-json",
901
- database,
902
- "SELECT name, CAST(data AS TEXT) AS value FROM preferences WHERE name LIKE 'autoUnlock%'"
903
- ], { encoding: "utf8" });
904
- const saved = Object.fromEntries(JSON.parse(rows || "[]").map(({ name, value }) => [name, JSON.parse(value)]));
905
- return saved.autoUnlocks && saved.autoUnlockPasscode ? {
906
- passcode: saved.autoUnlockPasscode,
907
- type: passcodeTypes[saved.autoUnlockPasscodeType ?? 0]
908
- } : void 0;
909
- } finally {
910
- fs.rmSync(work, {
911
- recursive: true,
912
- force: true
913
- });
914
- }
915
- }
916
- async function pair(device, id, overwrite = false) {
917
- if (!overwrite && await step(tr("checking Swipt on {device}", { device: device.name }), () => containerHasFile(device, id, pairingPath), { transient: true })) return false;
918
- const work = fs.mkdtempSync(path.join(os.tmpdir(), "swipt-pairing-"));
919
- let warning;
920
- try {
921
- await step(tr("pairing with {device}", { device: device.name }), async () => {
922
- const record = path.join(work, pairingFile);
923
- try {
924
- await exec(serverPath(), [
925
- "pair",
926
- "-d",
927
- device.udid,
928
- "-o",
929
- record
930
- ]);
931
- } catch (error) {
932
- if (typeof error.code === "number") warning = tr("Pairing failed, so Swipt pairs in Settings instead: {error}", { error: error.stderr.trim() });
933
- else if (error.code === "ENOENT") warning = tr("{hint}; Swipt pairs in Settings instead.", { hint: serverHint });
934
- throw error;
935
- }
936
- await pushToContainer(device, id, record, pairingPath);
937
- });
725
+ await step(tr("pairing with {device}", { device: device.name }), () => savePairing(device, id));
938
726
  } catch (error) {
939
- if (warning === void 0) throw error;
940
- console.error(warning);
727
+ if (context.signal.aborted) throw error;
728
+ console.error(tr("Pairing failed, so Swipt pairs in Settings instead: {error}", { error: error.message }));
941
729
  return false;
942
- } finally {
943
- fs.rmSync(work, {
944
- recursive: true,
945
- force: true
946
- });
947
730
  }
948
731
  return true;
949
732
  }
950
- async function serve(udid, passcode, signal, diskImage) {
951
- const server = spawn(serverPath(), [
952
- "-d",
953
- udid,
954
- ...passcode ? [
955
- "--passcode",
956
- passcode.passcode,
957
- "--passcode-type",
958
- passcode.type
959
- ] : [],
960
- "--disk-image",
961
- diskImage
962
- ], {
963
- stdio: [
964
- "ignore",
965
- "pipe",
966
- "pipe"
967
- ],
968
- signal
969
- });
970
- let logs = "";
971
- server.stderr.on("data", (chunk) => {
972
- logs += chunk;
973
- });
974
- const exited = new Promise((resolve) => server.once("close", resolve));
975
- return {
976
- url: new Promise((resolve, reject) => {
977
- server.once("error", (error) => reject(error.code === "ENOENT" ? new Error(serverHint) : error));
978
- exited.then((code) => reject(Object.assign(/* @__PURE__ */ new Error(`swipt-server exited with ${code ?? "a signal"}${logs.trim() === "" ? "" : `: ${logs.trim()}`}`), { exitCode: code })));
979
- readline.createInterface({ input: server.stdout }).on("line", (line) => {
980
- const found = /^Swipt API: (\S+)/.exec(line);
981
- if (found) {
982
- const parsed = new URL(found[1]);
983
- parsed.hostname = "127.0.0.1";
984
- resolve(parsed.origin);
985
- }
986
- });
987
- }),
988
- stop() {
989
- server.kill("SIGTERM");
990
- return exited;
991
- }
992
- };
993
- }
994
- async function launchUnlocking(device, id, args, signal, diskImage) {
733
+ async function launchUnlocking(device, id, args, signal) {
995
734
  try {
996
735
  await launchApp(device, id, args);
997
736
  return;
998
737
  } catch (error) {
999
- if (!lockedError.test(error.message)) throw error;
738
+ if (error.code !== failures.locked) throw error;
1000
739
  const passcode = await savedPasscode(device, id);
1001
740
  if (passcode === void 0) throw error;
1002
- const server = await serve(device.udid, passcode, signal, diskImage);
741
+ const driven = serve(device.udid, {
742
+ passcode,
743
+ token: randomToken(),
744
+ signal
745
+ });
1003
746
  try {
1004
- const failure = await tryUnlock(open({
1005
- url: await server.url,
1006
- token: ""
1007
- }), signal);
747
+ const failure = await tryUnlock(open((await driven.serving).local), signal);
1008
748
  if (failure !== void 0) throw new Error(failure);
1009
749
  } finally {
1010
- await server.stop();
750
+ await driven.stop();
1011
751
  }
1012
752
  }
1013
753
  await launchApp(device, id, args);
1014
754
  }
1015
- async function trustAndOpen(context, device, id, given, updated, diskImage) {
755
+ async function trustAndOpen(context, device, id, given, updated) {
1016
756
  const lines = [];
1017
757
  let failure;
1018
758
  let passcode = given;
1019
759
  try {
1020
760
  await step(tr("opening Swipt on {device}", { device: device.name }), async (update) => {
1021
761
  if (updated) try {
1022
- await launchUnlocking(device, id, context.options["no-setup-api"] ? [] : [publishArgument], context.signal, diskImage);
762
+ await launchUnlocking(device, id, context.options["no-setup-api"] ? [] : [publishArgument], context.signal);
1023
763
  return;
1024
764
  } catch (error) {
1025
- if (!/trusted by the user/.test(error.message) && !lockedError.test(error.message)) throw error;
765
+ if (error.code !== failures.untrusted && error.code !== failures.locked) throw error;
1026
766
  }
1027
767
  passcode ??= await savedPasscode(device, id);
768
+ await terminateApp(device, id);
1028
769
  const unlock = passcode !== void 0 ? "passcode" : process.stderr.isTTY ? "wait" : "";
1029
- let server;
1030
- let url;
1031
- while (url === void 0) {
1032
- server = await serve(device.udid, passcode, context.signal, diskImage);
770
+ let driven;
771
+ let local;
772
+ while (local === void 0) {
773
+ driven = serve(device.udid, {
774
+ passcode,
775
+ token: randomToken(),
776
+ signal: context.signal
777
+ });
1033
778
  try {
1034
- url = await server.url;
779
+ local = (await driven.serving).local;
1035
780
  } catch (error) {
1036
- if (error.exitCode !== deviceNotListedExit || unlock !== "wait") throw error;
781
+ if (error.code !== failures.deviceNotListed || unlock !== "wait") throw error;
1037
782
  update(tr("waiting for {device}", { device: device.name }));
1038
783
  await setTimeout(1e3, void 0, { signal: context.signal });
1039
784
  }
1040
785
  }
1041
786
  try {
1042
- const client = open({
1043
- url,
1044
- token: ""
1045
- });
787
+ const client = open(local);
1046
788
  const run = async (args) => {
1047
789
  for await (const response of client.repl.execute({
1048
790
  code: fs.readFileSync(new URL("../sideload/trust.js", import.meta.url), "utf8"),
@@ -1069,7 +811,7 @@ async function trustAndOpen(context, device, id, given, updated, diskImage) {
1069
811
  try {
1070
812
  await launchApp(device, id, args);
1071
813
  } catch (error) {
1072
- if (!/trusted by the user/.test(error.message)) throw error;
814
+ if (error.code !== failures.untrusted) throw error;
1073
815
  await run([
1074
816
  id,
1075
817
  "trust",
@@ -1081,7 +823,7 @@ async function trustAndOpen(context, device, id, given, updated, diskImage) {
1081
823
  }
1082
824
  await run([id, "prompts"]);
1083
825
  } finally {
1084
- await server.stop();
826
+ await driven.stop();
1085
827
  }
1086
828
  });
1087
829
  } catch (error) {
@@ -1098,7 +840,7 @@ async function trustAndOpen(context, device, id, given, updated, diskImage) {
1098
840
  }
1099
841
  }
1100
842
  async function uninstall(context) {
1101
- const device = await coreDevice(context, { filter: sideloadedDevices });
843
+ const device = await trustedDevice(context, { filter: sideloadedDevices });
1102
844
  const { team, current } = await locate(context, device);
1103
845
  if (current === void 0) throw new Error(team === void 0 ? tr("Swipt isn't sideloaded on {device}.", { device: device.name }) : tr("Swipt isn't sideloaded on {device} by team {team}.", {
1104
846
  device: device.name,
@@ -1110,6 +852,6 @@ async function uninstall(context) {
1110
852
  device: device.name
1111
853
  }));
1112
854
  }
1113
- export { bundleId, install, installAndOpen, installPasscode, setup, uninstall, update };
855
+ export { install, installAndOpen, installPasscode, setup, uninstall, update };
1114
856
 
1115
857
  //# sourceMappingURL=sideload.js.map