browser-debugger-cli 0.8.0 → 0.10.0

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 (304) hide show
  1. package/README.md +7 -1
  2. package/dist/cdp/schema.d.ts +4 -1
  3. package/dist/cdp/schema.js +48 -7
  4. package/dist/commands/cdp.js +3 -2
  5. package/dist/commands/cleanup.d.ts +11 -0
  6. package/dist/commands/cleanup.js +161 -57
  7. package/dist/commands/console.d.ts +20 -1
  8. package/dist/commands/console.js +57 -17
  9. package/dist/commands/details.js +3 -2
  10. package/dist/commands/dom/DomElementResolver.d.ts +10 -3
  11. package/dist/commands/dom/DomElementResolver.js +35 -17
  12. package/dist/commands/dom/a11y.d.ts +10 -0
  13. package/dist/commands/dom/a11y.js +29 -6
  14. package/dist/commands/dom/eval.d.ts +3 -1
  15. package/dist/commands/dom/eval.js +29 -4
  16. package/dist/commands/dom/form.js +16 -62
  17. package/dist/commands/dom/formInteraction.js +189 -119
  18. package/dist/commands/dom/formSummary.d.ts +49 -0
  19. package/dist/commands/dom/formSummary.js +180 -0
  20. package/dist/commands/dom/frames.d.ts +2 -1
  21. package/dist/commands/dom/frames.js +17 -2
  22. package/dist/commands/dom/get.d.ts +6 -5
  23. package/dist/commands/dom/get.js +92 -82
  24. package/dist/commands/dom/helpers/index.d.ts +1 -1
  25. package/dist/commands/dom/helpers/index.js +1 -1
  26. package/dist/commands/dom/helpers/keyAttributes.d.ts +20 -0
  27. package/dist/commands/dom/helpers/keyAttributes.js +54 -0
  28. package/dist/commands/dom/helpers/query.d.ts +44 -17
  29. package/dist/commands/dom/helpers/query.js +300 -106
  30. package/dist/commands/dom/helpers/runElementCommand.d.ts +10 -2
  31. package/dist/commands/dom/helpers/runElementCommand.js +98 -30
  32. package/dist/commands/dom/helpers/screenshot.d.ts +4 -1
  33. package/dist/commands/dom/helpers/screenshot.js +239 -51
  34. package/dist/commands/dom/index.d.ts +4 -1
  35. package/dist/commands/dom/index.js +22 -7
  36. package/dist/commands/dom/inspect.d.ts +15 -0
  37. package/dist/commands/dom/inspect.js +82 -0
  38. package/dist/commands/dom/layout.d.ts +14 -0
  39. package/dist/commands/dom/layout.js +54 -0
  40. package/dist/commands/dom/listeners.d.ts +5 -1
  41. package/dist/commands/dom/listeners.js +15 -5
  42. package/dist/commands/dom/query.js +2 -3
  43. package/dist/commands/dom/screenshot.d.ts +12 -2
  44. package/dist/commands/dom/screenshot.js +27 -3
  45. package/dist/commands/dom/semanticUtils.d.ts +16 -10
  46. package/dist/commands/dom/semanticUtils.js +53 -16
  47. package/dist/commands/dom/wait.d.ts +13 -0
  48. package/dist/commands/dom/wait.js +83 -0
  49. package/dist/commands/helpJson.js +2 -2
  50. package/dist/commands/network/list.js +17 -13
  51. package/dist/commands/optionBehaviors.js +154 -21
  52. package/dist/commands/page.d.ts +3 -2
  53. package/dist/commands/page.js +100 -5
  54. package/dist/commands/peek.js +4 -11
  55. package/dist/commands/sessions.d.ts +8 -0
  56. package/dist/commands/sessions.js +19 -0
  57. package/dist/commands/shared/CommandRunner.js +4 -4
  58. package/dist/commands/shared/commonOptions.d.ts +4 -0
  59. package/dist/commands/shared/commonOptions.js +9 -0
  60. package/dist/commands/shared/dataFetcher.js +2 -2
  61. package/dist/commands/shared/followMode.d.ts +21 -1
  62. package/dist/commands/shared/followMode.js +29 -2
  63. package/dist/commands/shared/handleValidationError.d.ts +2 -2
  64. package/dist/commands/shared/handleValidationError.js +12 -3
  65. package/dist/commands/shared/optionTypes.d.ts +61 -5
  66. package/dist/commands/shared/startHelpers.d.ts +66 -0
  67. package/dist/commands/shared/startHelpers.js +103 -13
  68. package/dist/commands/shared/validation.d.ts +14 -2
  69. package/dist/commands/shared/validation.js +20 -3
  70. package/dist/commands/start.d.ts +63 -0
  71. package/dist/commands/start.js +115 -15
  72. package/dist/commands/status.js +29 -7
  73. package/dist/commands/stop.js +7 -6
  74. package/dist/commands/tail.js +4 -11
  75. package/dist/commands/types.d.ts +2 -0
  76. package/dist/commands.js +2 -0
  77. package/dist/connection/chromeIdentity.d.ts +65 -0
  78. package/dist/connection/chromeIdentity.js +143 -0
  79. package/dist/connection/launcher/profilePreferences.d.ts +47 -0
  80. package/dist/connection/launcher/profilePreferences.js +151 -0
  81. package/dist/connection/launcher.d.ts +21 -2
  82. package/dist/connection/launcher.js +42 -16
  83. package/dist/connection/portReservation.d.ts +14 -4
  84. package/dist/connection/portReservation.js +21 -6
  85. package/dist/connection/startupExit.d.ts +8 -0
  86. package/dist/connection/startupExit.js +15 -6
  87. package/dist/constants.d.ts +6 -2
  88. package/dist/constants.js +9 -2
  89. package/dist/daemon/SessionController.js +23 -7
  90. package/dist/daemon/errors.d.ts +1 -1
  91. package/dist/daemon/errors.js +1 -1
  92. package/dist/daemon/launcher.d.ts +10 -2
  93. package/dist/daemon/launcher.js +8 -7
  94. package/dist/daemon/server/SocketServer.js +1 -2
  95. package/dist/daemon/session/Session.d.ts +20 -0
  96. package/dist/daemon/session/Session.js +80 -9
  97. package/dist/daemon/session/chromeConnection.d.ts +9 -0
  98. package/dist/daemon/session/chromeConnection.js +45 -8
  99. package/dist/daemon/session/commandRegistry.d.ts +14 -1
  100. package/dist/daemon/session/commandRegistry.js +113 -67
  101. package/dist/daemon/session/interactions.d.ts +48 -9
  102. package/dist/daemon/session/interactions.js +46 -9
  103. package/dist/daemon/session/triggeredRequests.d.ts +67 -0
  104. package/dist/daemon/session/triggeredRequests.js +157 -0
  105. package/dist/daemon/session/types.d.ts +5 -1
  106. package/dist/daemon.js +10630 -3601
  107. package/dist/errors/messages.d.ts +456 -24
  108. package/dist/errors/messages.js +862 -67
  109. package/dist/index.js +6915 -3401
  110. package/dist/ipc/client.d.ts +21 -1
  111. package/dist/ipc/client.js +35 -3
  112. package/dist/ipc/protocol/commands.d.ts +145 -5
  113. package/dist/ipc/protocol/commands.js +4 -0
  114. package/dist/ipc/protocol/domTypes.d.ts +291 -7
  115. package/dist/ipc/protocol/inspectTypes.d.ts +388 -0
  116. package/dist/ipc/protocol/inspectTypes.js +10 -0
  117. package/dist/ipc/session/lifecycle.d.ts +8 -1
  118. package/dist/ipc/session/queries.d.ts +5 -1
  119. package/dist/ipc/session/types.d.ts +5 -0
  120. package/dist/ipc/transport/index.d.ts +2 -1
  121. package/dist/ipc/transport/index.js +2 -2
  122. package/dist/runtime/dom/actionEffects.d.ts +185 -0
  123. package/dist/runtime/dom/actionEffects.js +402 -0
  124. package/dist/runtime/dom/actionEffectsScripts.d.ts +90 -0
  125. package/dist/runtime/dom/actionEffectsScripts.js +426 -0
  126. package/dist/runtime/dom/elementGeometry.d.ts +170 -0
  127. package/dist/runtime/dom/elementGeometry.js +553 -0
  128. package/dist/runtime/dom/elementInfo.d.ts +103 -0
  129. package/dist/runtime/dom/elementInfo.js +256 -0
  130. package/dist/runtime/dom/evalHelpers.d.ts +51 -6
  131. package/dist/runtime/dom/evalHelpers.js +136 -26
  132. package/dist/runtime/dom/eventListeners.d.ts +2 -1
  133. package/dist/runtime/dom/eventListeners.js +184 -47
  134. package/dist/runtime/dom/formDiscovery.d.ts +1 -1
  135. package/dist/runtime/dom/formDiscovery.js +116 -16
  136. package/dist/runtime/dom/formFillHelpers/fill.d.ts +9 -0
  137. package/dist/runtime/dom/formFillHelpers/fill.js +178 -14
  138. package/dist/runtime/dom/formFillHelpers/index.d.ts +2 -2
  139. package/dist/runtime/dom/formFillHelpers/index.js +2 -2
  140. package/dist/runtime/dom/formFillHelpers/pressKey.js +14 -3
  141. package/dist/runtime/dom/formFillHelpers/scroll.d.ts +3 -0
  142. package/dist/runtime/dom/formFillHelpers/scroll.js +60 -18
  143. package/dist/runtime/dom/formFillHelpers/shared.d.ts +17 -0
  144. package/dist/runtime/dom/formFillHelpers/shared.js +25 -1
  145. package/dist/runtime/dom/formFillHelpers/stability.d.ts +20 -6
  146. package/dist/runtime/dom/formFillHelpers/stability.js +50 -19
  147. package/dist/runtime/dom/formSubmitHelpers.d.ts +3 -0
  148. package/dist/runtime/dom/formSubmitHelpers.js +89 -15
  149. package/dist/runtime/dom/frameLayout.d.ts +60 -0
  150. package/dist/runtime/dom/frameLayout.js +140 -0
  151. package/dist/runtime/dom/frameOrigin.d.ts +50 -0
  152. package/dist/runtime/dom/frameOrigin.js +62 -0
  153. package/dist/runtime/dom/frameScopedConnection.d.ts +92 -0
  154. package/dist/runtime/dom/frameScopedConnection.js +252 -0
  155. package/dist/runtime/dom/frameSelection.d.ts +12 -1
  156. package/dist/runtime/dom/frameSelection.js +22 -3
  157. package/dist/runtime/dom/frames.d.ts +61 -5
  158. package/dist/runtime/dom/frames.js +329 -75
  159. package/dist/runtime/dom/inspect.d.ts +28 -0
  160. package/dist/runtime/dom/inspect.js +557 -0
  161. package/dist/runtime/dom/inspectAllStyles.d.ts +62 -0
  162. package/dist/runtime/dom/inspectAllStyles.js +385 -0
  163. package/dist/runtime/dom/inspectCascade.d.ts +94 -0
  164. package/dist/runtime/dom/inspectCascade.js +371 -0
  165. package/dist/runtime/dom/inspectCascadeModel.d.ts +39 -0
  166. package/dist/runtime/dom/inspectCascadeModel.js +232 -0
  167. package/dist/runtime/dom/inspectHints.d.ts +62 -0
  168. package/dist/runtime/dom/inspectHints.js +305 -0
  169. package/dist/runtime/dom/inspectLayoutModel.d.ts +87 -0
  170. package/dist/runtime/dom/inspectLayoutModel.js +346 -0
  171. package/dist/runtime/dom/inspectModel.d.ts +74 -0
  172. package/dist/runtime/dom/inspectModel.js +184 -0
  173. package/dist/runtime/dom/inspectPaintModel.d.ts +157 -0
  174. package/dist/runtime/dom/inspectPaintModel.js +461 -0
  175. package/dist/runtime/dom/inspectRules.d.ts +37 -0
  176. package/dist/runtime/dom/inspectRules.js +101 -0
  177. package/dist/runtime/dom/inspectScripts.d.ts +132 -0
  178. package/dist/runtime/dom/inspectScripts.js +263 -0
  179. package/dist/runtime/dom/inspectTree.d.ts +40 -0
  180. package/dist/runtime/dom/inspectTree.js +134 -0
  181. package/dist/runtime/dom/inspectVariables.d.ts +33 -0
  182. package/dist/runtime/dom/inspectVariables.js +94 -0
  183. package/dist/runtime/dom/inspectWhyModel.d.ts +20 -0
  184. package/dist/runtime/dom/inspectWhyModel.js +134 -0
  185. package/dist/runtime/dom/layout.d.ts +71 -0
  186. package/dist/runtime/dom/layout.js +340 -0
  187. package/dist/runtime/dom/listenerPageScripts.d.ts +72 -0
  188. package/dist/runtime/dom/listenerPageScripts.js +365 -0
  189. package/dist/runtime/dom/listenerSummary.d.ts +136 -11
  190. package/dist/runtime/dom/listenerSummary.js +361 -22
  191. package/dist/runtime/dom/pageActivity.d.ts +41 -0
  192. package/dist/runtime/dom/pageActivity.js +123 -0
  193. package/dist/runtime/dom/reactEventHelpers.d.ts +63 -2
  194. package/dist/runtime/dom/reactEventHelpers.js +220 -41
  195. package/dist/runtime/dom/targetNode.d.ts +80 -27
  196. package/dist/runtime/dom/targetNode.js +249 -33
  197. package/dist/runtime/dom/wait.d.ts +25 -0
  198. package/dist/runtime/dom/wait.js +199 -0
  199. package/dist/runtime/dom/waitCondition.d.ts +71 -0
  200. package/dist/runtime/dom/waitCondition.js +75 -0
  201. package/dist/runtime/page/emulation.d.ts +71 -0
  202. package/dist/runtime/page/emulation.js +117 -0
  203. package/dist/runtime/page/loadingState.d.ts +36 -0
  204. package/dist/runtime/page/loadingState.js +86 -0
  205. package/dist/runtime/page/navigation.d.ts +46 -2
  206. package/dist/runtime/page/navigation.js +69 -33
  207. package/dist/session/QueryCacheManager.d.ts +11 -1
  208. package/dist/session/QueryCacheManager.js +25 -3
  209. package/dist/session/chromeOwners.d.ts +34 -0
  210. package/dist/session/chromeOwners.js +51 -0
  211. package/dist/session/cleanup/staleSession.d.ts +11 -1
  212. package/dist/session/cleanup/staleSession.js +17 -6
  213. package/dist/session/cleanup/userCommands.js +2 -4
  214. package/dist/session/metadata.d.ts +5 -1
  215. package/dist/session/metadata.js +2 -1
  216. package/dist/session/paths.d.ts +77 -3
  217. package/dist/session/paths.js +111 -5
  218. package/dist/session/port.d.ts +31 -7
  219. package/dist/session/port.js +50 -43
  220. package/dist/session/portClaims.d.ts +66 -0
  221. package/dist/session/portClaims.js +284 -0
  222. package/dist/session/sessionList.d.ts +58 -0
  223. package/dist/session/sessionList.js +199 -0
  224. package/dist/session/sessionName.d.ts +46 -0
  225. package/dist/session/sessionName.js +97 -0
  226. package/dist/telemetry/a11y.d.ts +18 -3
  227. package/dist/telemetry/a11y.js +170 -29
  228. package/dist/telemetry/console.d.ts +1 -0
  229. package/dist/telemetry/console.js +100 -5
  230. package/dist/telemetry/network.js +3 -1
  231. package/dist/telemetry/requestKinds.d.ts +32 -0
  232. package/dist/telemetry/requestKinds.js +61 -0
  233. package/dist/telemetry/requestState.d.ts +31 -0
  234. package/dist/telemetry/requestState.js +38 -0
  235. package/dist/types.d.ts +112 -3
  236. package/dist/ui/formatters/a11y.js +3 -0
  237. package/dist/ui/formatters/console/chronological.d.ts +8 -0
  238. package/dist/ui/formatters/console/chronological.js +17 -4
  239. package/dist/ui/formatters/console/json.js +3 -4
  240. package/dist/ui/formatters/console/shared.d.ts +12 -0
  241. package/dist/ui/formatters/console.d.ts +2 -2
  242. package/dist/ui/formatters/console.js +1 -1
  243. package/dist/ui/formatters/details.d.ts +8 -0
  244. package/dist/ui/formatters/details.js +61 -4
  245. package/dist/ui/formatters/dom.d.ts +27 -14
  246. package/dist/ui/formatters/dom.js +88 -59
  247. package/dist/ui/formatters/form.js +29 -18
  248. package/dist/ui/formatters/inspect.d.ts +39 -0
  249. package/dist/ui/formatters/inspect.js +596 -0
  250. package/dist/ui/formatters/keyAttributes.d.ts +19 -0
  251. package/dist/ui/formatters/keyAttributes.js +84 -0
  252. package/dist/ui/formatters/layout.d.ts +31 -0
  253. package/dist/ui/formatters/layout.js +53 -0
  254. package/dist/ui/formatters/listeners.d.ts +3 -2
  255. package/dist/ui/formatters/listeners.js +73 -9
  256. package/dist/ui/formatters/networkHeaders.d.ts +13 -0
  257. package/dist/ui/formatters/networkHeaders.js +36 -3
  258. package/dist/ui/formatters/networkList.d.ts +29 -1
  259. package/dist/ui/formatters/networkList.js +86 -20
  260. package/dist/ui/formatters/preview.js +2 -1
  261. package/dist/ui/formatters/requestStatus.d.ts +1 -17
  262. package/dist/ui/formatters/requestStatus.js +2 -30
  263. package/dist/ui/formatters/sessions.d.ts +12 -0
  264. package/dist/ui/formatters/sessions.js +40 -0
  265. package/dist/ui/formatters/status.d.ts +21 -2
  266. package/dist/ui/formatters/status.js +47 -10
  267. package/dist/ui/formatters/triggeredRequests.d.ts +36 -0
  268. package/dist/ui/formatters/triggeredRequests.js +65 -0
  269. package/dist/ui/formatting.d.ts +19 -0
  270. package/dist/ui/formatting.js +31 -36
  271. package/dist/ui/messages/chrome.d.ts +9 -0
  272. package/dist/ui/messages/chrome.js +17 -5
  273. package/dist/ui/messages/commands.d.ts +504 -14
  274. package/dist/ui/messages/commands.js +835 -21
  275. package/dist/ui/messages/consoleMessages.d.ts +10 -0
  276. package/dist/ui/messages/consoleMessages.js +17 -0
  277. package/dist/ui/messages/hints.js +2 -1
  278. package/dist/ui/messages/networkMessages.d.ts +14 -0
  279. package/dist/ui/messages/networkMessages.js +18 -0
  280. package/dist/ui/messages/preview.js +5 -4
  281. package/dist/ui/messages/session.d.ts +30 -21
  282. package/dist/ui/messages/session.js +48 -26
  283. package/dist/ui/messages/sessionCommand.d.ts +43 -0
  284. package/dist/ui/messages/sessionCommand.js +52 -0
  285. package/dist/utils/async.d.ts +17 -0
  286. package/dist/utils/async.js +36 -0
  287. package/dist/utils/color.d.ts +84 -0
  288. package/dist/utils/color.js +376 -0
  289. package/dist/utils/cssValues.d.ts +109 -0
  290. package/dist/utils/cssValues.js +236 -0
  291. package/dist/utils/http.d.ts +22 -1
  292. package/dist/utils/http.js +28 -9
  293. package/dist/utils/selectorFilters.d.ts +48 -8
  294. package/dist/utils/selectorFilters.js +296 -53
  295. package/dist/utils/shellDetection.d.ts +8 -2
  296. package/dist/utils/shellDetection.js +120 -33
  297. package/dist/utils/suggestions.d.ts +26 -0
  298. package/dist/utils/suggestions.js +73 -0
  299. package/dist/utils/taskMappings.js +10 -0
  300. package/dist/utils/url.d.ts +12 -2
  301. package/dist/utils/url.js +69 -7
  302. package/package.json +1 -1
  303. package/dist/ui/formatters/sessionFormatters.d.ts +0 -58
  304. package/dist/ui/formatters/sessionFormatters.js +0 -121
@@ -0,0 +1,284 @@
1
+ /**
2
+ * Port claims across concurrent sessions.
3
+ *
4
+ * Sessions started at the same time must not pick the same CDP port: Chrome
5
+ * binds it only after the choice is made. A session claims its port by
6
+ * writing `port.txt` while holding a lock; a running session's claim is
7
+ * skipped by the others.
8
+ *
9
+ * Ports belong to the machine, not to a session directory, so the lock and a
10
+ * registry of claiming session directories live in one directory per user
11
+ * under the OS temp directory: sessions of different `BDG_SESSION_DIR`s see
12
+ * each other's claims too. That directory is used only if it is a real
13
+ * directory owned by the user that nobody else can write to; otherwise the
14
+ * lock falls back to the base session directory and only that directory's
15
+ * claims are seen (the launched Chrome's identity is still checked).
16
+ */
17
+ import * as fs from 'fs';
18
+ import * as os from 'os';
19
+ import * as path from 'path';
20
+ import { getSessionBaseDir, getSessionDir, listSessionDirs, sessionFilePathIn, } from './paths.js';
21
+ import { createLogger, logDebugError } from '../ui/logging/index.js';
22
+ import { delay } from '../utils/async.js';
23
+ const log = createLogger('session');
24
+ /** Lock file guarding port selection, in the port registry (or base session) directory */
25
+ const PORT_LOCK_FILE = 'port.lock';
26
+ /** Subdirectory of the port registry: one file per claimed port, holding the claiming session directory */
27
+ const CLAIMS_DIR = 'claims';
28
+ /** Overrides the port registry directory (tests) */
29
+ const PORT_REGISTRY_DIR_ENV = 'BDG_PORT_REGISTRY_DIR';
30
+ /** How long to wait for the lock before choosing a port without it */
31
+ const LOCK_WAIT_MS = 5000;
32
+ /** Lock age after which its holder is assumed dead */
33
+ const STALE_LOCK_MS = 10000;
34
+ const LOCK_POLL_MS = 25;
35
+ /** Permission bits that let other users write */
36
+ const GROUP_OTHER_WRITE = 0o022;
37
+ /**
38
+ * Read a port number from a `port.txt` file.
39
+ *
40
+ * @param portPath - File path
41
+ * @returns Port, or null if missing or invalid
42
+ */
43
+ export function readPortFile(portPath) {
44
+ try {
45
+ const port = parseInt(fs.readFileSync(portPath, 'utf-8').trim(), 10);
46
+ return Number.isInteger(port) && port >= 1 && port <= 65535 ? port : null;
47
+ }
48
+ catch (error) {
49
+ logDebugError(log, `read ${portPath}`, error);
50
+ return null;
51
+ }
52
+ }
53
+ /**
54
+ * Directory holding the port lock and the claims registry, shared by every
55
+ * session of the user on this machine.
56
+ *
57
+ * @returns `$BDG_PORT_REGISTRY_DIR`, else `<os temp dir>/bdg-ports-<uid>`
58
+ */
59
+ export function getPortRegistryDir() {
60
+ const override = process.env[PORT_REGISTRY_DIR_ENV]?.trim();
61
+ if (override)
62
+ return path.resolve(override);
63
+ const uid = process.getuid?.();
64
+ return path.join(os.tmpdir(), uid === undefined ? 'bdg-ports' : `bdg-ports-${uid}`);
65
+ }
66
+ /**
67
+ * Whether a path is a directory the current user can trust: a real directory
68
+ * (not a symlink), owned by the user, not writable by group or others.
69
+ *
70
+ * @param dir - Directory
71
+ * @returns Why it cannot be trusted, or null if it can
72
+ */
73
+ export function untrustedDirReason(dir) {
74
+ const stat = fs.lstatSync(dir);
75
+ if (!stat.isDirectory())
76
+ return 'not a directory';
77
+ const uid = process.getuid?.();
78
+ if (uid !== undefined && stat.uid !== uid)
79
+ return `owned by uid ${stat.uid}`;
80
+ if (process.platform !== 'win32' && (stat.mode & GROUP_OTHER_WRITE) !== 0) {
81
+ return `writable by others (mode ${(stat.mode & 0o777).toString(8)})`;
82
+ }
83
+ return null;
84
+ }
85
+ /**
86
+ * The port registry directory, created (mode 0700) if missing, if it can be
87
+ * trusted (see {@link untrustedDirReason}).
88
+ *
89
+ * @param create - Create the directory (and its claims subdirectory) if missing
90
+ * @returns The directory, or null if it is missing or untrusted
91
+ */
92
+ function trustedRegistryDir(create) {
93
+ const dir = getPortRegistryDir();
94
+ try {
95
+ if (create) {
96
+ fs.mkdirSync(path.dirname(dir), { recursive: true });
97
+ fs.mkdirSync(path.join(dir, CLAIMS_DIR), { recursive: true, mode: 0o700 });
98
+ }
99
+ if (!fs.existsSync(dir))
100
+ return null;
101
+ const reason = untrustedDirReason(dir) ?? untrustedDirReason(path.join(dir, CLAIMS_DIR));
102
+ if (reason === null)
103
+ return dir;
104
+ log.info(`Not using the port registry ${dir} (${reason}); port claims are per directory`);
105
+ }
106
+ catch (error) {
107
+ logDebugError(log, `use the port registry ${dir}`, error);
108
+ }
109
+ return null;
110
+ }
111
+ /**
112
+ * Record in the registry that this session directory claims a port. Written
113
+ * to a new temporary file that is renamed into place, so no symlink is
114
+ * followed. The claim holds while that session runs and its `port.txt` names
115
+ * the port; it needs no removal.
116
+ *
117
+ * @param registryDir - Trusted registry directory
118
+ * @param port - Claimed port
119
+ */
120
+ function writePortClaim(registryDir, port) {
121
+ const claimPath = path.join(registryDir, CLAIMS_DIR, String(port));
122
+ const tempPath = `${claimPath}.${process.pid}.tmp`;
123
+ try {
124
+ fs.writeFileSync(tempPath, getSessionDir(), { encoding: 'utf8', flag: 'wx', mode: 0o600 });
125
+ fs.renameSync(tempPath, claimPath);
126
+ }
127
+ catch (error) {
128
+ logDebugError(log, `record the claim of port ${port}`, error);
129
+ fs.rmSync(tempPath, { force: true });
130
+ }
131
+ }
132
+ /**
133
+ * Session directories in the registry (any base directory).
134
+ *
135
+ * @returns Claiming session directories; none if the registry is untrusted
136
+ */
137
+ function registeredSessionDirs() {
138
+ const registryDir = trustedRegistryDir(false);
139
+ if (registryDir === null)
140
+ return [];
141
+ const claimsDir = path.join(registryDir, CLAIMS_DIR);
142
+ try {
143
+ return fs
144
+ .readdirSync(claimsDir)
145
+ .filter((file) => /^\d+$/.test(file))
146
+ .map((file) => readClaim(path.join(claimsDir, file)))
147
+ .filter((dir) => dir !== null);
148
+ }
149
+ catch (error) {
150
+ logDebugError(log, `list ${claimsDir}`, error);
151
+ return [];
152
+ }
153
+ }
154
+ /**
155
+ * Read the session directory of one claim.
156
+ *
157
+ * @param claimPath - Claim file
158
+ * @returns Absolute session directory, or null if unreadable or partly written
159
+ */
160
+ function readClaim(claimPath) {
161
+ try {
162
+ const dir = fs.readFileSync(claimPath, 'utf8').trim();
163
+ return path.isAbsolute(dir) ? dir : null;
164
+ }
165
+ catch (error) {
166
+ logDebugError(log, `read ${claimPath}`, error);
167
+ return null;
168
+ }
169
+ }
170
+ /**
171
+ * Session directories other than the selected one that bdg knows of: those of
172
+ * this base directory, and those of any base directory found in the
173
+ * machine-wide registry. They need not hold a running session.
174
+ *
175
+ * @returns Session directories
176
+ */
177
+ export function otherSessionDirs() {
178
+ const ownDir = getSessionDir();
179
+ const dirs = new Set([...listSessionDirs().map(({ dir }) => dir), ...registeredSessionDirs()]);
180
+ return [...dirs].filter((dir) => dir !== ownDir);
181
+ }
182
+ /**
183
+ * Ports claimed by other sessions that are running or starting (their daemon
184
+ * socket exists), see {@link otherSessionDirs}.
185
+ *
186
+ * @returns Claimed ports
187
+ */
188
+ export function portsClaimedByOtherSessions() {
189
+ const ports = otherSessionDirs()
190
+ .filter((dir) => fs.existsSync(sessionFilePathIn(dir, 'DAEMON_SOCKET')))
191
+ .map((dir) => readPortFile(sessionFilePathIn(dir, 'PORT')));
192
+ return new Set(ports.filter((port) => port !== null));
193
+ }
194
+ /**
195
+ * Take the port-selection lock.
196
+ *
197
+ * @param lockPath - Lock file path
198
+ * @param token - Written into the lock so only its owner removes it
199
+ * @returns True if the lock was taken; false after {@link LOCK_WAIT_MS} or
200
+ * when the lock file cannot be created
201
+ */
202
+ async function acquireLock(lockPath, token) {
203
+ const deadline = Date.now() + LOCK_WAIT_MS;
204
+ while (Date.now() < deadline) {
205
+ try {
206
+ fs.writeFileSync(lockPath, token, { flag: 'wx' });
207
+ return true;
208
+ }
209
+ catch (error) {
210
+ if (error.code !== 'EEXIST') {
211
+ logDebugError(log, 'take the port lock', error);
212
+ return false;
213
+ }
214
+ removeStaleLock(lockPath);
215
+ await delay(LOCK_POLL_MS);
216
+ }
217
+ }
218
+ return false;
219
+ }
220
+ /**
221
+ * Remove a lock left by a process that died while holding it. The lock is
222
+ * moved aside first (only one waiter's rename succeeds); if another process
223
+ * took a fresh lock in the meantime, that one is put back.
224
+ *
225
+ * @param lockPath - Lock file path
226
+ */
227
+ function removeStaleLock(lockPath) {
228
+ try {
229
+ if (Date.now() - fs.statSync(lockPath).mtimeMs <= STALE_LOCK_MS)
230
+ return;
231
+ const staleOwner = fs.readFileSync(lockPath, 'utf8');
232
+ const moved = `${lockPath}.${process.pid}.stale`;
233
+ fs.renameSync(lockPath, moved);
234
+ if (fs.readFileSync(moved, 'utf8') !== staleOwner)
235
+ fs.linkSync(moved, lockPath);
236
+ fs.rmSync(moved, { force: true });
237
+ }
238
+ catch (error) {
239
+ logDebugError(log, 'check the port lock', error);
240
+ }
241
+ }
242
+ /**
243
+ * Release the lock if it is still ours (it may have been taken over as stale).
244
+ *
245
+ * @param lockPath - Lock file path
246
+ * @param token - The token written when the lock was taken
247
+ */
248
+ function releaseLock(lockPath, token) {
249
+ try {
250
+ if (fs.readFileSync(lockPath, 'utf8') === token)
251
+ fs.rmSync(lockPath, { force: true });
252
+ }
253
+ catch (error) {
254
+ logDebugError(log, 'release the port lock', error);
255
+ }
256
+ }
257
+ /**
258
+ * Run port selection under the lock shared by all sessions of the user on
259
+ * this machine (in the trusted registry directory; else in the base session
260
+ * directory). If the lock cannot be taken in time, the selection runs anyway.
261
+ *
262
+ * @param select - Chooses the port; gets a function recording the claim in
263
+ * the registry, a no-op without the registry lock
264
+ * @returns The chosen port
265
+ */
266
+ export async function withPortLock(select) {
267
+ const registryDir = trustedRegistryDir(true);
268
+ const lockDir = registryDir ?? getSessionBaseDir();
269
+ fs.mkdirSync(lockDir, { recursive: true });
270
+ const lockPath = path.join(lockDir, PORT_LOCK_FILE);
271
+ const token = `${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`;
272
+ const locked = await acquireLock(lockPath, token);
273
+ if (!locked)
274
+ log.debug('Port lock busy; choosing a port without it');
275
+ const recordClaim = locked && registryDir !== null ? (port) => writePortClaim(registryDir, port) : () => { };
276
+ try {
277
+ return await select(recordClaim);
278
+ }
279
+ finally {
280
+ if (locked)
281
+ releaseLock(lockPath, token);
282
+ }
283
+ }
284
+ //# sourceMappingURL=portClaims.js.map
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Sessions across the default and named session directories (`bdg sessions`):
3
+ * running ones, and ones whose daemon died and left a Chrome or files behind.
4
+ */
5
+ import type { StatusResponseData } from '../ipc/session/queries.js';
6
+ import { type SocketProbeResult } from './daemonSocket.js';
7
+ import { type SessionDirEntry } from './paths.js';
8
+ /**
9
+ * State of a session: its daemon runs (`active`, `starting`, `ending`,
10
+ * `unresponsive`), or died and left its Chrome running (`crashed`) or only
11
+ * files (`stale`).
12
+ */
13
+ export type RunningSessionState = 'active' | 'starting' | 'ending' | 'unresponsive' | 'crashed' | 'stale';
14
+ /**
15
+ * One session in the list.
16
+ */
17
+ export interface RunningSessionInfo {
18
+ /** Session name, or null for the default session */
19
+ name: string | null;
20
+ state: RunningSessionState;
21
+ /** Current page URL (or the URL being opened while starting) */
22
+ url?: string;
23
+ /** CDP port */
24
+ port?: number;
25
+ daemonPid?: number;
26
+ /** Chrome launched by bdg (absent for an attached Chrome) */
27
+ chromePid?: number;
28
+ /** Command that cleans up a crashed or stale session */
29
+ cleanup?: string;
30
+ }
31
+ /**
32
+ * Summarize a daemon's status response.
33
+ *
34
+ * @param name - Session name
35
+ * @param data - Status data
36
+ * @returns Session info
37
+ */
38
+ export declare function toRunningSession(name: string | null, data: StatusResponseData): RunningSessionInfo;
39
+ /**
40
+ * A session whose daemon is gone: `crashed` while the Chrome bdg launched for
41
+ * it still runs, `stale` when only its files are left. Nothing is changed on
42
+ * disk; `cleanup` names the command that removes them.
43
+ *
44
+ * @param entry - Session directory
45
+ * @param probe - Result of probing its daemon socket
46
+ * @returns Session info, or null when the directory holds no session state
47
+ */
48
+ export declare function describeLeftovers({ name, dir }: SessionDirEntry, probe: SocketProbeResult): RunningSessionInfo | null;
49
+ /**
50
+ * Every session: the default one first, then named sessions by name. Includes
51
+ * crashed and stale sessions, and directories `--session` cannot reach, so
52
+ * their leftovers can be cleaned up. A directory differing only in case
53
+ * (`ALPHA`) that `--session alpha` reaches is listed once, as `alpha`.
54
+ *
55
+ * @returns Sessions
56
+ */
57
+ export declare function listRunningSessions(): Promise<RunningSessionInfo[]>;
58
+ //# sourceMappingURL=sessionList.d.ts.map
@@ -0,0 +1,199 @@
1
+ /**
2
+ * Sessions across the default and named session directories (`bdg sessions`):
3
+ * running ones, and ones whose daemon died and left a Chrome or files behind.
4
+ */
5
+ import * as fs from 'fs';
6
+ import { getStatus } from '../ipc/client.js';
7
+ import { isSessionChrome, readLiveDaemonPid } from './cleanup/staleSession.js';
8
+ import { probeDaemonSocket } from './daemonSocket.js';
9
+ import { SESSION_STATE_FILES, getNamedSessionDir, listSessionDirs, sessionFilePathIn, } from './paths.js';
10
+ import { readPidFromFile } from './pid.js';
11
+ import { readPortFile } from './portClaims.js';
12
+ import { isValidSessionName, normalizeSessionName } from './sessionName.js';
13
+ import { createLogger, logDebugError } from '../ui/logging/index.js';
14
+ import { removeDirCommand, sessionCommand } from '../ui/messages/sessionCommand.js';
15
+ import { isProcessAlive } from '../utils/process.js';
16
+ const log = createLogger('session');
17
+ /**
18
+ * Summarize a daemon's status response.
19
+ *
20
+ * @param name - Session name
21
+ * @param data - Status data
22
+ * @returns Session info
23
+ */
24
+ export function toRunningSession(name, data) {
25
+ const meta = data.sessionMetadata;
26
+ const state = meta ? 'active' : data.ending ? 'ending' : 'starting';
27
+ const url = data.pageState?.url ?? data.starting?.url;
28
+ return {
29
+ name,
30
+ state,
31
+ ...(url !== undefined && { url }),
32
+ ...(meta && { port: meta.port }),
33
+ daemonPid: data.daemonPid,
34
+ ...(meta?.chromePid && { chromePid: meta.chromePid }),
35
+ };
36
+ }
37
+ /**
38
+ * Describe the session of a directory: a running daemon, or what a dead
39
+ * one left behind.
40
+ *
41
+ * @param entry - Session directory
42
+ * @returns Session info, or null when there is no session
43
+ */
44
+ async function describeSession(entry) {
45
+ const { name, dir } = entry;
46
+ const socketPath = sessionFilePathIn(dir, 'DAEMON_SOCKET');
47
+ const probe = await probeDaemonSocket(socketPath);
48
+ if (probe !== 'alive')
49
+ return describeWithoutSocket(entry, probe);
50
+ try {
51
+ const response = await getStatus(socketPath);
52
+ if (response.status === 'ok' && response.data)
53
+ return toRunningSession(name, response.data);
54
+ }
55
+ catch (error) {
56
+ logDebugError(log, `get status of ${dir}`, error);
57
+ }
58
+ return { name, state: 'unresponsive' };
59
+ }
60
+ /**
61
+ * A session whose daemon socket does not answer: `starting` while its daemon
62
+ * (from daemon.pid, verified by command line) runs but has not bound the
63
+ * socket yet, otherwise see {@link describeLeftovers}.
64
+ *
65
+ * @param entry - Session directory
66
+ * @param probe - Result of probing its daemon socket
67
+ * @returns Session info, or null when the directory holds no session state
68
+ */
69
+ function describeWithoutSocket(entry, probe) {
70
+ const daemonPid = readLiveDaemonPid(entry.dir);
71
+ if (daemonPid !== null)
72
+ return { name: entry.name, state: 'starting', daemonPid };
73
+ return describeLeftovers(entry, probe);
74
+ }
75
+ /**
76
+ * A session whose daemon is gone: `crashed` while the Chrome bdg launched for
77
+ * it still runs, `stale` when only its files are left. Nothing is changed on
78
+ * disk; `cleanup` names the command that removes them.
79
+ *
80
+ * @param entry - Session directory
81
+ * @param probe - Result of probing its daemon socket
82
+ * @returns Session info, or null when the directory holds no session state
83
+ */
84
+ export function describeLeftovers({ name, dir }, probe) {
85
+ const chromePid = readPidFromFile(sessionFilePathIn(dir, 'CHROME_PID'));
86
+ const orphan = chromePid !== null && isProcessAlive(chromePid) && isSessionChrome(chromePid, dir);
87
+ const leftover = probe === 'stale' ||
88
+ SESSION_STATE_FILES.some((type) => fs.existsSync(sessionFilePathIn(dir, type)));
89
+ if (!orphan && !leftover)
90
+ return null;
91
+ const port = leftoverPort(dir);
92
+ return {
93
+ name,
94
+ state: orphan ? 'crashed' : 'stale',
95
+ ...(port !== null && { port }),
96
+ ...(orphan && { chromePid }),
97
+ cleanup: sessionCommand('bdg cleanup', name),
98
+ };
99
+ }
100
+ /**
101
+ * The port a dead session used: from its metadata, else its `port.txt`.
102
+ *
103
+ * @param dir - Session directory
104
+ * @returns Port, or null if unknown
105
+ */
106
+ function leftoverPort(dir) {
107
+ try {
108
+ const meta = JSON.parse(fs.readFileSync(sessionFilePathIn(dir, 'METADATA'), 'utf8'));
109
+ if (typeof meta.port === 'number')
110
+ return meta.port;
111
+ }
112
+ catch (error) {
113
+ logDebugError(log, `read the metadata in ${dir}`, error);
114
+ }
115
+ return readPortFile(sessionFilePathIn(dir, 'PORT'));
116
+ }
117
+ /**
118
+ * Whether a directory entry is a session `--session` can select: the
119
+ * default session, or a valid lower-case name.
120
+ *
121
+ * @param entry - Session directory
122
+ * @returns True if selectable
123
+ */
124
+ function isSelectable({ name }) {
125
+ return name === null || (isValidSessionName(name) && name === normalizeSessionName(name));
126
+ }
127
+ /**
128
+ * Whether two paths are the same directory (same inode and device), e.g.
129
+ * `sessions/ALPHA` and `sessions/alpha` on a case-insensitive file system.
130
+ *
131
+ * @param a - First path
132
+ * @param b - Second path
133
+ * @returns True if both exist and are the same directory
134
+ */
135
+ function isSameDir(a, b) {
136
+ try {
137
+ const first = fs.statSync(a);
138
+ const second = fs.statSync(b);
139
+ return first.ino === second.ino && first.dev === second.dev;
140
+ }
141
+ catch (error) {
142
+ logDebugError(log, `compare ${a} with ${b}`, error);
143
+ return false;
144
+ }
145
+ }
146
+ /**
147
+ * The session `--session` reaches in a directory: the entry itself when its
148
+ * name is selectable, the lower-cased session when the name differs only in
149
+ * case and `--session <lower-case>` resolves to this very directory (a
150
+ * case-insensitive file system), else null.
151
+ *
152
+ * @param entry - Session directory
153
+ * @returns Selectable entry, or null
154
+ */
155
+ function selectableEntry(entry) {
156
+ if (isSelectable(entry) || entry.name === null)
157
+ return entry;
158
+ const lower = normalizeSessionName(entry.name);
159
+ if (!isValidSessionName(lower))
160
+ return null;
161
+ return isSameDir(entry.dir, getNamedSessionDir(lower)) ? { name: lower, dir: entry.dir } : null;
162
+ }
163
+ /**
164
+ * A directory `--session` cannot reach (e.g. `--json`, or `ALPHA` on a
165
+ * case-sensitive file system, made by an earlier build): described like any
166
+ * session while its daemon answers, otherwise `stale` with the command that
167
+ * removes it by hand.
168
+ *
169
+ * @param entry - Session directory
170
+ * @returns Session info
171
+ */
172
+ async function describeUnselectable(entry) {
173
+ const socketPath = sessionFilePathIn(entry.dir, 'DAEMON_SOCKET');
174
+ if ((await probeDaemonSocket(socketPath)) === 'alive')
175
+ return describeSession(entry);
176
+ return { name: entry.name, state: 'stale', cleanup: removeDirCommand(entry.dir) };
177
+ }
178
+ /**
179
+ * Every session: the default one first, then named sessions by name. Includes
180
+ * crashed and stale sessions, and directories `--session` cannot reach, so
181
+ * their leftovers can be cleaned up. A directory differing only in case
182
+ * (`ALPHA`) that `--session alpha` reaches is listed once, as `alpha`.
183
+ *
184
+ * @returns Sessions
185
+ */
186
+ export async function listRunningSessions() {
187
+ const listed = new Set();
188
+ const sessions = await Promise.all(listSessionDirs().map((entry) => {
189
+ const selectable = selectableEntry(entry);
190
+ if (selectable === null)
191
+ return describeUnselectable(entry);
192
+ if (listed.has(selectable.name))
193
+ return Promise.resolve(null);
194
+ listed.add(selectable.name);
195
+ return describeSession(selectable);
196
+ }));
197
+ return sessions.filter((session) => session !== null);
198
+ }
199
+ //# sourceMappingURL=sessionList.js.map
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Named sessions (`--session <name>` / `BDG_SESSION`).
3
+ *
4
+ * A named session lives in `<base>/sessions/<name>/` with its own daemon,
5
+ * socket, Chrome and port, so several agents can run bdg side by side.
6
+ * Names are case-insensitive: they are lower-cased when selected, so `ALPHA`
7
+ * and `alpha` are the same session (and directory) on every file system.
8
+ */
9
+ /** Longest session name */
10
+ export declare const MAX_SESSION_NAME_LENGTH = 40;
11
+ /**
12
+ * Whether a name has the allowed characters and length (case-insensitive).
13
+ *
14
+ * @param name - Session name
15
+ * @returns True for a valid name
16
+ */
17
+ export declare function isValidSessionName(name: string): boolean;
18
+ /**
19
+ * The canonical form of a session name: lower case.
20
+ *
21
+ * @param name - Session name as given
22
+ * @returns Lower-cased name
23
+ */
24
+ export declare function normalizeSessionName(name: string): string;
25
+ /**
26
+ * Check a session name: allowed characters, length, and a daemon socket path
27
+ * the OS accepts. When even the shortest name would make the socket path too
28
+ * long, the base directory is blamed instead of the name.
29
+ *
30
+ * @param name - Session name
31
+ * @throws CommandError (81) for an invalid name or a too-long socket path
32
+ */
33
+ export declare function validateSessionName(name: string): void;
34
+ /**
35
+ * Select the session the command acts on.
36
+ *
37
+ * `--session` wins over `BDG_SESSION`; the choice is stored in `BDG_SESSION`
38
+ * so the rest of the process (and a daemon it spawns) resolves the same
39
+ * session directory. The name is stored lower-cased. An empty `BDG_SESSION`
40
+ * means the default session.
41
+ *
42
+ * @param optionValue - Value of `--session`, if given
43
+ * @throws CommandError (81) for an invalid name
44
+ */
45
+ export declare function selectSession(optionValue: string | undefined): void;
46
+ //# sourceMappingURL=sessionName.d.ts.map
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Named sessions (`--session <name>` / `BDG_SESSION`).
3
+ *
4
+ * A named session lives in `<base>/sessions/<name>/` with its own daemon,
5
+ * socket, Chrome and port, so several agents can run bdg side by side.
6
+ * Names are case-insensitive: they are lower-cased when selected, so `ALPHA`
7
+ * and `alpha` are the same session (and directory) on every file system.
8
+ */
9
+ import { CommandError } from '../errors/index.js';
10
+ import { invalidSessionNameError, sessionNameSocketTooLongError, socketPathTooLongError, } from '../errors/messages.js';
11
+ import { MAX_DAEMON_SOCKET_PATH_BYTES, SESSION_NAME_ENV, getNamedSessionDir, sessionFilePathIn, } from './paths.js';
12
+ import { EXIT_CODES } from '../utils/exitCodes.js';
13
+ /** Longest session name */
14
+ export const MAX_SESSION_NAME_LENGTH = 40;
15
+ /**
16
+ * Characters allowed in a session name: a letter or digit first (so a name
17
+ * never looks like an option), then letters, digits, `-` or `_`.
18
+ */
19
+ const SESSION_NAME_PATTERN = new RegExp(`^[A-Za-z0-9][A-Za-z0-9_-]{0,${MAX_SESSION_NAME_LENGTH - 1}}$`);
20
+ /**
21
+ * Whether a name has the allowed characters and length (case-insensitive).
22
+ *
23
+ * @param name - Session name
24
+ * @returns True for a valid name
25
+ */
26
+ export function isValidSessionName(name) {
27
+ return SESSION_NAME_PATTERN.test(name);
28
+ }
29
+ /**
30
+ * The canonical form of a session name: lower case.
31
+ *
32
+ * @param name - Session name as given
33
+ * @returns Lower-cased name
34
+ */
35
+ export function normalizeSessionName(name) {
36
+ return name.toLowerCase();
37
+ }
38
+ /**
39
+ * Check a session name: allowed characters, length, and a daemon socket path
40
+ * the OS accepts. When even the shortest name would make the socket path too
41
+ * long, the base directory is blamed instead of the name.
42
+ *
43
+ * @param name - Session name
44
+ * @throws CommandError (81) for an invalid name or a too-long socket path
45
+ */
46
+ export function validateSessionName(name) {
47
+ if (!isValidSessionName(name)) {
48
+ throwInvalid(invalidSessionNameError(name, MAX_SESSION_NAME_LENGTH));
49
+ }
50
+ const shortest = namedSocketPath('a');
51
+ if (Buffer.byteLength(shortest) > MAX_DAEMON_SOCKET_PATH_BYTES) {
52
+ throwInvalid(socketPathTooLongError(shortest, MAX_DAEMON_SOCKET_PATH_BYTES));
53
+ }
54
+ const socketPath = namedSocketPath(name);
55
+ if (Buffer.byteLength(socketPath) > MAX_DAEMON_SOCKET_PATH_BYTES) {
56
+ throwInvalid(sessionNameSocketTooLongError(name, socketPath, MAX_DAEMON_SOCKET_PATH_BYTES));
57
+ }
58
+ }
59
+ /**
60
+ * Daemon socket path of a named session.
61
+ *
62
+ * @param name - Session name
63
+ * @returns Socket path
64
+ */
65
+ function namedSocketPath(name) {
66
+ return sessionFilePathIn(getNamedSessionDir(name), 'DAEMON_SOCKET');
67
+ }
68
+ /**
69
+ * Throw an invalid-arguments error (81).
70
+ *
71
+ * @param err - Message and suggestion
72
+ * @throws CommandError always
73
+ */
74
+ function throwInvalid(err) {
75
+ throw new CommandError(err.message, { suggestion: err.suggestion }, EXIT_CODES.INVALID_ARGUMENTS);
76
+ }
77
+ /**
78
+ * Select the session the command acts on.
79
+ *
80
+ * `--session` wins over `BDG_SESSION`; the choice is stored in `BDG_SESSION`
81
+ * so the rest of the process (and a daemon it spawns) resolves the same
82
+ * session directory. The name is stored lower-cased. An empty `BDG_SESSION`
83
+ * means the default session.
84
+ *
85
+ * @param optionValue - Value of `--session`, if given
86
+ * @throws CommandError (81) for an invalid name
87
+ */
88
+ export function selectSession(optionValue) {
89
+ const name = optionValue ?? process.env[SESSION_NAME_ENV]?.trim();
90
+ if (name === undefined || (optionValue === undefined && name === '')) {
91
+ delete process.env[SESSION_NAME_ENV];
92
+ return;
93
+ }
94
+ validateSessionName(name);
95
+ process.env[SESSION_NAME_ENV] = normalizeSessionName(name);
96
+ }
97
+ //# sourceMappingURL=sessionName.js.map