@akanjs/cli 3.0.0-beta.20 → 3.0.0-beta.22

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 (64) hide show
  1. package/.build-stamp +1 -1
  2. package/{CodeAgent-awv258wb.js → CodeAgent-0dh9fzzg.js} +2 -2
  3. package/{CodeTui-1nqh35ez.js → CodeTui-drwdvwg9.js} +1 -1
  4. package/{agent.command-1s9ag7sb.js → agent.command-ttn09rx3.js} +5 -5
  5. package/akanCode.js +2 -2
  6. package/{application.command-49hwy6va.js → application.command-mm5v2gzp.js} +43 -41
  7. package/{applicationBuildRunner-ybyp97pv.js → applicationBuildRunner-38exmejd.js} +2 -2
  8. package/buildBatch.proc.js +10 -4
  9. package/{cloud.command-d7rqtzt9.js → cloud.command-f1pnvp2a.js} +9 -8
  10. package/cloud.script-d61mcf0q.js +20 -0
  11. package/{code.command-nn48xzej.js → code.command-1jgk14tc.js} +6 -6
  12. package/commandManifest.json +1 -1
  13. package/{context.command-s3mcmvpa.js → context.command-4vpjmg22.js} +13 -13
  14. package/context.runner-ehjs419v.js +21 -0
  15. package/{guideline.command-sct4qnt5.js → guideline.command-7jk47fgq.js} +2 -2
  16. package/guidelines/agentRule/agentRule.instruction.md +3 -3
  17. package/guidelines/conventions/conventions.instruction.md +17 -5
  18. package/guidelines/runtimeRule/runtimeRule.instruction.md +3 -3
  19. package/incrementalBuilder.proc.js +1 -1
  20. package/{index-5pc1qrbv.js → index-1db2cw0y.js} +2 -2
  21. package/{index-13ffe9wp.js → index-2gh9sndr.js} +4 -4
  22. package/{index-ahemdr5n.js → index-4dn1p115.js} +3 -3
  23. package/{index-ygn77a5w.js → index-9629w7ns.js} +5 -3
  24. package/{index-ddxvdd1p.js → index-aadpbnt2.js} +5 -5
  25. package/{index-xsjh6nzh.js → index-aaz7n8s2.js} +3 -3
  26. package/{index-9d9bgcx4.js → index-ga6hygxr.js} +514 -480
  27. package/{index-ztp3e73t.js → index-hb8sgepf.js} +1 -1
  28. package/{index-xqpzbab5.js → index-m0ms3n1c.js} +7 -7
  29. package/{index-ww4z397j.js → index-m79y8b2h.js} +82 -168
  30. package/{index-as7xmyz8.js → index-mgfx3mfs.js} +5 -4
  31. package/{index-3sq321ak.js → index-pp54p5zk.js} +2 -2
  32. package/{index-xqjwd384.js → index-q44jbw48.js} +1 -1
  33. package/{index-w2zdcw3k.js → index-rmcw8yc8.js} +1 -1
  34. package/{index-dzf3r49a.js → index-rnt66vym.js} +1 -1
  35. package/{index-8sf7wmdr.js → index-sz0myv9k.js} +5 -5
  36. package/{index-8mna0947.js → index-tgjy8xf3.js} +4 -4
  37. package/{index-nv5976x3.js → index-vj1cwwy5.js} +24 -13
  38. package/{index-przybvy5.js → index-wp43xrjv.js} +4 -4
  39. package/{index-31yr441d.js → index-ya5qbmyg.js} +3 -3
  40. package/{index-axzjaqve.js → index-yjkte9aj.js} +5 -4
  41. package/index-ys6f0bvh.js +471 -0
  42. package/{index-myhc3c1j.js → index-yy4s1j72.js} +1 -1
  43. package/index.js +21 -21
  44. package/{library.command-1gx04jgn.js → library.command-ccb1cp92.js} +3 -3
  45. package/{localRegistry.command-zndxj1q6.js → localRegistry.command-pgbr7vjj.js} +8 -7
  46. package/{module.command-3waddk95.js → module.command-5k6h407d.js} +5 -5
  47. package/{package.command-zrc7br1y.js → package.command-e6ntvpez.js} +3 -3
  48. package/package.json +2 -3
  49. package/{page.command-vpjgardh.js → page.command-v4f90wb8.js} +3 -3
  50. package/{primitive.command-sz84tk4t.js → primitive.command-g6km57q5.js} +6 -6
  51. package/{quality.command-g869hafs.js → quality.command-de3p36pz.js} +5 -4
  52. package/{repair.command-chsnjvvv.js → repair.command-d3x1javq.js} +5 -5
  53. package/{scalar.command-2v21newx.js → scalar.command-7ezrac2b.js} +4 -4
  54. package/{subspace.command-ckcbwfp1.js → subspace.command-g2tq9nrn.js} +4 -4
  55. package/templates/workspaceRoot/.gitignore.template +0 -1
  56. package/{tunnel.command-kd2yr4fx.js → tunnel.command-hsrv2mny.js} +2 -2
  57. package/{workflow.command-44252cqv.js → workflow.command-z2p32nmf.js} +10 -10
  58. package/{workspace.command-fqcztt5p.js → workspace.command-s82wd61q.js} +20 -20
  59. package/applicationReleasePackager-esnrphw8.js +0 -224
  60. package/capacitorApp-1synz4en.js +0 -11
  61. package/cloud.script-bkbpcr96.js +0 -19
  62. package/context.runner-k99nb5pk.js +0 -21
  63. package/index-5e0n4hqx.js +0 -75
  64. package/index-mxav6j3c.js +0 -1377
package/index-mxav6j3c.js DELETED
@@ -1,1377 +0,0 @@
1
- // @bun
2
- import {
3
- CommandExecutionError
4
- } from "./index-9d9bgcx4.js";
5
- import {
6
- resolveMobilePath,
7
- targetHtmlFilename
8
- } from "./index-5e0n4hqx.js";
9
-
10
- // pkgs/@akanjs/devkit/capacitorApp.ts
11
- import { cp, mkdir, readFile, rm, writeFile } from "fs/promises";
12
- import os from "os";
13
- import path from "path";
14
- import { select } from "@inquirer/prompts";
15
- import { MobileProject } from "@trapezedev/project";
16
- import { capitalize, isRecord } from "akanjs/common";
17
-
18
- // pkgs/@akanjs/devkit/fileEditor.ts
19
- class FileEditor {
20
- #filePath;
21
- #content;
22
- constructor(filePath, content) {
23
- this.#filePath = filePath;
24
- this.#content = content;
25
- }
26
- static async create(filePath) {
27
- try {
28
- const content = await Bun.file(filePath).text();
29
- return new FileEditor(filePath, content);
30
- } catch (_error) {
31
- throw new Error(`Failed to read file: ${filePath}`);
32
- }
33
- }
34
- find(pattern) {
35
- const regex = typeof pattern === "string" ? new RegExp(pattern) : pattern;
36
- return this.#content.split(`
37
- `).findIndex((line) => !!line && regex.test(line));
38
- }
39
- findAll(pattern) {
40
- const regex = typeof pattern === "string" ? new RegExp(pattern) : pattern;
41
- return this.#content.split(`
42
- `).flatMap((line, index) => line && regex.test(line) ? [index] : []);
43
- }
44
- insertAfter(pattern, data) {
45
- return this.#insertAt(pattern, data, 1);
46
- }
47
- insertBefore(pattern, data) {
48
- return this.#insertAt(pattern, data, 0);
49
- }
50
- #insertAt(pattern, data, offset) {
51
- const lineIndex = this.find(pattern);
52
- if (lineIndex === -1)
53
- throw new Error(`Pattern not found: ${pattern}`);
54
- const lines = this.#content.split(`
55
- `);
56
- lines.splice(lineIndex + offset, 0, data);
57
- this.#content = lines.join(`
58
- `);
59
- return this;
60
- }
61
- replace(pattern, replacement) {
62
- const regex = typeof pattern === "string" ? new RegExp(pattern, "g") : pattern;
63
- this.#content = this.#content.replace(regex, replacement);
64
- return this;
65
- }
66
- append(data) {
67
- this.#content += `
68
- ${data}`;
69
- return this;
70
- }
71
- prepend(data) {
72
- this.#content = `${data}
73
- ${this.#content}`;
74
- return this;
75
- }
76
- async save() {
77
- try {
78
- await Bun.write(this.#filePath, this.#content);
79
- } catch (_error) {
80
- throw new Error(`Failed to save file: ${this.#filePath}`);
81
- }
82
- }
83
- getContent() {
84
- return this.#content;
85
- }
86
- setContent(content) {
87
- this.#content = content;
88
- return this;
89
- }
90
- }
91
-
92
- // pkgs/@akanjs/devkit/capacitorApp.ts
93
- var SWIFTUICORE_MIN_IOS_MAJOR = 18;
94
- var iosNativeBlockedEnvKeys = new Set("AR AS CC CFLAGS CONDA_BUILD_SYSROOT CONDA_PREFIX CPP CPPFLAGS CPATH CXX CXXFLAGS LD LDFLAGS LIBRARY_PATH".split(" ").concat("MACOSX_DEPLOYMENT_TARGET NM OBJC OBJCXX PREFIX RANLIB SDKROOT STRIP".split(" ")));
95
- var rootCapacitorConfigFilenames = [
96
- "capacitor.config.ts",
97
- "capacitor.config.js",
98
- "capacitor.config.json"
99
- ];
100
- var rootCapacitorConfigPaths = (appRoot) => rootCapacitorConfigFilenames.map((file) => path.join(appRoot, file));
101
- async function clearRootCapacitorConfigs(appRoot) {
102
- await Promise.all(rootCapacitorConfigPaths(appRoot).map((file) => rm(file, { force: true })));
103
- }
104
- async function writeRootCapacitorConfig(appRoot, content) {
105
- await clearRootCapacitorConfigs(appRoot);
106
- await Bun.write(path.join(appRoot, "capacitor.config.json"), content);
107
- }
108
- var virtualInterfacePrefixes = "bridge utun llw awdl ap vmnet vnic tap tun docker veth vboxnet gif stf".split(" ");
109
- var physicalInterfacePrefixes = ["en", "eth", "wlan", "wlp", "enp", "eno", "wlo"];
110
- var isPrivateLanIpv4 = (address) => {
111
- if (address.startsWith("10.") || address.startsWith("192.168."))
112
- return true;
113
- const secondOctet = Number(address.match(/^172\.(\d+)\./)?.[1]);
114
- return Number.isFinite(secondOctet) && secondOctet >= 16 && secondOctet <= 31;
115
- };
116
- var scoreDevHostCandidate = (name, address) => {
117
- const lowerName = name.toLowerCase();
118
- let score = 0;
119
- if (address.startsWith("169.254."))
120
- score -= 1000;
121
- if (virtualInterfacePrefixes.some((prefix) => lowerName.startsWith(prefix)))
122
- score -= 100;
123
- else if (physicalInterfacePrefixes.some((prefix) => lowerName.startsWith(prefix)))
124
- score += 100;
125
- if (isPrivateLanIpv4(address))
126
- score += 10;
127
- return score;
128
- };
129
- var selectLocalDevHost = (interfaces, { override } = {}) => {
130
- const candidates = [];
131
- for (const [name, aliases] of Object.entries(interfaces)) {
132
- for (const alias of aliases ?? []) {
133
- if (alias.family !== "IPv4" || alias.internal)
134
- continue;
135
- candidates.push({ name, address: alias.address });
136
- }
137
- }
138
- const trimmedOverride = override?.trim();
139
- if (trimmedOverride)
140
- return { host: trimmedOverride, source: "override", candidates };
141
- const [best] = [...candidates].sort((a, b) => scoreDevHostCandidate(b.name, b.address) - scoreDevHostCandidate(a.name, a.address) || a.name.localeCompare(b.name) || a.address.localeCompare(b.address));
142
- return best ? { host: best.address, source: "detected", candidates } : { host: "127.0.0.1", source: "loopback", candidates };
143
- };
144
- var asString = (value) => typeof value === "string" ? value : undefined;
145
- var firstString = (...values) => values.find((value) => typeof value === "string");
146
- var scoreIosDeviceTarget = (target) => {
147
- const state = target.state?.toLowerCase() ?? "";
148
- return (state.includes("available") ? 4 : 0) + (state.includes("wired") ? 2 : 0) + (state.includes("paired") ? 1 : 0);
149
- };
150
- var dedupeIosRunTargets = (targets) => {
151
- const byKey = new Map;
152
- const runnableTargets = targets.filter((target) => !target.state?.toLowerCase().includes("unavailable"));
153
- for (const target of runnableTargets) {
154
- const key = target.xcodebuildId ?? target.id;
155
- const current = byKey.get(key);
156
- if (!current || scoreIosDeviceTarget(target) > scoreIosDeviceTarget(current))
157
- byKey.set(key, target);
158
- }
159
- return [...byKey.values()];
160
- };
161
- var formatSimctlRuntime = (key) => {
162
- if (!key)
163
- return;
164
- if (/^(iOS|watchOS|tvOS|visionOS)\s+[\d.]+$/i.test(key))
165
- return key;
166
- const match = key.match(/(iOS|watchOS|tvOS|visionOS)-(\d+)(?:-(\d+))?/i);
167
- if (!match)
168
- return;
169
- return `${match[1]} ${match[2]}${match[3] ? `.${match[3]}` : ""}`;
170
- };
171
- var parseIosRuntimeMajor = (runtime) => {
172
- const major = runtime?.match(/\d+/)?.[0];
173
- return major === undefined ? undefined : Number.parseInt(major, 10);
174
- };
175
- var iosRunTargetRank = (target) => {
176
- const state = target.state?.toLowerCase() ?? "";
177
- const ready = state.includes("booted") || state.includes("connected") || state.includes("available") ? 1000 : 0;
178
- const device = target.kind === "device" ? 500 : 0;
179
- return ready + device + (parseIosRuntimeMajor(target.runtime) ?? 0);
180
- };
181
- var sortIosRunTargets = (targets) => [...targets].sort((a, b) => iosRunTargetRank(b) - iosRunTargetRank(a) || a.name.localeCompare(b.name));
182
- function walkRecords(value, visit) {
183
- if (Array.isArray(value)) {
184
- for (const item of value)
185
- walkRecords(item, visit);
186
- return;
187
- }
188
- if (!isRecord(value))
189
- return;
190
- visit(value);
191
- for (const item of Object.values(value))
192
- walkRecords(item, visit);
193
- }
194
- function parseDevicectlDevices(output) {
195
- try {
196
- const json = JSON.parse(output);
197
- const targets = new Map;
198
- walkRecords(json, (record) => {
199
- const deviceProperties = isRecord(record.deviceProperties) ? record.deviceProperties : {};
200
- const hardwareProperties = isRecord(record.hardwareProperties) ? record.hardwareProperties : {};
201
- const connectionProperties = isRecord(record.connectionProperties) ? record.connectionProperties : {};
202
- const devicectlId = firstString(record.identifier, record.deviceIdentifier);
203
- const potentialHostnames = Array.isArray(connectionProperties.potentialHostnames) ? connectionProperties.potentialHostnames.filter((value) => typeof value === "string") : [];
204
- const hostnameUdid = potentialHostnames.map((hostname) => hostname.match(/([0-9A-Fa-f]{8}-[0-9A-Fa-f]{16})\.coredevice\.local/)?.[1]).find((value) => Boolean(value));
205
- const udid = firstString(hardwareProperties.udid, hostnameUdid, record.udid, record.UDID);
206
- const id = udid ?? devicectlId;
207
- const name = firstString(deviceProperties.name, record.name, record.deviceName, record.displayName);
208
- if (!id || !name)
209
- return;
210
- const state = [
211
- firstString(record.state, record.connectionState, record.availability, connectionProperties.tunnelState),
212
- firstString(connectionProperties.transportType),
213
- firstString(connectionProperties.pairingState)
214
- ].filter(Boolean).join(" ");
215
- targets.set(id, { id, name, kind: "device", state, devicectlId, xcodebuildId: udid ?? id });
216
- });
217
- return dedupeIosRunTargets([...targets.values()]);
218
- } catch {
219
- const targets = [];
220
- for (const line of output.split(/\r?\n/)) {
221
- const id = line.match(/[0-9A-Fa-f]{8}-[0-9A-Fa-f]{16}|[0-9A-Fa-f-]{25,}/)?.[0];
222
- if (!id)
223
- continue;
224
- const name = line.replace(id, "").replace(/[()]/g, " ").trim().replace(/\s+/g, " ") || id;
225
- targets.push({ id, name, kind: "device" });
226
- }
227
- return dedupeIosRunTargets(targets);
228
- }
229
- }
230
- function parseSimctlDevices(output) {
231
- try {
232
- const json = JSON.parse(output);
233
- const devices = json.devices ?? {};
234
- return Object.entries(devices).flatMap(([runtimeKey, list]) => {
235
- const runtime = formatSimctlRuntime(runtimeKey);
236
- return (Array.isArray(list) ? list : []).filter(isRecord).flatMap((device) => {
237
- const id = firstString(device.udid, device.UDID, device.identifier);
238
- const name = firstString(device.name, device.displayName);
239
- const isAvailable = device.isAvailable !== false && device.availabilityError === undefined;
240
- if (!id || !name || !isAvailable)
241
- return [];
242
- return [
243
- {
244
- id,
245
- name,
246
- kind: "simulator",
247
- state: asString(device.state),
248
- runtime: runtime ?? formatSimctlRuntime(asString(device.runtimeIdentifier))
249
- }
250
- ];
251
- });
252
- });
253
- } catch {
254
- const targets = [];
255
- let runtime;
256
- for (const line of output.split(/\r?\n/)) {
257
- const header = line.match(/^--\s*(.+?)\s*--\s*$/);
258
- if (header) {
259
- runtime = formatSimctlRuntime(header[1]);
260
- continue;
261
- }
262
- const match = line.match(/^\s*(.+?)\s+\(([0-9A-Fa-f-]{20,})\)\s+\(([^)]+)\)/);
263
- if (!match)
264
- continue;
265
- targets.push({ id: match[2], name: match[1].trim(), kind: "simulator", state: match[3], runtime });
266
- }
267
- return targets;
268
- }
269
- }
270
- function buildIosNativeRunCommand({
271
- appRoot,
272
- device,
273
- scheme = "App",
274
- configuration = "Debug"
275
- }) {
276
- const derivedDataPath = path.join(appRoot, "ios/DerivedData", device.id);
277
- const productPlatform = device.kind === "device" ? "iphoneos" : "iphonesimulator";
278
- const destination = device.kind === "device" ? `id=${device.xcodebuildId ?? device.id}` : `platform=iOS Simulator,id=${device.id}`;
279
- return {
280
- configuration,
281
- derivedDataPath,
282
- appPath: path.join(derivedDataPath, "Build/Products", `${configuration}-${productPlatform}`, "App.app"),
283
- xcodebuildArgs: [
284
- "-project",
285
- "App.xcodeproj",
286
- "-scheme",
287
- scheme,
288
- "-configuration",
289
- configuration,
290
- "-destination",
291
- destination,
292
- "-derivedDataPath",
293
- derivedDataPath,
294
- "build"
295
- ]
296
- };
297
- }
298
- function classifyIosRunFailure(log) {
299
- const lower = log.toLowerCase();
300
- if (lower.includes("swiftuicore") && (lower.includes("library not loaded") || lower.includes("library missing") || lower.includes("dyld"))) {
301
- return {
302
- kind: "simulator-runtime",
303
- title: "App crashed loading SwiftUICore \u2014 the iOS runtime is too old.",
304
- detail: `The build links SwiftUICore, which only exists on iOS ${SWIFTUICORE_MIN_IOS_MAJOR}+. Rerun on an iOS ${SWIFTUICORE_MIN_IOS_MAJOR} or newer simulator/device (pass --device to pick one non-interactively).`
305
- };
306
- }
307
- if (lower.includes("unknown argument: '-index-store-path'") || lower.includes("compiler was not recognized")) {
308
- return {
309
- kind: "compiler-toolchain",
310
- title: "iOS build is using a non-Xcode compiler from the shell environment.",
311
- detail: "Akan removes common Conda/compiler environment variables for native iOS runs. If this persists, run outside the activated toolchain environment."
312
- };
313
- }
314
- if (lower.includes("developer mode") && lower.includes("disabled")) {
315
- return {
316
- kind: "device-state",
317
- title: "iOS device Developer Mode is disabled.",
318
- detail: "Enable Developer Mode on the iPhone, then reconnect and run the command again."
319
- };
320
- }
321
- if (lower.includes("untrusted") || lower.includes("not paired") || lower.includes("locked")) {
322
- return {
323
- kind: "device-state",
324
- title: "iOS device is not ready for installation.",
325
- detail: "Unlock the iPhone, trust this computer, and make sure the device is paired before retrying."
326
- };
327
- }
328
- if (lower.includes('unable to find utility "devicectl"') || lower.includes("devicectl") && lower.includes("not found")) {
329
- return {
330
- kind: "devicectl-unavailable",
331
- title: "Xcode devicectl is not available.",
332
- detail: "Install a recent Xcode version and verify xcode-select points to that Xcode installation."
333
- };
334
- }
335
- if (lower.includes("there are no accounts registered with xcode") || lower.includes("unable to log in with account")) {
336
- return {
337
- kind: "apple-account",
338
- title: "Xcode Apple ID is not available.",
339
- detail: "Sign in to an Apple ID in Xcode Settings > Accounts, then retry the Akan iOS command."
340
- };
341
- }
342
- if (lower.includes("failed registering bundle identifier") || lower.includes("cannot be registered to your development team")) {
343
- return {
344
- kind: "bundle-identifier",
345
- title: "iOS bundle identifier is not available for this Apple Developer Team.",
346
- detail: "Change mobile appId to a globally unique bundle identifier that your team can register, then rerun the iOS command."
347
- };
348
- }
349
- if (lower.includes("does not have permission") || lower.includes("your account") && lower.includes("permission")) {
350
- return {
351
- kind: "team-permission",
352
- title: "Apple Developer Team permission is missing.",
353
- detail: "Check that the signed-in Apple ID has permission for the selected DEVELOPMENT_TEAM."
354
- };
355
- }
356
- if (lower.includes("license agreement") || lower.includes("program license agreement")) {
357
- return {
358
- kind: "license-agreement",
359
- title: "Apple Developer Program license agreement is not accepted.",
360
- detail: "Accept the latest Apple Developer Program license agreement, then retry."
361
- };
362
- }
363
- if (lower.includes("no signing certificate") || lower.includes("doesn't include signing certificate")) {
364
- return {
365
- kind: "certificate",
366
- title: "iOS development signing certificate is missing.",
367
- detail: "Create or download an Apple Development certificate for the selected team."
368
- };
369
- }
370
- if (lower.includes("device") && lower.includes("not") && lower.includes("registered")) {
371
- return {
372
- kind: "device-registration",
373
- title: "iPhone is not registered in the provisioning profile.",
374
- detail: "Allow provisioning updates with a team that can register this device, or register the device manually."
375
- };
376
- }
377
- if (lower.includes("no profiles for") || lower.includes("requires a provisioning profile")) {
378
- return {
379
- kind: "provisioning-profile",
380
- title: "Matching iOS provisioning profile was not found.",
381
- detail: "Akan can request Xcode provisioning updates for physical devices, but the Apple account and team must be valid."
382
- };
383
- }
384
- return {
385
- kind: "unknown",
386
- title: "iOS native run failed.",
387
- detail: "Review the xcodebuild/devicectl output above. You can retry with --no-allow-provisioning-updates to use the conservative path."
388
- };
389
- }
390
- function formatIosRunFailureMessage(input) {
391
- return [
392
- input.classification.title,
393
- input.classification.detail,
394
- `Mobile target: ${input.targetName}`,
395
- `Bundle ID: ${input.appId}`,
396
- input.teamId ? `Development Team: ${input.teamId}` : null,
397
- "Capacitor is still used for native project generation and sync; Akan only runs the native build/install step directly."
398
- ].filter((line) => Boolean(line)).join(`
399
- `);
400
- }
401
- function sanitizeIosNativeRunEnv(env) {
402
- return Object.fromEntries(Object.entries(env).filter(([key]) => !iosNativeBlockedEnvKeys.has(key)));
403
- }
404
- var PLACEHOLDER_APP_IDS = [
405
- "com.myapp.app",
406
- "com.myorg.myapp",
407
- "com.example.app",
408
- "com.example.myapp"
409
- ];
410
- var placeholderAppIdSegment = /^(example|examples|myorg|myapp|mycompany|myorganization|changeme|todo|sample|test)$/;
411
- var isPlaceholderAppId2 = (appId) => {
412
- const normalized = appId?.trim().toLowerCase() ?? "";
413
- if (!normalized)
414
- return true;
415
- if (PLACEHOLDER_APP_IDS.includes(normalized))
416
- return true;
417
- return normalized.split(".").some((segment) => placeholderAppIdSegment.test(segment));
418
- };
419
- var androidReleaseSigningKeys = [
420
- "MYAPP_RELEASE_STORE_FILE",
421
- "MYAPP_RELEASE_STORE_PASSWORD",
422
- "MYAPP_RELEASE_KEY_ALIAS",
423
- "MYAPP_RELEASE_KEY_PASSWORD"
424
- ];
425
- function getMissingAndroidReleaseSigningKeys({
426
- env = process.env,
427
- gradleProperties = ""
428
- } = {}) {
429
- return androidReleaseSigningKeys.filter((key) => {
430
- const gradleEnvKey = `ORG_GRADLE_PROJECT_${key}`;
431
- return env[key] === undefined && env[gradleEnvKey] === undefined && !new RegExp(`^\\s*${key}\\s*=`, "m").test(gradleProperties);
432
- });
433
- }
434
- function formatAndroidReleaseSigningError(missingKeys) {
435
- return [
436
- "Android release signing configuration is incomplete.",
437
- `Missing: ${missingKeys.join(", ")}`,
438
- "Set these values in android/gradle.properties or ORG_GRADLE_PROJECT_* environment variables before building a release artifact."
439
- ].join(`
440
- `);
441
- }
442
- function getAdbDeviceStateIssues(output) {
443
- return output.split(/\r?\n/).map((line) => line.trim().split(/\s+/)).filter(([id, state]) => id && state && id !== "List").flatMap(([id, state]) => {
444
- if (state === "unauthorized")
445
- return [`Android device ${id} is unauthorized. Confirm USB debugging authorization on the device.`];
446
- if (state === "offline")
447
- return [`Android device ${id} is offline. Reconnect the device or restart adb.`];
448
- return [];
449
- });
450
- }
451
- function getAndroidLocalServerHost(adbDevicesOutput, fallbackHost) {
452
- const onlineDeviceIds = adbDevicesOutput?.split(/\r?\n/).map((line) => line.trim().split(/\s+/)).filter(([id, state]) => id && state === "device").map(([id]) => id) ?? [];
453
- return onlineDeviceIds.length === 1 && onlineDeviceIds[0]?.startsWith("emulator-") ? "10.0.2.2" : fallbackHost;
454
- }
455
- var ANDROID_MIN_SDK_VERSION = 26;
456
- function raiseGradleMinSdkVersion(content, floor = ANDROID_MIN_SDK_VERSION) {
457
- const match = content.match(/minSdkVersion\s*=\s*(\d+)/);
458
- if (!match?.[1])
459
- return null;
460
- const current = Number.parseInt(match[1], 10);
461
- if (Number.isNaN(current) || current >= floor)
462
- return null;
463
- return content.replace(/(minSdkVersion\s*=\s*)\d+/, `$1${floor}`);
464
- }
465
- var iosUsageDescriptionKeys = {
466
- cameraUsageDescription: ["NSCameraUsageDescription"],
467
- photoAddUsageDescription: ["NSPhotoLibraryAddUsageDescription"],
468
- photoUsageDescription: ["NSPhotoLibraryUsageDescription"],
469
- contactsUsageDescription: ["NSContactsUsageDescription"],
470
- locationAlwaysUsageDescription: ["NSLocationAlwaysAndWhenInUseUsageDescription", "NSLocationAlwaysUsageDescription"],
471
- locationWhenInUseUsageDescription: ["NSLocationWhenInUseUsageDescription"],
472
- microphoneUsageDescription: ["NSMicrophoneUsageDescription"],
473
- speechRecognitionUsageDescription: ["NSSpeechRecognitionUsageDescription"]
474
- };
475
- var toIosInfoPlistUsageDescriptions = (descriptions) => Object.fromEntries(Object.entries(descriptions).flatMap(([key, value]) => {
476
- const plistKeys = Object.hasOwn(iosUsageDescriptionKeys, key) ? iosUsageDescriptionKeys[key] : [`NS${capitalize(key)}`];
477
- return plistKeys.map((plistKey) => [plistKey, value]);
478
- }));
479
- var mergeAllowNavigation = (configured, localIp) => {
480
- const values = Array.isArray(configured) ? configured.filter((value) => typeof value === "string") : [];
481
- if (localIp)
482
- values.push(localIp);
483
- values.push("localhost");
484
- return [...new Set(values)];
485
- };
486
- function assertJsonSerializable(value, label = "capacitor.config", seen = new WeakSet) {
487
- if (value === null)
488
- return;
489
- const valueType = typeof value;
490
- if (valueType === "function" || valueType === "symbol" || valueType === "bigint" || valueType === "undefined") {
491
- throw new Error(`${label} must be JSON serializable. Found ${valueType}.`);
492
- }
493
- if (valueType === "number" && !Number.isFinite(value)) {
494
- throw new Error(`${label} must be JSON serializable. Found non-finite number.`);
495
- }
496
- if (valueType !== "object")
497
- return;
498
- const objectValue = value;
499
- if (seen.has(objectValue))
500
- throw new Error(`${label} must be JSON serializable. Found circular reference.`);
501
- seen.add(objectValue);
502
- if (Array.isArray(value)) {
503
- for (const [index, item] of value.entries())
504
- assertJsonSerializable(item, `${label}[${index}]`, seen);
505
- return;
506
- }
507
- for (const [key, item] of Object.entries(value)) {
508
- assertJsonSerializable(item, `${label}.${key}`, seen);
509
- }
510
- }
511
- function materializeCapacitorConfig(target, { operation, localServerUrl, localIp }) {
512
- const {
513
- name,
514
- basePath: _basePath,
515
- indexPath: _indexPath,
516
- version: _version,
517
- buildNum: _buildNum,
518
- assets: _assets,
519
- permissions: _permissions,
520
- deepLinks: _deepLinks,
521
- files: _files,
522
- appId,
523
- appName,
524
- webDir: _webDir,
525
- plugins,
526
- server,
527
- android,
528
- ios,
529
- cordova,
530
- experimental,
531
- ...capacitorConfig
532
- } = target;
533
- const serverConfig = isRecord(server) ? server : undefined;
534
- const cordovaConfig = isRecord(cordova) ? cordova : undefined;
535
- const experimentalConfig = isRecord(experimental) ? experimental : undefined;
536
- const pluginsConfig = isRecord(plugins) ? plugins : {};
537
- const keyboardPluginConfig = isRecord(pluginsConfig.Keyboard) ? pluginsConfig.Keyboard : {};
538
- const pushNotificationsPluginConfig = isRecord(pluginsConfig.PushNotifications) ? pluginsConfig.PushNotifications : {};
539
- const usesPushNotifications = target.permissions?.includes("push") ?? false;
540
- const config = {
541
- ...capacitorConfig,
542
- appId,
543
- appName,
544
- webDir: path.posix.join(".akan", "mobile", name, "www"),
545
- plugins: {
546
- CapacitorCookies: { enabled: true },
547
- ...pluginsConfig,
548
- ...usesPushNotifications || isRecord(pluginsConfig.PushNotifications) ? {
549
- PushNotifications: {
550
- ...usesPushNotifications ? { presentationOptions: ["badge", "sound", "alert"] } : {},
551
- ...pushNotificationsPluginConfig
552
- }
553
- } : {},
554
- Keyboard: {
555
- resize: "none",
556
- ...keyboardPluginConfig
557
- }
558
- },
559
- android: {
560
- ...isRecord(android) ? android : {},
561
- path: "android"
562
- },
563
- ios: {
564
- ...isRecord(ios) ? ios : {},
565
- path: "ios"
566
- }
567
- };
568
- if (operation === "local") {
569
- if (!localServerUrl)
570
- throw new Error(`Local server URL is required for mobile target '${name}'.`);
571
- config.server = {
572
- ...serverConfig,
573
- androidScheme: "http",
574
- url: localServerUrl,
575
- cleartext: true,
576
- allowNavigation: mergeAllowNavigation(serverConfig?.allowNavigation, localIp)
577
- };
578
- } else if (serverConfig && Object.keys(serverConfig).length > 0) {
579
- config.server = serverConfig;
580
- }
581
- if (cordovaConfig && Object.keys(cordovaConfig).length > 0) {
582
- config.cordova = cordovaConfig;
583
- }
584
- if (experimentalConfig && Object.keys(experimentalConfig).length > 0) {
585
- config.experimental = experimentalConfig;
586
- }
587
- assertJsonSerializable(config);
588
- return config;
589
- }
590
-
591
- class CapacitorApp2 {
592
- app;
593
- target;
594
- project;
595
- iosTargetName = "App";
596
- targetRoot;
597
- targetRootPath;
598
- targetWebRoot;
599
- targetAssetRoot;
600
- iosRootPath = "ios";
601
- iosProjectPath = "ios/App";
602
- androidRootPath = "android";
603
- androidAssetsPath = "android/app/src/main/assets";
604
- #iosEntitlements = {};
605
- constructor(app, target) {
606
- this.app = app;
607
- this.target = target;
608
- this.targetRootPath = path.posix.join(".akan", "mobile", this.target.name);
609
- this.targetRoot = path.join(this.app.cwdPath, this.targetRootPath);
610
- this.targetWebRoot = path.join(this.targetRoot, "www");
611
- this.targetAssetRoot = path.join(this.targetRoot, "assets");
612
- this.project = new MobileProject(this.app.cwdPath, {
613
- android: { path: this.androidRootPath },
614
- ios: { path: this.iosProjectPath }
615
- });
616
- }
617
- async init({
618
- platform,
619
- operation = "release",
620
- env = "debug",
621
- regenerate = false
622
- } = {}) {
623
- await mkdir(this.targetRoot, { recursive: true });
624
- if (regenerate) {
625
- if (!platform || platform === "ios")
626
- await rm(path.join(this.app.cwdPath, this.iosRootPath), { recursive: true, force: true });
627
- if (!platform || platform === "android")
628
- await rm(path.join(this.app.cwdPath, this.androidRootPath), { recursive: true, force: true });
629
- }
630
- const project = this.project;
631
- await this.project.load();
632
- if ((!platform || platform === "android") && !project.android) {
633
- await this.#spawnMobile("npx", ["cap", "add", "android"], { operation, env });
634
- await this.project.load();
635
- }
636
- if ((!platform || platform === "ios") && !project.ios) {
637
- await this.#spawnMobile("npx", ["cap", "add", "ios"], { operation, env });
638
- await this.project.load();
639
- }
640
- return this;
641
- }
642
- async save() {
643
- await this.project.commit();
644
- }
645
- async#prepareIos({ operation, env, regenerate = false, iosRunTargetKind }) {
646
- await this.init({ platform: "ios", operation, env, regenerate });
647
- await this.#prepareTargetAssets();
648
- await this.#prepareExternalFiles("ios");
649
- await this.#applyIosMetadata();
650
- await this.#applyPermissions({ operation, env });
651
- await this.#applyDeepLinks("ios", { operation, env });
652
- await this.#flushIosEntitlements();
653
- await this.project.commit();
654
- await this.#setCodeSignEntitlementsInIosIfExists("App/App.entitlements");
655
- await this.#generateAssets({ operation, env });
656
- this.app.verbose(`syncing iOS`);
657
- await this.#spawnMobile("npx", ["cap", "sync", "ios"], { operation, env }, { iosRunTargetKind });
658
- this.app.verbose(`sync completed.`);
659
- }
660
- async buildIos({ env = "debug", regenerate = false } = {}) {
661
- await this.prepareWww();
662
- await this.#prepareIos({ operation: "release", env, regenerate });
663
- await this.#spawnMobile("npx", ["cap", "build", "ios"], { operation: "release", env }, { stdio: "inherit" });
664
- this.app.verbose(`build completed iOS.`);
665
- }
666
- async syncIos() {
667
- await this.#spawnMobile("npx", ["cap", "sync", "ios"], { operation: "local", env: "local" });
668
- }
669
- async openIos() {
670
- await this.#spawnMobile("npx", ["cap", "open", "ios"], { operation: "local", env: "local" });
671
- }
672
- async runIos({ operation, env, regenerate = false, noAllowProvisioningUpdates = false, iosDeviceId }) {
673
- if (operation === "release")
674
- await this.prepareWww();
675
- const runTarget = await this.#selectIosRunTarget(iosDeviceId);
676
- await this.#prepareIos({ operation, env, regenerate, iosRunTargetKind: runTarget.kind });
677
- if (runTarget.kind === "simulator") {
678
- await this.#spawnMobile("npx", ["cap", "run", "ios", "--target", runTarget.id, "--no-sync"], { operation, env }, { stdio: "inherit", platform: "ios", iosRunTargetKind: runTarget.kind });
679
- return;
680
- }
681
- await this.#runIosPhysicalDevice({ operation, env, runTarget, noAllowProvisioningUpdates });
682
- }
683
- async#selectIosRunTarget(deviceId) {
684
- const targets = sortIosRunTargets([
685
- ...await this.#loadPhysicalIosDevices(),
686
- ...await this.#loadIosSimulators()
687
- ]);
688
- if (deviceId) {
689
- const needle = deviceId.toLowerCase();
690
- const found = targets.find((target) => target.id === deviceId) ?? targets.find((target) => target.name.toLowerCase() === needle) ?? targets.find((target) => target.name.toLowerCase().includes(needle) || target.id.toLowerCase().includes(needle) || (target.runtime?.toLowerCase().includes(needle) ?? false));
691
- if (!found) {
692
- const available = targets.map((t) => `${t.name}${t.runtime ? ` (${t.runtime})` : ""}`).join(", ") || "none";
693
- throw new Error(`iOS run target '${deviceId}' was not found. Available: ${available}`);
694
- }
695
- this.#warnIfLegacySimulatorRuntime(found);
696
- return found;
697
- }
698
- if (targets.length === 0) {
699
- throw new Error("No iOS run targets found. Open Simulator or connect an iPhone, then retry.");
700
- }
701
- const selected = await select({
702
- message: "Select iOS run target",
703
- choices: targets.map((target) => ({
704
- name: `[${target.kind}] ${target.name}${target.runtime ? ` \u2014 ${target.runtime}` : ""}${target.state ? ` (${target.state})` : ""}`,
705
- value: target
706
- }))
707
- });
708
- this.#warnIfLegacySimulatorRuntime(selected);
709
- return selected;
710
- }
711
- #warnIfLegacySimulatorRuntime(target) {
712
- if (target.kind !== "simulator")
713
- return;
714
- const major = parseIosRuntimeMajor(target.runtime);
715
- if (major === undefined || major >= SWIFTUICORE_MIN_IOS_MAJOR)
716
- return;
717
- this.app.logger.warn(`Selected simulator runs ${target.runtime ?? "an older iOS"}. Recent SDK builds link SwiftUICore and require iOS ${SWIFTUICORE_MIN_IOS_MAJOR}+; if the app crashes at launch with a "Library not loaded: SwiftUICore" dyld error, pick an iOS ${SWIFTUICORE_MIN_IOS_MAJOR}+ simulator instead.`);
718
- }
719
- async#loadPhysicalIosDevices() {
720
- try {
721
- return parseDevicectlDevices(await this.#spawn("xcrun", ["devicectl", "list", "devices", "--json-output", "-"]));
722
- } catch (jsonError) {
723
- try {
724
- return parseDevicectlDevices(await this.#spawn("xcrun", ["devicectl", "list", "devices"]));
725
- } catch (textError) {
726
- const classification = classifyIosRunFailure(`${jsonError instanceof Error ? jsonError.message : ""}
727
- ${textError instanceof Error ? textError.message : ""}`);
728
- if (classification.kind === "devicectl-unavailable")
729
- this.app.logger.warn(classification.detail);
730
- return [];
731
- }
732
- }
733
- }
734
- async#loadIosSimulators() {
735
- try {
736
- return parseSimctlDevices(await this.#spawn("xcrun", ["simctl", "list", "devices", "available", "--json"]));
737
- } catch {
738
- try {
739
- return parseSimctlDevices(await this.#spawn("xcrun", ["simctl", "list", "devices", "available"]));
740
- } catch {
741
- return [];
742
- }
743
- }
744
- }
745
- async#runIosPhysicalDevice({
746
- operation,
747
- env,
748
- runTarget,
749
- noAllowProvisioningUpdates
750
- }) {
751
- const mobileEnv = sanitizeIosNativeRunEnv(await this.#commandEnv(operation, env));
752
- const configContent = await this.#writeCapacitorConfig({ operation, platform: "ios", iosRunTargetKind: runTarget.kind }, mobileEnv);
753
- await writeRootCapacitorConfig(this.app.cwdPath, configContent);
754
- const command = buildIosNativeRunCommand({
755
- appRoot: this.app.cwdPath,
756
- device: runTarget,
757
- scheme: isRecord(this.target.ios) && typeof this.target.ios.scheme === "string" ? this.target.ios.scheme : "App",
758
- configuration: operation === "release" ? "Release" : "Debug"
759
- });
760
- const xcodebuildArgs = noAllowProvisioningUpdates ? command.xcodebuildArgs : [...command.xcodebuildArgs.slice(0, -1), "-allowProvisioningUpdates", ...command.xcodebuildArgs.slice(-1)];
761
- try {
762
- await this.#spawn("xcodebuild", xcodebuildArgs, {
763
- cwd: path.join(this.app.cwdPath, this.iosProjectPath),
764
- env: mobileEnv
765
- });
766
- const devicectlId = runTarget.devicectlId ?? runTarget.id;
767
- const devicectl = (verb, subject) => this.#spawn("xcrun", ["devicectl", "device", ...verb, "--device", devicectlId, subject], { env: mobileEnv });
768
- await devicectl(["install", "app"], command.appPath);
769
- await devicectl(["process", "launch"], this.target.appId);
770
- } catch (error) {
771
- throw new Error(formatIosRunFailureMessage({
772
- classification: classifyIosRunFailure(this.#errorOutput(error)),
773
- appId: this.target.appId,
774
- targetName: this.target.name,
775
- teamId: await this.#getIosDevelopmentTeam()
776
- }));
777
- } finally {
778
- await clearRootCapacitorConfigs(this.app.cwdPath);
779
- }
780
- }
781
- async#getIosDevelopmentTeam() {
782
- const pbxprojPath = path.join(this.app.cwdPath, this.iosProjectPath, "App.xcodeproj/project.pbxproj");
783
- if (!await Bun.file(pbxprojPath).exists())
784
- return;
785
- return (await Bun.file(pbxprojPath).text()).match(/DEVELOPMENT_TEAM = ([^;]+);/)?.[1]?.trim();
786
- }
787
- #errorOutput(error) {
788
- if (error instanceof CommandExecutionError)
789
- return `${error.stdout}
790
- ${error.stderr}
791
- ${error.message}`;
792
- return error instanceof Error ? error.message : String(error);
793
- }
794
- async#prepareAndroid({ operation, env, regenerate = false }) {
795
- await this.init({ platform: "android", operation, env, regenerate });
796
- await this.#prepareTargetAssets();
797
- await this.#prepareExternalFiles("android");
798
- await this.#applyAndroidMetadata();
799
- await this.#applyAndroidMinSdkVersion();
800
- await this.#applyPermissions({ operation, env });
801
- await this.#applyDeepLinks("android", { operation, env });
802
- await this.#disableNativeKeyboardResizeInAndroid();
803
- await this.project.commit();
804
- await this.#generateAssets({ operation, env });
805
- await mkdir(path.join(this.app.cwdPath, this.androidAssetsPath), { recursive: true });
806
- await this.#ensureAndroidDebugKeystore();
807
- await this.#spawnMobile("npx", ["cap", "sync", "android"], { operation, env });
808
- await this.#setDeepLinksInAndroid(this.target.deepLinks?.schemes ?? [], this.target.deepLinks?.domains ?? []);
809
- }
810
- async#updateAndroidBuildTypes() {
811
- const appGradle = await FileEditor.create(path.join(this.app.cwdPath, this.androidRootPath, "app/build.gradle"));
812
- const buildTypesBlock = `
813
- debug {
814
- applicationIdSuffix ".debug"
815
- versionNameSuffix "-DEBUG"
816
- debuggable true
817
- minifyEnabled false
818
- }
819
- `;
820
- const singinConfigBlock = `
821
- signingConfigs {
822
- debug {
823
- storeFile file('debug.keystore')
824
- storePassword 'android'
825
- keyAlias 'androiddebugkey'
826
- keyPassword 'android'
827
- }
828
- release {
829
- if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) {
830
- storeFile file(MYAPP_RELEASE_STORE_FILE)
831
- storePassword MYAPP_RELEASE_STORE_PASSWORD
832
- keyAlias MYAPP_RELEASE_KEY_ALIAS
833
- keyPassword MYAPP_RELEASE_KEY_PASSWORD
834
- }
835
- }
836
- }
837
- `;
838
- if (appGradle.find("signingConfigs {") === -1) {
839
- appGradle.insertBefore("buildTypes {", singinConfigBlock);
840
- }
841
- if (appGradle.find(`applicationIdSuffix ".debug"`) === -1) {
842
- appGradle.insertAfter("buildTypes {", buildTypesBlock);
843
- }
844
- await appGradle.save();
845
- }
846
- async buildAndroid(assembleType, { env = "debug", regenerate = false } = {}) {
847
- await this.prepareWww();
848
- await this.#prepareAndroid({ operation: "release", env, regenerate });
849
- await this.#assertAndroidReleaseSigningConfig();
850
- await this.#updateAndroidBuildTypes();
851
- const gradleCommand = process.platform === "win32" ? "gradlew.bat" : "./gradlew";
852
- await this.app.spawn(gradleCommand, [assembleType === "apk" ? "assembleRelease" : "bundleRelease"], {
853
- stdio: "inherit",
854
- cwd: path.join(this.app.cwdPath, this.androidRootPath),
855
- env: await this.#commandEnv("release", env)
856
- });
857
- }
858
- async openAndroid() {
859
- await this.#spawnMobile("npx", ["cap", "open", "android"], { operation: "local", env: "local" });
860
- }
861
- async#disableNativeKeyboardResizeInAndroid() {
862
- const manifestPath = path.join(this.app.cwdPath, this.androidRootPath, "app/src/main/AndroidManifest.xml");
863
- let manifest = await readFile(manifestPath, "utf8");
864
- let changed = false;
865
- manifest = manifest.replace(/<activity\b[^>]*android:name="\.MainActivity"[^>]*>/, (activityTag) => {
866
- if (activityTag.includes("android:windowSoftInputMode=")) {
867
- const nextTag = activityTag.replace(/android:windowSoftInputMode="[^"]*"/, 'android:windowSoftInputMode="adjustNothing"');
868
- changed ||= nextTag !== activityTag;
869
- return nextTag;
870
- }
871
- changed = true;
872
- return activityTag.replace(/>$/, `
873
- android:windowSoftInputMode="adjustNothing">`);
874
- });
875
- if (changed)
876
- await writeFile(manifestPath, manifest);
877
- }
878
- async#ensureAndroidDebugKeystore() {
879
- const keystorePath = path.join(this.app.cwdPath, this.androidRootPath, "app/debug.keystore");
880
- if (await Bun.file(keystorePath).exists())
881
- return;
882
- const options = "-storepass android -alias androiddebugkey -keypass android -keyalg RSA -keysize 2048 -validity 10000";
883
- await this.#spawn("keytool", [
884
- "-genkeypair",
885
- "-v",
886
- "-keystore",
887
- keystorePath,
888
- ...options.split(" "),
889
- "-dname",
890
- "CN=Android Debug,O=Android,C=US"
891
- ]);
892
- }
893
- async syncAndroid(options = {}) {
894
- await this.prepareWww();
895
- await this.#prepareAndroid({ operation: "release", env: "debug", ...options });
896
- this.app.log(`Sync Android Completed.`);
897
- }
898
- async runAndroid({ operation, env, regenerate = false }) {
899
- if (operation === "release")
900
- await this.prepareWww();
901
- await this.#prepareAndroid({ operation, env, regenerate });
902
- await this.#assertAndroidAdbReady();
903
- this.app.logger.info(`Running Android in ${operation} mode on ${env} env`);
904
- await this.#spawnMobile("npx", ["cap", "run", "android"], { operation, env }, { stdio: "inherit" });
905
- }
906
- async#assertAndroidReleaseSigningConfig() {
907
- const gradlePropertiesPath = path.join(this.app.cwdPath, this.androidRootPath, "gradle.properties");
908
- const gradleProperties = await Bun.file(gradlePropertiesPath).exists() ? await Bun.file(gradlePropertiesPath).text() : "";
909
- const missingKeys = getMissingAndroidReleaseSigningKeys({ gradleProperties });
910
- if (missingKeys.length > 0)
911
- throw new Error(formatAndroidReleaseSigningError(missingKeys));
912
- }
913
- async#assertAndroidAdbReady() {
914
- try {
915
- const issues = getAdbDeviceStateIssues(await this.#spawn("adb", ["devices"]));
916
- if (issues.length > 0)
917
- throw new Error(issues.join(`
918
- `));
919
- } catch (error) {
920
- if (error instanceof CommandExecutionError)
921
- return;
922
- throw error;
923
- }
924
- }
925
- async releaseIos() {
926
- await this.prepareWww();
927
- await this.#prepareIos({ operation: "release", env: "main" });
928
- }
929
- async releaseAndroid() {
930
- await this.prepareWww();
931
- await this.#prepareAndroid({ operation: "release", env: "main" });
932
- }
933
- async prepareWww() {
934
- const htmlSource = path.join(this.app.dist.cwdPath, "csr", targetHtmlFilename(this.target));
935
- if (!await Bun.file(htmlSource).exists())
936
- throw new Error(`CSR html for mobile target '${this.target.name}' not found: ${htmlSource}`);
937
- await rm(this.targetWebRoot, { recursive: true, force: true });
938
- await mkdir(this.targetWebRoot, { recursive: true });
939
- await Bun.write(path.join(this.targetWebRoot, "index.html"), this.#injectMobileTargetMeta(await Bun.file(htmlSource).text()));
940
- }
941
- #injectMobileTargetMeta(html) {
942
- const basePath = this.target.basePath?.replace(/^\/+|\/+$/g, "") ?? "";
943
- const script = `<script>window.__AKAN_MOBILE_TARGET__=${JSON.stringify({
944
- name: this.target.name,
945
- basePath,
946
- indexPath: this.target.indexPath
947
- })};</script>`;
948
- if (html.includes("window.__AKAN_MOBILE_TARGET__"))
949
- return html;
950
- return html.replace(/<\/head\s*>/i, `${script}
951
- </head>`);
952
- }
953
- async#writeCapacitorConfig({
954
- operation,
955
- platform,
956
- iosRunTargetKind
957
- }, commandEnv) {
958
- await mkdir(this.targetRoot, { recursive: true });
959
- let localIp;
960
- if (operation === "local") {
961
- const override = commandEnv.AKAN_PUBLIC_CLIENT_HOST ?? process.env.AKAN_PUBLIC_CLIENT_HOST;
962
- const resolution = await this.#resolveLocalDevHost({ override, platform, iosRunTargetKind });
963
- localIp = resolution.host;
964
- this.#logDevHostResolution(resolution, commandEnv);
965
- }
966
- const config = materializeCapacitorConfig(this.target, {
967
- operation,
968
- localIp,
969
- localServerUrl: localIp ? this.#localCsrUrl(localIp, commandEnv) : undefined
970
- });
971
- const content = `${JSON.stringify(config, null, 2)}
972
- `;
973
- await Bun.write(path.join(this.targetRoot, "capacitor.config.json"), content);
974
- return content;
975
- }
976
- async#resolveLocalDevHost({
977
- override,
978
- platform,
979
- iosRunTargetKind
980
- }) {
981
- const resolution = selectLocalDevHost(os.networkInterfaces(), { override });
982
- if (resolution.source === "override")
983
- return resolution;
984
- if (platform === "ios" && iosRunTargetKind === "simulator")
985
- return { ...resolution, host: "localhost", source: "platform" };
986
- if (platform === "android") {
987
- try {
988
- const host = getAndroidLocalServerHost(await this.#spawn("adb", ["devices"]), resolution.host);
989
- return host === resolution.host ? resolution : { ...resolution, host, source: "platform" };
990
- } catch {
991
- return resolution;
992
- }
993
- }
994
- return resolution;
995
- }
996
- #logDevHostResolution(resolution, commandEnv) {
997
- this.app.log(`Mobile live-reload server: ${this.#localCsrUrl(resolution.host, commandEnv)}`);
998
- if (resolution.source === "override" || resolution.source === "platform")
999
- return;
1000
- const suspicious = resolution.host === "127.0.0.1" || resolution.host.startsWith("169.254.");
1001
- const alternatives = resolution.candidates.filter((candidate) => candidate.address !== resolution.host);
1002
- if (!suspicious && alternatives.length === 0)
1003
- return;
1004
- const alternativeText = alternatives.length ? ` Other interfaces: ${alternatives.map((candidate) => `${candidate.address} (${candidate.name})`).join(", ")}.` : "";
1005
- this.app.logger.warn(`A physical device must reach ${resolution.host} on your LAN.${suspicious ? " That address looks non-routable." : ""}${alternativeText} If the device shows a blank screen, pin the right one with AKAN_PUBLIC_CLIENT_HOST=<ip>.`);
1006
- }
1007
- async#prepareTargetAssets() {
1008
- if (!this.target.assets)
1009
- return;
1010
- await mkdir(this.targetAssetRoot, { recursive: true });
1011
- for (const [name, source] of [
1012
- ["icon", this.target.assets.icon],
1013
- ["splash", this.target.assets.splash]
1014
- ])
1015
- if (source)
1016
- await cp(path.join(this.app.cwdPath, source), path.join(this.targetAssetRoot, `${name}.png`), { force: true });
1017
- }
1018
- async#prepareExternalFiles(platform) {
1019
- const files = this.target.files?.[platform];
1020
- if (!files)
1021
- return;
1022
- const platformRoot = path.join(this.app.cwdPath, platform === "ios" ? this.iosRootPath : this.androidRootPath);
1023
- await Promise.all(Object.entries(files).map(async ([to, from]) => {
1024
- const targetPath = path.join(platformRoot, to);
1025
- await mkdir(path.dirname(targetPath), { recursive: true });
1026
- await cp(path.join(this.app.cwdPath, from), targetPath, { force: true });
1027
- }));
1028
- }
1029
- async#generateAssets({ operation, env }) {
1030
- if (!this.target.assets)
1031
- return;
1032
- await this.#spawnMobile("npx", [
1033
- "@capacitor/assets",
1034
- "generate",
1035
- "--assetPath",
1036
- path.posix.join(this.targetRootPath, "assets"),
1037
- "--iosProject",
1038
- this.iosProjectPath,
1039
- "--androidProject",
1040
- this.androidRootPath
1041
- ], { operation, env });
1042
- }
1043
- async#applyIosMetadata() {
1044
- this.project.ios.setBundleId("App", "Debug", this.target.appId);
1045
- this.project.ios.setBundleId("App", "Release", this.target.appId);
1046
- await this.project.ios.setVersion("App", "Debug", this.target.version);
1047
- await this.project.ios.setVersion("App", "Release", this.target.version);
1048
- await this.project.ios.setBuild("App", "Debug", this.target.buildNum);
1049
- await this.project.ios.setBuild("App", "Release", this.target.buildNum);
1050
- }
1051
- async#applyAndroidMetadata() {
1052
- await this.project.android.setVersionName(this.target.version);
1053
- await this.project.android.setPackageName(this.target.appId);
1054
- await this.project.android.setVersionCode(this.target.buildNum);
1055
- await this.project.android.setAppName(this.target.appName);
1056
- }
1057
- async#applyAndroidMinSdkVersion() {
1058
- const variablesGradlePath = path.join(this.app.cwdPath, this.androidRootPath, "variables.gradle");
1059
- if (!await Bun.file(variablesGradlePath).exists())
1060
- return;
1061
- const updated = raiseGradleMinSdkVersion(await Bun.file(variablesGradlePath).text());
1062
- if (!updated)
1063
- return;
1064
- await writeFile(variablesGradlePath, updated);
1065
- this.app.verbose(`Raised Android minSdkVersion to ${ANDROID_MIN_SDK_VERSION} in variables.gradle`);
1066
- }
1067
- async#applyPermissions({ operation, env }) {
1068
- const plugins = await this.app.collectPlugins();
1069
- const nativePlugins = new Map;
1070
- for (const plugin of plugins) {
1071
- const permission = plugin.capacitor?.permission;
1072
- if (!permission || !plugin.capacitor?.configureNative)
1073
- continue;
1074
- const claimants = nativePlugins.get(permission) ?? [];
1075
- claimants.push(plugin);
1076
- nativePlugins.set(permission, claimants);
1077
- }
1078
- for (const permission of this.target.permissions ?? []) {
1079
- const claimants = nativePlugins.get(permission);
1080
- if (claimants?.length) {
1081
- const ctx = this.#makeNativeContext({ operation, env });
1082
- for (const plugin of claimants)
1083
- await plugin.capacitor?.configureNative?.(ctx);
1084
- continue;
1085
- }
1086
- if (permission === "camera")
1087
- await this.addCamera();
1088
- else if (permission === "contacts")
1089
- await this.addContact();
1090
- else if (permission === "location")
1091
- await this.addLocation();
1092
- }
1093
- }
1094
- #makeNativeContext({ operation, env }) {
1095
- return {
1096
- appPath: this.app.cwdPath,
1097
- executor: this.app,
1098
- target: this.target,
1099
- operation,
1100
- env,
1101
- setIosUsageDescriptions: (descriptions) => this.#setPermissionInIos(descriptions),
1102
- updateIosInfoPlist: (values) => this.#updateIosInfoPlist(values),
1103
- addIosEntitlements: (entitlements) => this.#addIosEntitlements(entitlements),
1104
- editIosAppDelegate: (transform) => this.#editIosAppDelegate(transform),
1105
- addAndroidPermissions: (permissions) => this.#setPermissionsInAndroid(permissions),
1106
- addAndroidFeatures: (features) => this.#setFeaturesInAndroid(features)
1107
- };
1108
- }
1109
- async#applyDeepLinks(platform, { operation, env }) {
1110
- const deepLinks = this.target.deepLinks;
1111
- if (!deepLinks)
1112
- return;
1113
- const schemes = deepLinks.schemes ?? [];
1114
- const domains = deepLinks.domains ?? [];
1115
- if (domains.length > 0)
1116
- this.#assertDeepLinkVerificationConfig(platform, { operation, env });
1117
- if (platform === "ios") {
1118
- if (schemes.length > 0) {
1119
- await this.#setPermissionInIos({
1120
- appTransportSecurity: ""
1121
- });
1122
- await this.#setUrlSchemesInIos(schemes);
1123
- }
1124
- if (domains.length > 0)
1125
- this.#addIosEntitlements({
1126
- "com.apple.developer.associated-domains": domains.map((domain) => `applinks:${domain}`)
1127
- });
1128
- return;
1129
- }
1130
- if (platform === "android") {
1131
- for (const scheme of schemes) {
1132
- this.project.android.getAndroidManifest().injectFragment("activity", `<intent-filter><action android:name="android.intent.action.VIEW" /><category android:name="android.intent.category.DEFAULT" /><category android:name="android.intent.category.BROWSABLE" /><data android:scheme="${scheme}" /></intent-filter>`);
1133
- }
1134
- for (const domain of domains) {
1135
- const pathPrefix = resolveMobilePath(this.target, "/");
1136
- this.project.android.getAndroidManifest().injectFragment("activity", `<intent-filter android:autoVerify="true"><action android:name="android.intent.action.VIEW" /><category android:name="android.intent.category.DEFAULT" /><category android:name="android.intent.category.BROWSABLE" /><data android:scheme="https" android:host="${domain}" android:pathPrefix="${pathPrefix}" /></intent-filter>`);
1137
- }
1138
- await this.#setDeepLinksInAndroid(schemes, domains);
1139
- }
1140
- }
1141
- #assertDeepLinkVerificationConfig(platform, { operation, env }) {
1142
- const deepLinks = this.target.deepLinks;
1143
- if (!deepLinks?.domains?.length)
1144
- return;
1145
- if (platform === "ios" && !deepLinks.ios?.teamId) {
1146
- throw new Error(`Mobile target '${this.target.name}' uses deepLinks.domains but is missing deepLinks.ios.teamId in apps/${this.app.name}/akan.config.ts`);
1147
- }
1148
- if (platform === "android" && !deepLinks.android?.sha256CertFingerprints?.length) {
1149
- const message = `Mobile target '${this.target.name}' uses deepLinks.domains but is missing deepLinks.android.sha256CertFingerprints in apps/${this.app.name}/akan.config.ts`;
1150
- if (operation === "release" || env === "main")
1151
- throw new Error(message);
1152
- this.app.logger.warn(message);
1153
- }
1154
- }
1155
- async#commandEnv(operation, env) {
1156
- const devPort = operation === "local" ? (await this.app.getDevPort()).toString() : undefined;
1157
- return this.app.getCommandEnv({
1158
- APP_OPERATION_MODE: operation,
1159
- AKAN_PUBLIC_OPERATION_MODE: env === "local" ? "local" : "cloud",
1160
- AKAN_PUBLIC_ENV: env,
1161
- AKAN_MOBILE_TARGET: this.target.name,
1162
- ...devPort ? { PORT: devPort, AKAN_PUBLIC_CLIENT_PORT: devPort, AKAN_PUBLIC_SERVER_PORT: devPort } : {}
1163
- });
1164
- }
1165
- #localCsrUrl(ip, commandEnv) {
1166
- const basePath = this.target.basePath?.replace(/^\/+|\/+$/g, "");
1167
- const locale = commandEnv.AKAN_PUBLIC_DEFAULT_LOCALE ?? "en";
1168
- const pathname = basePath ? `${locale}/${basePath}` : `${locale}/`;
1169
- const port = commandEnv.AKAN_PUBLIC_CLIENT_PORT ?? commandEnv.PORT ?? "8282";
1170
- const params = new URLSearchParams({ csr: "true", akanMobileTarget: this.target.name });
1171
- if (basePath)
1172
- params.set("akanMobileBasePath", basePath);
1173
- if (this.target.indexPath)
1174
- params.set("akanMobileIndexPath", this.target.indexPath);
1175
- return `http://${ip}:${port}/${pathname}?${params}`;
1176
- }
1177
- async#spawn(command, args = [], options = {}) {
1178
- return await this.app.spawn(command, args, { cwd: this.app.cwdPath, ...options });
1179
- }
1180
- async#spawnMobile(command, args = [], { operation, env }, options = {}) {
1181
- const { iosRunTargetKind, platform, ...spawnOptions } = options;
1182
- const mobileEnv = { ...await this.#commandEnv(operation, env), ...options.env };
1183
- const configContent = await this.#writeCapacitorConfig({ operation, platform: platform ?? this.#inferMobilePlatform(args), iosRunTargetKind }, mobileEnv);
1184
- await writeRootCapacitorConfig(this.app.cwdPath, configContent);
1185
- try {
1186
- return await this.#spawn(command, args, { ...spawnOptions, env: mobileEnv });
1187
- } finally {
1188
- await clearRootCapacitorConfigs(this.app.cwdPath);
1189
- }
1190
- }
1191
- #inferMobilePlatform(args) {
1192
- if (args.includes("android"))
1193
- return "android";
1194
- if (args.includes("ios"))
1195
- return "ios";
1196
- return;
1197
- }
1198
- async addCamera() {
1199
- await this.#setPermissionInIos({
1200
- cameraUsageDescription: "$(PRODUCT_NAME) requires access to the camera to take photos.",
1201
- photoAddUsageDescription: "$(PRODUCT_NAME) requires access to the photo library to take photos.",
1202
- photoUsageDescription: "$(PRODUCT_NAME) requires access to the photo library to take photos."
1203
- });
1204
- this.#setPermissionsInAndroid(["READ_MEDIA_IMAGES", "READ_EXTERNAL_STORAGE", "WRITE_EXTERNAL_STORAGE"]);
1205
- }
1206
- async addContact() {
1207
- await this.#setPermissionInIos({
1208
- contactsUsageDescription: "$(PRODUCT_NAME) requires access to the contacts to add new contacts."
1209
- });
1210
- this.#setPermissionsInAndroid(["READ_CONTACTS", "WRITE_CONTACTS"]);
1211
- }
1212
- async addLocation() {
1213
- await this.#setPermissionInIos({
1214
- locationAlwaysUsageDescription: "$(PRODUCT_NAME) requires access to the location to get the user's location.",
1215
- locationWhenInUseUsageDescription: "$(PRODUCT_NAME) requires access to the location to get the user's location."
1216
- });
1217
- this.#setPermissionsInAndroid(["ACCESS_COARSE_LOCATION", "ACCESS_FINE_LOCATION"]);
1218
- this.#setFeaturesInAndroid(["android.hardware.location.gps"]);
1219
- }
1220
- #addIosEntitlements(entitlements) {
1221
- Object.assign(this.#iosEntitlements, entitlements);
1222
- }
1223
- async#editIosAppDelegate(transform) {
1224
- const appDelegatePath = path.join(this.app.cwdPath, this.iosProjectPath, "App/AppDelegate.swift");
1225
- if (!await Bun.file(appDelegatePath).exists())
1226
- return;
1227
- const editor = await FileEditor.create(appDelegatePath);
1228
- const content = editor.getContent();
1229
- const next = transform(content);
1230
- if (next !== content)
1231
- await editor.setContent(next).save();
1232
- }
1233
- async#updateIosInfoPlist(values) {
1234
- await Promise.all(["Debug", "Release"].map((build) => this.project.ios.updateInfoPlist(this.iosTargetName, build, values)));
1235
- }
1236
- async#setPermissionInIos(permissions) {
1237
- await this.#updateIosInfoPlist(toIosInfoPlistUsageDescriptions(permissions));
1238
- }
1239
- async#setUrlSchemesInIos(schemes) {
1240
- await this.#updateIosInfoPlist({
1241
- CFBundleURLTypes: schemes.map((scheme) => ({ CFBundleURLName: this.target.appId, CFBundleURLSchemes: [scheme] }))
1242
- });
1243
- }
1244
- #serializeIosEntitlements(entitlements) {
1245
- const lines = [];
1246
- for (const [key, value] of Object.entries(entitlements)) {
1247
- lines.push(` <key>${key}</key>`);
1248
- if (Array.isArray(value)) {
1249
- lines.push(" <array>", ...value.map((item) => ` <string>${item}</string>`), " </array>");
1250
- } else {
1251
- lines.push(` <string>${value}</string>`);
1252
- }
1253
- }
1254
- return lines;
1255
- }
1256
- async#flushIosEntitlements() {
1257
- if (Object.keys(this.#iosEntitlements).length === 0)
1258
- return;
1259
- const entitlementsRelPath = "App/App.entitlements";
1260
- const entitlementsPath = path.join(this.app.cwdPath, this.iosProjectPath, entitlementsRelPath);
1261
- const body = [
1262
- '<?xml version="1.0" encoding="UTF-8"?>',
1263
- '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
1264
- '<plist version="1.0">',
1265
- "<dict>",
1266
- ...this.#serializeIosEntitlements(this.#iosEntitlements),
1267
- "</dict>",
1268
- "</plist>",
1269
- ""
1270
- ].join(`
1271
- `);
1272
- const currentBody = await Bun.file(entitlementsPath).exists() ? await Bun.file(entitlementsPath).text() : undefined;
1273
- if (currentBody !== body)
1274
- await writeFile(entitlementsPath, body);
1275
- await this.#setCodeSignEntitlementsInIos(entitlementsRelPath);
1276
- }
1277
- async#setCodeSignEntitlementsInIos(entitlementsRelPath) {
1278
- const pbxprojPath = path.join(this.app.cwdPath, this.iosProjectPath, "App.xcodeproj/project.pbxproj");
1279
- const lines = (await readFile(pbxprojPath, "utf8")).split(`
1280
- `);
1281
- let changed = false;
1282
- for (let index = 0;index < lines.length; index++) {
1283
- const line = lines[index] ?? "";
1284
- if (!line.includes(`PRODUCT_BUNDLE_IDENTIFIER = ${this.target.appId};`))
1285
- continue;
1286
- let start = index;
1287
- while (start >= 0 && !lines[start]?.includes("buildSettings = {"))
1288
- start--;
1289
- let end = index;
1290
- while (end < lines.length && !/^\s*\};\s*$/.test(lines[end] ?? ""))
1291
- end++;
1292
- const settings = lines.slice(start, end + 1);
1293
- const configName = lines.slice(end + 1, end + 8).find((setting) => setting.includes("name = ")) ?? "";
1294
- const indent = line.match(/^\s*/)?.[0] ?? "";
1295
- const insertSettings = [];
1296
- if (!settings.some((setting) => setting.includes("CODE_SIGN_ENTITLEMENTS"))) {
1297
- insertSettings.push(`${indent}CODE_SIGN_ENTITLEMENTS = ${entitlementsRelPath};`);
1298
- }
1299
- if (configName.includes("name = Debug;") && !settings.some((setting) => setting.includes("CODE_SIGN_ALLOW_ENTITLEMENTS_MODIFICATION"))) {
1300
- insertSettings.push(`${indent}CODE_SIGN_ALLOW_ENTITLEMENTS_MODIFICATION = YES;`);
1301
- }
1302
- if (insertSettings.length > 0) {
1303
- lines.splice(index, 0, ...insertSettings);
1304
- index += insertSettings.length;
1305
- changed = true;
1306
- }
1307
- }
1308
- if (changed)
1309
- await writeFile(pbxprojPath, lines.join(`
1310
- `));
1311
- }
1312
- async#setCodeSignEntitlementsInIosIfExists(entitlementsRelPath) {
1313
- const entitlementsPath = path.join(this.app.cwdPath, this.iosProjectPath, entitlementsRelPath);
1314
- if (!await Bun.file(entitlementsPath).exists())
1315
- return;
1316
- await this.#setCodeSignEntitlementsInIos(entitlementsRelPath);
1317
- }
1318
- async#setDeepLinksInAndroid(schemes, domains) {
1319
- const manifestPath = path.join(this.app.cwdPath, this.androidRootPath, "app/src/main/AndroidManifest.xml");
1320
- const original = await readFile(manifestPath, "utf8");
1321
- const pathPrefix = resolveMobilePath(this.target, "/");
1322
- let manifest = original;
1323
- for (const scheme of schemes) {
1324
- if (manifest.includes(`android:scheme="${scheme}"`))
1325
- continue;
1326
- manifest = CapacitorApp2.#withIntentFilter(manifest, "<intent-filter>", `<data android:scheme="${scheme}" />`);
1327
- }
1328
- for (const domain of domains) {
1329
- if (manifest.includes(`android:host="${domain}"`) && manifest.includes('android:scheme="https"'))
1330
- continue;
1331
- manifest = CapacitorApp2.#withIntentFilter(manifest, '<intent-filter android:autoVerify="true">', `<data android:scheme="https" android:host="${domain}" android:pathPrefix="${pathPrefix}" />`);
1332
- }
1333
- if (manifest !== original)
1334
- await writeFile(manifestPath, manifest);
1335
- }
1336
- static #withIntentFilter(manifest, open, data) {
1337
- const filter = [
1338
- ` ${open}`,
1339
- ' <action android:name="android.intent.action.VIEW" />',
1340
- ' <category android:name="android.intent.category.DEFAULT" />',
1341
- ' <category android:name="android.intent.category.BROWSABLE" />',
1342
- ` ${data}`,
1343
- " </intent-filter>"
1344
- ].join(`
1345
- `);
1346
- return manifest.replace(/(\s*<\/activity>)/, `
1347
- ${filter}$1`);
1348
- }
1349
- #setFeaturesInAndroid(features) {
1350
- for (const feature of features) {
1351
- if (this.#androidManifestNames("uses-feature").includes(feature)) {
1352
- this.app.logger.info(`${feature} already exists in android`);
1353
- return;
1354
- }
1355
- this.app.logger.info(`Adding ${feature} to android`);
1356
- this.project.android.getAndroidManifest().injectFragment("manifest", `<uses-feature android:name="${feature}" />`);
1357
- }
1358
- }
1359
- #setPermissionsInAndroid(permissions) {
1360
- for (const permission of permissions) {
1361
- if (this.#androidManifestNames("uses-permission").includes(`android.permission.${permission}`)) {
1362
- this.app.logger.info(`${permission} already exists in android`);
1363
- continue;
1364
- }
1365
- this.app.logger.info(`Adding ${permission} to android`);
1366
- this.project.android.getAndroidManifest().injectFragment("manifest", `<uses-permission android:name="android.permission.${permission}" />`);
1367
- }
1368
- }
1369
- #androidManifestNames(tagName) {
1370
- const element = this.project.android.getAndroidManifest().getDocumentElement();
1371
- if (!element)
1372
- throw new Error("manifest not found");
1373
- return Array.from(element.getElementsByTagName(tagName)).map((node) => node.getAttribute("android:name"));
1374
- }
1375
- }
1376
-
1377
- export { isPlaceholderAppId2, CapacitorApp2 };