@patodo/localapp 0.1.1 → 0.2.5

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 (97) hide show
  1. package/.localapp-artifact.json +160 -130
  2. package/README.md +14 -3
  3. package/bin/localapp.mjs +699 -192
  4. package/package.json +1 -1
  5. package/runtime/native/adapter-manifest.json +10 -10
  6. package/runtime/native/darwin-arm64/LocalAppBridge.app/Contents/MacOS/LocalAppBridge +0 -0
  7. package/runtime/native/darwin-arm64/LocalAppBridge.app/Contents/Resources/localapp-native-ipc-client.mjs +57 -5
  8. package/runtime/native/darwin-arm64/LocalAppBridge.app/Contents/_CodeSignature/CodeResources +2 -2
  9. package/runtime/native/darwin-x64/LocalAppBridge.app/Contents/MacOS/LocalAppBridge +0 -0
  10. package/runtime/native/darwin-x64/LocalAppBridge.app/Contents/Resources/localapp-native-ipc-client.mjs +57 -5
  11. package/runtime/native/darwin-x64/LocalAppBridge.app/Contents/_CodeSignature/CodeResources +2 -2
  12. package/runtime/native/linux-x64/localapp-native-ipc-client.mjs +57 -5
  13. package/runtime/native/linux-x64/localapp-notifications +0 -0
  14. package/runtime/native/win32-x64/localapp-native-ipc-client.mjs +57 -5
  15. package/runtime/native/win32-x64/localapp-native.exe +0 -0
  16. package/runtime/server/.localapp-server-runtime.json +62 -62
  17. package/runtime/server/bin/server-cli.cjs +14 -2
  18. package/runtime/server/bin/worker.cjs +12706 -3168
  19. package/runtime/server/web/404.html +1 -1
  20. package/runtime/server/web/_next/static/chunks/{416-53d48ad9442eb7b2.js → 416-c15a156fd32eefc3.js} +1 -1
  21. package/runtime/server/web/_next/static/chunks/app/(dashboard)/page-3252f21360e42fa1.js +1 -0
  22. package/runtime/server/web/_next/static/chunks/app/{layout-5557bc90d966fded.js → layout-2231382739460b63.js} +1 -1
  23. package/runtime/server/web/_next/static/css/b8973d29c0d3fd9b.css +3 -0
  24. package/runtime/server/web/inbox.html +1 -1
  25. package/runtime/server/web/inbox.txt +7 -7
  26. package/runtime/server/web/index.html +1 -1
  27. package/runtime/server/web/index.txt +8 -8
  28. package/runtime/server/web/my/analytics.html +1 -1
  29. package/runtime/server/web/my/analytics.txt +7 -7
  30. package/runtime/server/web/my/apps/placeholder/settings.html +1 -1
  31. package/runtime/server/web/my/apps/placeholder/settings.txt +7 -7
  32. package/runtime/server/web/my/apps.html +1 -1
  33. package/runtime/server/web/my/apps.txt +7 -7
  34. package/runtime/server/web/my/dashboard.html +1 -1
  35. package/runtime/server/web/my/dashboard.txt +7 -7
  36. package/runtime/server/web/my/device-actions.html +1 -1
  37. package/runtime/server/web/my/device-actions.txt +7 -7
  38. package/runtime/server/web/my/device-notifications.html +1 -1
  39. package/runtime/server/web/my/device-notifications.txt +7 -7
  40. package/runtime/server/web/my/favorites.html +1 -1
  41. package/runtime/server/web/my/favorites.txt +7 -7
  42. package/runtime/server/web/my/groups.html +1 -1
  43. package/runtime/server/web/my/groups.txt +7 -7
  44. package/runtime/server/web/my/info.html +1 -1
  45. package/runtime/server/web/my/info.txt +7 -7
  46. package/runtime/server/web/my/keys.html +1 -1
  47. package/runtime/server/web/my/keys.txt +7 -7
  48. package/runtime/server/web/my/orgs.html +1 -1
  49. package/runtime/server/web/my/orgs.txt +7 -7
  50. package/runtime/server/web/my/pages.html +1 -1
  51. package/runtime/server/web/my/pages.txt +7 -7
  52. package/runtime/server/web/my/peers.html +1 -1
  53. package/runtime/server/web/my/peers.txt +7 -7
  54. package/runtime/server/web/my/recent.html +1 -1
  55. package/runtime/server/web/my/recent.txt +7 -7
  56. package/runtime/server/web/my/settings.html +1 -1
  57. package/runtime/server/web/my/settings.txt +7 -7
  58. package/runtime/server/web/my/studio.html +1 -1
  59. package/runtime/server/web/my/studio.txt +7 -7
  60. package/runtime/server/web/my/subscriptions.html +1 -1
  61. package/runtime/server/web/my/subscriptions.txt +7 -7
  62. package/runtime/server/web/my/system.html +1 -1
  63. package/runtime/server/web/my/system.txt +7 -7
  64. package/runtime/server/web/my/tasks.html +1 -1
  65. package/runtime/server/web/my/tasks.txt +7 -7
  66. package/runtime/server/web/my/users.html +1 -1
  67. package/runtime/server/web/my/users.txt +7 -7
  68. package/runtime/server/web/my.html +1 -1
  69. package/runtime/server/web/my.txt +7 -7
  70. package/runtime/server/web/platform-shell/placeholder/placeholder.html +1 -1
  71. package/runtime/server/web/platform-shell/placeholder/placeholder.txt +8 -8
  72. package/runtime/server/web/platform-shell-preview.html +1 -1
  73. package/runtime/server/web/platform-shell-preview.txt +8 -8
  74. package/runtime/server/web/setup.html +1 -1
  75. package/runtime/server/web/setup.txt +7 -7
  76. package/template/.claude/skills/localapp-collaboration/SKILL.md +92 -0
  77. package/template/AGENTS.md +6 -0
  78. package/template/CLAUDE.md +6 -0
  79. package/template/package.json +2 -1
  80. package/template/runtime/platform-capabilities.json +13 -1
  81. package/template/runtime/sdk/crdt/package.json +39 -0
  82. package/template/runtime/sdk/crdt/src/index.ts +440 -0
  83. package/template/runtime/sdk/crdt/src/react.ts +67 -0
  84. package/template/runtime/sdk/crdt/tests/provider.test.ts +169 -0
  85. package/template/runtime/sdk/crdt/tsconfig.json +18 -0
  86. package/template/runtime/server-core/dist/generated/platform-capabilities.d.ts +14 -2
  87. package/template/runtime/server-core/dist/generated/platform-capabilities.d.ts.map +1 -1
  88. package/template/runtime/server-core/dist/generated/platform-capabilities.js +14 -2
  89. package/template/runtime/server-core/dist/generated/platform-capabilities.js.map +1 -1
  90. package/template/runtime/server-core/dist/lib/__tests__/platform-capabilities.test.js +13 -2
  91. package/template/runtime/server-core/dist/lib/__tests__/platform-capabilities.test.js.map +1 -1
  92. package/template/runtime/version.json +1 -1
  93. package/template/tests/agent-guidance-template.test.ts +14 -0
  94. package/runtime/server/web/_next/static/chunks/app/(dashboard)/page-f4641be7b88818a2.js +0 -1
  95. package/runtime/server/web/_next/static/css/afdc0938fca59693.css +0 -3
  96. /package/runtime/server/web/_next/static/{q1M2-7PPyORakTt3WglxD → xssdbCxur5ZBKtk-0DVhn}/_buildManifest.js +0 -0
  97. /package/runtime/server/web/_next/static/{q1M2-7PPyORakTt3WglxD → xssdbCxur5ZBKtk-0DVhn}/_ssgManifest.js +0 -0
package/bin/localapp.mjs CHANGED
@@ -552,9 +552,9 @@ var require_yauzl = __commonJS({
552
552
  exports.Entry = Entry;
553
553
  exports.LocalFileHeader = LocalFileHeader;
554
554
  exports.RandomAccessReader = RandomAccessReader;
555
- function openPromise(path34, options2) {
555
+ function openPromise(path35, options2) {
556
556
  return new Promise((resolve2, reject) => {
557
- open2(path34, { ...options2, lazyEntries: true }, function(err, zipfile) {
557
+ open2(path35, { ...options2, lazyEntries: true }, function(err, zipfile) {
558
558
  if (err) return reject(err);
559
559
  resolve2(zipfile);
560
560
  });
@@ -584,7 +584,7 @@ var require_yauzl = __commonJS({
584
584
  });
585
585
  });
586
586
  }
587
- function open2(path34, options2, callback) {
587
+ function open2(path35, options2, callback) {
588
588
  if (typeof options2 === "function") {
589
589
  callback = options2;
590
590
  options2 = null;
@@ -596,7 +596,7 @@ var require_yauzl = __commonJS({
596
596
  if (options2.validateEntrySizes == null) options2.validateEntrySizes = true;
597
597
  if (options2.strictFileNames == null) options2.strictFileNames = false;
598
598
  if (callback == null) callback = defaultCallback;
599
- fs30.open(path34, "r", function(err, fd) {
599
+ fs30.open(path35, "r", function(err, fd) {
600
600
  if (err) return callback(err);
601
601
  fromFd(fd, options2, function(err2, zipfile) {
602
602
  if (err2) fs30.close(fd, defaultCallback);
@@ -3288,13 +3288,13 @@ function getStat(file, followSymlinks) {
3288
3288
  });
3289
3289
  });
3290
3290
  }
3291
- async function* exploreWalkAsync(dir, path34, followSymlinks, useStat, shouldSkip, strict) {
3292
- let files = await readdir2(path34 + dir, strict);
3291
+ async function* exploreWalkAsync(dir, path35, followSymlinks, useStat, shouldSkip, strict) {
3292
+ let files = await readdir2(path35 + dir, strict);
3293
3293
  for (const file of files) {
3294
3294
  let name = file.name;
3295
3295
  const filename = dir + "/" + name;
3296
3296
  const relative = filename.slice(1);
3297
- const absolute = path34 + "/" + relative;
3297
+ const absolute = path35 + "/" + relative;
3298
3298
  let stat2 = file;
3299
3299
  if (useStat || followSymlinks) stat2 = await getStat(absolute, followSymlinks) ?? stat2;
3300
3300
  if (stat2.isDirectory()) {
@@ -3304,7 +3304,7 @@ async function* exploreWalkAsync(dir, path34, followSymlinks, useStat, shouldSki
3304
3304
  absolute,
3305
3305
  stat: stat2
3306
3306
  };
3307
- yield* exploreWalkAsync(filename, path34, followSymlinks, useStat, shouldSkip, false);
3307
+ yield* exploreWalkAsync(filename, path35, followSymlinks, useStat, shouldSkip, false);
3308
3308
  }
3309
3309
  } else yield {
3310
3310
  relative,
@@ -3313,8 +3313,8 @@ async function* exploreWalkAsync(dir, path34, followSymlinks, useStat, shouldSki
3313
3313
  };
3314
3314
  }
3315
3315
  }
3316
- async function* explore(path34, followSymlinks, useStat, shouldSkip) {
3317
- yield* exploreWalkAsync("", path34, followSymlinks, useStat, shouldSkip, true);
3316
+ async function* explore(path35, followSymlinks, useStat, shouldSkip) {
3317
+ yield* exploreWalkAsync("", path35, followSymlinks, useStat, shouldSkip, true);
3318
3318
  }
3319
3319
  function readOptions(options2) {
3320
3320
  return {
@@ -13799,22 +13799,22 @@ var require_ours = __commonJS({
13799
13799
  // node_modules/.pnpm/normalize-path@3.0.0/node_modules/normalize-path/index.js
13800
13800
  var require_normalize_path = __commonJS({
13801
13801
  "node_modules/.pnpm/normalize-path@3.0.0/node_modules/normalize-path/index.js"(exports, module) {
13802
- module.exports = function(path34, stripTrailing) {
13803
- if (typeof path34 !== "string") {
13802
+ module.exports = function(path35, stripTrailing) {
13803
+ if (typeof path35 !== "string") {
13804
13804
  throw new TypeError("expected path to be a string");
13805
13805
  }
13806
- if (path34 === "\\" || path34 === "/") return "/";
13807
- var len = path34.length;
13808
- if (len <= 1) return path34;
13806
+ if (path35 === "\\" || path35 === "/") return "/";
13807
+ var len = path35.length;
13808
+ if (len <= 1) return path35;
13809
13809
  var prefix = "";
13810
- if (len > 4 && path34[3] === "\\") {
13811
- var ch = path34[2];
13812
- if ((ch === "?" || ch === ".") && path34.slice(0, 2) === "\\\\") {
13813
- path34 = path34.slice(2);
13810
+ if (len > 4 && path35[3] === "\\") {
13811
+ var ch = path35[2];
13812
+ if ((ch === "?" || ch === ".") && path35.slice(0, 2) === "\\\\") {
13813
+ path35 = path35.slice(2);
13814
13814
  prefix = "//";
13815
13815
  }
13816
13816
  }
13817
- var segs = path34.split(/[/\\]+/);
13817
+ var segs = path35.split(/[/\\]+/);
13818
13818
  if (stripTrailing !== false && segs[segs.length - 1] === "") {
13819
13819
  segs.pop();
13820
13820
  }
@@ -24809,6 +24809,309 @@ var require_websocket_server = __commonJS({
24809
24809
  }
24810
24810
  });
24811
24811
 
24812
+ // packages/localapp/src/cli/help.ts
24813
+ var TOPICS = /* @__PURE__ */ new Map([
24814
+ ["", "root"],
24815
+ ["server", "server"],
24816
+ ["server start", "server-start"],
24817
+ ["server run", "server-run"],
24818
+ ["server stop", "server-stop"],
24819
+ ["server restart", "server-restart"],
24820
+ ["server status", "server-status"],
24821
+ ["server logs", "server-logs"],
24822
+ ["server uninstall", "server-uninstall"],
24823
+ ["init", "init"],
24824
+ ["check", "check"],
24825
+ ["build", "build"],
24826
+ ["login", "login"],
24827
+ ["logout", "logout"],
24828
+ ["whoami", "whoami"],
24829
+ ["app", "app"],
24830
+ ["app install", "app-install"],
24831
+ ["app sync", "app-sync"],
24832
+ ["dev", "dev"],
24833
+ ["sync-template", "sync-template"],
24834
+ ["eject-template", "eject-template"],
24835
+ ["version", "version"]
24836
+ ]);
24837
+ var HELP = /* @__PURE__ */ new Map([
24838
+ ["root", `LocalApp \u2014 run, develop, install, and synchronize LocalApp applications.
24839
+
24840
+ Usage:
24841
+ localapp <command> [options]
24842
+ localapp help [command [subcommand]]
24843
+
24844
+ Commands:
24845
+ server [start] Install system integration and start the user daemon
24846
+ server run Run the same Server in the foreground
24847
+ server <action> stop, restart, status, logs, or uninstall the daemon
24848
+ init [name] Create an application from the built-in template
24849
+ dev Start the application development environment
24850
+ check Validate the current application before installation
24851
+ build --package Build a distributable .localapp package
24852
+ app install Install the current application on a target Server
24853
+ app sync Synchronize an application to a configured peer
24854
+ login [url] Save credentials for a Server profile
24855
+ logout Remove credentials for a Server profile
24856
+ whoami Show the authenticated user for a Server profile
24857
+ sync-template Update the CLI-managed application runtime and skills
24858
+ eject-template Stop CLI management of the application template
24859
+ version Print the installed LocalApp version
24860
+
24861
+ Global options:
24862
+ -h, --help Show help for a command
24863
+ -V, --version Print the installed LocalApp version
24864
+
24865
+ Examples:
24866
+ localapp server
24867
+ localapp init interview-app
24868
+ localapp dev
24869
+ localapp app install --target local
24870
+ localapp help app sync
24871
+
24872
+ Run 'localapp help <command>' or 'localapp <command> --help' for details.
24873
+ `],
24874
+ ["server", `Manage the current user's unified LocalApp Server daemon.
24875
+
24876
+ Usage:
24877
+ localapp server [start]
24878
+ localapp server <action>
24879
+
24880
+ Actions:
24881
+ start Install localapp:// integration and start the daemon (default)
24882
+ run Run the same Server in the foreground
24883
+ stop Stop the daemon
24884
+ restart Restart the daemon
24885
+ status Print daemon and Server health information
24886
+ logs Print daemon logs
24887
+ uninstall Stop and unregister the current-user service
24888
+
24889
+ Options:
24890
+ -h, --help Show this help
24891
+
24892
+ Examples:
24893
+ localapp server
24894
+ localapp server status
24895
+ localapp server logs
24896
+ localapp server run --host 0.0.0.0 --port 3000
24897
+
24898
+ Run 'localapp help server <action>' for action-specific help.
24899
+ `],
24900
+ ["server-start", noOptionsHelp(
24901
+ "Install localapp:// integration and start the current-user daemon.",
24902
+ "localapp server [start]",
24903
+ ["localapp server", "localapp server start"]
24904
+ )],
24905
+ ["server-run", `Run the unified LocalApp Server in the foreground.
24906
+
24907
+ Usage:
24908
+ localapp server run [options]
24909
+
24910
+ Options:
24911
+ --data-dir <path> Server database, files, and configuration directory
24912
+ --host <address> Listen address (default: 127.0.0.1)
24913
+ --port <number> Listen port, 0 selects an available port (default: 0)
24914
+ -h, --help Show this help
24915
+
24916
+ Examples:
24917
+ localapp server run
24918
+ localapp server run --data-dir ./localapp-data --port 3000
24919
+ localapp server run --host 0.0.0.0 --port 3000
24920
+ `],
24921
+ ["server-stop", noOptionsHelp("Stop the current-user LocalApp daemon.", "localapp server stop", ["localapp server stop"])],
24922
+ ["server-restart", noOptionsHelp("Restart the current-user LocalApp daemon.", "localapp server restart", ["localapp server restart"])],
24923
+ ["server-status", noOptionsHelp("Print daemon status and Server health information as JSON.", "localapp server status", ["localapp server status"])],
24924
+ ["server-logs", noOptionsHelp("Print logs from the current-user LocalApp daemon.", "localapp server logs", ["localapp server logs"])],
24925
+ ["server-uninstall", noOptionsHelp("Stop and unregister the current-user LocalApp service.", "localapp server uninstall", ["localapp server uninstall"])],
24926
+ ["init", `Create or initialize an application from the built-in template.
24927
+
24928
+ Usage:
24929
+ localapp init [name] [options]
24930
+
24931
+ Arguments:
24932
+ name Project name (default: current directory name)
24933
+
24934
+ Options:
24935
+ --skip-install Do not install template dependencies
24936
+ --skip-deploy Do not install the new application on a Server
24937
+ -h, --help Show this help
24938
+
24939
+ Examples:
24940
+ localapp init interview-app
24941
+ localapp init --skip-install --skip-deploy
24942
+ `],
24943
+ ["check", `Validate the current application, contracts, migrations, and package metadata.
24944
+
24945
+ Usage:
24946
+ localapp check [options]
24947
+
24948
+ Options:
24949
+ --json Emit machine-readable JSON
24950
+ --profile <name> Use the named Server profile
24951
+ -h, --help Show this help
24952
+
24953
+ Examples:
24954
+ localapp check
24955
+ localapp check --json
24956
+ `],
24957
+ ["build", `Build the current application as a distributable .localapp package.
24958
+
24959
+ Usage:
24960
+ localapp build --package [options]
24961
+
24962
+ Options:
24963
+ --package Required package-build mode
24964
+ --output <path> Output file or directory
24965
+ -h, --help Show this help
24966
+
24967
+ Examples:
24968
+ localapp build --package
24969
+ localapp build --package --output ./dist
24970
+ `],
24971
+ ["login", `Save an API key for a LocalApp Server profile.
24972
+
24973
+ Usage:
24974
+ localapp login [server-url] [options]
24975
+
24976
+ Arguments:
24977
+ server-url Target LocalApp Server URL
24978
+
24979
+ Options:
24980
+ --api-key <key> API key issued by the target Server
24981
+ --profile <name> Save under the named profile
24982
+ -h, --help Show this help
24983
+
24984
+ Example:
24985
+ localapp login http://192.168.2.9:3000 --profile office --api-key <key>
24986
+ `],
24987
+ ["logout", profileHelp("Remove saved credentials for a LocalApp Server profile.", "logout")],
24988
+ ["whoami", profileHelp("Show the authenticated identity for a LocalApp Server profile.", "whoami")],
24989
+ ["app", `Install or synchronize LocalApp applications.
24990
+
24991
+ Usage:
24992
+ localapp app <command> [options]
24993
+
24994
+ Commands:
24995
+ install Build or read a .localapp package and install it on a Server
24996
+ sync Synchronize an installed application to a configured peer
24997
+
24998
+ Options:
24999
+ -h, --help Show this help
25000
+
25001
+ Examples:
25002
+ localapp app install --target local
25003
+ localapp app sync --peer office
25004
+
25005
+ Run 'localapp help app <command>' for command-specific help.
25006
+ `],
25007
+ ["app-install", `Install the current project or an existing .localapp package.
25008
+
25009
+ Usage:
25010
+ localapp app install [options]
25011
+
25012
+ Options:
25013
+ --target <name> Server profile or explicit target (default: project target)
25014
+ --package <path> Install an existing .localapp package instead of building
25015
+ -h, --help Show this help
25016
+
25017
+ Examples:
25018
+ localapp app install --target local
25019
+ localapp app install --target office --package ./dist/notes.localapp
25020
+ `],
25021
+ ["app-sync", `Synchronize an installed application to a configured peer Server.
25022
+
25023
+ Usage:
25024
+ localapp app sync --peer <name> [options]
25025
+
25026
+ Options:
25027
+ --peer <name> Required destination peer configured on the source Server
25028
+ --target <name> Source Server profile (default: project target)
25029
+ --with-data Also replace the destination application data and files
25030
+ --confirm-app <name> Exact application name required with --with-data
25031
+ -h, --help Show this help
25032
+
25033
+ By default only the application package, manifest, migrations, and backend
25034
+ contract are synchronized. --with-data first backs up the destination, then
25035
+ atomically replaces that application's database and files.
25036
+
25037
+ Examples:
25038
+ localapp app sync --peer office
25039
+ localapp app sync --peer office --with-data --confirm-app notes
25040
+ `],
25041
+ ["dev", noOptionsHelp(
25042
+ "Start the local application development environment and Dev Shell.",
25043
+ "localapp dev",
25044
+ ["localapp dev"]
25045
+ )],
25046
+ ["sync-template", `Update CLI-managed runtime files and Agent skills in the current project.
25047
+
25048
+ Usage:
25049
+ localapp sync-template [options]
25050
+
25051
+ Options:
25052
+ --quiet Suppress the success result
25053
+ -h, --help Show this help
25054
+
25055
+ Example:
25056
+ localapp sync-template
25057
+ `],
25058
+ ["eject-template", noOptionsHelp(
25059
+ "Stop CLI management of the current project's template files. This is irreversible.",
25060
+ "localapp eject-template",
25061
+ ["localapp eject-template"]
25062
+ )],
25063
+ ["version", `Print the installed LocalApp version.
25064
+
25065
+ Usage:
25066
+ localapp version
25067
+ localapp --version
25068
+ localapp -V
25069
+ `]
25070
+ ]);
25071
+ function resolveHelpTopic(path35) {
25072
+ return TOPICS.get(path35.join(" "));
25073
+ }
25074
+ function renderHelp(topic) {
25075
+ const help2 = HELP.get(topic);
25076
+ if (help2 === void 0) throw new Error(`Missing LocalApp help topic: ${topic}`);
25077
+ return help2;
25078
+ }
25079
+ function helpHint(argv) {
25080
+ const parent = argv[0] === "server" || argv[0] === "app" ? argv[0] : void 0;
25081
+ const commandPath = parent !== void 0 ? argv.slice(0, 2).filter((value2) => value2 !== void 0 && !value2.startsWith("-")) : argv.slice(0, 1).filter((value2) => !value2.startsWith("-"));
25082
+ const topic = resolveHelpTopic(commandPath);
25083
+ if (topic === void 0 && parent !== void 0) return `Run 'localapp ${parent} --help' for usage.`;
25084
+ if (topic === void 0 || topic === "root") return "Run 'localapp --help' for usage.";
25085
+ return `Run 'localapp ${commandPath.join(" ")} --help' for usage.`;
25086
+ }
25087
+ function noOptionsHelp(description, usage, examples) {
25088
+ return `${description}
25089
+
25090
+ Usage:
25091
+ ${usage}
25092
+
25093
+ Options:
25094
+ -h, --help Show this help
25095
+
25096
+ ${examples.length === 1 ? "Example" : "Examples"}:
25097
+ ${examples.map((example) => ` ${example}`).join("\n")}
25098
+ `;
25099
+ }
25100
+ function profileHelp(description, command) {
25101
+ return `${description}
25102
+
25103
+ Usage:
25104
+ localapp ${command} [options]
25105
+
25106
+ Options:
25107
+ --profile <name> Use the named Server profile
25108
+ -h, --help Show this help
25109
+
25110
+ Example:
25111
+ localapp ${command} --profile office
25112
+ `;
25113
+ }
25114
+
24812
25115
  // packages/localapp/src/cli/args.ts
24813
25116
  var LocalAppArgumentError = class extends Error {
24814
25117
  constructor(message, option) {
@@ -24822,11 +25125,14 @@ var LocalAppArgumentError = class extends Error {
24822
25125
  function parseLocalAppArgs(argv) {
24823
25126
  const args = [...argv];
24824
25127
  const command = args.shift();
24825
- if (command === void 0 || command === "help" || command === "--help" || command === "-h") {
25128
+ if (command === void 0) return help("root");
25129
+ if (command === "help") return parseHelp(args);
25130
+ if (command === "--help" || command === "-h") {
24826
25131
  requireNoArguments(args);
24827
- return { kind: "help" };
25132
+ return help("root");
24828
25133
  }
24829
25134
  if (command === "version" || command === "--version" || command === "-V") {
25135
+ if (hasHelp(args)) return help("version");
24830
25136
  requireNoArguments(args);
24831
25137
  return { kind: "version" };
24832
25138
  }
@@ -24834,25 +25140,27 @@ function parseLocalAppArgs(argv) {
24834
25140
  case "server":
24835
25141
  return parseServer(args);
24836
25142
  case "init":
24837
- return parseInit(args);
25143
+ return hasHelp(args) ? help("init") : parseInit(args);
24838
25144
  case "check":
24839
- return parseCheck(args);
25145
+ return hasHelp(args) ? help("check") : parseCheck(args);
24840
25146
  case "build":
24841
- return parseBuild(args);
25147
+ return hasHelp(args) ? help("build") : parseBuild(args);
24842
25148
  case "login":
24843
- return parseLogin(args);
25149
+ return hasHelp(args) ? help("login") : parseLogin(args);
24844
25150
  case "logout":
24845
- return parseProfileCommand(args, "logout");
25151
+ return hasHelp(args) ? help("logout") : parseProfileCommand(args, "logout");
24846
25152
  case "whoami":
24847
- return parseProfileCommand(args, "whoami");
25153
+ return hasHelp(args) ? help("whoami") : parseProfileCommand(args, "whoami");
24848
25154
  case "app":
24849
25155
  return parseApp(args);
24850
25156
  case "dev":
25157
+ if (hasHelp(args)) return help("dev");
24851
25158
  requireNoArguments(args);
24852
25159
  return { kind: "dev" };
24853
25160
  case "sync-template":
24854
- return parseSyncTemplate(args);
25161
+ return hasHelp(args) ? help("sync-template") : parseSyncTemplate(args);
24855
25162
  case "eject-template":
25163
+ if (hasHelp(args)) return help("eject-template");
24856
25164
  requireNoArguments(args);
24857
25165
  return { kind: "eject-template" };
24858
25166
  case "_daemon":
@@ -24864,11 +25172,14 @@ function parseLocalAppArgs(argv) {
24864
25172
  }
24865
25173
  function parseServer(args) {
24866
25174
  const action = args.shift();
25175
+ if (isHelpFlag(action)) return help("server");
24867
25176
  if (action === void 0 || action === "start") {
25177
+ if (hasHelp(args)) return help("server-start");
24868
25178
  requireNoArguments(args);
24869
25179
  return { kind: "server-start" };
24870
25180
  }
24871
25181
  if (action === "run") {
25182
+ if (hasHelp(args)) return help("server-run");
24872
25183
  const options2 = consumeOptions(args, /* @__PURE__ */ new Set(["--data-dir", "--host", "--port"]));
24873
25184
  requireNoPositionals(options2);
24874
25185
  const port = value(options2, "--port");
@@ -24880,6 +25191,7 @@ function parseServer(args) {
24880
25191
  };
24881
25192
  }
24882
25193
  if (["stop", "restart", "status", "logs", "uninstall"].includes(action)) {
25194
+ if (hasHelp(args)) return help(`server-${action}`);
24883
25195
  requireNoArguments(args);
24884
25196
  return { kind: "server-control", action };
24885
25197
  }
@@ -24930,7 +25242,9 @@ function parseProfileCommand(args, command) {
24930
25242
  }
24931
25243
  function parseApp(args) {
24932
25244
  const command = args.shift();
25245
+ if (isHelpFlag(command)) return help("app");
24933
25246
  if (command === "install") {
25247
+ if (hasHelp(args)) return help("app-install");
24934
25248
  const options2 = consumeOptions(args, /* @__PURE__ */ new Set(["--target", "--package"]));
24935
25249
  requireNoPositionals(options2);
24936
25250
  const target = value(options2, "--target");
@@ -24938,6 +25252,7 @@ function parseApp(args) {
24938
25252
  return { kind: "app-install", ...target === void 0 ? {} : { target }, ...packagePath === void 0 ? {} : { packagePath } };
24939
25253
  }
24940
25254
  if (command === "sync") {
25255
+ if (hasHelp(args)) return help("app-sync");
24941
25256
  const options2 = consumeOptions(args, /* @__PURE__ */ new Set(["--peer", "--target", "--with-data", "--confirm-app"]), /* @__PURE__ */ new Set(["--with-data"]));
24942
25257
  requireNoPositionals(options2);
24943
25258
  const peer = value(options2, "--peer");
@@ -24954,6 +25269,24 @@ function parseApp(args) {
24954
25269
  }
24955
25270
  throw new LocalAppArgumentError(`Unknown app command: ${command ?? ""}`, command);
24956
25271
  }
25272
+ function parseHelp(args) {
25273
+ const topicPath = args.filter((argument) => !isHelpFlag(argument));
25274
+ const topic = resolveHelpTopic(topicPath);
25275
+ if (topic === void 0) {
25276
+ const requested = topicPath.join(" ");
25277
+ throw new LocalAppArgumentError(`Unknown help topic: ${requested}`, topicPath[0]);
25278
+ }
25279
+ return help(topic);
25280
+ }
25281
+ function help(topic) {
25282
+ return { kind: "help", topic };
25283
+ }
25284
+ function hasHelp(args) {
25285
+ return args.some(isHelpFlag);
25286
+ }
25287
+ function isHelpFlag(argument) {
25288
+ return argument === "--help" || argument === "-h";
25289
+ }
24957
25290
  function parseSyncTemplate(args) {
24958
25291
  const options2 = consumeOptions(args, /* @__PURE__ */ new Set(["--quiet"]), /* @__PURE__ */ new Set(["--quiet"]));
24959
25292
  requireNoPositionals(options2);
@@ -25236,9 +25569,9 @@ var LocalAppClient = class {
25236
25569
  this.setTimeout = dependencies.setTimeout ?? globalThis.setTimeout;
25237
25570
  this.clearTimeout = dependencies.clearTimeout ?? globalThis.clearTimeout;
25238
25571
  }
25239
- async requestJson(path34, options2 = {}) {
25572
+ async requestJson(path35, options2 = {}) {
25240
25573
  const body = options2.body === void 0 ? void 0 : JSON.stringify(options2.body);
25241
- return this.request(path34, {
25574
+ return this.request(path35, {
25242
25575
  method: options2.method ?? "GET",
25243
25576
  body,
25244
25577
  timeoutMs: options2.timeoutMs ?? 3e4,
@@ -25246,11 +25579,11 @@ var LocalAppClient = class {
25246
25579
  signal: options2.signal
25247
25580
  });
25248
25581
  }
25249
- async getJson(path34, timeoutMs = 3e4) {
25250
- return this.requestJson(path34, { method: "GET", timeoutMs });
25582
+ async getJson(path35, timeoutMs = 3e4) {
25583
+ return this.requestJson(path35, { method: "GET", timeoutMs });
25251
25584
  }
25252
- async postJson(path34, body, timeoutMs = 3e4) {
25253
- return this.requestJson(path34, { method: "POST", body, timeoutMs });
25585
+ async postJson(path35, body, timeoutMs = 3e4) {
25586
+ return this.requestJson(path35, { method: "POST", body, timeoutMs });
25254
25587
  }
25255
25588
  async installPackage(packagePath, signal) {
25256
25589
  const form = new FormData();
@@ -25263,8 +25596,8 @@ var LocalAppClient = class {
25263
25596
  async getSyncJob(id) {
25264
25597
  return this.getJson(`/api/sync-jobs/${encodeURIComponent(id)}`);
25265
25598
  }
25266
- async request(path34, options2) {
25267
- if (!path34.startsWith("/") || path34.startsWith("//")) return { ok: false, error: "Request path must be relative to the LocalApp Server" };
25599
+ async request(path35, options2) {
25600
+ if (!path35.startsWith("/") || path35.startsWith("//")) return { ok: false, error: "Request path must be relative to the LocalApp Server" };
25268
25601
  const controller = new AbortController();
25269
25602
  let timedOut = false;
25270
25603
  const timeout2 = this.setTimeout(() => {
@@ -25276,7 +25609,7 @@ var LocalAppClient = class {
25276
25609
  if (options2.signal?.aborted) onExternalAbort();
25277
25610
  try {
25278
25611
  const version = await loadPackageVersion();
25279
- const response = await fetch(`${this.serverUrl}${path34}`, {
25612
+ const response = await fetch(`${this.serverUrl}${path35}`, {
25280
25613
  method: options2.method,
25281
25614
  body: options2.body,
25282
25615
  headers: { "X-API-Key": this.apiKey, "X-CLI-Version": version, ...options2.headers },
@@ -26285,9 +26618,9 @@ var MAX_APP_PACKAGE_BYTES = 512 * 1024 * 1024;
26285
26618
  var METADATA_PATHS = /* @__PURE__ */ new Set(["package.json", "checksums.json"]);
26286
26619
  var FIXED_ARCHIVE_DATE = /* @__PURE__ */ new Date("1980-01-01T00:00:00.000Z");
26287
26620
  var AppPackageValidationError = class extends Error {
26288
- constructor(message, path34) {
26621
+ constructor(message, path35) {
26289
26622
  super(message);
26290
- this.path = path34;
26623
+ this.path = path35;
26291
26624
  this.name = "AppPackageValidationError";
26292
26625
  }
26293
26626
  path;
@@ -26725,7 +27058,7 @@ import { createHash } from "node:crypto";
26725
27058
  var PLATFORM_CAPABILITIES = {
26726
27059
  "$schema": "./capabilities.schema.json",
26727
27060
  "schemaVersion": 1,
26728
- "platformVersion": "1.2.0",
27061
+ "platformVersion": "1.3.0",
26729
27062
  "content": {
26730
27063
  "upload": {
26731
27064
  "enabled": true,
@@ -26818,6 +27151,18 @@ var PLATFORM_CAPABILITIES = {
26818
27151
  "pageOwner": true,
26819
27152
  "groups": true
26820
27153
  },
27154
+ "collaboration": {
27155
+ "recordVersioned": {
27156
+ "enabled": true
27157
+ },
27158
+ "crdt": {
27159
+ "enabled": true,
27160
+ "protocol": "yjs-v1",
27161
+ "maxDocumentBytes": 16777216,
27162
+ "awareness": true,
27163
+ "editingOverlay": true
27164
+ }
27165
+ },
26821
27166
  "verification": {
26822
27167
  "enabled": true,
26823
27168
  "isolatedDatabase": true,
@@ -28148,11 +28493,12 @@ async function detectPackageManager(projectDir, packageJson) {
28148
28493
  return "npm";
28149
28494
  }
28150
28495
  async function runProjectCommand(invocation) {
28151
- const command = process.platform === "win32" ? `${invocation.command}.cmd` : invocation.command;
28496
+ const isWindows = process.platform === "win32";
28497
+ const command = isWindows ? `${invocation.command}.cmd` : invocation.command;
28152
28498
  return new Promise((resolve2, reject) => {
28153
28499
  const child = spawn2(command, invocation.args, {
28154
28500
  cwd: invocation.cwd,
28155
- shell: false,
28501
+ shell: isWindows,
28156
28502
  stdio: "ignore",
28157
28503
  windowsHide: true,
28158
28504
  signal: invocation.signal
@@ -28235,10 +28581,37 @@ function validateCapabilities(manifest) {
28235
28581
  if (identities.get(identity) !== true) diagnostics.push(errorDiagnostic("CAPABILITY_IDENTITY_UNSUPPORTED", "capabilities", `Target platform does not provide identity context ${identity}`, "manifest.json"));
28236
28582
  }
28237
28583
  for (const primitive of manifest.requires.primitives) {
28238
- diagnostics.push(errorDiagnostic("CAPABILITY_PRIMITIVE_UNSUPPORTED", "capabilities", `Target platform does not declare primitive ${primitive}`, "manifest.json"));
28584
+ const supported = primitive === "crdt" && PLATFORM_CAPABILITIES.collaboration.crdt.enabled || primitive === "editing-awareness-overlay" && PLATFORM_CAPABILITIES.collaboration.crdt.editingOverlay;
28585
+ if (!supported) {
28586
+ diagnostics.push(errorDiagnostic("CAPABILITY_PRIMITIVE_UNSUPPORTED", "capabilities", `Target platform does not declare primitive ${primitive}`, "manifest.json"));
28587
+ }
28588
+ }
28589
+ const collaboration = isRecord6(manifest.raw.collaboration) ? manifest.raw.collaboration : void 0;
28590
+ const resources = isRecord6(collaboration?.resources) ? collaboration.resources : void 0;
28591
+ const crdtResources = resources ? Object.values(resources).filter((resource) => isRecord6(resource) && resource.mode === "crdt") : [];
28592
+ if (collaboration?.enabled === true && crdtResources.length > 0) {
28593
+ if (!manifest.requires.primitives.includes("crdt")) {
28594
+ diagnostics.push(errorDiagnostic("CAPABILITY_REQUIREMENT_MISSING", "capabilities", "CRDT collaboration must declare requires.primitives: crdt", "manifest.json"));
28595
+ }
28596
+ const usesOverlay = collaboration.overlay !== false && crdtResources.some(
28597
+ (resource) => isRecord6(resource) && resource.awareness !== false && resource.overlay !== false
28598
+ );
28599
+ if (usesOverlay && !manifest.requires.primitives.includes("editing-awareness-overlay")) {
28600
+ diagnostics.push(errorDiagnostic("CAPABILITY_REQUIREMENT_MISSING", "capabilities", "CRDT editing overlay must declare requires.primitives: editing-awareness-overlay", "manifest.json"));
28601
+ }
28602
+ const minimum = minimumPlatformVersion(manifest.platformVersion);
28603
+ if (!minimum || compareVersion(minimum, [1, 3, 0]) < 0) {
28604
+ diagnostics.push(errorDiagnostic("CAPABILITY_PLATFORM_VERSION_TOO_LOW", "capabilities", "CRDT collaboration requires platformVersion ^1.3 or a range with minimum 1.3", "manifest.json"));
28605
+ }
28239
28606
  }
28240
28607
  return diagnostics;
28241
28608
  }
28609
+ function minimumPlatformVersion(range2) {
28610
+ const trimmed = range2.trim();
28611
+ if (trimmed.startsWith("^")) return parseVersion(trimmed.slice(1));
28612
+ const match2 = /^>=\s*([^\s,]+)\s*,?\s*<\s*([^\s,]+)$/.exec(trimmed);
28613
+ return match2 ? parseVersion(match2[1]) : null;
28614
+ }
28242
28615
  function parseBackend(value2) {
28243
28616
  if (value2 === void 0 || value2 === null) return void 0;
28244
28617
  if (!isRecord6(value2)) throw new Error("manifest backend must be an object");
@@ -28931,8 +29304,8 @@ import { randomBytes as randomBytes2 } from "node:crypto";
28931
29304
  import { chmodSync, renameSync } from "node:fs";
28932
29305
  import fs18 from "node:fs/promises";
28933
29306
  import net from "node:net";
28934
- import path22 from "node:path";
28935
- import { fileURLToPath as fileURLToPath3 } from "node:url";
29307
+ import path23 from "node:path";
29308
+ import { fileURLToPath as fileURLToPath4 } from "node:url";
28936
29309
 
28937
29310
  // packages/localapp/src/dev/credentials.ts
28938
29311
  import { randomBytes } from "node:crypto";
@@ -29005,9 +29378,28 @@ import { spawn as spawn5 } from "node:child_process";
29005
29378
 
29006
29379
  // packages/localapp/src/native/native-adapter.ts
29007
29380
  import { spawn as spawn4 } from "node:child_process";
29381
+ import { existsSync } from "node:fs";
29008
29382
  import fs17 from "node:fs/promises";
29009
29383
  import { homedir as homedir2 } from "node:os";
29010
- import path21 from "node:path";
29384
+ import path22 from "node:path";
29385
+
29386
+ // packages/localapp/src/artifact-directory.ts
29387
+ import { realpathSync } from "node:fs";
29388
+ import path20 from "node:path";
29389
+ import { fileURLToPath as fileURLToPath3 } from "node:url";
29390
+ function artifactDirectoryFromEntrypoint(entrypoint) {
29391
+ const canonical = realpathSync(entrypoint);
29392
+ return path20.resolve(path20.dirname(canonical), "..");
29393
+ }
29394
+ function localAppArtifactDirectory(entrypoint = process.argv[1]) {
29395
+ if (entrypoint !== void 0 && entrypoint.length > 0) {
29396
+ try {
29397
+ return artifactDirectoryFromEntrypoint(entrypoint);
29398
+ } catch {
29399
+ }
29400
+ }
29401
+ return path20.resolve(path20.dirname(fileURLToPath3(import.meta.url)), "..");
29402
+ }
29011
29403
 
29012
29404
  // packages/server/src/lib/device-action-types.ts
29013
29405
  var DEVICE_ACTION_PROTOCOL_VERSION = 2;
@@ -29133,21 +29525,21 @@ function invalid2() {
29133
29525
  // packages/localapp/src/native/adapter-selection.ts
29134
29526
  import crypto5 from "node:crypto";
29135
29527
  import fs16 from "node:fs/promises";
29136
- import path20 from "node:path";
29528
+ import path21 from "node:path";
29137
29529
  async function selectNativeAdapter(options2) {
29138
29530
  const platform = options2.platform ?? process.platform;
29139
29531
  const arch = options2.arch ?? process.arch;
29140
29532
  const target = targetFor(platform, arch);
29141
- const root = path20.resolve(options2.root);
29533
+ const root = path21.resolve(options2.root);
29142
29534
  let value2;
29143
29535
  try {
29144
- value2 = JSON.parse(await fs16.readFile(path20.join(root, "adapter-manifest.json"), "utf8"));
29536
+ value2 = JSON.parse(await fs16.readFile(path21.join(root, "adapter-manifest.json"), "utf8"));
29145
29537
  } catch {
29146
29538
  throw unsupported(platform, arch);
29147
29539
  }
29148
29540
  const manifest = parseManifest(value2, target, root, platform, arch);
29149
29541
  for (const asset of manifest.assets) {
29150
- const absolute = path20.join(root, ...asset.path.split("/"));
29542
+ const absolute = path21.join(root, ...asset.path.split("/"));
29151
29543
  let bytes;
29152
29544
  try {
29153
29545
  const stat2 = await fs16.lstat(absolute);
@@ -29168,8 +29560,8 @@ async function selectNativeAdapter(options2) {
29168
29560
  return {
29169
29561
  target,
29170
29562
  root,
29171
- executable: path20.join(root, ...executable.split("/")),
29172
- ipcClient: path20.join(root, ...ipcClient.split("/")),
29563
+ executable: path21.join(root, ...executable.split("/")),
29564
+ ipcClient: path21.join(root, ...ipcClient.split("/")),
29173
29565
  signing: manifest.signing,
29174
29566
  assets: manifest.assets
29175
29567
  };
@@ -29202,7 +29594,7 @@ function parseSingleManifest(value2, target, root, platform, arch) {
29202
29594
  throw unsupported(platform, arch);
29203
29595
  }
29204
29596
  const assets = value2.assets.map((asset) => {
29205
- if (!record(asset) || !exactKeys(asset, ["path", "sha256"]) || typeof asset.path !== "string" || typeof asset.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(asset.sha256) || !safeRelativeAsset(asset.path) || !asset.path.startsWith(`${target}/`) || path20.resolve(root, ...asset.path.split("/")).startsWith(`${root}${path20.sep}`) === false) {
29597
+ if (!record(asset) || !exactKeys(asset, ["path", "sha256"]) || typeof asset.path !== "string" || typeof asset.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(asset.sha256) || !safeRelativeAsset(asset.path) || !asset.path.startsWith(`${target}/`) || path21.resolve(root, ...asset.path.split("/")).startsWith(`${root}${path21.sep}`) === false) {
29206
29598
  throw unsupported(platform, arch);
29207
29599
  }
29208
29600
  return { path: asset.path, sha256: asset.sha256 };
@@ -29211,7 +29603,7 @@ function parseSingleManifest(value2, target, root, platform, arch) {
29211
29603
  return { signing: { mode: value2.signing.mode }, assets };
29212
29604
  }
29213
29605
  function safeRelativeAsset(value2) {
29214
- return value2.length > 0 && value2.length <= 512 && !value2.includes("\\") && !value2.startsWith("/") && !value2.endsWith("/") && path20.posix.normalize(value2) === value2 && value2.split("/").every((part) => part && part !== "." && part !== "..");
29606
+ return value2.length > 0 && value2.length <= 512 && !value2.includes("\\") && !value2.startsWith("/") && !value2.endsWith("/") && path21.posix.normalize(value2) === value2 && value2.split("/").every((part) => part && part !== "." && part !== "..");
29215
29607
  }
29216
29608
  function record(value2) {
29217
29609
  return value2 !== null && typeof value2 === "object" && !Array.isArray(value2);
@@ -29328,9 +29720,9 @@ function validateNativeNotificationEnvelope(value2, platform = process.platform)
29328
29720
  async function installLinuxScheme(options2) {
29329
29721
  if (!safeAbsoluteLocalPath(options2.dataHome, "linux")) throw lifecycleError("native_adapter_invalid", "The Linux data directory is invalid");
29330
29722
  const desktop = buildLinuxDesktopEntry(options2.nodePath, options2.ipcClientPath);
29331
- const applications = path21.posix.join(options2.dataHome, "applications");
29723
+ const applications = path22.posix.join(options2.dataHome, "applications");
29332
29724
  const filename = "localapp.desktop";
29333
- const destination = path21.posix.join(applications, filename);
29725
+ const destination = path22.posix.join(applications, filename);
29334
29726
  await fs17.mkdir(applications, { recursive: true, mode: 448 });
29335
29727
  const current = await fs17.readFile(destination, "utf8").catch((error) => error.code === "ENOENT" ? void 0 : Promise.reject(error));
29336
29728
  if (current !== desktop) await fs17.writeFile(destination, desktop, { mode: 420 });
@@ -29362,7 +29754,7 @@ async function writeBridgeConfiguration(options2) {
29362
29754
  if (options2.environment !== void 0) configuration.environment = options2.environment;
29363
29755
  const content = `${JSON.stringify(configuration)}
29364
29756
  `;
29365
- await fs17.mkdir(path21.dirname(options2.configPath), { recursive: true, mode: 448 });
29757
+ await fs17.mkdir(path22.dirname(options2.configPath), { recursive: true, mode: 448 });
29366
29758
  const current = await fs17.readFile(options2.configPath, "utf8").catch((error) => error.code === "ENOENT" ? void 0 : Promise.reject(error));
29367
29759
  if (current !== content) await fs17.writeFile(options2.configPath, content, { mode: 384 });
29368
29760
  }
@@ -29378,20 +29770,20 @@ function bridgeRuntimeEnvironment(env, platform) {
29378
29770
  return Object.keys(environment).length === 0 ? void 0 : environment;
29379
29771
  }
29380
29772
  function nativeBridgeConfigPath(platform, supportDir, env) {
29381
- if (supportDir !== void 0) return platform === "win32" ? path21.win32.join(supportDir, "native-bridge.json") : path21.join(supportDir, "native-bridge.json");
29382
- if (platform === "darwin") return path21.join(homedir2(), "Library", "Application Support", "LocalApp", "native-bridge.json");
29383
- if (platform === "win32") return path21.win32.join(env.LOCALAPPDATA ?? path21.win32.join(homedir2(), "AppData", "Local"), "LocalApp", "native-bridge.json");
29384
- return path21.join(env.XDG_DATA_HOME ?? path21.join(homedir2(), ".local", "share"), "localapp", "native-bridge.json");
29773
+ if (supportDir !== void 0) return platform === "win32" ? path22.win32.join(supportDir, "native-bridge.json") : path22.join(supportDir, "native-bridge.json");
29774
+ if (platform === "darwin") return path22.join(homedir2(), "Library", "Application Support", "LocalApp", "native-bridge.json");
29775
+ if (platform === "win32") return path22.win32.join(env.LOCALAPPDATA ?? path22.win32.join(homedir2(), "AppData", "Local"), "LocalApp", "native-bridge.json");
29776
+ return path22.join(env.XDG_DATA_HOME ?? path22.join(homedir2(), ".local", "share"), "localapp", "native-bridge.json");
29385
29777
  }
29386
29778
  function linuxDataHome(env) {
29387
- return env.XDG_DATA_HOME ?? path21.join(homedir2(), ".local", "share");
29779
+ return env.XDG_DATA_HOME ?? path22.join(homedir2(), ".local", "share");
29388
29780
  }
29389
29781
  function createWindowsProcessTreeAdapter(helper) {
29390
29782
  return { spawnOwned: (command, args, options2) => helper.spawn(command, args, options2) };
29391
29783
  }
29392
29784
  function createWindowsProcessTreeAdapterFromEnvironment() {
29393
29785
  if (process.platform !== "win32") return void 0;
29394
- const executable = windowsNativeExecutableFromEnvironment();
29786
+ const executable = resolveWindowsNativeExecutable();
29395
29787
  if (executable === void 0) return void 0;
29396
29788
  return createWindowsProcessTreeAdapter({
29397
29789
  spawn(command, args, options2) {
@@ -29406,6 +29798,17 @@ function createWindowsProcessTreeAdapterFromEnvironment() {
29406
29798
  }
29407
29799
  });
29408
29800
  }
29801
+ function resolveWindowsNativeExecutable(options2 = {}) {
29802
+ const env = options2.env ?? process.env;
29803
+ const arch = options2.arch ?? process.arch;
29804
+ const roots = [env.LOCALAPP_RELEASE_PATH, options2.artifactDirectory ?? localAppArtifactDirectory()];
29805
+ for (const root of roots) {
29806
+ if (root === void 0 || root.length === 0) continue;
29807
+ const candidate = path22.join(root, "runtime", "native", `win32-${arch}`, "localapp-native.exe");
29808
+ if (existsSync(candidate)) return candidate;
29809
+ }
29810
+ return void 0;
29811
+ }
29409
29812
  async function openValidatedExternalUrl(url) {
29410
29813
  let parsed;
29411
29814
  try {
@@ -29419,18 +29822,13 @@ async function openValidatedExternalUrl(url) {
29419
29822
  if (process.platform === "darwin") return waitForChild(spawn4("/usr/bin/open", [url], { shell: false, stdio: "ignore" }));
29420
29823
  if (process.platform === "linux") return waitForChild(spawn4("xdg-open", [url], { shell: false, stdio: "ignore" }));
29421
29824
  if (process.platform === "win32") {
29422
- const executable = windowsNativeExecutableFromEnvironment();
29825
+ const executable = resolveWindowsNativeExecutable();
29423
29826
  if (executable === void 0) throw lifecycleError("native_adapter_unsupported", "NATIVE_ADAPTER_UNSUPPORTED: the Windows opener is unavailable");
29424
29827
  await waitForChild(spawn4(executable, ["--open-url", url], { shell: false, stdio: "ignore", windowsHide: true }));
29425
29828
  return;
29426
29829
  }
29427
29830
  throw unsupported2(process.platform);
29428
29831
  }
29429
- function windowsNativeExecutableFromEnvironment() {
29430
- const release = process.env.LOCALAPP_RELEASE_PATH;
29431
- if (!release) return void 0;
29432
- return path21.join(release, "runtime", "native", `win32-${process.arch}`, "localapp-native.exe");
29433
- }
29434
29832
  async function runCommand(command, args, timeoutMs, environment = process.env) {
29435
29833
  const child = spawn4(command, [...args], { shell: false, windowsHide: true, stdio: ["ignore", "pipe", "pipe"], env: environment });
29436
29834
  let stdout = "";
@@ -29566,7 +29964,7 @@ var PackagedLinuxNotificationSession = class {
29566
29964
  function createPackagedLinuxNotificationSession(selected, nodePath, environment, timeoutMs) {
29567
29965
  const relative = `${selected.target}/localapp-notifications`;
29568
29966
  if (!selected.assets.some((asset) => asset.path === relative)) return unsupportedLinuxNotificationSession();
29569
- return new PackagedLinuxNotificationSession(path21.join(selected.root, ...relative.split("/")), nodePath, selected.ipcClient, environment, timeoutMs);
29967
+ return new PackagedLinuxNotificationSession(path22.join(selected.root, ...relative.split("/")), nodePath, selected.ipcClient, environment, timeoutMs);
29570
29968
  }
29571
29969
  function readLinuxAccepted(child, timeoutMs) {
29572
29970
  return new Promise((resolve2, reject) => {
@@ -29643,7 +30041,7 @@ function desktopExecQuote(value2) {
29643
30041
  }
29644
30042
  function safeAbsoluteLocalPath(value2, platform) {
29645
30043
  if (typeof value2 !== "string" || value2.length === 0 || value2.includes("\0") || /[\r\n]/.test(value2) || /^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(value2)) return false;
29646
- const pathApi = platform === "win32" ? path21.win32 : path21.posix;
30044
+ const pathApi = platform === "win32" ? path22.win32 : path22.posix;
29647
30045
  if (!pathApi.isAbsolute(value2) || pathApi.normalize(value2) !== value2) return false;
29648
30046
  return !value2.split(/[\\/]/).some((part) => part === "." || part === "..");
29649
30047
  }
@@ -29680,7 +30078,7 @@ function spawnOwnedProcess(command, args, options2 = {}) {
29680
30078
  if (platform === "win32") {
29681
30079
  const windowsAdapter = options2.windowsAdapter ?? createWindowsProcessTreeAdapterFromEnvironment();
29682
30080
  if (windowsAdapter === void 0) {
29683
- throw new Error("Windows process-tree adapter is unavailable; refusing to spawn without atomic Job Object ownership");
30081
+ throw lifecycleError("native_adapter_unsupported", "NATIVE_ADAPTER_UNSUPPORTED: the Windows process-tree adapter is unavailable without the packaged LocalApp native helper");
29684
30082
  }
29685
30083
  return ownedWindowsProcess(windowsAdapter.spawnOwned(command, args, spawnOptions), options2);
29686
30084
  }
@@ -30173,10 +30571,10 @@ function isRecord9(value2) {
30173
30571
  // packages/localapp/src/commands/dev.ts
30174
30572
  var DEV_USER_ID = "dev-user";
30175
30573
  async function runDev(options2, dependencies = {}) {
30176
- const projectDir = path22.resolve(options2.projectDir);
30177
- const stateRoot = path22.join(projectDir, "tmp/localapp-dev");
30178
- const dataDir = path22.join(stateRoot, "server");
30179
- const packagesDir = path22.join(stateRoot, "packages");
30574
+ const projectDir = path23.resolve(options2.projectDir);
30575
+ const stateRoot = path23.join(projectDir, "tmp/localapp-dev");
30576
+ const dataDir = path23.join(stateRoot, "server");
30577
+ const packagesDir = path23.join(stateRoot, "packages");
30180
30578
  const spawnProcess = dependencies.spawnOwnedProcess ?? spawnOwnedProcess;
30181
30579
  const lifecycle = new DevLifecycle();
30182
30580
  const abort = () => lifecycle.abort();
@@ -30228,7 +30626,7 @@ async function runDev(options2, dependencies = {}) {
30228
30626
  const initialize = dependencies.initializeServer ?? initializeServer;
30229
30627
  await lifecycle.runPhase((signal) => initialize(ready.listenUrl, ready.setupUrl, credentials.password, signal));
30230
30628
  const version = uniqueDevVersion();
30231
- const packagePath = path22.join(packagesDir, `${manifest.name}-${version}.localapp`);
30629
+ const packagePath = path23.join(packagesDir, `${manifest.name}-${version}.localapp`);
30232
30630
  const build = dependencies.buildApplicationPackage ?? buildApplicationPackage;
30233
30631
  const runBuildCommand = createOwnedProjectCommandRunner(lifecycle, spawnProcess, dependencies.windowsAdapter);
30234
30632
  const applicationPackage = await lifecycle.runPhase((signal) => build({
@@ -30486,15 +30884,15 @@ function isErrorCode(value2, code) {
30486
30884
  }
30487
30885
  async function writeDevConfig(options2) {
30488
30886
  throwIfAborted(options2.signal);
30489
- const projectDir = path22.resolve(options2.projectDir);
30490
- const localAppDir = path22.join(projectDir, ".localapp");
30491
- const stateRoot = path22.join(projectDir, "tmp/localapp-dev");
30887
+ const projectDir = path23.resolve(options2.projectDir);
30888
+ const localAppDir = path23.join(projectDir, ".localapp");
30889
+ const stateRoot = path23.join(projectDir, "tmp/localapp-dev");
30492
30890
  await Promise.all([
30493
30891
  fs18.mkdir(localAppDir, { recursive: true }),
30494
30892
  fs18.mkdir(stateRoot, { recursive: true, mode: 448 })
30495
30893
  ]);
30496
- const temporary = path22.join(stateRoot, `dev-config.${process.pid}.${randomBytes2(8).toString("hex")}.next`);
30497
- const destination = path22.join(localAppDir, "dev-config.json");
30894
+ const temporary = path23.join(stateRoot, `dev-config.${process.pid}.${randomBytes2(8).toString("hex")}.next`);
30895
+ const destination = path23.join(localAppDir, "dev-config.json");
30498
30896
  const value2 = {
30499
30897
  serverUrl: options2.serverUrl,
30500
30898
  userId: DEV_USER_ID,
@@ -30516,12 +30914,12 @@ async function writeDevConfig(options2) {
30516
30914
  }
30517
30915
  }
30518
30916
  function embeddedServerLauncher() {
30519
- return path22.resolve(path22.dirname(fileURLToPath3(import.meta.url)), "../runtime/server/bin/server.mjs");
30917
+ return path23.resolve(path23.dirname(fileURLToPath4(import.meta.url)), "../runtime/server/bin/server.mjs");
30520
30918
  }
30521
30919
  async function readManifest(projectDir) {
30522
30920
  let value2;
30523
30921
  try {
30524
- value2 = JSON.parse(await fs18.readFile(path22.join(projectDir, "manifest.json"), "utf8"));
30922
+ value2 = JSON.parse(await fs18.readFile(path23.join(projectDir, "manifest.json"), "utf8"));
30525
30923
  } catch {
30526
30924
  throw lifecycleError("project_manifest_missing", "No valid manifest.json found. Run 'localapp init' first.");
30527
30925
  }
@@ -30629,9 +31027,7 @@ function isRecord10(value2) {
30629
31027
 
30630
31028
  // packages/localapp/src/commands/server.ts
30631
31029
  import fs25 from "node:fs/promises";
30632
- import { realpathSync } from "node:fs";
30633
- import path29 from "node:path";
30634
- import { fileURLToPath as fileURLToPath4 } from "node:url";
31030
+ import path30 from "node:path";
30635
31031
 
30636
31032
  // packages/localapp/src/daemon/ipc-client.ts
30637
31033
  import net2 from "node:net";
@@ -30897,19 +31293,19 @@ function transportError(error) {
30897
31293
  import crypto6 from "node:crypto";
30898
31294
  import fs19 from "node:fs/promises";
30899
31295
  import { constants as fsConstants } from "node:fs";
30900
- import path23 from "node:path";
31296
+ import path24 from "node:path";
30901
31297
  var DIGEST = /^[0-9a-f]{64}$/;
30902
31298
  var VERSION = /^[0-9A-Za-z][0-9A-Za-z.+_-]{0,127}$/;
30903
31299
  async function verifyReleaseArtifact(directory) {
30904
- return (await inspectReleaseArtifact(path23.resolve(directory))).manifest;
31300
+ return (await inspectReleaseArtifact(path24.resolve(directory))).manifest;
30905
31301
  }
30906
31302
  async function publishRelease(options2) {
30907
- const sourceDirectory = path23.resolve(options2.sourceDirectory);
31303
+ const sourceDirectory = path24.resolve(options2.sourceDirectory);
30908
31304
  const inspected = await inspectReleaseArtifact(sourceDirectory);
30909
31305
  await ensurePrivateDirectories(options2.layout);
30910
31306
  return withReleaseLock(options2.layout, options2.lockTimeoutMs ?? 5e3, async () => {
30911
31307
  const releaseName = `${inspected.manifest.version}-${inspected.manifest.artifactDigest}`;
30912
- const releasePath = path23.join(options2.layout.releasesDir, releaseName);
31308
+ const releasePath = path24.join(options2.layout.releasesDir, releaseName);
30913
31309
  const existing = await lstatOptional2(releasePath);
30914
31310
  if (existing === void 0) {
30915
31311
  await publishImmutableDirectory(releasePath, inspected, options2.layout.releasesDir);
@@ -30925,7 +31321,7 @@ async function publishRelease(options2) {
30925
31321
  entrypoint: inspected.manifest.entrypoint,
30926
31322
  bootstrapEntrypoint: inspected.manifest.bootstrapEntrypoint
30927
31323
  };
30928
- const launcherBytes = await readRegularFile(path23.join(releasePath, ...inspected.manifest.bootstrapEntrypoint.split("/")));
31324
+ const launcherBytes = await readRegularFile(path24.join(releasePath, ...inspected.manifest.bootstrapEntrypoint.split("/")));
30929
31325
  await ensureStableLauncher(options2.layout.launcherPath, launcherBytes);
30930
31326
  await writeAtomic(options2.layout.currentManifestPath, Buffer.from(`${JSON.stringify(current, null, 2)}
30931
31327
  `), 384);
@@ -30942,8 +31338,8 @@ async function readCurrentRelease(layout) {
30942
31338
  if (!isRecord12(value2) || !hasExactKeys2(value2, ["version", "artifactDigest", "releasePath", "entrypoint", "bootstrapEntrypoint"]) || typeof value2.version !== "string" || !VERSION.test(value2.version) || typeof value2.artifactDigest !== "string" || !DIGEST.test(value2.artifactDigest) || typeof value2.releasePath !== "string" || typeof value2.entrypoint !== "string" || typeof value2.bootstrapEntrypoint !== "string") {
30943
31339
  throw lifecycleError("release_current_invalid", "The current LocalApp release manifest is missing or invalid");
30944
31340
  }
30945
- const expectedPath = path23.join(layout.releasesDir, `${value2.version}-${value2.artifactDigest}`);
30946
- if (path23.resolve(value2.releasePath) !== path23.resolve(expectedPath) || !isSafeRelativeFile(value2.entrypoint) || !isSafeRelativeFile(value2.bootstrapEntrypoint)) {
31341
+ const expectedPath = path24.join(layout.releasesDir, `${value2.version}-${value2.artifactDigest}`);
31342
+ if (path24.resolve(value2.releasePath) !== path24.resolve(expectedPath) || !isSafeRelativeFile(value2.entrypoint) || !isSafeRelativeFile(value2.bootstrapEntrypoint)) {
30947
31343
  throw lifecycleError("release_current_invalid", "The current LocalApp release manifest is missing or invalid");
30948
31344
  }
30949
31345
  return {
@@ -30958,7 +31354,7 @@ async function inspectReleaseArtifact(directory) {
30958
31354
  try {
30959
31355
  const root = await fs19.lstat(directory);
30960
31356
  if (!root.isDirectory() || root.isSymbolicLink()) throw invalidArtifact();
30961
- const manifestPath = path23.join(directory, ".localapp-artifact.json");
31357
+ const manifestPath = path24.join(directory, ".localapp-artifact.json");
30962
31358
  const manifestBytes = await readRegularFile(manifestPath);
30963
31359
  const manifest = parseArtifactManifest(JSON.parse(manifestBytes.toString("utf8")));
30964
31360
  const observed = await listArtifactFiles(directory);
@@ -30968,7 +31364,7 @@ async function inspectReleaseArtifact(directory) {
30968
31364
  }
30969
31365
  const files = /* @__PURE__ */ new Map();
30970
31366
  for (const entry of manifest.files) {
30971
- const bytes = await readRegularFile(path23.join(directory, ...entry.path.split("/")));
31367
+ const bytes = await readRegularFile(path24.join(directory, ...entry.path.split("/")));
30972
31368
  if (bytes.byteLength !== entry.size || sha2563(bytes) !== entry.sha256) throw invalidArtifact();
30973
31369
  files.set(entry.path, bytes);
30974
31370
  }
@@ -31101,7 +31497,7 @@ async function listArtifactFiles(root) {
31101
31497
  if (relativePath2 === ".localapp-artifact.json") continue;
31102
31498
  if (!isSafeRelativeFile(relativePath2)) throw invalidArtifact();
31103
31499
  if (entry.isSymbolicLink()) throw invalidArtifact();
31104
- if (entry.isDirectory()) await visit(path23.join(directory, entry.name), relativePath2);
31500
+ if (entry.isDirectory()) await visit(path24.join(directory, entry.name), relativePath2);
31105
31501
  else if (entry.isFile()) files.add(relativePath2);
31106
31502
  else throw invalidArtifact();
31107
31503
  }
@@ -31110,15 +31506,15 @@ async function listArtifactFiles(root) {
31110
31506
  return files;
31111
31507
  }
31112
31508
  async function publishImmutableDirectory(releasePath, inspected, releasesDirectory) {
31113
- const staging = await fs19.mkdtemp(path23.join(releasesDirectory, ".release-stage-"));
31509
+ const staging = await fs19.mkdtemp(path24.join(releasesDirectory, ".release-stage-"));
31114
31510
  if (process.platform !== "win32") await fs19.chmod(staging, 448);
31115
31511
  try {
31116
31512
  for (const [relativePath2, bytes] of inspected.files) {
31117
- const destination = path23.join(staging, ...relativePath2.split("/"));
31118
- await fs19.mkdir(path23.dirname(destination), { recursive: true, mode: 448 });
31513
+ const destination = path24.join(staging, ...relativePath2.split("/"));
31514
+ await fs19.mkdir(path24.dirname(destination), { recursive: true, mode: 448 });
31119
31515
  await fs19.writeFile(destination, bytes, { flag: "wx", mode: isExecutableReleaseFile(relativePath2, inspected.manifest) ? 448 : 384 });
31120
31516
  }
31121
- await fs19.writeFile(path23.join(staging, ".localapp-artifact.json"), inspected.manifestBytes, { flag: "wx", mode: 384 });
31517
+ await fs19.writeFile(path24.join(staging, ".localapp-artifact.json"), inspected.manifestBytes, { flag: "wx", mode: 384 });
31122
31518
  await inspectReleaseArtifact(staging);
31123
31519
  try {
31124
31520
  await fs19.rename(staging, releasePath);
@@ -31138,7 +31534,7 @@ function isExecutableReleaseFile(relativePath2, manifest) {
31138
31534
  async function ensurePrivateDirectories(layout) {
31139
31535
  validateRuntimeLayout(layout);
31140
31536
  await ensurePrivateDirectory(layout.supportDir);
31141
- for (const directory of [layout.releasesDir, layout.logsDir, path23.dirname(layout.launcherPath), layout.runtimeDir]) {
31537
+ for (const directory of [layout.releasesDir, layout.logsDir, path24.dirname(layout.launcherPath), layout.runtimeDir]) {
31142
31538
  await ensurePrivateDirectory(directory);
31143
31539
  }
31144
31540
  }
@@ -31161,7 +31557,7 @@ async function withReleaseLock(layout, timeoutMs, operation) {
31161
31557
  }
31162
31558
  }
31163
31559
  async function tryCreateReleaseLock(layout) {
31164
- const temporary = path23.join(layout.runtimeDir, `.release-lock.${process.pid}.${crypto6.randomUUID()}.next`);
31560
+ const temporary = path24.join(layout.runtimeDir, `.release-lock.${process.pid}.${crypto6.randomUUID()}.next`);
31165
31561
  let handle;
31166
31562
  let identity;
31167
31563
  let linked = false;
@@ -31247,14 +31643,14 @@ async function ensurePrivateDirectory(directory) {
31247
31643
  }
31248
31644
  }
31249
31645
  function validateRuntimeLayout(layout) {
31250
- const support = path23.resolve(layout.supportDir);
31646
+ const support = path24.resolve(layout.supportDir);
31251
31647
  const expected = [
31252
- [layout.releasesDir, path23.join(support, "releases")],
31253
- [layout.currentManifestPath, path23.join(support, "current.json")],
31254
- [layout.launcherPath, path23.join(support, "bin", "localapp-daemon-bootstrap.mjs")],
31255
- [layout.logsDir, path23.join(support, "logs")]
31648
+ [layout.releasesDir, path24.join(support, "releases")],
31649
+ [layout.currentManifestPath, path24.join(support, "current.json")],
31650
+ [layout.launcherPath, path24.join(support, "bin", "localapp-daemon-bootstrap.mjs")],
31651
+ [layout.logsDir, path24.join(support, "logs")]
31256
31652
  ];
31257
- if (expected.some(([actual, canonical]) => path23.resolve(actual) !== path23.resolve(canonical)) || path23.resolve(layout.releaseLockPath) !== path23.resolve(layout.runtimeDir, "release.lock")) {
31653
+ if (expected.some(([actual, canonical]) => path24.resolve(actual) !== path24.resolve(canonical)) || path24.resolve(layout.releaseLockPath) !== path24.resolve(layout.runtimeDir, "release.lock")) {
31258
31654
  throw lifecycleError("release_path_unsafe", "The LocalApp release layout is invalid");
31259
31655
  }
31260
31656
  }
@@ -31277,8 +31673,8 @@ async function ensureStableLauncher(filePath, bytes) {
31277
31673
  if (process.platform !== "win32") await fs19.chmod(filePath, 448);
31278
31674
  }
31279
31675
  async function writeAtomic(filePath, bytes, mode) {
31280
- await fs19.mkdir(path23.dirname(filePath), { recursive: true, mode: 448 });
31281
- const temporary = path23.join(path23.dirname(filePath), `.${path23.basename(filePath)}.${process.pid}.${crypto6.randomUUID()}.next`);
31676
+ await fs19.mkdir(path24.dirname(filePath), { recursive: true, mode: 448 });
31677
+ const temporary = path24.join(path24.dirname(filePath), `.${path24.basename(filePath)}.${process.pid}.${crypto6.randomUUID()}.next`);
31282
31678
  let handle;
31283
31679
  try {
31284
31680
  handle = await fs19.open(temporary, "wx", mode);
@@ -31310,7 +31706,7 @@ async function readRegularFile(filePath) {
31310
31706
  }
31311
31707
  }
31312
31708
  function isSafeRelativeFile(value2) {
31313
- return value2.length > 0 && value2.length <= 512 && !value2.includes("\\") && !value2.startsWith("/") && path23.posix.normalize(value2) === value2 && !value2.endsWith("/") && value2.split("/").every((segment) => segment !== "" && segment !== "." && segment !== "..");
31709
+ return value2.length > 0 && value2.length <= 512 && !value2.includes("\\") && !value2.startsWith("/") && path24.posix.normalize(value2) === value2 && !value2.endsWith("/") && value2.split("/").every((segment) => segment !== "" && segment !== "." && segment !== "..");
31314
31710
  }
31315
31711
  function compareArtifactFiles(left, right) {
31316
31712
  return left.path < right.path ? -1 : left.path > right.path ? 1 : 0;
@@ -31339,12 +31735,12 @@ async function lstatOptional2(filePath) {
31339
31735
  // packages/localapp/src/daemon/runtime-layout.ts
31340
31736
  import crypto7 from "node:crypto";
31341
31737
  import { homedir as homedir3 } from "node:os";
31342
- import path24 from "node:path";
31738
+ import path25 from "node:path";
31343
31739
  function createRuntimeLayout(options2 = {}) {
31344
31740
  const platform = options2.platform ?? process.platform;
31345
31741
  const env = options2.env ?? process.env;
31346
31742
  const homeDirectory = options2.homeDir ?? homedir3();
31347
- const pathApi = platform === "win32" ? path24.win32 : path24.posix;
31743
+ const pathApi = platform === "win32" ? path25.win32 : path25.posix;
31348
31744
  const supportDir = options2.supportDir ?? defaultSupportDirectory(platform, env, homeDirectory, pathApi);
31349
31745
  const runtimeDir = options2.runtimeDir ?? defaultRuntimeDirectory(platform, env, homeDirectory, supportDir, options2.uid, pathApi);
31350
31746
  const dataDir = options2.dataDir ?? pathApi.join(supportDir, "data");
@@ -31387,20 +31783,20 @@ import { spawn as spawn6 } from "node:child_process";
31387
31783
 
31388
31784
  // packages/localapp/src/service/linux-systemd-user.ts
31389
31785
  import fs21 from "node:fs/promises";
31390
- import path26 from "node:path";
31786
+ import path27 from "node:path";
31391
31787
 
31392
31788
  // packages/localapp/src/service/service-files.ts
31393
31789
  import crypto8 from "node:crypto";
31394
31790
  import fs20 from "node:fs/promises";
31395
- import path25 from "node:path";
31791
+ import path26 from "node:path";
31396
31792
  async function writeServiceFile(filePath, value2) {
31397
31793
  const existing = await fs20.readFile(filePath, "utf8").catch((error) => {
31398
31794
  if (error.code === "ENOENT") return void 0;
31399
31795
  throw error;
31400
31796
  });
31401
31797
  if (existing === value2) return false;
31402
- await fs20.mkdir(path25.dirname(filePath), { recursive: true, mode: 448 });
31403
- const temporary = path25.join(path25.dirname(filePath), `.${path25.basename(filePath)}.${process.pid}.${crypto8.randomUUID()}.next`);
31798
+ await fs20.mkdir(path26.dirname(filePath), { recursive: true, mode: 448 });
31799
+ const temporary = path26.join(path26.dirname(filePath), `.${path26.basename(filePath)}.${process.pid}.${crypto8.randomUUID()}.next`);
31404
31800
  let handle;
31405
31801
  try {
31406
31802
  handle = await fs20.open(temporary, "wx", 384);
@@ -31423,8 +31819,8 @@ function xmlEscape(value2) {
31423
31819
  // packages/localapp/src/service/linux-systemd-user.ts
31424
31820
  var UNIT_NAME = "localapp.service";
31425
31821
  function createLinuxSystemdUserService(options2) {
31426
- const configHome = options2.env?.XDG_CONFIG_HOME ?? path26.join(options2.homeDir, ".config");
31427
- const registrationPath = path26.join(configHome, "systemd", "user", UNIT_NAME);
31822
+ const configHome = options2.env?.XDG_CONFIG_HOME ?? path27.join(options2.homeDir, ".config");
31823
+ const registrationPath = path27.join(configHome, "systemd", "user", UNIT_NAME);
31428
31824
  const unit = buildUnit(options2);
31429
31825
  const systemctl = options2.env?.SYSTEMCTL_PATH ?? "systemctl";
31430
31826
  return {
@@ -31440,7 +31836,7 @@ function createLinuxSystemdUserService(options2) {
31440
31836
  return { mode: "service", installed };
31441
31837
  },
31442
31838
  async start(signal) {
31443
- await runServiceCommand(options2.run, withAbortSignal({ command: systemctl, args: ["--user", "start", UNIT_NAME] }, signal));
31839
+ await runServiceCommand(options2.run, withAbortSignal({ command: systemctl, args: ["--user", "restart", UNIT_NAME] }, signal));
31444
31840
  },
31445
31841
  async stop() {
31446
31842
  const result = await options2.run({ command: systemctl, args: ["--user", "stop", UNIT_NAME] });
@@ -31481,8 +31877,8 @@ Type=simple
31481
31877
  ExecStart=${systemdQuote(options2.nodePath)} ${systemdQuote(options2.layout.launcherPath)}
31482
31878
  Restart=on-failure
31483
31879
  RestartSec=2
31484
- StandardOutput=append:${systemdQuote(options2.layout.daemonLogPath)}
31485
- StandardError=append:${systemdQuote(options2.layout.daemonLogPath)}
31880
+ StandardOutput=append:${options2.layout.daemonLogPath}
31881
+ StandardError=append:${options2.layout.daemonLogPath}
31486
31882
  ${environment ? `${environment}
31487
31883
  ` : ""}
31488
31884
  [Install]
@@ -31499,14 +31895,14 @@ function systemdQuote(value2) {
31499
31895
  // packages/localapp/src/service/macos-launch-agent.ts
31500
31896
  import crypto9 from "node:crypto";
31501
31897
  import fs22 from "node:fs/promises";
31502
- import path27 from "node:path";
31898
+ import path28 from "node:path";
31503
31899
  var LABEL = "com.localapp.daemon";
31504
31900
  function createMacosLaunchAgent(options2) {
31505
31901
  const uid = options2.uid ?? (typeof process.getuid === "function" ? process.getuid() : void 0);
31506
31902
  if (!Number.isSafeInteger(uid) || (uid ?? -1) < 0) {
31507
31903
  throw lifecycleError("user_service_configuration_invalid", "The current macOS user identity is unavailable");
31508
31904
  }
31509
- const registrationPath = path27.join(options2.homeDir, "Library", "LaunchAgents", `${LABEL}.plist`);
31905
+ const registrationPath = path28.join(options2.homeDir, "Library", "LaunchAgents", `${LABEL}.plist`);
31510
31906
  const domain = `gui/${uid}`;
31511
31907
  const target = `${domain}/${LABEL}`;
31512
31908
  const plist = buildPlist(options2);
@@ -31599,12 +31995,12 @@ ${environment}
31599
31995
 
31600
31996
  // packages/localapp/src/service/windows-user-task.ts
31601
31997
  import fs23 from "node:fs/promises";
31602
- import path28 from "node:path";
31998
+ import path29 from "node:path";
31603
31999
  var TASK_NAME = "LocalApp User Daemon";
31604
32000
  function createWindowsUserTask(options2) {
31605
- const registrationPath = path28.join(options2.layout.supportDir, "service", "windows-user-task.json");
32001
+ const registrationPath = path29.join(options2.layout.supportDir, "service", "windows-user-task.json");
31606
32002
  const systemRoot = options2.env?.SystemRoot ?? options2.env?.SYSTEMROOT ?? "C:\\Windows";
31607
- const scheduler = path28.win32.join(systemRoot, "System32", "schtasks.exe");
32003
+ const scheduler = path29.win32.join(systemRoot, "System32", "schtasks.exe");
31608
32004
  const taskCommand = `${quoteWindowsArgument(options2.nodePath)} ${quoteWindowsArgument(options2.layout.launcherPath)}`;
31609
32005
  const metadata = `${JSON.stringify({
31610
32006
  schemaVersion: 1,
@@ -31617,18 +32013,25 @@ function createWindowsUserTask(options2) {
31617
32013
  registrationPath,
31618
32014
  async install() {
31619
32015
  const installed = await writeServiceFile(registrationPath, metadata);
32016
+ const definitionPath = path29.join(path29.dirname(registrationPath), "windows-user-task.xml");
32017
+ await fs23.mkdir(path29.dirname(definitionPath), { recursive: true });
32018
+ await fs23.writeFile(definitionPath, taskDefinition(options2.nodePath, options2.layout.launcherPath));
31620
32019
  await runServiceCommand(options2.run, {
31621
32020
  command: scheduler,
31622
- args: ["/Create", "/TN", TASK_NAME, "/SC", "ONLOGON", "/RL", "LIMITED", "/TR", taskCommand, "/F"]
32021
+ args: ["/Create", "/TN", TASK_NAME, "/XML", definitionPath, "/F"]
31623
32022
  });
31624
32023
  return { mode: "service", installed };
31625
32024
  },
31626
32025
  async start(signal) {
32026
+ const ended = await options2.run(withAbortSignal({ command: scheduler, args: ["/End", "/TN", TASK_NAME] }, signal));
32027
+ if (ended.code !== 0 && !isNotRunningTask(ended.stderr)) {
32028
+ throw lifecycleError("user_service_command_failed", "The Windows user task could not be stopped");
32029
+ }
31627
32030
  await runServiceCommand(options2.run, withAbortSignal({ command: scheduler, args: ["/Run", "/TN", TASK_NAME] }, signal));
31628
32031
  },
31629
32032
  async stop() {
31630
32033
  const result = await options2.run({ command: scheduler, args: ["/End", "/TN", TASK_NAME] });
31631
- if (result.code !== 0 && !/cannot find|does not exist|not currently running/i.test(result.stderr)) {
32034
+ if (result.code !== 0 && !isNotRunningTask(result.stderr)) {
31632
32035
  throw lifecycleError("user_service_command_failed", "The Windows user task could not be stopped");
31633
32036
  }
31634
32037
  },
@@ -31649,6 +32052,51 @@ function createWindowsUserTask(options2) {
31649
32052
  }
31650
32053
  };
31651
32054
  }
32055
+ function isNotRunningTask(stderr) {
32056
+ return /cannot find|does not exist|not currently running/i.test(stderr);
32057
+ }
32058
+ function taskDefinition(nodePath, launcherPath) {
32059
+ const xml = `<?xml version="1.0" encoding="UTF-16"?>
32060
+ <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
32061
+ <RegistrationInfo>
32062
+ <Description>LocalApp per-user daemon</Description>
32063
+ </RegistrationInfo>
32064
+ <Triggers>
32065
+ <LogonTrigger>
32066
+ <Enabled>true</Enabled>
32067
+ </LogonTrigger>
32068
+ </Triggers>
32069
+ <Principals>
32070
+ <Principal id="Author">
32071
+ <LogonType>S4U</LogonType>
32072
+ <RunLevel>LeastPrivilege</RunLevel>
32073
+ </Principal>
32074
+ </Principals>
32075
+ <Settings>
32076
+ <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
32077
+ <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
32078
+ <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
32079
+ <AllowStartOnDemand>true</AllowStartOnDemand>
32080
+ <Enabled>true</Enabled>
32081
+ <Hidden>false</Hidden>
32082
+ <RunOnlyIfIdle>false</RunOnlyIfIdle>
32083
+ <WakeToRun>false</WakeToRun>
32084
+ <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
32085
+ <Priority>7</Priority>
32086
+ </Settings>
32087
+ <Actions Context="Author">
32088
+ <Exec>
32089
+ <Command>${xmlEscape2(nodePath)}</Command>
32090
+ <Arguments>${xmlEscape2(launcherPath)}</Arguments>
32091
+ </Exec>
32092
+ </Actions>
32093
+ </Task>
32094
+ `;
32095
+ return Buffer.concat([Buffer.from([255, 254]), Buffer.from(xml, "utf16le")]);
32096
+ }
32097
+ function xmlEscape2(value2) {
32098
+ return value2.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&apos;");
32099
+ }
31652
32100
  function quoteWindowsArgument(value2) {
31653
32101
  if (value2.includes("\0") || /[\r\n]/.test(value2)) {
31654
32102
  throw lifecycleError("user_service_configuration_invalid", "The Windows service command path is invalid");
@@ -31781,7 +32229,7 @@ async function runServerCommand(options2, dependencies = {}) {
31781
32229
  const artifactDirectory = dependencies.artifactDirectory ?? defaultArtifactDirectory();
31782
32230
  await (dependencies.verifyReleaseArtifact ?? verifyReleaseArtifact)(artifactDirectory);
31783
32231
  const release = await (dependencies.publishRelease ?? publishRelease)({ sourceDirectory: artifactDirectory, layout });
31784
- const native = await (dependencies.createNativeAdapter ?? createNativeAdapter)(path29.join(release.releasePath, "runtime", "native"), { supportDir: layout.supportDir });
32232
+ const native = await (dependencies.createNativeAdapter ?? createNativeAdapter)(path30.join(release.releasePath, "runtime", "native"), { supportDir: layout.supportDir });
31785
32233
  await native.installScheme();
31786
32234
  const manager = service();
31787
32235
  const installed = await manager.install();
@@ -31821,7 +32269,7 @@ async function runServerForeground(options2, dependencies = {}) {
31821
32269
  const artifact = dependencies.artifactDirectory ?? defaultArtifactDirectory();
31822
32270
  const manifest = await verifyReleaseArtifact(artifact);
31823
32271
  if (typeof manifest.serverEntrypoint !== "string") throw lifecycleError("canonical_server_unavailable", "The packed canonical LocalApp Server runtime is unavailable");
31824
- const entrypoint = path29.join(artifact, ...manifest.serverEntrypoint.split("/"));
32272
+ const entrypoint = path30.join(artifact, ...manifest.serverEntrypoint.split("/"));
31825
32273
  const child = (dependencies.spawnOwnedProcess ?? spawnOwnedProcess)(process.execPath, [
31826
32274
  entrypoint,
31827
32275
  "start",
@@ -31933,13 +32381,7 @@ function defaultServiceManager(layout) {
31933
32381
  return createCurrentUserServiceManager(layout);
31934
32382
  }
31935
32383
  function defaultArtifactDirectory() {
31936
- const fromEntry = process.argv[1] === void 0 ? void 0 : artifactDirectoryFromEntrypoint(process.argv[1]);
31937
- if (fromEntry !== void 0) return fromEntry;
31938
- return path29.resolve(path29.dirname(fileURLToPath4(import.meta.url)), "../..");
31939
- }
31940
- function artifactDirectoryFromEntrypoint(entrypoint) {
31941
- const canonical = realpathSync(entrypoint);
31942
- return path29.resolve(path29.dirname(canonical), "..");
32384
+ return localAppArtifactDirectory();
31943
32385
  }
31944
32386
  function runtimeLayoutFromEnvironment(environment = process.env) {
31945
32387
  return createRuntimeLayout({
@@ -31965,7 +32407,7 @@ function delay2(ms) {
31965
32407
  // packages/localapp/src/daemon/daemon.ts
31966
32408
  import crypto11 from "node:crypto";
31967
32409
  import fs28 from "node:fs/promises";
31968
- import path32 from "node:path";
32410
+ import path33 from "node:path";
31969
32411
 
31970
32412
  // packages/localapp/src/activation/activation-broker.ts
31971
32413
  var DEVICE_ACTION_STATUSES = /* @__PURE__ */ new Set([
@@ -32075,7 +32517,7 @@ import crypto10 from "node:crypto";
32075
32517
  import { execFile } from "node:child_process";
32076
32518
  import { constants as constants4 } from "node:fs";
32077
32519
  import fs26 from "node:fs/promises";
32078
- import path30 from "node:path";
32520
+ import path31 from "node:path";
32079
32521
  import { promisify } from "node:util";
32080
32522
  var EMPTY_STATE = { version: 1, sources: [] };
32081
32523
  var SOURCE_ID = /^[A-Za-z0-9](?:[A-Za-z0-9_-]{0,127})$/;
@@ -32099,7 +32541,7 @@ var DeliveryStore = class {
32099
32541
  tail = Promise.resolve();
32100
32542
  poisoned = false;
32101
32543
  constructor(options2) {
32102
- this.statePath = path30.resolve(options2.statePath);
32544
+ this.statePath = path31.resolve(options2.statePath);
32103
32545
  this.now = options2.now ?? (() => /* @__PURE__ */ new Date());
32104
32546
  this.randomBytes = options2.randomBytes ?? crypto10.randomBytes;
32105
32547
  this.fault = options2.fault;
@@ -32132,7 +32574,7 @@ var DeliveryStore = class {
32132
32574
  return snapshot(source);
32133
32575
  });
32134
32576
  }
32135
- async preparePending(sourceId, value2, expiresAt, sourceLabel = sourceId, iconPath = path30.resolve(process.cwd(), "localapp-notification.png")) {
32577
+ async preparePending(sourceId, value2, expiresAt, sourceLabel = sourceId, iconPath = path31.resolve(process.cwd(), "localapp-notification.png")) {
32136
32578
  return this.mutate((state) => {
32137
32579
  const source = requiredSource(state, sourceId);
32138
32580
  const delivery = validateDelivery(value2);
@@ -32275,9 +32717,9 @@ var DeliveryStore = class {
32275
32717
  });
32276
32718
  }
32277
32719
  async withFileLock(operation) {
32278
- const parent = path30.dirname(this.statePath);
32720
+ const parent = path31.dirname(this.statePath);
32279
32721
  await ensurePrivateParent(parent);
32280
- const lockPath = path30.join(parent, `.${path30.basename(this.statePath)}.lock`);
32722
+ const lockPath = path31.join(parent, `.${path31.basename(this.statePath)}.lock`);
32281
32723
  const deadline = Date.now() + this.lockTimeoutMs;
32282
32724
  let lock;
32283
32725
  while (lock === void 0) {
@@ -32288,7 +32730,7 @@ var DeliveryStore = class {
32288
32730
  await new Promise((resolve2) => setTimeout(resolve2, 10));
32289
32731
  }
32290
32732
  try {
32291
- await removeOwnedStaleTemps(parent, path30.basename(this.statePath));
32733
+ await removeOwnedStaleTemps(parent, path31.basename(this.statePath));
32292
32734
  return await operation();
32293
32735
  } finally {
32294
32736
  await lock.handle.close().catch(() => void 0);
@@ -32304,7 +32746,7 @@ var DeliveryStore = class {
32304
32746
  return run;
32305
32747
  }
32306
32748
  async read() {
32307
- await ensurePrivateParent(path30.dirname(this.statePath));
32749
+ await ensurePrivateParent(path31.dirname(this.statePath));
32308
32750
  let handle;
32309
32751
  try {
32310
32752
  const before = await fs26.lstat(this.statePath, { bigint: true });
@@ -32326,11 +32768,11 @@ var DeliveryStore = class {
32326
32768
  }
32327
32769
  }
32328
32770
  async publish(state) {
32329
- const parent = path30.dirname(this.statePath);
32771
+ const parent = path31.dirname(this.statePath);
32330
32772
  const parentBefore = await privateDirectoryIdentity(parent);
32331
32773
  const parentHandle = await fs26.open(parent, "r");
32332
32774
  let existing;
32333
- const temporary = path30.join(parent, `.${path30.basename(this.statePath)}.${process.pid}.${this.token(12)}.tmp`);
32775
+ const temporary = path31.join(parent, `.${path31.basename(this.statePath)}.${process.pid}.${this.token(12)}.tmp`);
32334
32776
  let handle;
32335
32777
  let tempIdentity;
32336
32778
  let renamed = false;
@@ -32357,7 +32799,7 @@ var DeliveryStore = class {
32357
32799
  if (!optionalSameIdentity(existing, current)) throw unsafe("Notification delivery state was replaced");
32358
32800
  await this.fault?.("before-rename");
32359
32801
  try {
32360
- await renameInPinnedParent(parent, path30.basename(temporary), path30.basename(this.statePath), parentBefore, tempIdentity);
32802
+ await renameInPinnedParent(parent, path31.basename(temporary), path31.basename(this.statePath), parentBefore, tempIdentity);
32361
32803
  renamed = true;
32362
32804
  } catch (error) {
32363
32805
  if (error instanceof PinnedRenamePreconditionError) throw error;
@@ -32502,7 +32944,7 @@ function validateDisplaySourceLabel(value2) {
32502
32944
  return value2;
32503
32945
  }
32504
32946
  function validateIconPath(value2) {
32505
- if (typeof value2 !== "string" || value2.length > 2048 || !path30.isAbsolute(value2) || path30.resolve(value2) !== value2 || /[\u0000-\u001f\u007f]/.test(value2)) throw new Error("Notification icon path is invalid");
32947
+ if (typeof value2 !== "string" || value2.length > 2048 || !path31.isAbsolute(value2) || path31.resolve(value2) !== value2 || /[\u0000-\u001f\u007f]/.test(value2)) throw new Error("Notification icon path is invalid");
32506
32948
  return value2;
32507
32949
  }
32508
32950
  function validateSourceId(value2) {
@@ -32571,11 +33013,11 @@ async function ensurePrivateParent(directory) {
32571
33013
  await privateDirectoryIdentity(directory);
32572
33014
  }
32573
33015
  async function assertNoSymlinkAncestors(target, allowMissingTail) {
32574
- const absolute = path30.resolve(target);
32575
- const parsed = path30.parse(absolute);
33016
+ const absolute = path31.resolve(target);
33017
+ const parsed = path31.parse(absolute);
32576
33018
  let current = parsed.root;
32577
- for (const segment of absolute.slice(parsed.root.length).split(path30.sep).filter(Boolean)) {
32578
- current = path30.join(current, segment);
33019
+ for (const segment of absolute.slice(parsed.root.length).split(path31.sep).filter(Boolean)) {
33020
+ current = path31.join(current, segment);
32579
33021
  const stat2 = await optionalLstat(current);
32580
33022
  if (stat2 === void 0) {
32581
33023
  if (allowMissingTail) return;
@@ -32642,7 +33084,7 @@ async function removeOwnedStaleTemps(parent, basename2) {
32642
33084
  const names = (await fs26.readdir(parent)).filter((name) => name.startsWith(prefix) && name.endsWith(".tmp"));
32643
33085
  if (names.length === 0) return;
32644
33086
  for (const name of names) {
32645
- const target = path30.join(parent, name);
33087
+ const target = path31.join(parent, name);
32646
33088
  const stat2 = await fs26.lstat(target, { bigint: true });
32647
33089
  assertPrivateRegular(stat2, "Notification delivery stale temporary file");
32648
33090
  await unlinkOwned(target, { dev: BigInt(stat2.dev), ino: BigInt(stat2.ino) });
@@ -32740,7 +33182,7 @@ function strictJsonParse(input) {
32740
33182
  return result;
32741
33183
  }
32742
33184
  async function tryAcquireLock(lockPath) {
32743
- const temporary = path30.join(path30.dirname(lockPath), `.${path30.basename(lockPath)}.${process.pid}.${crypto10.randomUUID()}.next`);
33185
+ const temporary = path31.join(path31.dirname(lockPath), `.${path31.basename(lockPath)}.${process.pid}.${crypto10.randomUUID()}.next`);
32744
33186
  let handle;
32745
33187
  let identity;
32746
33188
  let linked = false;
@@ -32777,12 +33219,14 @@ async function tryAcquireLock(lockPath) {
32777
33219
  async function reclaimDeadLock(lockPath) {
32778
33220
  const before = await optionalLstat(lockPath);
32779
33221
  if (before === void 0) return true;
32780
- const linkedTemporary = await validateVisibleLock(before, lockPath);
33222
+ const visible = await validateVisibleLock(before, lockPath);
33223
+ if (!visible.stable) return false;
33224
+ const linkedTemporary = visible.linkedTemporary;
32781
33225
  let handle;
32782
33226
  try {
32783
33227
  handle = await fs26.open(lockPath, process.platform === "win32" ? "r" : constants4.O_RDONLY | constants4.O_NOFOLLOW);
32784
33228
  const opened = await handle.stat({ bigint: true });
32785
- if (!sameIdentity(before, opened)) throw unsafe("Notification delivery lock identity changed");
33229
+ if (!sameIdentity(before, opened)) return false;
32786
33230
  const bytes = await handle.readFile();
32787
33231
  if (bytes.byteLength > 1024) throw unsafe("Notification delivery lock is invalid");
32788
33232
  const value2 = JSON.parse(bytes.toString("utf8"));
@@ -32803,25 +33247,30 @@ async function reclaimDeadLock(lockPath) {
32803
33247
  }
32804
33248
  }
32805
33249
  async function validateVisibleLock(stat2, lockPath) {
32806
- if (!stat2.isFile() || stat2.isSymbolicLink() || stat2.nlink !== 1n && stat2.nlink !== 2n) throw unsafe("Notification delivery lock path is unsafe");
33250
+ if (!stat2.isFile() || stat2.isSymbolicLink() || stat2.nlink !== 1n && stat2.nlink !== 2n) {
33251
+ const current = await optionalLstat(lockPath);
33252
+ if (!optionalSameIdentity(stat2, current)) return { stable: false };
33253
+ throw unsafe("Notification delivery lock path is unsafe");
33254
+ }
32807
33255
  if (process.platform !== "win32" && ((BigInt(stat2.mode) & 0o777n) !== 0o600n || BigInt(stat2.uid) !== BigInt(process.getuid?.() ?? Number(stat2.uid)))) {
32808
33256
  throw unsafe("Notification delivery lock path is unsafe");
32809
33257
  }
32810
- if (stat2.nlink === 1n) return void 0;
32811
- const prefix = `.${path30.basename(lockPath)}.`;
32812
- const candidates = (await fs26.readdir(path30.dirname(lockPath))).filter((name) => name.startsWith(prefix) && name.endsWith(".next"));
33258
+ if (stat2.nlink === 1n) return { stable: true, linkedTemporary: void 0 };
33259
+ const prefix = `.${path31.basename(lockPath)}.`;
33260
+ const candidates = (await fs26.readdir(path31.dirname(lockPath))).filter((name) => name.startsWith(prefix) && name.endsWith(".next"));
32813
33261
  const same = [];
32814
33262
  for (const name of candidates) {
32815
- const candidate = path30.join(path30.dirname(lockPath), name);
33263
+ const candidate = path31.join(path31.dirname(lockPath), name);
32816
33264
  const metadata = await optionalLstat(candidate);
32817
33265
  if (metadata !== void 0 && sameIdentity(stat2, metadata)) same.push(candidate);
32818
33266
  }
32819
33267
  if (same.length !== 1) {
32820
33268
  const current = await optionalLstat(lockPath);
32821
- if (current === void 0 || sameIdentity(stat2, current) && current.nlink === 1n) return void 0;
33269
+ if (current === void 0 || !sameIdentity(stat2, current)) return { stable: false };
33270
+ if (current.nlink === 1n) return { stable: true, linkedTemporary: void 0 };
32822
33271
  throw unsafe("Notification delivery lock hard-link identity is unsafe");
32823
33272
  }
32824
- return same[0];
33273
+ return { stable: true, linkedTemporary: same[0] };
32825
33274
  }
32826
33275
  function processExists2(pid) {
32827
33276
  try {
@@ -33550,7 +33999,7 @@ function delay3(ms, signal) {
33550
33999
  // packages/localapp/src/daemon/ipc-server.ts
33551
34000
  import fs27 from "node:fs/promises";
33552
34001
  import net3 from "node:net";
33553
- import path31 from "node:path";
34002
+ import path32 from "node:path";
33554
34003
  var DEFAULT_TIMEOUT_MS2 = 5e3;
33555
34004
  async function createIpcServer(options2) {
33556
34005
  const platform = options2.platform ?? process.platform;
@@ -33560,7 +34009,7 @@ async function createIpcServer(options2) {
33560
34009
  const sockets = /* @__PURE__ */ new Set();
33561
34010
  const server = net3.createServer({ allowHalfOpen: true }, (socket) => {
33562
34011
  sockets.add(socket);
33563
- void serveConnection(socket, options2.handle, options2.afterResponse, options2.timeoutMs ?? DEFAULT_TIMEOUT_MS2).finally(() => sockets.delete(socket));
34012
+ void serveConnection(socket, options2.handle, options2.afterResponse, options2.timeoutMs ?? DEFAULT_TIMEOUT_MS2, platform).finally(() => sockets.delete(socket));
33564
34013
  });
33565
34014
  await new Promise((resolve2, reject) => {
33566
34015
  server.once("error", reject);
@@ -33581,7 +34030,7 @@ async function createIpcServer(options2) {
33581
34030
  let closing;
33582
34031
  return { close: () => closing ??= closeServer(server, sockets, options2.endpoint, identity, options2.timeoutMs ?? DEFAULT_TIMEOUT_MS2) };
33583
34032
  }
33584
- function serveConnection(socket, handle, afterResponse, timeoutMs) {
34033
+ function serveConnection(socket, handle, afterResponse, timeoutMs, platform) {
33585
34034
  return new Promise((resolve2) => {
33586
34035
  socket.setNoDelay(true);
33587
34036
  let bytes = Buffer.alloc(0);
@@ -33626,14 +34075,7 @@ function serveConnection(socket, handle, afterResponse, timeoutMs) {
33626
34075
  timer.unref?.();
33627
34076
  socket.once("error", close);
33628
34077
  socket.once("close", close);
33629
- socket.on("data", (chunk) => {
33630
- if (settled || requestEnded || bytes.byteLength + chunk.byteLength > CONTROL_FRAME_LIMIT_BYTES) {
33631
- if (!settled) fail2("IPC_MESSAGE_TOO_LARGE");
33632
- return;
33633
- }
33634
- bytes = Buffer.concat([bytes, chunk]);
33635
- });
33636
- socket.once("end", () => {
34078
+ const dispatch = () => {
33637
34079
  requestEnded = true;
33638
34080
  if (settled) return;
33639
34081
  try {
@@ -33642,11 +34084,23 @@ function serveConnection(socket, handle, afterResponse, timeoutMs) {
33642
34084
  } catch (error) {
33643
34085
  fail2(typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" ? error.code : "IPC_REQUEST_INVALID");
33644
34086
  }
34087
+ };
34088
+ socket.on("data", (chunk) => {
34089
+ if (settled || requestEnded || bytes.byteLength + chunk.byteLength > CONTROL_FRAME_LIMIT_BYTES) {
34090
+ if (!settled) fail2("IPC_MESSAGE_TOO_LARGE");
34091
+ return;
34092
+ }
34093
+ bytes = Buffer.concat([bytes, chunk]);
34094
+ if (platform === "win32" && bytes.indexOf(10) >= 0) dispatch();
34095
+ });
34096
+ socket.once("end", () => {
34097
+ if (requestEnded || settled) return;
34098
+ dispatch();
33645
34099
  });
33646
34100
  });
33647
34101
  }
33648
34102
  async function prepareUnixEndpoint(endpoint, reclaim) {
33649
- const parent = path31.dirname(endpoint);
34103
+ const parent = path32.dirname(endpoint);
33650
34104
  const parentStat = await fs27.lstat(parent).catch((error) => error.code === "ENOENT" ? void 0 : Promise.reject(error));
33651
34105
  if (parentStat === void 0 || !parentStat.isDirectory() || parentStat.isSymbolicLink() || (Number(parentStat.mode) & 63) !== 0) throw lifecycleError("ipc_path_unsafe", "The LocalApp control directory is not private");
33652
34106
  const existing = await fs27.lstat(endpoint, { bigint: true }).catch((error) => error.code === "ENOENT" ? void 0 : Promise.reject(error));
@@ -33837,9 +34291,9 @@ var LocalAppDaemon = class {
33837
34291
  const current = await readCurrentRelease(this.options.layout);
33838
34292
  const manifest = await verifyReleaseArtifact(current.releasePath);
33839
34293
  if (typeof manifest.serverEntrypoint !== "string") throw lifecycleError("canonical_server_unavailable", "The packed canonical LocalApp Server runtime is unavailable");
33840
- const entrypoint = path32.join(current.releasePath, ...manifest.serverEntrypoint.split("/"));
33841
- const spawn7 = this.options.spawnOwnedProcess ?? spawnOwnedProcess;
33842
- const server = spawn7(process.execPath, [entrypoint, "start", "--data-dir", this.options.layout.dataDir, "--host", "127.0.0.1", "--port", "0"], {
34294
+ const entrypoint = path33.join(current.releasePath, ...manifest.serverEntrypoint.split("/"));
34295
+ const spawn8 = this.options.spawnOwnedProcess ?? spawnOwnedProcess;
34296
+ const server = spawn8(process.execPath, [entrypoint, "start", "--data-dir", this.options.layout.dataDir, "--host", "127.0.0.1", "--port", "0"], {
33843
34297
  cwd: current.releasePath,
33844
34298
  env: { ...process.env, LOCALAPP_DEVICE_CONTROL_TOKEN: this.deviceControlToken, LOCALAPP_NOTIFICATION_CONTROL_TOKEN: this.notificationControlToken, LOCALAPP_DEV_TOOLS: void 0 },
33845
34299
  stdio: ["ignore", "pipe", "inherit"]
@@ -33907,12 +34361,12 @@ var LocalAppDaemon = class {
33907
34361
  if (failure !== void 0) throw failure;
33908
34362
  }
33909
34363
  async createDefaultNotificationRuntime(options2) {
33910
- const store = new DeliveryStore({ statePath: path32.join(this.options.layout.supportDir, "notifications", "delivery-state.json") });
33911
- const native = await createNativeAdapter(path32.join(options2.releasePath, "runtime", "native"), { supportDir: this.options.layout.supportDir });
34364
+ const store = new DeliveryStore({ statePath: path33.join(this.options.layout.supportDir, "notifications", "delivery-state.json") });
34365
+ const native = await createNativeAdapter(path33.join(options2.releasePath, "runtime", "native"), { supportDir: this.options.layout.supportDir });
33912
34366
  const dispatcher = new NotificationDispatcher({
33913
34367
  store,
33914
34368
  adapter: native,
33915
- iconPath: path32.join(options2.releasePath, "runtime", "server", "web", "home", "redline-launch-hero.png")
34369
+ iconPath: path33.join(options2.releasePath, "runtime", "server", "web", "home", "redline-launch-hero.png")
33916
34370
  });
33917
34371
  const manager = new NotificationConnectionManager({
33918
34372
  localServerOrigin: options2.listenUrl,
@@ -34003,7 +34457,7 @@ async function verifyHealth2(listenUrl, timeoutMs) {
34003
34457
  }
34004
34458
  async function readLock(lockPath) {
34005
34459
  const before = await fs28.lstat(lockPath, { bigint: true });
34006
- if (!before.isFile() || before.isSymbolicLink() || (Number(before.mode) & 63) !== 0) {
34460
+ if (!before.isFile() || before.isSymbolicLink() || process.platform !== "win32" && (Number(before.mode) & 63) !== 0) {
34007
34461
  throw lifecycleError("daemon_lock_invalid", "The LocalApp daemon lock is unsafe");
34008
34462
  }
34009
34463
  let value2;
@@ -34056,7 +34510,7 @@ async function unlinkOwned2(filePath, identity) {
34056
34510
  return true;
34057
34511
  }
34058
34512
  function digestDataRoot(dataDir) {
34059
- return crypto11.createHash("sha256").update(path32.resolve(dataDir)).digest("hex");
34513
+ return crypto11.createHash("sha256").update(path33.resolve(dataDir)).digest("hex");
34060
34514
  }
34061
34515
  async function withCleanupTimeout(operation, timeoutMs) {
34062
34516
  let timer;
@@ -34070,8 +34524,57 @@ async function withCleanupTimeout(operation, timeoutMs) {
34070
34524
  }
34071
34525
  }
34072
34526
 
34527
+ // packages/localapp/src/daemon/windows-identity.ts
34528
+ import { spawn as spawn7 } from "node:child_process";
34529
+ var VERIFY_TIMEOUT_MS = 8e3;
34530
+ async function verifyWindowsRuntimeOwnership(layout) {
34531
+ const systemRoot = process.env.SystemRoot ?? process.env.SYSTEMROOT ?? "C:\\Windows";
34532
+ const powershell = `${systemRoot}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
34533
+ const script = [
34534
+ "$errorActionPreference='Stop'",
34535
+ "try {",
34536
+ " $dir = $env:LOCALAPP_VERIFY_DIR",
34537
+ " if (-not $dir) { 'false'; exit }",
34538
+ " $identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()",
34539
+ " $current = [string]$identity.User.Value",
34540
+ " $owner = (Get-Acl -LiteralPath $dir).Owner",
34541
+ " $ownerSid = ([System.Security.Principal.NTAccount]$owner).Translate([System.Security.Principal.SecurityIdentifier]).Value",
34542
+ " if ($current -eq [string]$ownerSid) { 'true'; exit }",
34543
+ " $isAdmin = @($identity.Groups | ForEach-Object { [string]$_.Value }) -contains 'S-1-5-32-544'",
34544
+ " if ([string]$ownerSid -eq 'S-1-5-32-544' -and $isAdmin) { 'true'; exit }",
34545
+ " 'false'",
34546
+ "} catch { 'false' }"
34547
+ ].join("\n");
34548
+ return await new Promise((resolve2) => {
34549
+ let stdout = "";
34550
+ let settled = false;
34551
+ const settle = (value2) => {
34552
+ if (settled) return;
34553
+ settled = true;
34554
+ clearTimeout(timer);
34555
+ resolve2(value2);
34556
+ };
34557
+ const child = spawn7(powershell, ["-NoProfile", "-NonInteractive", "-Command", script], {
34558
+ windowsHide: true,
34559
+ stdio: ["ignore", "pipe", "ignore"],
34560
+ env: { ...process.env, LOCALAPP_VERIFY_DIR: layout.runtimeDir }
34561
+ });
34562
+ const timer = setTimeout(() => {
34563
+ child.kill();
34564
+ settle(false);
34565
+ }, VERIFY_TIMEOUT_MS);
34566
+ timer.unref?.();
34567
+ child.stdout?.setEncoding("utf8");
34568
+ child.stdout?.on("data", (chunk) => {
34569
+ stdout += chunk;
34570
+ });
34571
+ child.once("error", () => settle(false));
34572
+ child.once("close", () => settle(stdout.trim() === "true"));
34573
+ });
34574
+ }
34575
+
34073
34576
  // packages/localapp/src/main.ts
34074
- import path33 from "node:path";
34577
+ import path34 from "node:path";
34075
34578
  import fs29 from "node:fs";
34076
34579
  import { fileURLToPath as fileURLToPath5 } from "node:url";
34077
34580
  async function runLocalApp(argv, io = defaultCliIo()) {
@@ -34081,7 +34584,7 @@ async function runLocalApp(argv, io = defaultCliIo()) {
34081
34584
  io.stdout(`localapp ${await loadPackageVersion()}
34082
34585
  `);
34083
34586
  } else if (command.kind === "help") {
34084
- io.stdout("Usage: localapp <command>\n");
34587
+ io.stdout(renderHelp(command.topic));
34085
34588
  } else if (command.kind === "login") {
34086
34589
  return login(command, io);
34087
34590
  } else if (command.kind === "logout") {
@@ -34089,7 +34592,7 @@ async function runLocalApp(argv, io = defaultCliIo()) {
34089
34592
  } else if (command.kind === "whoami") {
34090
34593
  return whoami(command, io);
34091
34594
  } else if (command.kind === "init") {
34092
- const name = command.name ?? path33.basename(process.cwd());
34595
+ const name = command.name ?? path34.basename(process.cwd());
34093
34596
  await initializeProject({ cwd: process.cwd(), name, skipInstall: command.skipInstall, skipDeploy: command.skipDeploy, io });
34094
34597
  } else if (command.kind === "sync-template") {
34095
34598
  const result = await syncManagedTemplate(process.cwd(), command);
@@ -34142,7 +34645,10 @@ async function runLocalApp(argv, io = defaultCliIo()) {
34142
34645
  runtimeDir: process.env.LOCALAPP_RUNTIME_DIR,
34143
34646
  dataDir: process.env.LOCALAPP_DATA_DIR
34144
34647
  });
34145
- const daemon = new LocalAppDaemon({ layout });
34648
+ const daemon = new LocalAppDaemon({
34649
+ layout,
34650
+ ...layout.platform === "win32" ? { verifyWindowsCurrentUser: () => verifyWindowsRuntimeOwnership(layout) } : {}
34651
+ });
34146
34652
  const stop = () => {
34147
34653
  void daemon.stop().catch(() => void 0);
34148
34654
  };
@@ -34157,6 +34663,7 @@ async function runLocalApp(argv, io = defaultCliIo()) {
34157
34663
  writeStructuredError(io, {
34158
34664
  code: error.code,
34159
34665
  message: error.message,
34666
+ ...error instanceof LocalAppArgumentError ? { hint: helpHint(argv) } : {},
34160
34667
  ...error instanceof LocalAppArgumentError && error.option !== void 0 ? { option: error.option } : {}
34161
34668
  });
34162
34669
  return 1;
@@ -34174,7 +34681,7 @@ function isMainModule(modulePath, invokedPath) {
34174
34681
  try {
34175
34682
  return fs29.realpathSync(modulePath) === fs29.realpathSync(invokedPath);
34176
34683
  } catch {
34177
- return path33.resolve(modulePath) === path33.resolve(invokedPath);
34684
+ return path34.resolve(modulePath) === path34.resolve(invokedPath);
34178
34685
  }
34179
34686
  }
34180
34687
  export {