@countinghouse/ch-local 0.0.0-stage → 1.0.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 (262) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +361 -2
  3. package/bin/ch-local.js +472 -0
  4. package/clients/claude-code/.claude-plugin/plugin.json +6 -0
  5. package/clients/claude-code/.mcp.json +11 -0
  6. package/clients/claude-code/bin/launch.js +235 -0
  7. package/clients/claude-code/bin/win-acl.js +420 -0
  8. package/clients/claude-code/skills/ci-failure-triage/SKILL.md +21 -0
  9. package/clients/claude-code/skills/countinghouse-module/SKILL.md +177 -0
  10. package/clients/claude-code/skills/countinghouse-setup/SKILL.md +74 -0
  11. package/lib/allowlist.js +65 -0
  12. package/lib/aside.js +16 -0
  13. package/lib/atomic.js +45 -0
  14. package/lib/auto-apply.js +245 -0
  15. package/lib/auto-upgrade.js +98 -0
  16. package/lib/availability.js +307 -0
  17. package/lib/ceiling.js +280 -0
  18. package/lib/clean-text.js +20 -0
  19. package/lib/cli-change.js +38 -0
  20. package/lib/client-conditions-fixtures.js +143 -0
  21. package/lib/client-conditions.js +656 -0
  22. package/lib/clients.js +179 -0
  23. package/lib/command-line.js +202 -0
  24. package/lib/conditions-command.js +116 -0
  25. package/lib/control.js +134 -0
  26. package/lib/credential-store.js +414 -0
  27. package/lib/credentials-command.js +344 -0
  28. package/lib/daemon-requests.js +137 -0
  29. package/lib/daemon.js +888 -0
  30. package/lib/describe-module.js +137 -0
  31. package/lib/description-check.js +175 -0
  32. package/lib/failed-json.js +43 -0
  33. package/lib/gc.js +274 -0
  34. package/lib/github-token.js +57 -0
  35. package/lib/handoff-io.js +73 -0
  36. package/lib/held-back.js +116 -0
  37. package/lib/hidden-input.js +64 -0
  38. package/lib/history.js +49 -0
  39. package/lib/home.js +372 -0
  40. package/lib/in-place.js +1036 -0
  41. package/lib/install-plan.js +142 -0
  42. package/lib/install.js +846 -0
  43. package/lib/installed-description.js +153 -0
  44. package/lib/integrity.js +7 -0
  45. package/lib/lock.js +456 -0
  46. package/lib/lockfile-rules.js +98 -0
  47. package/lib/machine.js +20 -0
  48. package/lib/module-credentials.js +403 -0
  49. package/lib/module-record.js +298 -0
  50. package/lib/module-roles.js +44 -0
  51. package/lib/module-seams.js +26 -0
  52. package/lib/module-store.js +202 -0
  53. package/lib/module-values.js +334 -0
  54. package/lib/names.js +31 -0
  55. package/lib/next-steps.js +8 -0
  56. package/lib/node-check.js +56 -0
  57. package/lib/npm-fetch.js +123 -0
  58. package/lib/npm-release.js +99 -0
  59. package/lib/npm-upgrade.js +146 -0
  60. package/lib/npm.js +41 -0
  61. package/lib/outside-edits.js +162 -0
  62. package/lib/own-applied.js +175 -0
  63. package/lib/own-command.js +380 -0
  64. package/lib/own-file.js +120 -0
  65. package/lib/own-record.js +96 -0
  66. package/lib/own-tree.js +336 -0
  67. package/lib/pack-table.js +290 -0
  68. package/lib/packs-command.js +570 -0
  69. package/lib/packs.js +219 -0
  70. package/lib/pins.js +64 -0
  71. package/lib/pipe-probe.js +82 -0
  72. package/lib/plain-read.js +63 -0
  73. package/lib/private-file.js +90 -0
  74. package/lib/private-write.js +33 -0
  75. package/lib/provenance.js +234 -0
  76. package/lib/record.js +82 -0
  77. package/lib/registry.js +22 -0
  78. package/lib/release-pins.js +350 -0
  79. package/lib/release-pins.json +4225 -0
  80. package/lib/release-tags.js +12 -0
  81. package/lib/release.js +36 -0
  82. package/lib/restart-command.js +161 -0
  83. package/lib/rollback.js +227 -0
  84. package/lib/run-liveness.js +15 -0
  85. package/lib/runtime-log.js +287 -0
  86. package/lib/sandbox-support.js +17 -0
  87. package/lib/semver-order.js +40 -0
  88. package/lib/session-socket.js +69 -0
  89. package/lib/session-table.js +238 -0
  90. package/lib/session.js +281 -0
  91. package/lib/settings-command.js +82 -0
  92. package/lib/settings.js +564 -0
  93. package/lib/shim-binary.js +152 -0
  94. package/lib/shim-config.js +159 -0
  95. package/lib/shim-install.js +365 -0
  96. package/lib/sigstore/README.md +44 -0
  97. package/lib/sigstore/npm-keys.json +18 -0
  98. package/lib/sigstore/trusted-root.json +126 -0
  99. package/lib/snippets.js +76 -0
  100. package/lib/start.js +721 -0
  101. package/lib/store-files.js +48 -0
  102. package/lib/store-paths.js +33 -0
  103. package/lib/swap-preload.js +38 -0
  104. package/lib/tar.js +220 -0
  105. package/lib/uninstall.js +314 -0
  106. package/lib/unpack.js +41 -0
  107. package/lib/upgrade-stamp.js +63 -0
  108. package/lib/upgrade.js +281 -0
  109. package/lib/watch.js +40 -0
  110. package/lib/win-acl.js +420 -0
  111. package/node_modules/@sigstore/bundle/LICENSE +202 -0
  112. package/node_modules/@sigstore/bundle/README.md +19 -0
  113. package/node_modules/@sigstore/bundle/dist/build.d.ts +18 -0
  114. package/node_modules/@sigstore/bundle/dist/build.js +100 -0
  115. package/node_modules/@sigstore/bundle/dist/bundle.d.ts +74 -0
  116. package/node_modules/@sigstore/bundle/dist/bundle.js +24 -0
  117. package/node_modules/@sigstore/bundle/dist/error.d.ts +4 -0
  118. package/node_modules/@sigstore/bundle/dist/error.js +25 -0
  119. package/node_modules/@sigstore/bundle/dist/index.d.ts +8 -0
  120. package/node_modules/@sigstore/bundle/dist/index.js +43 -0
  121. package/node_modules/@sigstore/bundle/dist/serialized.d.ts +74 -0
  122. package/node_modules/@sigstore/bundle/dist/serialized.js +49 -0
  123. package/node_modules/@sigstore/bundle/dist/utility.d.ts +14 -0
  124. package/node_modules/@sigstore/bundle/dist/utility.js +2 -0
  125. package/node_modules/@sigstore/bundle/dist/validate.d.ts +7 -0
  126. package/node_modules/@sigstore/bundle/dist/validate.js +199 -0
  127. package/node_modules/@sigstore/bundle/package.json +35 -0
  128. package/node_modules/@sigstore/core/LICENSE +202 -0
  129. package/node_modules/@sigstore/core/README.md +10 -0
  130. package/node_modules/@sigstore/core/dist/asn1/error.d.ts +4 -0
  131. package/node_modules/@sigstore/core/dist/asn1/error.js +24 -0
  132. package/node_modules/@sigstore/core/dist/asn1/index.d.ts +1 -0
  133. package/node_modules/@sigstore/core/dist/asn1/index.js +20 -0
  134. package/node_modules/@sigstore/core/dist/asn1/length.d.ts +3 -0
  135. package/node_modules/@sigstore/core/dist/asn1/length.js +62 -0
  136. package/node_modules/@sigstore/core/dist/asn1/obj.d.ts +14 -0
  137. package/node_modules/@sigstore/core/dist/asn1/obj.js +155 -0
  138. package/node_modules/@sigstore/core/dist/asn1/parse.d.ts +6 -0
  139. package/node_modules/@sigstore/core/dist/asn1/parse.js +124 -0
  140. package/node_modules/@sigstore/core/dist/asn1/tag.d.ts +16 -0
  141. package/node_modules/@sigstore/core/dist/asn1/tag.js +89 -0
  142. package/node_modules/@sigstore/core/dist/crypto.d.ts +6 -0
  143. package/node_modules/@sigstore/core/dist/crypto.js +69 -0
  144. package/node_modules/@sigstore/core/dist/dsse.d.ts +1 -0
  145. package/node_modules/@sigstore/core/dist/dsse.js +29 -0
  146. package/node_modules/@sigstore/core/dist/encoding.d.ts +2 -0
  147. package/node_modules/@sigstore/core/dist/encoding.js +27 -0
  148. package/node_modules/@sigstore/core/dist/index.d.ts +9 -0
  149. package/node_modules/@sigstore/core/dist/index.js +66 -0
  150. package/node_modules/@sigstore/core/dist/json.d.ts +1 -0
  151. package/node_modules/@sigstore/core/dist/json.js +60 -0
  152. package/node_modules/@sigstore/core/dist/oid.d.ts +3 -0
  153. package/node_modules/@sigstore/core/dist/oid.js +20 -0
  154. package/node_modules/@sigstore/core/dist/pem.d.ts +2 -0
  155. package/node_modules/@sigstore/core/dist/pem.js +43 -0
  156. package/node_modules/@sigstore/core/dist/rfc3161/error.d.ts +2 -0
  157. package/node_modules/@sigstore/core/dist/rfc3161/error.js +21 -0
  158. package/node_modules/@sigstore/core/dist/rfc3161/index.d.ts +1 -0
  159. package/node_modules/@sigstore/core/dist/rfc3161/index.js +20 -0
  160. package/node_modules/@sigstore/core/dist/rfc3161/timestamp.d.ts +36 -0
  161. package/node_modules/@sigstore/core/dist/rfc3161/timestamp.js +212 -0
  162. package/node_modules/@sigstore/core/dist/rfc3161/tstinfo.d.ts +12 -0
  163. package/node_modules/@sigstore/core/dist/rfc3161/tstinfo.js +72 -0
  164. package/node_modules/@sigstore/core/dist/stream.d.ts +21 -0
  165. package/node_modules/@sigstore/core/dist/stream.js +117 -0
  166. package/node_modules/@sigstore/core/dist/x509/cert.d.ts +43 -0
  167. package/node_modules/@sigstore/core/dist/x509/cert.js +245 -0
  168. package/node_modules/@sigstore/core/dist/x509/ext.d.ts +41 -0
  169. package/node_modules/@sigstore/core/dist/x509/ext.js +146 -0
  170. package/node_modules/@sigstore/core/dist/x509/index.d.ts +2 -0
  171. package/node_modules/@sigstore/core/dist/x509/index.js +23 -0
  172. package/node_modules/@sigstore/core/dist/x509/sct.d.ts +25 -0
  173. package/node_modules/@sigstore/core/dist/x509/sct.js +158 -0
  174. package/node_modules/@sigstore/core/package.json +31 -0
  175. package/node_modules/@sigstore/protobuf-specs/LICENSE +202 -0
  176. package/node_modules/@sigstore/protobuf-specs/README.md +5 -0
  177. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/envelope.d.ts +44 -0
  178. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/envelope.js +59 -0
  179. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/events.d.ts +64 -0
  180. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/events.js +174 -0
  181. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/api/field_behavior.d.ts +74 -0
  182. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/api/field_behavior.js +141 -0
  183. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/protobuf/any.d.ts +74 -0
  184. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/protobuf/any.js +35 -0
  185. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/protobuf/descriptor.d.ts +1309 -0
  186. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/protobuf/descriptor.js +2191 -0
  187. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/protobuf/timestamp.d.ts +113 -0
  188. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/google/protobuf/timestamp.js +29 -0
  189. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/dsse.d.ts +23 -0
  190. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/dsse.js +55 -0
  191. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/entry.d.ts +43 -0
  192. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/entry.js +81 -0
  193. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/hashedrekord.d.ts +22 -0
  194. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/hashedrekord.js +56 -0
  195. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/verifier.d.ts +35 -0
  196. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/rekor/v2/verifier.js +74 -0
  197. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_bundle.d.ts +146 -0
  198. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_bundle.js +103 -0
  199. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_common.d.ts +304 -0
  200. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_common.js +612 -0
  201. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_monitor.d.ts +33 -0
  202. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_monitor.js +55 -0
  203. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_rekor.d.ts +144 -0
  204. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_rekor.js +137 -0
  205. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_trustroot.d.ts +386 -0
  206. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_trustroot.js +284 -0
  207. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_verification.d.ts +191 -0
  208. package/node_modules/@sigstore/protobuf-specs/dist/__generated__/sigstore_verification.js +281 -0
  209. package/node_modules/@sigstore/protobuf-specs/dist/index.d.ts +6 -0
  210. package/node_modules/@sigstore/protobuf-specs/dist/index.js +37 -0
  211. package/node_modules/@sigstore/protobuf-specs/dist/rekor/v2/index.d.ts +4 -0
  212. package/node_modules/@sigstore/protobuf-specs/dist/rekor/v2/index.js +35 -0
  213. package/node_modules/@sigstore/protobuf-specs/package.json +35 -0
  214. package/node_modules/@sigstore/verify/README.md +9 -0
  215. package/node_modules/@sigstore/verify/dist/bundle/dsse.d.ts +12 -0
  216. package/node_modules/@sigstore/verify/dist/bundle/dsse.js +44 -0
  217. package/node_modules/@sigstore/verify/dist/bundle/index.d.ts +4 -0
  218. package/node_modules/@sigstore/verify/dist/bundle/index.js +59 -0
  219. package/node_modules/@sigstore/verify/dist/bundle/message.d.ts +13 -0
  220. package/node_modules/@sigstore/verify/dist/bundle/message.js +54 -0
  221. package/node_modules/@sigstore/verify/dist/error.d.ts +16 -0
  222. package/node_modules/@sigstore/verify/dist/error.js +34 -0
  223. package/node_modules/@sigstore/verify/dist/index.d.ts +6 -0
  224. package/node_modules/@sigstore/verify/dist/index.js +28 -0
  225. package/node_modules/@sigstore/verify/dist/key/certificate.d.ts +21 -0
  226. package/node_modules/@sigstore/verify/dist/key/certificate.js +216 -0
  227. package/node_modules/@sigstore/verify/dist/key/index.d.ts +10 -0
  228. package/node_modules/@sigstore/verify/dist/key/index.js +75 -0
  229. package/node_modules/@sigstore/verify/dist/key/sct.d.ts +4 -0
  230. package/node_modules/@sigstore/verify/dist/key/sct.js +78 -0
  231. package/node_modules/@sigstore/verify/dist/policy.d.ts +5 -0
  232. package/node_modules/@sigstore/verify/dist/policy.js +50 -0
  233. package/node_modules/@sigstore/verify/dist/shared.types.d.ts +50 -0
  234. package/node_modules/@sigstore/verify/dist/shared.types.js +2 -0
  235. package/node_modules/@sigstore/verify/dist/timestamp/index.d.ts +11 -0
  236. package/node_modules/@sigstore/verify/dist/timestamp/index.js +24 -0
  237. package/node_modules/@sigstore/verify/dist/timestamp/tsa.d.ts +3 -0
  238. package/node_modules/@sigstore/verify/dist/timestamp/tsa.js +63 -0
  239. package/node_modules/@sigstore/verify/dist/tlog/checkpoint.d.ts +11 -0
  240. package/node_modules/@sigstore/verify/dist/tlog/checkpoint.js +154 -0
  241. package/node_modules/@sigstore/verify/dist/tlog/dsse.d.ts +6 -0
  242. package/node_modules/@sigstore/verify/dist/tlog/dsse.js +106 -0
  243. package/node_modules/@sigstore/verify/dist/tlog/hashedrekord.d.ts +6 -0
  244. package/node_modules/@sigstore/verify/dist/tlog/hashedrekord.js +94 -0
  245. package/node_modules/@sigstore/verify/dist/tlog/index.d.ts +5 -0
  246. package/node_modules/@sigstore/verify/dist/tlog/index.js +92 -0
  247. package/node_modules/@sigstore/verify/dist/tlog/intoto.d.ts +3 -0
  248. package/node_modules/@sigstore/verify/dist/tlog/intoto.js +62 -0
  249. package/node_modules/@sigstore/verify/dist/tlog/merkle.d.ts +3 -0
  250. package/node_modules/@sigstore/verify/dist/tlog/merkle.js +104 -0
  251. package/node_modules/@sigstore/verify/dist/tlog/set.d.ts +3 -0
  252. package/node_modules/@sigstore/verify/dist/tlog/set.js +60 -0
  253. package/node_modules/@sigstore/verify/dist/trust/filter.d.ts +8 -0
  254. package/node_modules/@sigstore/verify/dist/trust/filter.js +23 -0
  255. package/node_modules/@sigstore/verify/dist/trust/index.d.ts +5 -0
  256. package/node_modules/@sigstore/verify/dist/trust/index.js +90 -0
  257. package/node_modules/@sigstore/verify/dist/trust/trust.types.d.ts +29 -0
  258. package/node_modules/@sigstore/verify/dist/trust/trust.types.js +2 -0
  259. package/node_modules/@sigstore/verify/dist/verifier.d.ts +31 -0
  260. package/node_modules/@sigstore/verify/dist/verifier.js +160 -0
  261. package/node_modules/@sigstore/verify/package.json +36 -0
  262. package/package.json +37 -4
@@ -0,0 +1,336 @@
1
+ 'use strict';
2
+ // A user's own module folder, judged, hashed and copied into the home
3
+ // (B-own-add; the own-modules design §2.1). The same rules the runtime's
4
+ // profile validation applies (countinghouse lib/own-module-check.js),
5
+ // checked here again since this copy is what loads:
6
+ // - checkFolder: an absolute folder reached through no link, neither
7
+ // inside the home nor holding it; walked by lstat alone first -- a link,
8
+ // a file with a second name, anything neither a file nor a folder, more
9
+ // than MAX_ENTRIES entries or MAX_TREE_BYTES, a node_modules folder, a
10
+ // native file -- and only then package.json and api.json read, plainly
11
+ // (no link followed, no blocking, a regular file under one name,
12
+ // bounded): a package name not in @countinghouse/, role "scenario", no
13
+ // npm dependencies, a device friendlyName.
14
+ // - treeHash: sha256 over the sorted (relative path, kind, executable bit,
15
+ // sha256 of content) of every entry: the identity a yes binds to.
16
+ // - placeCopy: the folder copied into <own>/<name>/<tree>.new-<random>,
17
+ // the copy hashed -- it must be the tree the user saw -- then renamed
18
+ // to <own>/<name>/<tree>/ with its marker <tree>.json (ch-local's own,
19
+ // so gc and remove-module may take it).
20
+ // Answers name files, never their content.
21
+ const crypto = require('node:crypto');
22
+ const fs = require('node:fs');
23
+ const path = require('node:path');
24
+ const {PACKAGE, endsTrimmed} = require('./names');
25
+ const {writeAtomic} = require('./atomic');
26
+ const {terminalText} = require('./command-line');
27
+
28
+ const MAX_ENTRIES = 20000;
29
+ const MAX_TREE_BYTES = 16 * 1024 * 1024;
30
+ const MAX_JSON_BYTES = 4 * 1024 * 1024;
31
+ const DEPENDENCY_FIELDS = ['dependencies', 'optionalDependencies', 'peerDependencies', 'bundleDependencies', 'bundledDependencies'];
32
+ const PLAIN_FLAGS = fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0) | (fs.constants.O_NONBLOCK || 0);
33
+ const isWin = () => process.platform === 'win32';
34
+ const norm = (p) => (isWin() ? p.toLowerCase() : p);
35
+ const isObject = (x) => x != null && typeof x === 'object' && !Array.isArray(x);
36
+
37
+ // whether p is root or inside it (real paths); <root>/..mine is inside
38
+ function inside(p, root) {
39
+ const rel = path.relative(norm(root), norm(p));
40
+ return rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel));
41
+ }
42
+
43
+ // Each folder on the way to an absolute, resolved path, from just below its
44
+ // root down to the path: the root (a drive, a UNC share) never a part (split
45
+ // on the separator, a Windows path's first part is its drive: countinghouse
46
+ // #499 looked up C:\\C:). p: the path flavour (a test pins both on every OS).
47
+ function pathsOnTheWay(resolved, p = path) {
48
+ const root = p.parse(resolved).root;
49
+ const out = [];
50
+ let at = root;
51
+ for (const part of resolved.slice(root.length).split(p.sep).filter((s) => s !== '')) {
52
+ at = p.join(at, part);
53
+ out.push(at);
54
+ }
55
+ return out;
56
+ }
57
+
58
+ // A file's bytes, read only if it is a plain one: opened without following
59
+ // a link and without blocking, judged on its descriptor. Throws ENOTPLAIN.
60
+ function readPlain(file, maxBytes) {
61
+ const fd = fs.openSync(file, PLAIN_FLAGS);
62
+ try {
63
+ const st = fs.fstatSync(fd);
64
+ if (!st.isFile() || st.nlink !== 1 || st.size > maxBytes) throw Object.assign(new Error('not a plain file'), {code: 'ENOTPLAIN'});
65
+ const buf = Buffer.alloc(st.size);
66
+ let off = 0;
67
+ while (off < st.size) {
68
+ const n = fs.readSync(fd, buf, off, st.size - off, off);
69
+ if (n === 0) break;
70
+ off += n;
71
+ }
72
+ return buf.subarray(0, off);
73
+ } finally {
74
+ fs.closeSync(fd);
75
+ }
76
+ }
77
+
78
+ // Every entry under dir, by lstat alone: [{rel, kind: 'dir'|'file', exec,
79
+ // size}] sorted by rel, and the problems that stop any read
80
+ function walk(dir) {
81
+ const entries = [];
82
+ const problems = [];
83
+ const links = [];
84
+ const twice = [];
85
+ const special = [];
86
+ let bytes = 0;
87
+ let over = false;
88
+ const visit = (at, rel) => {
89
+ if (over) return;
90
+ let names;
91
+ try { names = fs.readdirSync(at); } catch (e) { problems.push(`${rel === '' ? '.' : terminalText(rel, 120)} cannot be read`); return; }
92
+ for (const name of names.sort()) {
93
+ if (over) return;
94
+ if (entries.length >= MAX_ENTRIES) { over = true; return; }
95
+ const full = path.join(at, name);
96
+ const r = rel === '' ? name : `${rel}/${name}`;
97
+ let st;
98
+ try { st = fs.lstatSync(full); } catch (e) { problems.push(`${terminalText(r, 120)} cannot be read`); continue; }
99
+ if (st.isSymbolicLink()) { links.push(r); continue; }
100
+ if (st.isDirectory()) {
101
+ if (name === 'node_modules') problems.push('the folder has a node_modules folder: an own module has none in this release; copy the code it needs into its folder');
102
+ entries.push({rel: r, kind: 'dir', exec: false, size: 0});
103
+ visit(full, r);
104
+ } else if (st.isFile()) {
105
+ if (st.nlink > 1) twice.push(r);
106
+ if (name.endsWith('.node') || name === 'binding.gyp') problems.push(`${terminalText(r, 120)} is native code: an own module holds none`);
107
+ bytes += st.size;
108
+ entries.push({rel: r, kind: 'file', exec: (st.mode & 0o111) !== 0, size: st.size});
109
+ } else {
110
+ special.push(r);
111
+ }
112
+ }
113
+ };
114
+ visit(dir, '');
115
+ // (names as a terminal shows them: an odd name moves no cursor)
116
+ const few = (list) => `${list.slice(0, 3).map((n) => terminalText(n, 80)).join(', ')}${list.length > 3 ? ', …' : ''}`;
117
+ if (over) problems.push(`the folder has more than ${MAX_ENTRIES} entries`);
118
+ if (links.length > 0) problems.push(`the folder holds a link (${few(links)}): an own module's files are its own, never links`);
119
+ if (twice.length > 0) problems.push(`the folder holds a file with a second name (${few(twice)}): an own module's files are its own, one name each`);
120
+ if (special.length > 0) problems.push(`the folder holds something that is neither a file nor a folder (${few(special)}): an own module holds files only`);
121
+ if (bytes > MAX_TREE_BYTES) problems.push(`the folder holds more than ${MAX_TREE_BYTES / (1024 * 1024)} MiB of files`);
122
+ return {entries, problems};
123
+ }
124
+
125
+ // input: the folder the user named; home: the ch-local home -> {real, pkg,
126
+ // spec, entries} or {problems: [message]} (the first a path refusal alone)
127
+ function checkFolder(input, home) {
128
+ if (typeof input !== 'string' || input === '' || input.includes('\0') || !path.isAbsolute(path.resolve(input))) return {problems: ['name your module\'s folder']};
129
+ const resolved = path.resolve(input);
130
+ // no link on the way: each part of the path as written, from its root
131
+ for (const at of pathsOnTheWay(resolved)) {
132
+ let st;
133
+ try { st = fs.lstatSync(at); } catch (e) { return {problems: ['the folder is not there']}; }
134
+ if (st.isSymbolicLink()) return {problems: ['the path goes through a link: name the folder by its real path']};
135
+ }
136
+ let st;
137
+ try { st = fs.statSync(resolved); } catch (e) { return {problems: ['the folder is not there']}; }
138
+ if (!st.isDirectory()) return {problems: ['the path is not a folder']};
139
+ const real = fs.realpathSync.native(resolved);
140
+ let homeReal = null;
141
+ try { homeReal = fs.realpathSync.native(home); } catch (e) { homeReal = null; }
142
+ if (homeReal != null && inside(real, homeReal)) return {problems: ['the folder is inside the ch-local home: keep your own module\'s folder elsewhere']};
143
+ if (homeReal != null && inside(homeReal, real)) return {problems: ['the folder holds the ch-local home: name your module\'s own folder']};
144
+ // the walk first: nothing read until it passes
145
+ const {entries, problems} = walk(real);
146
+ if (problems.length > 0) return {problems};
147
+ // (the bytes kept: what the question shows must be what is hashed)
148
+ let pkg;
149
+ let pkgBytes;
150
+ try { pkgBytes = readPlain(path.join(real, 'package.json'), MAX_JSON_BYTES); pkg = JSON.parse(pkgBytes.toString('utf8')); } catch (e) { return {problems: ['package.json cannot be read as JSON']}; }
151
+ if (!isObject(pkg)) return {problems: ['package.json is not a JSON object']};
152
+ const out = [];
153
+ if (typeof pkg.name !== 'string' || !PACKAGE.test(pkg.name)) out.push('package.json\'s name is not a package name');
154
+ else if (pkg.name.startsWith('@countinghouse/')) out.push('The @countinghouse/ scope is countinghouse\'s own: give your module another name.');
155
+ // (Windows drops a trailing dot: "my-tool." would be my-tool's data)
156
+ else if (endsTrimmed(pkg.name)) out.push('package.json\'s name ends in a dot: on Windows that is another module\'s name; give your module another name.');
157
+ if (typeof pkg.version !== 'string' || pkg.version === '' || pkg.version.length > 64) out.push('package.json has no version');
158
+ // (shown in the question: nothing in it may move the terminal's cursor)
159
+ else if (!/^[0-9A-Za-z][0-9A-Za-z.+-]*$/.test(pkg.version)) out.push('package.json\'s version is not a plain version: letters, digits, ".", "+" and "-" only');
160
+ const ch = isObject(pkg.countinghouse) ? pkg.countinghouse : null;
161
+ if (ch == null || ch.role !== 'scenario') out.push('An own module is a scenario: set "countinghouse": {"role": "scenario"} in its package.json, or its tools are never listed.');
162
+ const declared = DEPENDENCY_FIELDS.filter((f) => pkg[f] != null && (Array.isArray(pkg[f]) ? pkg[f].length > 0 : (isObject(pkg[f]) && Object.keys(pkg[f]).length > 0)));
163
+ if (declared.length > 0) out.push(`package.json declares npm dependencies (${declared.join(', ')}): an own module has none in this release; copy the code it needs into its folder`);
164
+ let spec = null;
165
+ let specBytes = null;
166
+ try { specBytes = readPlain(path.join(real, 'api.json'), MAX_JSON_BYTES); spec = JSON.parse(specBytes.toString('utf8')); } catch (e) { out.push('api.json cannot be read as JSON'); }
167
+ const friendlyName = (spec != null && isObject(spec.device)) ? spec.device.friendlyName : null;
168
+ if (spec != null && (typeof friendlyName !== 'string' || friendlyName === '' || friendlyName.length > 64)) out.push('api.json has no device friendlyName');
169
+ if (out.length > 0) return {problems: out};
170
+ return {real, pkg, spec, entries, pkgBytes, specBytes};
171
+ }
172
+
173
+ // dir (a checked folder, or a copy) and its entries -> the tree's sha256.
174
+ // capture: {<rel>: null, ...}, each filled with the bytes hashed for that
175
+ // file (add-module: the package.json and api.json the question showed)
176
+ function treeHash(dir, entries, capture = null) {
177
+ const h = crypto.createHash('sha256');
178
+ for (const e of entries) {
179
+ if (e.kind === 'dir') {
180
+ h.update(`${e.rel}\0dir\n`);
181
+ } else {
182
+ const bytes = readPlain(path.join(dir, ...e.rel.split('/')), MAX_TREE_BYTES);
183
+ if (capture != null && Object.prototype.hasOwnProperty.call(capture, e.rel)) capture[e.rel] = bytes;
184
+ const content = crypto.createHash('sha256').update(bytes).digest('hex');
185
+ h.update(`${e.rel}\0file\0${e.exec ? 'x' : '-'}\0${content}\n`);
186
+ }
187
+ }
188
+ return h.digest('hex');
189
+ }
190
+
191
+ // A copy made read-only (the own-modules design §2.1 step 4; the
192
+ // reviewer's high on #113, 2): each file 0444 (0555 when executable: the
193
+ // hash keeps that bit), each folder 0555, the deepest first. On Windows a
194
+ // file's chmod sets its read-only attribute, and a folder's does nothing.
195
+ // So a change to a copy takes an explicit chmod first. (A same-user process
196
+ // that does that can still edit it; start and the applier re-check the
197
+ // hash, a worker's spawn does not: R6, a 1.1 row.)
198
+ // A path's mode set on the entry itself, never through a link (the medium
199
+ // on #113's round 1). POSIX: opened with O_NOFOLLOW (a link: ELOOP) and
200
+ // O_NONBLOCK, then fchmod'ed, so an entry swapped for a link after an lstat
201
+ // changes nothing outside. Windows -- the one Windows-only boundary here --
202
+ // refuses fchmod on a handle opened to read (EPERM: the reviewer on #113 at
203
+ // 10220b9), and its chmod only sets or clears the read-only attribute: an
204
+ // entry lstat finds a link (or junction) is refused there, any other is
205
+ // chmod'ed by path. (A link swapped in between lstat and chmod needs the
206
+ // symlink privilege on Windows: the reparse residual, a 1.1 row.) platform:
207
+ // a test's, so both branches run on every OS.
208
+ function chmodNoFollow(p, mode, platform = process.platform) {
209
+ if (platform === 'win32') {
210
+ if (fs.lstatSync(p).isSymbolicLink()) throw Object.assign(new Error(`ELOOP: a link is not followed, '${p}'`), {code: 'ELOOP'});
211
+ fs.chmodSync(p, mode);
212
+ return;
213
+ }
214
+ const fd = fs.openSync(p, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0) | (fs.constants.O_NONBLOCK || 0));
215
+ try { fs.fchmodSync(fd, mode); } finally { fs.closeSync(fd); }
216
+ }
217
+ function lockCopy(dir) {
218
+ const visit = (at) => {
219
+ for (const name of fs.readdirSync(at)) {
220
+ const full = path.join(at, name);
221
+ const st = fs.lstatSync(full);
222
+ if (st.isSymbolicLink()) continue;
223
+ if (st.isDirectory()) { visit(full); chmodNoFollow(full, 0o555); } else if (st.isFile()) chmodNoFollow(full, (st.mode & 0o111) !== 0 ? 0o555 : 0o444);
224
+ }
225
+ };
226
+ visit(dir);
227
+ chmodNoFollow(dir, 0o555);
228
+ }
229
+ // The opposite, before ch-local deletes a copy (gc, remove-module,
230
+ // uninstall, a repair): every folder and file under root writable by its
231
+ // owner again, by lstat, never through a link. Missing: nothing to do.
232
+ function unlockTree(root) {
233
+ let st;
234
+ try { st = fs.lstatSync(root); } catch (e) { return; }
235
+ if (st.isSymbolicLink()) return;
236
+ if (st.isFile()) { chmodNoFollow(root, (st.mode & 0o777) | 0o600); return; }
237
+ if (!st.isDirectory()) return;
238
+ chmodNoFollow(root, (st.mode & 0o777) | 0o700);
239
+ for (const name of fs.readdirSync(root)) unlockTree(path.join(root, name));
240
+ }
241
+
242
+ // the copy's folder and marker for a module and tree
243
+ const copyDir = (where, name, tree) => path.join(where.own, ...name.split('/'), tree);
244
+ const markerOf = (where, name, tree) => `${copyDir(where, name, tree)}.json`;
245
+
246
+ // Copies the checked folder into the home: staged, hashed -- the copy must
247
+ // hash to `tree`, what the user saw -- then renamed in, its marker last.
248
+ // -> the copy's folder. Throws when the folder changed since it was hashed
249
+ // (OWN_TREE_CHANGED). The caller holds packs.lock.
250
+ function placeCopy(where, name, real, entries, tree, {now = () => new Date()} = {}) {
251
+ const dir = copyDir(where, name, tree);
252
+ // (a whole copy that still hashes so is kept; one changed since is
253
+ // replaced: adding the folder again repairs it)
254
+ if (copyIntact(where, name, tree)) return dir;
255
+ const stage = `${dir}.new-${crypto.randomBytes(4).toString('hex')}`;
256
+ // (each folder here private to this user -- the copies are the user's own
257
+ // code -- made so, or kept so when an earlier one made it otherwise)
258
+ fs.mkdirSync(path.dirname(dir), {recursive: true, mode: 0o700});
259
+ if (process.platform !== 'win32') {
260
+ for (let at = path.dirname(dir); at.length >= where.own.length && at.startsWith(where.own); at = path.dirname(at)) chmodNoFollow(at, 0o700);
261
+ }
262
+ try {
263
+ fs.mkdirSync(stage, {mode: 0o755});
264
+ for (const e of entries) {
265
+ const to = path.join(stage, ...e.rel.split('/'));
266
+ if (e.kind === 'dir') { fs.mkdirSync(to, {mode: 0o755}); continue; }
267
+ fs.writeFileSync(to, readPlain(path.join(real, ...e.rel.split('/')), MAX_TREE_BYTES), {mode: e.exec ? 0o755 : 0o644, flag: 'wx'});
268
+ }
269
+ const copied = walk(stage);
270
+ if (copied.problems.length > 0 || treeHash(stage, copied.entries) !== tree) {
271
+ throw Object.assign(new Error('the folder changed while it was being added: run add-module again'), {code: 'OWN_TREE_CHANGED'});
272
+ }
273
+ // (a copy there that is not whole goes only now, the new one verified:
274
+ // made writable first, its marker removed only then -- a failure
275
+ // before that leaves it marked, so gc and remove-module still take it:
276
+ // the medium on #113's round 1, the reviewer's re-probe)
277
+ if (fs.existsSync(dir)) {
278
+ unlockTree(dir);
279
+ fs.rmSync(markerOf(where, name, tree), {force: true});
280
+ fs.rmSync(dir, {recursive: true, force: true});
281
+ }
282
+ fs.renameSync(stage, dir);
283
+ lockCopy(dir);
284
+ } finally {
285
+ fs.rmSync(stage, {recursive: true, force: true});
286
+ }
287
+ writeAtomic(markerOf(where, name, tree), `${JSON.stringify({name, tree, placedAt: now().toISOString()})}\n`);
288
+ return dir;
289
+ }
290
+
291
+ // -> the bytes of one file (rel) of the copy at <own>/<name>/<tree>, read
292
+ // once while the whole copy is hashed, or null when the copy is not whole or
293
+ // no longer hashes to tree: what is used is what was hashed (the medium on
294
+ // B-own-settings, 3)
295
+ function readIntact(where, name, tree, rel) {
296
+ const dir = copyDir(where, name, tree);
297
+ try {
298
+ const marker = JSON.parse(fs.readFileSync(markerOf(where, name, tree), 'utf8'));
299
+ if (marker == null || marker.name !== name || marker.tree !== tree) return null;
300
+ const w = walk(dir);
301
+ if (w.problems.length > 0) return null;
302
+ const capture = {[rel]: null};
303
+ return treeHash(dir, w.entries, capture) === tree && capture[rel] != null ? capture[rel] : null;
304
+ } catch (e) {
305
+ return null;
306
+ }
307
+ }
308
+
309
+ // -> whether the copy at <own>/<name>/<tree> is whole (its marker) and
310
+ // still hashes to tree (the start's check: a changed copy is never loaded)
311
+ // 'intact' | 'changed' | 'gone': gone only when the copy's directory is not
312
+ // there at all (E10: said apart from changed). Anything else not intact --
313
+ // there but unreadable, its marker missing, its hash another -- is changed
314
+ function copyState(where, name, tree) {
315
+ try {
316
+ fs.lstatSync(copyDir(where, name, tree));
317
+ } catch (e) {
318
+ if (e.code === 'ENOENT') return 'gone';
319
+ return 'changed';
320
+ }
321
+ return copyIntact(where, name, tree) ? 'intact' : 'changed';
322
+ }
323
+
324
+ function copyIntact(where, name, tree) {
325
+ const dir = copyDir(where, name, tree);
326
+ try {
327
+ const marker = JSON.parse(fs.readFileSync(markerOf(where, name, tree), 'utf8'));
328
+ if (marker == null || marker.name !== name || marker.tree !== tree) return false;
329
+ const w = walk(dir);
330
+ return w.problems.length === 0 && treeHash(dir, w.entries) === tree;
331
+ } catch (e) {
332
+ return false;
333
+ }
334
+ }
335
+
336
+ module.exports = {readIntact, chmodNoFollow, lockCopy, unlockTree, pathsOnTheWay, checkFolder, treeHash, placeCopy, copyIntact, copyState, copyDir, markerOf, readPlain, walk, MAX_ENTRIES, MAX_TREE_BYTES};
@@ -0,0 +1,290 @@
1
+ 'use strict';
2
+ // Between packs from different pins (#413 rev 3 section 9.4; L1b-2): each
3
+ // module of a pack being added, by the table, with p the pack's pinned
4
+ // version and a the module's active version in the home:
5
+ //
6
+ // not installed p is placed
7
+ // a = p skipped (shared)
8
+ // a newer than p, no breaking change skipped; the pack recorded with a
9
+ // a older than p, no breaking change p placed and active; its callers said
10
+ // a older than p, breaking, no installed caller the same
11
+ // a older than p, breaking, installed callers Question A
12
+ // a newer than p, breaking Question B
13
+ //
14
+ // A module's version is never lowered by adding a pack: a newer installed
15
+ // version stays active (rule 2: the highest any pack records), and the pack
16
+ // is recorded with it. A breaking change is semver's: the majors differ, or
17
+ // both are 0.x and the minors differ (0.0.x: the patches). "Installed
18
+ // modules that call it" are read from the installed modules' manifests'
19
+ // countinghouse.calls, the names before the slash, matched by friendly name
20
+ // (api.json's device.friendlyName) as the runtime matches them; the pack's
21
+ // own modules are not counted for Question A, and are the ones Question B
22
+ // names (read from its tarballs: not placed yet).
23
+ const fs = require('node:fs');
24
+ const path = require('node:path');
25
+ const {compareVersions, activeVersions, livePacks} = require('./module-record');
26
+ const {holds} = require('./packs');
27
+ const {versionDir, looksPlaced} = require('./store-paths');
28
+ const {readMember} = require('./tar');
29
+ const {short, manifestOf, friendlyOf, callsOf} = require('./availability');
30
+ const {chLocal} = require('./command-line');
31
+ const parts = (v) => String(v).split(/[-+]/)[0].split('.').map(Number);
32
+
33
+ // semver's breaking change between two versions
34
+ function breakingBetween(a, b) {
35
+ const [x, y] = [parts(a), parts(b)];
36
+ if (x[0] !== y[0]) return true;
37
+ if (x[0] !== 0) return false;
38
+ if (x[1] !== y[1]) return true;
39
+ return x[1] === 0 && x[2] !== y[2];
40
+ }
41
+ // the line a version is written for: 2.x, 0.4.x, 0.0.3
42
+ function lineOf(v) {
43
+ const [maj, min, pat] = parts(v);
44
+ if (maj !== 0) return `${maj}.x`;
45
+ if (min !== 0) return `0.${min}.x`;
46
+ return `0.0.${pat}`;
47
+ }
48
+
49
+ const json = (buf) => { try { return buf == null ? null : JSON.parse(buf.toString('utf8')); } catch (err) { return null; } };
50
+
51
+ // where, record (modules.json), pack (its name), spec ({packages}), pins
52
+ // ({m: {version}}), bytes ({m: the pinned tarball}, for the pack's own
53
+ // modules' manifests). -> {rows: [{module, case, a, p, place, recordAs,
54
+ // callers: [{module, version, pack}], question: null | 'A' | 'B'}],
55
+ // signature: what the rows were decided from (a change under the lock is
56
+ // refused)} | {problem} (a caller that decides a row cannot be read).
57
+ // memo: what the store answered, read once per module version and shared by
58
+ // decideBeforeLock's two passes (the medium review of the round, 7 and 8)
59
+ const newMemo = () => ({placed: new Map(), manifest: new Map(), name: new Map()});
60
+ const once = (map, key, f) => { if (!map.has(key)) map.set(key, f()); return map.get(key); };
61
+
62
+ function decide(where, record, pack, spec, pins, {bytes = {}, withOwnCallers = true, memo = newMemo()} = {}) {
63
+ const livePacked = livePacks(record.packs || {}, record.withdrawn);
64
+ const live = activeVersions(livePacked, []);
65
+ // a caller's pack: a live one (a withdrawn pack never loads)
66
+ const recordedBy = (m) => Object.entries(livePacked).filter(([, e]) => e != null && holds(e.modules, m)).map(([n]) => n);
67
+ const own = new Set(spec.modules);
68
+ const othersAt = activeVersions(Object.fromEntries(Object.entries(livePacked).filter(([n]) => n !== pack)), []);
69
+ // Callers are found as a start matches them (lib/availability.js): a
70
+ // placed module's calls, by the friendly name in its api.json; a module
71
+ // whose files are missing loads nothing and calls nothing, and is called
72
+ // by its short name. Unknown is never "no callers": a placed module whose
73
+ // package.json or api.json cannot be read refuses the operation where a
74
+ // caller decides the row (fail closed), naming it.
75
+ const installed = Object.keys(record.modules || {}).filter((m) => live[m] != null);
76
+ const dirOf = (m) => versionDir(where, m, live[m]);
77
+ const placed = (m) => once(memo.placed, `${m}@${live[m]}`, () => looksPlaced(where, m, live[m]));
78
+ const installedManifest = (o) => once(memo.manifest, `${o}@${live[o]}`, () => manifestOf(dirOf(o)));
79
+ const apiReadable = (dir) => { try { JSON.parse(fs.readFileSync(path.join(dir, 'api.json'), 'utf8')); return true; } catch (err) { return false; } };
80
+ const cannot = (m, o, file) => ({problem: `cannot tell which modules call ${short(m)}: ${short(o)}'s ${file} cannot be read; nothing was installed`});
81
+ // m's name as its callers write it, or {problem}
82
+ const nameOf = (m) => once(memo.name, `${m}@${live[m]}`, () => {
83
+ if (!placed(m)) return short(m);
84
+ if (!apiReadable(dirOf(m))) return cannot(m, m, 'api.json');
85
+ return friendlyOf(dirOf(m));
86
+ });
87
+ // the installed modules (not the pack's own, not m) that call m: [o] or {problem}
88
+ const installedCallers = (m) => {
89
+ const name = nameOf(m);
90
+ if (name != null && name.problem != null) return name;
91
+ const out = [];
92
+ for (const o of installed) {
93
+ if (own.has(o) || o === m || !placed(o)) continue;
94
+ const manifest = installedManifest(o);
95
+ if (manifest == null) return cannot(m, o, 'package.json');
96
+ if (name != null && callsOf(manifest).includes(name)) out.push(o);
97
+ }
98
+ return out;
99
+ };
100
+ // the pack's own modules: from their tarballs, or, for one the store
101
+ // holds at its pin already (no tarball read), from the store
102
+ const ownManifest = (m) => (bytes[m] != null ? json(readMember(bytes[m], 'package.json')) : manifestOf(versionDir(where, m, pins[m].version)));
103
+ const ownCallers = (m) => {
104
+ const name = nameOf(m);
105
+ if (name != null && name.problem != null) return name;
106
+ const out = [];
107
+ for (const o of own) {
108
+ if (o === m) continue;
109
+ const manifest = ownManifest(o);
110
+ if (manifest == null) return cannot(m, o, 'package.json');
111
+ if (name != null && callsOf(manifest).includes(name)) out.push(o);
112
+ }
113
+ return out;
114
+ };
115
+ const rows = [];
116
+ for (const m of spec.modules) {
117
+ const p = pins[m].version;
118
+ const a = live[m] != null ? live[m] : null;
119
+ // what the other packs record (not this one: a reinstall's own earlier
120
+ // entry is not shared, and remove-pack goes back only to what they keep)
121
+ const row = {module: m, a, p, place: false, recordAs: p, callers: [], question: null, othersAt: othersAt[m] != null ? othersAt[m] : null};
122
+ if (a == null) {
123
+ Object.assign(row, {case: 'new', place: true});
124
+ } else if (compareVersions(a, p) === 0) {
125
+ row.case = 'same';
126
+ } else if (compareVersions(a, p) > 0) {
127
+ // never lowered: the installed version stays, and the pack is recorded with it
128
+ row.recordAs = a;
129
+ if (!breakingBetween(a, p)) {
130
+ row.case = 'newer';
131
+ } else {
132
+ row.case = 'newer-breaking';
133
+ row.question = 'B';
134
+ // (under the lock they are not read again: see the signature)
135
+ const callers = withOwnCallers ? ownCallers(m) : [];
136
+ if (callers.problem != null) return callers;
137
+ row.callers = callers.map((o) => ({module: o, version: pins[o].version, pack}));
138
+ }
139
+ } else {
140
+ row.place = true;
141
+ const breaking = breakingBetween(a, p);
142
+ const callers = installedCallers(m);
143
+ // (not breaking: the callers only name who uses it too, said when known)
144
+ if (callers.problem != null && breaking) return callers;
145
+ row.callers = callers.problem != null ? [] : callers.map((o) => ({module: o, version: live[o], pack: recordedBy(o)[0] || null}));
146
+ if (!breaking) row.case = 'older';
147
+ else if (row.callers.length === 0) row.case = 'older-breaking-uncalled';
148
+ else { row.case = 'older-breaking'; row.question = 'A'; }
149
+ }
150
+ rows.push(row);
151
+ }
152
+ // (Question B's callers are the pack's own, read from its pinned,
153
+ // integrity-checked tarballs: they cannot change while the user is asked,
154
+ // and are not read again under the lock)
155
+ const signature = JSON.stringify(rows.map((r) => [r.module, r.a, r.p, r.case, r.question === 'B' ? [] : r.callers.map((c) => c.module)]));
156
+ return {rows, signature};
157
+ }
158
+
159
+ // Question A and B's text (section 9.4)
160
+ function questionOf(row, pack) {
161
+ const m = short(row.module);
162
+ if (row.question === 'A') {
163
+ return `${m} ${row.a} -> ${row.p} is a major version: it may change how it works.\nThese installed modules call it:\n`
164
+ + row.callers.map((c) => ` ${short(c.module)} ${c.version}${c.pack != null ? ` (pack ${c.pack})` : ''}`).join('\n')
165
+ + `\nUpdate ${m} anyway? [y/N] `;
166
+ }
167
+ return `${m} ${row.a} is installed, a newer major version than the pack "${pack}" was released with (${row.p}).\n`
168
+ + (row.callers.length > 0 ? `These modules of the pack call it and may not work with it:\n${row.callers.map((c) => ` ${short(c.module)} ${c.version}`).join('\n')}\n` : '')
169
+ + 'Install the pack anyway? [y/N] ';
170
+ }
171
+ // no terminal: what is said, nothing written (exit 2)
172
+ function noTerminal(row, pack) {
173
+ const m = short(row.module);
174
+ return row.question === 'A'
175
+ ? `this install updates ${m} across a major version, which is confirmed at a terminal: run it in one; nothing was installed`
176
+ : `this install adds the pack "${pack}" beside ${m} ${row.a}, a newer major version than it was released with, which is confirmed at a terminal: run it in one; nothing was installed`;
177
+ }
178
+
179
+ // The table's questions, every one asked before anything is written and
180
+ // before the home's lock is taken (no one holds it while someone types); any
181
+ // No ends the operation. Each answer is a history line. -> {code} (2: no
182
+ // terminal; 1: a No) or {signature} (checked again under the lock; null
183
+ // when nothing was asked).
184
+ async function askAll(where, decided, pack, io, fail) {
185
+ if (decided.problem != null) { fail(decided.problem); return {code: 1}; }
186
+ const questions = decided.rows.filter((r) => r.question != null);
187
+ if (questions.length > 0 && io.interactive !== true) { fail(noTerminal(questions[0], pack)); return {code: 2}; }
188
+ const {appendHistory} = require('./history');
189
+ for (const r of questions) {
190
+ const answer = String(await io.ask(questionOf(r, pack))).trim().toLowerCase();
191
+ const yes = answer === 'y' || answer === 'yes';
192
+ // the answer, as asked (Question B's module stays at from: to is the
193
+ // version the pack was released with, never placed)
194
+ appendHistory(where, {by: 'cli', question: r.question, module: r.module, from: r.a, to: r.p, callers: r.callers.map((c) => c.module), answer: yes ? 'yes' : 'no'});
195
+ if (!yes) { fail('nothing was installed'); return {code: 1}; }
196
+ }
197
+ // (with nothing asked, nothing is held to: the lock decides again)
198
+ return {signature: questions.length > 0 ? decided.signature : null};
199
+ }
200
+
201
+ // Under the lock: decided again. Answers given before it hold only for the
202
+ // home they were given about (a changed signature is refused); with nothing
203
+ // asked, the new decision stands, unless it now needs a question, which
204
+ // cannot be asked under the lock (the high review of #94, 5). -> {rows} or
205
+ // {problem}.
206
+ function recheck(where, record, pack, spec, pins, asked) {
207
+ const decided = decide(where, record, pack, spec, pins, {withOwnCallers: false});
208
+ if (decided.problem != null) return {problem: decided.problem};
209
+ const questions = decided.rows.filter((r) => r.question != null);
210
+ if ((asked == null && questions.length > 0) || (asked != null && decided.signature !== asked)) return {problem: 'the home changed while this was being asked; nothing was installed'};
211
+ return {rows: decided.rows};
212
+ }
213
+
214
+ // What the table changed, and how to go back (section 9.4). where: the
215
+ // home's layout, for the command's launcher form (lib/command-line.js).
216
+ function changedLines(rows, pack, where) {
217
+ const out = [];
218
+ const removePack = () => chLocal(where, `remove-pack ${pack}`);
219
+ for (const r of rows) {
220
+ const m = short(r.module);
221
+ if (r.case === 'older' || r.case === 'older-breaking-uncalled') {
222
+ const names = r.callers.map((c) => short(c.module));
223
+ out.push(`updated ${m} ${r.a} -> ${r.p}${names.length > 0 ? `; ${names.join(', ')} ${names.length === 1 ? 'uses' : 'use'} it too` : ''}`);
224
+ } else if (r.case === 'older-breaking') {
225
+ out.push(`updated ${m} ${r.a} -> ${r.p}`);
226
+ // the way back only where remove-pack keeps it: another pack records m
227
+ const back = r.othersAt != null ? `; if it stops working, \`${removePack()}\` puts ${m} back to ${r.othersAt}, unless a pack added later relies on the newer version` : '';
228
+ for (const c of r.callers) out.push(`${short(c.module)} ${c.version} was written for ${lineOf(r.a)} and still loads${back}`);
229
+ } else if (r.case === 'newer-breaking') {
230
+ out.push(`${m} stays at ${r.a}, newer than "${pack}" was released with (${r.p}); if the pack does not work with it, \`${removePack()}\` removes it`);
231
+ }
232
+ }
233
+ return out;
234
+ }
235
+
236
+ // Packs from different pins (section 9.4), one predicate for add-pack,
237
+ // install and remove-pack (the high review of #94, 9). The packs compared
238
+ // are the live ones that stay beside the operation's (not `except`: the
239
+ // packs it brings to its own pins, or drops); a withdrawn pack never loads.
240
+ // True when any stay and the home is a development one, or the operation
241
+ // takes development pins: one pins file is no guarantee of one version each,
242
+ // as the table records a pack at a kept newer version (the medium review of
243
+ // the round, 1-3). Otherwise, with `from` (the pins the operation takes):
244
+ // true when one of them comes from other pins; with from null (remove-pack):
245
+ // when they come from more than one.
246
+ function fromOtherPins(record, from, {except = []} = {}) {
247
+ const skip = new Set(except);
248
+ const froms = Object.entries(livePacks(record.packs || {}, record.withdrawn))
249
+ .filter(([n]) => !skip.has(n)).map(([, e]) => JSON.stringify(e.from));
250
+ if (froms.length === 0) return false;
251
+ if (record.unreleased === true || (from != null && from.unreleased != null)) return true;
252
+ if (from == null) return new Set(froms).size > 1;
253
+ return froms.some((f) => f !== JSON.stringify(from));
254
+ }
255
+
256
+ // The modules a pack shares with the packs already installed, as the table
257
+ // decided them (at the pin, or kept at a newer installed version), and the
258
+ // line both add-pack and install say it with (the high review of #94, 10).
259
+ const sharedOf = (rows) => rows.filter((r) => (r.case === 'same' || r.case === 'newer') && r.othersAt != null).map((r) => r.module);
260
+ const sharesText = (modules) => `it shares ${modules.map(short).join(', ')} with the packs already installed`;
261
+
262
+ // The tarballs read before the lock (the high review of #94, 3 and 7):
263
+ // those the locked path places (a row placed, or shared but not whole in
264
+ // the store), and, for a Question B row, the pack's own modules not whole
265
+ // in the store (their calls are read from them). A module the pack never
266
+ // places needs none, and each is read and hashed once: the bytes go on to
267
+ // the locked path.
268
+ function needsOf(where, rows, spec, pins) {
269
+ const {wholeAt} = require('./module-store');
270
+ const notWhole = (m) => { try { return !wholeAt(where, m, pins[m]); } catch (err) { return true; } };
271
+ const out = new Set(rows.filter((r) => r.place || r.case === 'same').map((r) => r.module).filter(notWhole));
272
+ if (rows.some((r) => r.question === 'B')) for (const m of spec.modules) if (notWhole(m)) out.add(m);
273
+ return [...out];
274
+ }
275
+
276
+ // Before the lock: decided, the tarballs it needs read (load(names) ->
277
+ // {problems, bytes}), and Question B's callers read from them.
278
+ // -> {decided, bytes} | {problems}.
279
+ function decideBeforeLock(where, record, pack, spec, pins, load) {
280
+ const memo = newMemo();
281
+ const first = decide(where, record, pack, spec, pins, {withOwnCallers: false, memo});
282
+ if (first.problem != null) return {decided: first, bytes: {}};
283
+ const {problems, bytes} = load(needsOf(where, first.rows, spec, pins));
284
+ if (problems.length > 0) return {problems};
285
+ // (the second pass, for Question B's callers, reads the store no more)
286
+ const decided = first.rows.some((r) => r.question === 'B') ? decide(where, record, pack, spec, pins, {bytes, memo}) : first;
287
+ return {decided, bytes};
288
+ }
289
+
290
+ module.exports = {decide, decideBeforeLock, fromOtherPins, sharedOf, sharesText, askAll, recheck, changedLines, questionOf, noTerminal, breakingBetween, lineOf, short};