akanjs 3.0.0-beta.26 → 3.0.0-beta.28

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 (226) hide show
  1. package/base/baseEnv.ts +19 -5
  2. package/client/csrTypes.ts +2 -0
  3. package/client/device.ts +28 -12
  4. package/client/index.ts +1 -0
  5. package/client/native/accessibility.ts +1 -0
  6. package/client/native/app-state.ts +1 -0
  7. package/client/native/app.ts +1 -0
  8. package/client/native/appearance.ts +1 -0
  9. package/client/native/auth-session.ts +1 -0
  10. package/client/native/autostart.ts +1 -0
  11. package/client/native/badge.ts +1 -0
  12. package/client/native/biometric.ts +1 -0
  13. package/client/native/browser.ts +1 -0
  14. package/client/native/camera.ts +1 -0
  15. package/client/native/clipboard.ts +1 -0
  16. package/client/native/contacts.ts +1 -0
  17. package/client/native/device.ts +1 -0
  18. package/client/native/dialog.ts +1 -0
  19. package/client/native/dock.ts +1 -0
  20. package/client/native/file-picker.ts +1 -0
  21. package/client/native/filesystem.ts +1 -0
  22. package/client/native/geolocation.ts +1 -0
  23. package/client/native/global-shortcut.ts +1 -0
  24. package/client/native/haptics.ts +1 -0
  25. package/client/native/http.ts +1 -0
  26. package/client/native/iap.ts +1 -0
  27. package/client/native/keep-awake.ts +1 -0
  28. package/client/native/keyboard.ts +1 -0
  29. package/client/native/local-notifications.ts +1 -0
  30. package/client/native/menu.ts +1 -0
  31. package/client/native/network.ts +1 -0
  32. package/client/native/opener.ts +1 -0
  33. package/client/native/preferences.ts +1 -0
  34. package/client/native/push.ts +1 -0
  35. package/client/native/screen-orientation.ts +1 -0
  36. package/client/native/screen.ts +1 -0
  37. package/client/native/secure-storage.ts +1 -0
  38. package/client/native/share.ts +1 -0
  39. package/client/native/single-instance.ts +1 -0
  40. package/client/native/splash-screen.ts +1 -0
  41. package/client/native/sqlite.ts +1 -0
  42. package/client/native/toast.ts +1 -0
  43. package/client/native/tray.ts +1 -0
  44. package/client/native/updates.ts +1 -0
  45. package/client/native/volume.ts +1 -0
  46. package/client/native/window-state.ts +1 -0
  47. package/client/native/window.ts +1 -0
  48. package/client/native.ts +31 -1
  49. package/client/resolveServerUrl.ts +11 -0
  50. package/client/router.ts +8 -0
  51. package/common/Logger.ts +26 -2
  52. package/common/RouteLayering.ts +52 -0
  53. package/common/index.ts +1 -0
  54. package/index.ts +115 -6
  55. package/native/desktop.ts +5 -0
  56. package/package.json +11 -1
  57. package/server/akanApp.ts +23 -3
  58. package/server/akanAppHeaders.ts +4 -1
  59. package/server/akanServer.ts +27 -7
  60. package/server/index.ts +1 -0
  61. package/server/lifecycle/orphanGroup.ts +21 -0
  62. package/server/nativeFile.ts +107 -0
  63. package/server/ops/opsRoute.ts +3 -2
  64. package/server/routeTreeBuilder.ts +14 -39
  65. package/server/routing/apiRouter.ts +26 -3
  66. package/server/routing/hostAllowlist.ts +24 -0
  67. package/server/selfExec.ts +25 -0
  68. package/server/types.tsx +3 -1
  69. package/server/webRouter.ts +7 -4
  70. package/service/ipcTypes.ts +4 -0
  71. package/signal/CrossSiteGuard.ts +7 -0
  72. package/test/signalTestRuntime.ts +8 -2
  73. package/types/base/baseEnv.d.ts +1 -0
  74. package/types/client/csrTypes.d.ts +2 -0
  75. package/types/client/index.d.ts +1 -0
  76. package/types/client/native/accessibility.d.ts +1 -0
  77. package/types/client/native/app-state.d.ts +1 -0
  78. package/types/client/native/app.d.ts +1 -0
  79. package/types/client/native/appearance.d.ts +1 -0
  80. package/types/client/native/auth-session.d.ts +1 -0
  81. package/types/client/native/autostart.d.ts +1 -0
  82. package/types/client/native/badge.d.ts +1 -0
  83. package/types/client/native/biometric.d.ts +1 -0
  84. package/types/client/native/browser.d.ts +1 -0
  85. package/types/client/native/camera.d.ts +1 -0
  86. package/types/client/native/clipboard.d.ts +1 -0
  87. package/types/client/native/contacts.d.ts +1 -0
  88. package/types/client/native/device.d.ts +1 -0
  89. package/types/client/native/dialog.d.ts +1 -0
  90. package/types/client/native/dock.d.ts +1 -0
  91. package/types/client/native/file-picker.d.ts +1 -0
  92. package/types/client/native/filesystem.d.ts +1 -0
  93. package/types/client/native/geolocation.d.ts +1 -0
  94. package/types/client/native/global-shortcut.d.ts +1 -0
  95. package/types/client/native/haptics.d.ts +1 -0
  96. package/types/client/native/http.d.ts +1 -0
  97. package/types/client/native/iap.d.ts +1 -0
  98. package/types/client/native/keep-awake.d.ts +1 -0
  99. package/types/client/native/keyboard.d.ts +1 -0
  100. package/types/client/native/local-notifications.d.ts +1 -0
  101. package/types/client/native/menu.d.ts +1 -0
  102. package/types/client/native/network.d.ts +1 -0
  103. package/types/client/native/opener.d.ts +1 -0
  104. package/types/client/native/preferences.d.ts +1 -0
  105. package/types/client/native/push.d.ts +1 -0
  106. package/types/client/native/screen-orientation.d.ts +1 -0
  107. package/types/client/native/screen.d.ts +1 -0
  108. package/types/client/native/secure-storage.d.ts +1 -0
  109. package/types/client/native/share.d.ts +1 -0
  110. package/types/client/native/single-instance.d.ts +1 -0
  111. package/types/client/native/splash-screen.d.ts +1 -0
  112. package/types/client/native/sqlite.d.ts +1 -0
  113. package/types/client/native/toast.d.ts +1 -0
  114. package/types/client/native/tray.d.ts +1 -0
  115. package/types/client/native/updates.d.ts +1 -0
  116. package/types/client/native/volume.d.ts +1 -0
  117. package/types/client/native/window-state.d.ts +1 -0
  118. package/types/client/native/window.d.ts +1 -0
  119. package/types/client/native.d.ts +14 -2
  120. package/types/client/resolveServerUrl.d.ts +1 -0
  121. package/types/client/router.d.ts +3 -0
  122. package/types/common/RouteLayering.d.ts +28 -0
  123. package/types/common/index.d.ts +1 -0
  124. package/types/index.d.ts +112 -6
  125. package/types/native/desktop.d.ts +3 -0
  126. package/types/server/akanAppHeaders.d.ts +2 -0
  127. package/types/server/index.d.ts +1 -0
  128. package/types/server/lifecycle/orphanGroup.d.ts +7 -0
  129. package/types/server/nativeFile.d.ts +10 -0
  130. package/types/server/routing/apiRouter.d.ts +3 -1
  131. package/types/server/routing/hostAllowlist.d.ts +8 -0
  132. package/types/server/selfExec.d.ts +8 -0
  133. package/types/server/types.d.ts +3 -1
  134. package/types/service/ipcTypes.d.ts +16 -0
  135. package/types/signal/CrossSiteGuard.d.ts +1 -0
  136. package/types/ui/recipe/buttonRecipe.d.ts +2 -2
  137. package/types/vendor/@akanjs/native/packages/cli/src/api.d.ts +57 -4
  138. package/types/vendor/@akanjs/native/packages/cli/src/config.d.ts +48 -0
  139. package/types/vendor/@akanjs/native/packages/cli/src/lib/desktop-server.d.ts +8 -0
  140. package/types/vendor/@akanjs/native/packages/cli/src/lib/prepare.d.ts +8 -2
  141. package/types/vendor/@akanjs/native/packages/cli/src/lib/project.d.ts +10 -0
  142. package/types/vendor/@akanjs/native/packages/cli/src/lib/publish.d.ts +24 -0
  143. package/types/vendor/@akanjs/native/packages/cli/src/lib/updates.d.ts +24 -0
  144. package/types/vendor/@akanjs/native/packages/cli/src/platforms/desktop-update.d.ts +4 -1
  145. package/types/vendor/@akanjs/native/packages/cli/src/platforms/macos.d.ts +5 -0
  146. package/types/vendor/@akanjs/native/packages/cli/src/platforms/windows-installer.d.ts +38 -0
  147. package/types/vendor/@akanjs/native/packages/desktop/src/dispatcher.d.ts +8 -1
  148. package/types/vendor/@akanjs/native/packages/desktop/src/grants.d.ts +11 -0
  149. package/types/vendor/@akanjs/native/packages/desktop/src/main.d.ts +11 -0
  150. package/types/vendor/@akanjs/native/packages/desktop/src/paths.d.ts +13 -2
  151. package/types/vendor/@akanjs/native/packages/desktop/src/plugin.d.ts +27 -0
  152. package/types/vendor/@akanjs/native/packages/desktop/src/relaunch.d.ts +21 -0
  153. package/types/vendor/@akanjs/native/packages/desktop/src/server.d.ts +79 -0
  154. package/types/vendor/@akanjs/native/plugins/app/src/index.d.ts +5 -0
  155. package/types/vendor/@akanjs/native/plugins/file-picker/src/index.d.ts +20 -1
  156. package/types/vendor/@akanjs/native/plugins/push/src/index.d.ts +9 -0
  157. package/types/vendor/@akanjs/native/plugins/updates/src/desktop.d.ts +28 -0
  158. package/types/vendor/@akanjs/native/plugins/volume/src/common.d.ts +10 -0
  159. package/types/vendor/@akanjs/native/plugins/volume/src/desktop.d.ts +18 -0
  160. package/types/vendor/@akanjs/native/plugins/volume/src/index.d.ts +28 -0
  161. package/types/vendor/@akanjs/native/plugins/volume/src.d.ts +1 -0
  162. package/types/webkit/csrFrameDump.d.ts +42 -0
  163. package/types/webkit/nativeNavigation.d.ts +1 -0
  164. package/types/webkit/nativePurchase.d.ts +6 -2
  165. package/types/webkit/nativeUpdates.d.ts +8 -0
  166. package/ui/Agent/Attach.tsx +6 -2
  167. package/ui/CsrImage.tsx +3 -2
  168. package/ui/System/CSR.tsx +4 -0
  169. package/vendor/@akanjs/native/native/android/src/com/akanjs/runtime/AkanNativeActivity.kt +5 -1
  170. package/vendor/@akanjs/native/native/android/src/com/akanjs/runtime/AkanNativeBridge.kt +19 -0
  171. package/vendor/@akanjs/native/native/desktop/Cargo.toml +1 -1
  172. package/vendor/@akanjs/native/native/desktop/src/lib.rs +161 -25
  173. package/vendor/@akanjs/native/native/desktop/src/volume.rs +184 -0
  174. package/vendor/@akanjs/native/native/desktop/src/win/mod.rs +3 -1
  175. package/vendor/@akanjs/native/native/desktop/src/win/volume.rs +71 -0
  176. package/vendor/@akanjs/native/native/ios/Sources/AkanNativeShell.swift +12 -2
  177. package/vendor/@akanjs/native/packages/cli/src/api.ts +142 -12
  178. package/vendor/@akanjs/native/packages/cli/src/commands/build.ts +5 -3
  179. package/vendor/@akanjs/native/packages/cli/src/commands/update.ts +10 -71
  180. package/vendor/@akanjs/native/packages/cli/src/config.ts +41 -0
  181. package/vendor/@akanjs/native/packages/cli/src/lib/configkeys.ts +9 -2
  182. package/vendor/@akanjs/native/packages/cli/src/lib/desktop-server.ts +58 -0
  183. package/vendor/@akanjs/native/packages/cli/src/lib/hmr.ts +2 -0
  184. package/vendor/@akanjs/native/packages/cli/src/lib/prepare.ts +10 -2
  185. package/vendor/@akanjs/native/packages/cli/src/lib/project.ts +38 -2
  186. package/vendor/@akanjs/native/packages/cli/src/lib/publish.ts +104 -0
  187. package/vendor/@akanjs/native/packages/cli/src/lib/updates.ts +85 -5
  188. package/vendor/@akanjs/native/packages/cli/src/platforms/android.ts +1 -0
  189. package/vendor/@akanjs/native/packages/cli/src/platforms/desktop-update.ts +6 -4
  190. package/vendor/@akanjs/native/packages/cli/src/platforms/desktop.ts +16 -0
  191. package/vendor/@akanjs/native/packages/cli/src/platforms/macos.ts +44 -1
  192. package/vendor/@akanjs/native/packages/cli/src/platforms/windows-installer.ts +436 -0
  193. package/vendor/@akanjs/native/packages/cli/src/platforms/windows.ts +2 -0
  194. package/vendor/@akanjs/native/packages/core/src/runtime.ts +26 -5
  195. package/vendor/@akanjs/native/packages/desktop/src/dispatcher.ts +20 -0
  196. package/vendor/@akanjs/native/packages/desktop/src/grants.ts +47 -0
  197. package/vendor/@akanjs/native/packages/desktop/src/host.ts +102 -14
  198. package/vendor/@akanjs/native/packages/desktop/src/main.ts +59 -11
  199. package/vendor/@akanjs/native/packages/desktop/src/paths.ts +38 -4
  200. package/vendor/@akanjs/native/packages/desktop/src/plugin.ts +28 -0
  201. package/vendor/@akanjs/native/packages/desktop/src/relaunch.ts +159 -0
  202. package/vendor/@akanjs/native/packages/desktop/src/server.ts +493 -0
  203. package/vendor/@akanjs/native/plugins/app/android/AppPlugin.kt +14 -0
  204. package/vendor/@akanjs/native/plugins/app/native-plugin.json +2 -2
  205. package/vendor/@akanjs/native/plugins/app/src/desktop.ts +5 -0
  206. package/vendor/@akanjs/native/plugins/app/src/index.ts +6 -1
  207. package/vendor/@akanjs/native/plugins/app/src/web.ts +3 -0
  208. package/vendor/@akanjs/native/plugins/file-picker/src/desktop.ts +39 -2
  209. package/vendor/@akanjs/native/plugins/file-picker/src/index.ts +36 -1
  210. package/vendor/@akanjs/native/plugins/push/android/PushPlugin.kt +9 -1
  211. package/vendor/@akanjs/native/plugins/push/ios/PushPlugin.swift +4 -0
  212. package/vendor/@akanjs/native/plugins/push/src/index.ts +10 -0
  213. package/vendor/@akanjs/native/plugins/updates/src/desktop.ts +464 -452
  214. package/vendor/@akanjs/native/plugins/volume/android/VolumePlugin.kt +107 -0
  215. package/vendor/@akanjs/native/plugins/volume/native-plugin.json +14 -0
  216. package/vendor/@akanjs/native/plugins/volume/src/common.ts +28 -0
  217. package/vendor/@akanjs/native/plugins/volume/src/desktop.ts +185 -0
  218. package/vendor/@akanjs/native/plugins/volume/src/index.ts +32 -0
  219. package/webkit/CsrRouteTable.ts +15 -35
  220. package/webkit/RenderLayer.tsx +71 -6
  221. package/webkit/bootCsr.tsx +11 -8
  222. package/webkit/csrFrameDump.ts +67 -0
  223. package/webkit/nativeNavigation.ts +17 -0
  224. package/webkit/nativePurchase.ts +12 -2
  225. package/webkit/nativeUpdates.ts +55 -0
  226. package/webkit/useCsrValues.ts +27 -0
@@ -12,8 +12,10 @@ import { linkArguments, registerDeepLinks } from "./deeplinks.ts";
12
12
  import { createDispatcher } from "./dispatcher.ts";
13
13
  import { cstr, FRAME_EVENT, FRAME_HEADER, FRAME_IPC, openNative, resolvePaths } from "./ffi.ts";
14
14
  import { createLifecycle } from "./lifecycle.ts";
15
- import { appDataDir, reservedDirs } from "./paths.ts";
15
+ import { appDataDir, appLocalDataDir, reservedDirs, serverDataDir } from "./paths.ts";
16
16
  import { type DesktopPlugin, useShellOpenLimit } from "./plugin.ts";
17
+ import { nextRelaunchDelay, relaunchAfterExit } from "./relaunch.ts";
18
+ import { createDesktopServer, pathWithFirst, readServerManifest, type ServerManifest } from "./server.ts";
17
19
 
18
20
  declare const self: Worker;
19
21
 
@@ -49,6 +51,9 @@ export function shellError(message: string): AkanNativeError {
49
51
 
50
52
  export function startHost(plugins: DesktopPlugin[]): void {
51
53
  const paths = resolvePaths();
54
+
55
+ const binDir = existsSync(join(paths.resources, "bin")) ? join(paths.resources, "bin") : null;
56
+ if (binDir) process.env.PATH = pathWithFirst(binDir, process.env.PATH);
52
57
  const lib = openNative(paths.lib);
53
58
  const native = lib.symbols;
54
59
 
@@ -103,6 +108,7 @@ export function startHost(plugins: DesktopPlugin[]): void {
103
108
  quitOnLastWindowClosed?: boolean;
104
109
  deepLinks?: string[];
105
110
  externalSchemes?: string[];
111
+ recovery?: "errorPage" | "reload";
106
112
  };
107
113
  const deepLinkSchemes = (shellConfig.deepLinks ?? []).map((s) => s.toLowerCase());
108
114
 
@@ -123,19 +129,36 @@ export function startHost(plugins: DesktopPlugin[]): void {
123
129
  });
124
130
 
125
131
  const reserved = reservedDirs(boot.app.id);
132
+
133
+ let manifest: ServerManifest | null = null;
134
+ let manifestProblem: unknown;
135
+ try {
136
+ manifest = readServerManifest(paths.resources);
137
+ } catch (error) {
138
+ manifestProblem = error;
139
+ }
140
+ const carriesServer = manifest !== null || manifestProblem !== undefined;
141
+ let settleServer = (_ready: boolean) => {};
142
+ const serverReady = new Promise<boolean>((resolve) => (settleServer = resolve));
126
143
  const dispatcher = createDispatcher(
127
144
  plugins,
128
145
  {
129
146
  app: boot.app,
147
+ dev: boot.dev === true,
130
148
  appDataDir: appDataDir(boot.app.id),
149
+ appLocalDataDir: appLocalDataDir(boot.app.id),
150
+ binDir,
151
+ server: carriesServer ? { ready: serverReady } : null,
131
152
  emit(window, message) {
132
153
  emitJs(window, `window.__AKAN_NATIVE__&&window.__AKAN_NATIVE__.receive(${JSON.stringify(message)})`);
133
154
  },
134
155
  builtins: {
135
-
156
+
136
157
  [CONSOLE_PLUGIN](req, window) {
137
- const line = `[page${window === 1 ? "" : ` ${window}`} ${req.method}] ${(req.args as { message?: string } | undefined)?.message ?? ""}`;
138
- (req.method === "error" || req.method === "warn" ? console.error : console.info)(line);
158
+ const message = (req.args as { message?: string } | undefined)?.message ?? "";
159
+ const scope = window === 1 ? "" : `#${window}`;
160
+ const lines = message.replace(/\n+$/, "").split("\n");
161
+ console.info(lines.map((line, i) => `[page${i === 0 ? "" : "+"}${scope} ${req.method}] ${line}`).join("\n"));
139
162
  },
140
163
 
141
164
  async [HOST_PLUGIN](req, window, signal) {
@@ -248,6 +271,28 @@ export function startHost(plugins: DesktopPlugin[]): void {
248
271
  respond(reqId, 200, await dispatcher.handle(decoder.decode(body), window));
249
272
  };
250
273
 
274
+ let shellRunning = false;
275
+ const heldAlerts: string[] = [];
276
+ const shellStarted = () => {
277
+ shellRunning = true;
278
+ for (const message of heldAlerts.splice(0)) serverAlert(message);
279
+ };
280
+
281
+ let browserExitHandled = false;
282
+ const relaunchAfterBrowserExit = () => {
283
+ if (browserExitHandled) return;
284
+ browserExitHandled = true;
285
+ const delayMs = nextRelaunchDelay(join(appLocalDataDir(boot.app.id), "akan-native-relaunch.json"));
286
+ if (delayMs === null) {
287
+ console.error("[akan-native] the webview's browser process kept ending after each relaunch; the app stops here");
288
+ void lifecycle.quit(1);
289
+ return;
290
+ }
291
+ relaunchAfterExit(process.execPath, [], { delayMs })
292
+ .then(() => lifecycle.quit(0))
293
+ .catch((error: unknown) => console.error("[akan-native] cannot relaunch the app", error));
294
+ };
295
+
251
296
  const onEvent = (event: NativeEvent) => {
252
297
  if (event.type === "shellReply" && typeof event.id === "number") {
253
298
  const pending = shellPending.get(event.id);
@@ -271,6 +316,8 @@ export function startHost(plugins: DesktopPlugin[]): void {
271
316
  gone++;
272
317
  console.error(`[akan-native] window ${window}: the page's process ended (${String(event.reason)})`);
273
318
  dispatcher.reset(window);
319
+
320
+ if (event.reason === "browserExited" && shellConfig.recovery === "reload") relaunchAfterBrowserExit();
274
321
  } else if (event.type === "window" && event.event === "destroyed") dispatcher.reset(window);
275
322
  else if (event.type === "window" && event.event === "closeRequested") void lifecycle.closeRequested(window);
276
323
  else if (event.type === "quitRequested")
@@ -298,6 +345,7 @@ export function startHost(plugins: DesktopPlugin[]): void {
298
345
  buffer = new Uint8Array(Math.max(size, buffer.length * 2));
299
346
  continue;
300
347
  }
348
+ if (!shellRunning) shellStarted();
301
349
  const view = new DataView(buffer.buffer, buffer.byteOffset, size);
302
350
  const kind = view.getUint8(0);
303
351
  const reqId = view.getBigUint64(1, true);
@@ -342,14 +390,54 @@ export function startHost(plugins: DesktopPlugin[]): void {
342
390
  }
343
391
 
344
392
  setInterval(() => {}, 2 ** 31 - 1);
345
-
346
- void dispatcher.launched.then((launch) => {
347
- self.postMessage({ type: "ready", ...launch });
348
- if (typeof launch.exit === "number") return;
349
-
350
- openLinks(process.argv.slice(2));
351
- registerDeepLinks(boot.app, deepLinkSchemes).catch((error) =>
352
- console.warn("[akan-native] cannot register the deep link schemes", error),
353
- );
354
- });
393
+ const serverAlert = (message: string) => {
394
+ if (!shellRunning) {
395
+ heldAlerts.push(message);
396
+ return;
397
+ }
398
+ void shell("alert.show", {
399
+ title: boot.app.name,
400
+ message,
401
+ buttons: [{ title: "OK" }],
402
+ tag: "akan-server",
403
+ }).catch((error: unknown) => console.error("[akan-native] cannot show the server alert", error));
404
+ };
405
+
406
+ const startServer = async (): Promise<Record<string, string> | undefined> => {
407
+ if (!carriesServer) return undefined;
408
+ const dataDir = serverDataDir(boot.app.id, boot.dev === true);
409
+ try {
410
+ if (!manifest) throw manifestProblem;
411
+ const server = createDesktopServer({
412
+ resources: paths.resources,
413
+ dataDir,
414
+ manifest,
415
+ binDir,
416
+ onGiveUp: serverAlert,
417
+ });
418
+ void server.ready.then(settleServer);
419
+ lifecycle.onQuit(() => server.stop());
420
+ const { url, ready } = await server.start();
421
+ console.info(`[akan-native] server ${ready ? "ready" : "not ready"} on ${url}`);
422
+ return { PUBLIC_AKAN_SERVER_URL: url };
423
+ } catch (error) {
424
+ console.error("[akan-native] the app's server could not start", error);
425
+ settleServer(false);
426
+ serverAlert(`The app's server cannot start: ${error instanceof Error ? error.message : String(error)}`);
427
+ return { PUBLIC_AKAN_SERVER_URL: "http://127.0.0.1:0" };
428
+ }
429
+ };
430
+
431
+ void dispatcher.launched
432
+ .then(async (launch) => {
433
+ const env = typeof launch.exit === "number" ? undefined : await startServer();
434
+ self.postMessage({ type: "ready", ...launch, ...(env ? { env } : {}) });
435
+ if (typeof launch.exit === "number") return;
436
+
437
+ openLinks(process.argv.slice(2));
438
+ registerDeepLinks(boot.app, deepLinkSchemes).catch((error) =>
439
+ console.warn("[akan-native] cannot register the deep link schemes", error),
440
+ );
441
+ })
442
+ .catch((error: unknown) => console.error("[akan-native] the launch phase failed", error));
355
443
  }
@@ -1,18 +1,29 @@
1
1
 
2
2
 
3
- import { existsSync, readFileSync } from "node:fs";
3
+ import { existsSync, mkdirSync, readFileSync } from "node:fs";
4
4
  import { join } from "node:path";
5
5
  import { renderInitScript } from "../../core/src/protocol.ts";
6
6
  import { ABI_MAJOR, cstr, lastError, openNative, resolvePaths } from "./ffi.ts";
7
- import { webviewDataDir } from "./paths.ts";
7
+ import { appLocalDataDir, webviewDataDir } from "./paths.ts";
8
8
  import type { Launch, LaunchWindow } from "./plugin.ts";
9
+ import { READY_TIMEOUT } from "./server.ts";
9
10
 
10
11
  const ENV_OVERRIDE_PREFIX = "AKAN_NATIVE_PUBLIC_";
11
12
 
12
- /** env.runtime.json, overlaid with AKAN_NATIVE_PUBLIC_* process variables (ENV-1, highest precedence). */
13
- function runtimeEnv(resources: string): Record<string, string> {
14
- const env = JSON.parse(readFileSync(join(resources, "env.runtime.json"), "utf8")) as Record<string, string>;
15
- for (const [key, value] of Object.entries(process.env)) {
13
+ /** How long the main thread waits for the launch phase: the plugins' setups, then the carried server. */
14
+ const LAUNCH_TIMEOUT = 10_000 + READY_TIMEOUT;
15
+
16
+ /**
17
+ * env.runtime.json, overlaid with what the launch phase learned (the carried server's URL), then with
18
+ * AKAN_NATIVE_PUBLIC_* process variables (ENV-1, highest precedence).
19
+ */
20
+ export function runtimeEnv(
21
+ file: Record<string, string>,
22
+ launched: Record<string, string> = {},
23
+ processEnv: Record<string, string | undefined> = process.env,
24
+ ): Record<string, string> {
25
+ const env = { ...file, ...launched };
26
+ for (const [key, value] of Object.entries(processEnv)) {
16
27
  if (key.startsWith(ENV_OVERRIDE_PREFIX) && value !== undefined) env[key.slice("AKAN_NATIVE_".length)] = value;
17
28
  }
18
29
  return env;
@@ -31,6 +42,13 @@ interface ShellConfig {
31
42
  startPath?: string;
32
43
  /** security.shell.externalSchemes (L0): schemes links may also hand to the OS. */
33
44
  externalSchemes?: string[];
45
+ /** desktop.recovery: what a window does when its page's process ends. */
46
+ recovery?: "errorPage" | "reload";
47
+ /** desktop.screenCapture (Windows): "auto" answers getDisplayMedia with the first screen. */
48
+ screenCapture?: "picker" | "auto";
49
+ /** desktop.window: the main window from its first frame, unless the launch phase says otherwise. */
50
+ fullscreen?: boolean;
51
+ skipTaskbar?: boolean;
34
52
  }
35
53
 
36
54
  const finite = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v);
@@ -42,9 +60,27 @@ export function launchBounds(window: LaunchWindow): LaunchWindow {
42
60
  if (finite(window.width) && window.width >= 1) out.width = window.width;
43
61
  if (finite(window.height) && window.height >= 1) out.height = window.height;
44
62
  if (window.maximized === true) out.maximized = true;
63
+ if (typeof window.fullscreen === "boolean") out.fullscreen = window.fullscreen;
64
+ if (typeof window.skipTaskbar === "boolean") out.skipTaskbar = window.skipTaskbar;
45
65
  return out;
46
66
  }
47
67
 
68
+ /**
69
+ * Windows renames no folder that is some process's working folder: an app started from its install folder (the
70
+ * installer, a shortcut, Explorer) would hand it to the webview's processes, and an update could never swap it
71
+ * (plugins/updates). Called after the launch phase, where single-instance forwards a second launch's folder.
72
+ */
73
+ export function leaveInstallFolder(appId: string, platform: NodeJS.Platform = process.platform): void {
74
+ if (platform !== "win32" || !appId) return;
75
+ try {
76
+ const dir = appLocalDataDir(appId);
77
+ mkdirSync(dir, { recursive: true });
78
+ process.chdir(dir);
79
+ } catch (error) {
80
+ console.warn("[akan-native] cannot leave the install folder; an update may not apply", error);
81
+ }
82
+ }
83
+
48
84
  function fail(message: string, error?: unknown): never {
49
85
  console.error(`[akan-native] ${message}`, error ?? "");
50
86
  process.exit(1);
@@ -53,13 +89,14 @@ function fail(message: string, error?: unknown): never {
53
89
  export async function startMain(workerUrl: string): Promise<never> {
54
90
  const paths = resolvePaths();
55
91
  let shell: ShellConfig;
56
- let initJs: string;
92
+ let boot: string;
93
+ let fileEnv: Record<string, string>;
57
94
  let dev = false;
58
95
  let appId = "";
59
96
  try {
60
97
  shell = JSON.parse(readFileSync(join(paths.resources, "shell.json"), "utf8"));
61
- const boot = readFileSync(join(paths.resources, "boot.json"), "utf8");
62
- initJs = renderInitScript(boot.trim(), JSON.stringify(runtimeEnv(paths.resources)));
98
+ boot = readFileSync(join(paths.resources, "boot.json"), "utf8");
99
+ fileEnv = JSON.parse(readFileSync(join(paths.resources, "env.runtime.json"), "utf8")) as Record<string, string>;
63
100
  const parsed = JSON.parse(boot) as { dev?: boolean; app?: { id?: string } };
64
101
  dev = parsed.dev === true;
65
102
  appId = parsed.app?.id ?? "";
@@ -86,7 +123,7 @@ export async function startMain(workerUrl: string): Promise<never> {
86
123
  const worker = new Worker(workerUrl, { argv: process.argv.slice(2) } as WorkerOptions);
87
124
 
88
125
  const launch = await new Promise<Launch>((resolve) => {
89
- const timer = setTimeout(() => fail("plugin host did not start within 10 s"), 10_000);
126
+ const timer = setTimeout(() => fail(`plugin host did not start within ${LAUNCH_TIMEOUT / 1000} s`), LAUNCH_TIMEOUT);
90
127
  worker.addEventListener("error", (event) =>
91
128
  fail("plugin host failed to start", (event as ErrorEvent).message ?? event),
92
129
  );
@@ -94,7 +131,7 @@ export async function startMain(workerUrl: string): Promise<never> {
94
131
  const data = (event as MessageEvent).data as { type?: string } & Partial<Launch>;
95
132
  if (data?.type === "ready") {
96
133
  clearTimeout(timer);
97
- resolve({ window: data.window ?? {}, exit: data.exit });
134
+ resolve({ window: data.window ?? {}, exit: data.exit, env: data.env });
98
135
  }
99
136
  });
100
137
  });
@@ -102,12 +139,21 @@ export async function startMain(workerUrl: string): Promise<never> {
102
139
  worker.terminate();
103
140
  process.exit(launch.exit);
104
141
  }
142
+ leaveInstallFolder(appId);
105
143
  const bounds = launchBounds(launch.window);
144
+ let initJs: string;
145
+ try {
146
+ initJs = renderInitScript(boot.trim(), JSON.stringify(runtimeEnv(fileEnv, launch.env)));
147
+ } catch (error) {
148
+ fail(`cannot render the page's init script from ${paths.resources}`, error);
149
+ }
106
150
 
107
151
  const config = {
108
152
  title: shell.title,
109
153
  width: shell.width ?? 1024,
110
154
  height: shell.height ?? 720,
155
+ fullscreen: shell.fullscreen === true,
156
+ skipTaskbar: shell.skipTaskbar === true,
111
157
  ...bounds,
112
158
  appDir: paths.appDir,
113
159
  initJs,
@@ -116,6 +162,8 @@ export async function startMain(workerUrl: string): Promise<never> {
116
162
  backgroundColor: shell.backgroundColor,
117
163
  backgroundColorDark: shell.backgroundColorDark,
118
164
  externalSchemes: shell.externalSchemes ?? [],
165
+ ...(shell.recovery ? { recovery: shell.recovery } : {}),
166
+ ...(shell.screenCapture ? { screenCapture: shell.screenCapture } : {}),
119
167
 
120
168
  activation: process.env.AKAN_NATIVE_ACTIVATION ?? "regular",
121
169
 
@@ -25,9 +25,24 @@ export function appDataDir(
25
25
  return join(xdg(env.XDG_DATA_HOME, join(home, ".local", "share")), id);
26
26
  }
27
27
 
28
+ /**
29
+ * What is large and belongs to this PC: the webview's storage, the carried server's databases and logs.
30
+ * Windows %LOCALAPPDATA%\<id> (never Roaming, which follows the user and may be a network share)
31
+ * macOS, Linux appDataDir
32
+ */
33
+ export function appLocalDataDir(
34
+ id: string,
35
+ platform: NodeJS.Platform = process.platform,
36
+ env: Env = process.env,
37
+ home = homedir(),
38
+ ): string {
39
+ if (platform === "win32") return join(env.LOCALAPPDATA || join(home, "AppData", "Local"), id);
40
+ return appDataDir(id, platform, env, home);
41
+ }
42
+
28
43
  /**
29
44
  * The webview's own storage and caches (Windows, Linux; WKWebView chooses its own on macOS):
30
- * Windows %LOCALAPPDATA%\<id>\WebView2 (large and machine-specific: not Roaming)
45
+ * Windows %LOCALAPPDATA%\<id>\WebView2
31
46
  * Linux $XDG_DATA_HOME/<id>/webview
32
47
  * WebView2's default would be next to the .exe, which is not writable once installed.
33
48
  */
@@ -37,14 +52,28 @@ export function webviewDataDir(
37
52
  env: Env = process.env,
38
53
  home = homedir(),
39
54
  ): string | undefined {
40
- if (platform === "win32") return join(env.LOCALAPPDATA || join(home, "AppData", "Local"), id, "WebView2");
55
+ if (platform === "win32") return join(appLocalDataDir(id, platform, env, home), "WebView2");
41
56
  if (platform === "linux") return join(appDataDir(id, platform, env, home), "webview");
42
57
  return undefined;
43
58
  }
44
59
 
60
+ /**
61
+ * The carried server's folder (server.ts): <app local data>/server. A debug build has the release app's id, so
62
+ * its server keeps its own folder and never opens the databases of the release app on the same PC.
63
+ */
64
+ export function serverDataDir(
65
+ id: string,
66
+ dev: boolean,
67
+ platform: NodeJS.Platform = process.platform,
68
+ env: Env = process.env,
69
+ home = homedir(),
70
+ ): string {
71
+ return join(appLocalDataDir(id, platform, env, home), dev ? "server-debug" : "server");
72
+ }
73
+
45
74
  /**
46
75
  * Folders whose files no FileRef may serve (L4): the shell's and the plugins' own storage
47
- * (preferences, secure storage, databases, update bundles, window state, the webview's data). Only
76
+ * (preferences, secure storage, databases, update bundles, window state, the webview's data, the server's). Only
48
77
  * the filesystem plugin's `data` base (<app data>/files) is servable inside the app data folder.
49
78
  */
50
79
  export function reservedDirs(
@@ -54,6 +83,11 @@ export function reservedDirs(
54
83
  home = homedir(),
55
84
  ): { root: string; except: string[] }[] {
56
85
  const data = appDataDir(id, platform, env, home);
86
+ const local = appLocalDataDir(id, platform, env, home);
57
87
  const webview = webviewDataDir(id, platform, env, home);
58
- return [{ root: data, except: [join(data, "files")] }, ...(webview ? [{ root: webview, except: [] }] : [])];
88
+ return [
89
+ { root: data, except: [join(data, "files")] },
90
+ ...(local !== data ? [{ root: local, except: [] }] : []),
91
+ ...(webview ? [{ root: webview, except: [] }] : []),
92
+ ];
59
93
  }
@@ -16,6 +16,8 @@ export type EmitTarget = { window: number } | "focused";
16
16
 
17
17
  export interface DesktopContext {
18
18
  app: AppInfo;
19
+ /** A dev build (boot.json `dev`): its pages come from a dev server the shell did not start. */
20
+ readonly dev: boolean;
19
21
  /**
20
22
  * The window whose page made this call (SH-6; 1 = the window the app opened). Only in method
21
23
  * calls; undefined in setup and event sources.
@@ -40,6 +42,22 @@ export interface DesktopContext {
40
42
  readonly document?: DocumentScope;
41
43
  /** Per-app data folder, e.g. ~/Library/Application Support/<app id>. Created on first access. */
42
44
  readonly appDataDir: string;
45
+ /**
46
+ * For what is large and belongs to this PC (caches, downloads, databases): %LOCALAPPDATA%\<app id> on Windows,
47
+ * where appDataDir roams with the user; appDataDir on macOS and Linux. Created on first access.
48
+ */
49
+ readonly appLocalDataDir: string;
50
+ /**
51
+ * The executables the app carries (desktop.bin, akanjs `bin`), or null. The host puts the folder first on
52
+ * process.env.PATH, which node:child_process and `Bun.spawn(cmd, { env: process.env })` use; a Bun.spawn or
53
+ * Bun.which without `env` reads the environment the app started with, so name a file here or pass the env.
54
+ */
55
+ readonly binDir: string | null;
56
+ /**
57
+ * The server the app carries (desktop.server), or null. `ready` settles once per session: true when the server
58
+ * first answered ready, false when it could not start or gave up before that.
59
+ */
60
+ readonly server: DesktopServerStatus | null;
43
61
  /** Pushes an event of this plugin to the pages that listen. Returns the windows reached. */
44
62
  emit(event: string, data?: unknown, target?: EmitTarget): number[];
45
63
  /** Serves a local file at /__akan_native/file/<id> for the rest of the session (PL-7). */
@@ -101,6 +119,10 @@ export interface DesktopContext {
101
119
  };
102
120
  }
103
121
 
122
+ export interface DesktopServerStatus {
123
+ readonly ready: Promise<boolean>;
124
+ }
125
+
104
126
  /** Which page load ended. `id` is "" for a page that sends no document id (v1 callers, tests). */
105
127
  export interface DocumentInfo {
106
128
  window: number;
@@ -129,12 +151,18 @@ export interface LaunchWindow {
129
151
  width?: number;
130
152
  height?: number;
131
153
  maximized?: boolean;
154
+ /** Borderless fullscreen from the first frame, on the display x and y are on (else the primary one). */
155
+ fullscreen?: boolean;
156
+ /** No taskbar button (Windows, Linux; macOS has none). */
157
+ skipTaskbar?: boolean;
132
158
  }
133
159
 
134
160
  /** What the launch phase decided; sent to the main thread with "ready". */
135
161
  export interface Launch {
136
162
  window: LaunchWindow;
137
163
  exit?: number;
164
+ /** PUBLIC_* values for the page known only at launch (the carried server's URL), under AKAN_NATIVE_PUBLIC_*. */
165
+ env?: Record<string, string>;
138
166
  }
139
167
 
140
168
  export interface NativeEvent {
@@ -0,0 +1,159 @@
1
+
2
+
3
+ import { spawn } from "node:child_process";
4
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
5
+ import { tmpdir } from "node:os";
6
+ import { dirname } from "node:path";
7
+
8
+ export interface RelaunchOptions {
9
+ /** How long the helper waits after this process exited before it starts the app. */
10
+ delayMs?: number;
11
+ }
12
+
13
+ let started: Promise<void> | null = null;
14
+
15
+ /**
16
+ * Once this process has exited: renames `moves` in order and starts `exe` with this environment. macOS and
17
+ * Linux rename a running app's folder right away, so only the start waits; Windows refuses that, so a helper
18
+ * does the renames too (and on a failed rename puts back what it moved, so there is always an app to start).
19
+ * Only the first call of a process starts a helper; later ones answer the same promise.
20
+ */
21
+ export function relaunchAfterExit(
22
+ exe: string,
23
+ moves: [string, string][] = [],
24
+ { delayMs = 0 }: RelaunchOptions = {},
25
+ ): Promise<void> {
26
+ if (started) return started;
27
+ try {
28
+ const helper = startHelper(exe, moves, Math.max(0, Math.round(delayMs)));
29
+ started = helper;
30
+ return helper;
31
+ } catch (error) {
32
+ return Promise.reject(error);
33
+ }
34
+ }
35
+
36
+ function startHelper(exe: string, moves: [string, string][], delayMs: number): Promise<void> {
37
+
38
+ const { AKAN_NATIVE_QUIT_ON_STDIN: _cli, ...inherited } = process.env;
39
+ const delay = (delayMs / 1000).toFixed(3);
40
+ if (process.platform !== "win32") {
41
+ for (const [from, to] of moves) renameSync(from, to);
42
+ const child = spawn(
43
+ "/bin/sh",
44
+ [
45
+ "-c",
46
+ 'while kill -0 "$AKAN_NATIVE_PARENT" 2>/dev/null; do sleep 0.2; done; sleep "$AKAN_NATIVE_DELAY"; exec "$AKAN_NATIVE_EXE"',
47
+ ],
48
+ {
49
+ detached: true,
50
+ stdio: "inherit",
51
+ env: {
52
+ ...inherited,
53
+ AKAN_NATIVE_PARENT: String(process.pid),
54
+ AKAN_NATIVE_EXE: exe,
55
+ AKAN_NATIVE_DELAY: delay,
56
+ },
57
+ },
58
+ );
59
+ child.once("error", (error) => console.error("[akan-native] cannot start the relaunch helper", error));
60
+ child.unref();
61
+ return Promise.resolve();
62
+ }
63
+
64
+ const script = `
65
+ $ErrorActionPreference = 'Stop'
66
+ $ProgressPreference = 'SilentlyContinue'
67
+ Wait-Process -Id $env:AKAN_NATIVE_PARENT -ErrorAction SilentlyContinue
68
+ $moves = $env:AKAN_NATIVE_MOVES | ConvertFrom-Json
69
+ $done = @()
70
+ try {
71
+ foreach ($m in $moves) {
72
+ for ($i = 0; ; $i++) { try { Move-Item -LiteralPath $m[0] -Destination $m[1]; break } catch { if ($i -ge 40) { throw }; Start-Sleep -Milliseconds 250 } }
73
+ $done = ,$m + $done
74
+ }
75
+ } catch {
76
+ foreach ($m in $done) { try { Move-Item -LiteralPath $m[1] -Destination $m[0] } catch {} }
77
+ }
78
+ Start-Sleep -Milliseconds ([int]$env:AKAN_NATIVE_DELAY_MS)
79
+ Start-Process -NoNewWindow -WorkingDirectory $env:AKAN_NATIVE_CWD -FilePath $env:AKAN_NATIVE_EXE
80
+ `;
81
+
82
+ const encoded = Buffer.from(script, "utf16le").toString("base64");
83
+
84
+ const cwd = tmpdir();
85
+ const env = {
86
+ ...inherited,
87
+ AKAN_NATIVE_PARENT: String(process.pid),
88
+ AKAN_NATIVE_EXE: exe,
89
+ AKAN_NATIVE_MOVES: JSON.stringify(moves),
90
+ AKAN_NATIVE_DELAY_MS: String(delayMs),
91
+ AKAN_NATIVE_CWD: cwd,
92
+ };
93
+ const args = [
94
+ "/d",
95
+ "/c",
96
+ "start",
97
+ "/b",
98
+ "powershell.exe",
99
+ "-NoProfile",
100
+ "-NonInteractive",
101
+ "-WindowStyle",
102
+ "Hidden",
103
+ "-EncodedCommand",
104
+ encoded,
105
+ ];
106
+ let child: ReturnType<typeof spawn>;
107
+ try {
108
+ child = spawn("cmd.exe", args, { cwd, stdio: "inherit", windowsHide: true, env });
109
+ } catch {
110
+ child = spawn("cmd.exe", args, { cwd, stdio: "ignore", windowsHide: true, env });
111
+ }
112
+ return new Promise((resolve) => {
113
+ const done = () => {
114
+ clearTimeout(timeout);
115
+ resolve();
116
+ };
117
+ const timeout = setTimeout(done, 2_500);
118
+ child.once("exit", done);
119
+ child.once("error", (error) => {
120
+ console.error("[akan-native] cannot start the relaunch helper", error);
121
+ done();
122
+ });
123
+ });
124
+ }
125
+
126
+ /** Relaunches after the browser process ended, in a row: each one's app ran less than RELAUNCH_HEALTHY. */
127
+ export const RELAUNCH_LIMIT = 10;
128
+ export const RELAUNCH_HEALTHY = 60_000;
129
+
130
+ interface RelaunchRecord {
131
+ streak: number;
132
+ /** When the last relaunched app was due to start (epoch ms). */
133
+ startsAt: number;
134
+ }
135
+
136
+ /**
137
+ * desktop.recovery "reload" after the webview's browser process ended: how long the relaunched app waits, or null
138
+ * once RELAUNCH_LIMIT relaunches in a row did not help. The first relaunch is immediate, then 1 s doubling to a
139
+ * minute (lib.rs recovery_wait); an app that ran for RELAUNCH_HEALTHY starts the count again. `file` keeps the
140
+ * count across the processes.
141
+ */
142
+ export function nextRelaunchDelay(file: string, now = Date.now()): number | null {
143
+ let last: RelaunchRecord | null = null;
144
+ try {
145
+ const raw = JSON.parse(readFileSync(file, "utf8")) as Partial<RelaunchRecord>;
146
+ if (typeof raw.streak === "number" && typeof raw.startsAt === "number")
147
+ last = { streak: raw.streak, startsAt: raw.startsAt };
148
+ } catch {}
149
+ const streak = last && now - last.startsAt < RELAUNCH_HEALTHY ? last.streak + 1 : 0;
150
+ if (streak >= RELAUNCH_LIMIT) return null;
151
+ const delay = streak === 0 ? 0 : Math.min(1000 * 2 ** Math.min(streak - 1, 6), 60_000);
152
+ try {
153
+ mkdirSync(dirname(file), { recursive: true });
154
+ writeFileSync(file, JSON.stringify({ streak, startsAt: now + delay } satisfies RelaunchRecord));
155
+ } catch (error) {
156
+ console.warn("[akan-native] cannot record the relaunch", error);
157
+ }
158
+ return delay;
159
+ }