@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,298 @@
1
+ 'use strict';
2
+ // <home>/modules.json: what the home holds, by module (module-level install,
3
+ // #413 section 9.2). It replaces packs.json (lib/record.js) once install
4
+ // writes it (L1a-2); the file name changes so no older reader takes the new
5
+ // shape for its own.
6
+ //
7
+ // {v: 2,
8
+ // runtime: {versions: {name: version}},
9
+ // release: {version, security: null | {fixes}},
10
+ // unreleased: true|false,
11
+ // packs: {<pack>: {from: {release: <ch-local version>} | {unreleased: <16 hex>},
12
+ // modules: {<module>: <version>}}},
13
+ // modules: {<module>: {version, role: 'scenario' | 'part' | null}},
14
+ // withdrawn: [<module>, ...],
15
+ // held: {<pack>: {from, modules}},
16
+ // shim?: {package, version}, at}
17
+ //
18
+ // - packs.<p>.from: the pins the pack was installed from: a release, or a
19
+ // development pins file (the first 16 hex digits of its SHA-256).
20
+ // - packs.<p>.modules: the version of each module the pack was installed with.
21
+ // - modules: derived from packs: the highest version any installed pack
22
+ // records for a module (in a released home, the one they all record: the
23
+ // pin), and that version's countinghouse.role. Written so that readers need
24
+ // no version arithmetic (the runtime's settings tool reads it); a record
25
+ // whose modules is not what its packs give is refused.
26
+ // - withdrawn: derived; the recorded modules no pack of the record's release
27
+ // lists (section 9.7), for a start still running from another release.
28
+ // - held: packs a release rollback's restored release does not have:
29
+ // recorded, never loaded, removed by remove-pack.
30
+ const fs = require('node:fs');
31
+ const {writeAtomic} = require('./atomic');
32
+ // a module's version is a store directory: the store's own check (#82's high
33
+ // review, 5), so a record never names a version the store will not hold;
34
+ // from lib/names.js, so a reader of the record loads none of the store's
35
+ // code (#82's medium, 8)
36
+ const {VERSION, PACKAGE, PACK, storeVersion} = require('./names');
37
+ const {chLocal, folderArg} = require('./command-line');
38
+ const UNRELEASED = /^[0-9a-f]{16}$/;
39
+ const ROLES = new Set(['scenario', 'part', null]);
40
+ const isObject = (x) => x != null && typeof x === 'object' && !Array.isArray(x);
41
+ // the one own-property helper (record.js and install-plan.js take it from
42
+ // here): null-safe
43
+ const own = (obj, key) => obj != null && Object.prototype.hasOwnProperty.call(obj, key);
44
+ // entries -> a map with no prototype: a key read from it (x[m]) can never
45
+ // reach Object.prototype ("constructor", "toString"...), wherever the record
46
+ // goes (the Reviewer's high review of #96, the root fix)
47
+ const bareEntries = (entries) => {
48
+ const out = Object.create(null);
49
+ for (const [k, v] of entries) out[k] = v;
50
+ return out;
51
+ };
52
+ // a copy of o as such a map, its entries mapped by f when given
53
+ const bare = (o, f = (v) => v) => bareEntries(Object.entries(o || {}).map(([k, v]) => [k, f(v)]));
54
+ // a pack (or a held pack) with its modules as such a map
55
+ const barePack = (p) => ({...p, modules: bare(p.modules)});
56
+
57
+ // Semver precedence (build metadata ignored), so "highest" is the one npm
58
+ // means. -> <0, 0, >0
59
+ function compareVersions(a, b) {
60
+ const parse = (v) => {
61
+ const [core, pre] = String(v).split('+')[0].split(/-(.*)/s);
62
+ return {nums: core.split('.').map(Number), pre: pre == null || pre === '' ? null : pre.split('.')};
63
+ };
64
+ const x = parse(a);
65
+ const y = parse(b);
66
+ for (let i = 0; i < 3; i++) if (x.nums[i] !== y.nums[i]) return x.nums[i] - y.nums[i];
67
+ if (x.pre == null || y.pre == null) return (x.pre == null ? 1 : 0) - (y.pre == null ? 1 : 0);
68
+ for (let i = 0; i < Math.max(x.pre.length, y.pre.length); i++) {
69
+ if (i >= x.pre.length) return -1;
70
+ if (i >= y.pre.length) return 1;
71
+ const [p, q] = [x.pre[i], y.pre[i]];
72
+ const [pn, qn] = [/^\d+$/.test(p), /^\d+$/.test(q)];
73
+ if (pn && qn && Number(p) !== Number(q)) return Number(p) - Number(q);
74
+ if (pn !== qn) return pn ? -1 : 1;
75
+ if (p !== q) return p < q ? -1 : 1;
76
+ }
77
+ return 0;
78
+ }
79
+
80
+ // packs -> {<module>: the highest version any pack records}
81
+ function highest(packs) {
82
+ const out = Object.create(null);
83
+ for (const p of Object.values(packs)) {
84
+ // equal precedence (they differ in build metadata only): the greater
85
+ // string, so the order of the packs never decides (medium review, 7)
86
+ for (const [m, v] of Object.entries(p.modules)) {
87
+ const c = own(out, m) ? compareVersions(v, out[m]) : 1;
88
+ if (c > 0 || (c === 0 && v > out[m])) out[m] = v;
89
+ }
90
+ }
91
+ return out;
92
+ }
93
+
94
+ // The packs the record's withdrawn list leaves live: none of whose modules
95
+ // it names (a withdrawn pack is never loaded: lib/packs.js heldWithdrawn).
96
+ const livePacks = (packs, withdrawn) => {
97
+ const gone = new Set(withdrawn || []);
98
+ return bareEntries(Object.entries(packs).filter(([, p]) => !Object.keys(p.modules).some((m) => gone.has(m))));
99
+ };
100
+
101
+ // Each module's active version: the highest the live packs record, and only
102
+ // for a module no live pack records, the highest the withdrawn ones do (it
103
+ // never loads). A withdrawn pack's newer version never overrides what a
104
+ // release pins for a live pack: a security release's lower pin is the one
105
+ // loaded (#83's high review, 2). -> {<module>: version}
106
+ function activeVersions(packs, withdrawn) {
107
+ return Object.assign(Object.create(null), highest(packs), highest(livePacks(packs, withdrawn)));
108
+ }
109
+
110
+ // The derived modules: each one's active version and that version's role.
111
+ // roleOf(name, version) -> 'scenario' | 'part' | null (lib/module-store.js's,
112
+ // with the home's layout bound); withdrawn: the record's list.
113
+ function derive(packs, roleOf, withdrawn = []) {
114
+ return bareEntries(Object.entries(activeVersions(packs, withdrawn)).sort(([a], [b]) => (a < b ? -1 : 1)).map(([m, version]) => [m, {version, role: roleOf(m, version)}]));
115
+ }
116
+
117
+ // The recorded modules no pack of `release` lists: a module is withdrawn when
118
+ // the release does not ship it (section 9.7). A development record is exempt.
119
+ // release: the pins' (version 1 lists a pack's packages, version 2 its
120
+ // modules). -> sorted names.
121
+ function withdrawnOf(record, release) {
122
+ if (record.unreleased === true) return [];
123
+ const listed = new Set();
124
+ for (const p of Object.values((release != null && release.packs) || {})) {
125
+ for (const m of (Array.isArray(p.modules) ? p.modules : (Array.isArray(p.packages) ? p.packages : []))) listed.add(m);
126
+ }
127
+ return Object.keys(highest(record.packs)).filter((m) => !listed.has(m)).sort();
128
+ }
129
+
130
+ // -> the module's active version (section 9.2), or null when no pack records it
131
+ function activeVersion(record, name) {
132
+ return own(record.modules, name) ? record.modules[name].version : null;
133
+ }
134
+
135
+ const recordOf = (where) => where.modulesRecord;
136
+ // Why a record could not be read, by code, so a caller decides by it and
137
+ // never by the message's wording (the medium review of the Reviewer's
138
+ // round on #83, 5): RECORD_FORMAT (not JSON, not a record), RECORD_IO (the
139
+ // file could not be read: it may be whole), RECORD_EARLIER_DEV (only an
140
+ // earlier development launcher's installed.json).
141
+ // reason: the bare why, with no advice after it (the Reviewer's round on
142
+ // #83, 8: never trimmed off a message)
143
+ // (where: the home's layout, for the command's launcher form:
144
+ // lib/command-line.js)
145
+ const recordError = (where, reason, code, advice = `run \`${chLocal(where, 'install')}\` again`) => Object.assign(new Error(`${reason}; ${advice}`), {code, reason});
146
+ // a record that can't be read for its permissions or owner: the fix is the
147
+ // file's, never a command (the reviewer's high on #124, 1)
148
+ const ioAdvice = (file) => `make it readable by you again: check its owner and mode (\`ls -l ${folderArg(file)}\`)`;
149
+ const earlierLine = (where) => `this home was made by an earlier ch-local; run \`${chLocal(where, 'install')}\` again`;
150
+
151
+ // -> the record, or null when nothing is installed. Throws when it cannot be
152
+ // read, or when only an earlier ch-local's packs.json is there (an install
153
+ // migrates it, section 10).
154
+ function readModulesRecord(where) {
155
+ if (where.journal != null && fs.existsSync(where.journal)) {
156
+ throw new Error(`a rollback was interrupted; run \`${chLocal(where, 'rollback')}\` to finish it`);
157
+ }
158
+ const file = recordOf(where);
159
+ let raw;
160
+ try {
161
+ raw = fs.readFileSync(file, 'utf8');
162
+ } catch (err) {
163
+ if (err.code !== 'ENOENT') throw recordError(where, `${file} is not readable (${err.code})`, 'RECORD_IO', ioAdvice(file));
164
+ // a migration cut short leaves both: modules.json is the one taken
165
+ if (where.packs != null && fs.existsSync(where.packs)) throw Object.assign(new Error(earlierLine(where)), {code: 'RECORD_EARLIER'});
166
+ // only an unreleased development launcher wrote installed.json
167
+ if (where.installed != null) {
168
+ let old = null;
169
+ try { old = JSON.parse(fs.readFileSync(where.installed, 'utf8')); } catch (e) { old = null; }
170
+ if (old != null) {
171
+ const pack = typeof old.pack === 'string' ? old.pack : '<name>';
172
+ throw recordError(where, 'this home was made by an earlier development ch-local', 'RECORD_EARLIER_DEV', `run \`${chLocal(where, `install --pack ${pack} --from <dir>`)}\` again`);
173
+ }
174
+ }
175
+ return null;
176
+ }
177
+ let r;
178
+ try { r = JSON.parse(raw); } catch (err) { r = null; }
179
+ const problem = shapeProblem(r);
180
+ if (problem != null) throw recordError(where, `${file} is not a ch-local record (${problem})`, 'RECORD_FORMAT');
181
+ return {
182
+ v: 2,
183
+ runtime: {versions: {...r.runtime.versions}},
184
+ release: r.release != null ? r.release : null,
185
+ unreleased: r.unreleased === true,
186
+ // (maps with no prototype, each pack's modules too: the root fix)
187
+ packs: bare(r.packs, barePack),
188
+ modules: bare(r.modules),
189
+ withdrawn: r.withdrawn,
190
+ held: bare(r.held, barePack),
191
+ ...(r.shim !== undefined ? {shim: {package: r.shim.package, version: r.shim.version}} : {}),
192
+ at: r.at
193
+ };
194
+ }
195
+
196
+ // -> why r is not a version 2 record, or null
197
+ function shapeProblem(r) {
198
+ const versions = (x, {nonEmpty = false} = {}) => isObject(x) && (!nonEmpty || Object.keys(x).length > 0) &&
199
+ Object.entries(x).every(([n, v]) => PACKAGE.test(n) && typeof v === 'string' && VERSION.test(v));
200
+ const moduleVersions = (x) => isObject(x) && Object.keys(x).length > 0 && Object.entries(x).every(([n, v]) => PACKAGE.test(n) && storeVersion(v));
201
+ const from = (f) => isObject(f) && Object.keys(f).length === 1 &&
202
+ ((typeof f.release === 'string' && VERSION.test(f.release)) || (typeof f.unreleased === 'string' && UNRELEASED.test(f.unreleased)));
203
+ const pack = (p) => isObject(p) && from(p.from) && moduleVersions(p.modules);
204
+ const packs = (o) => isObject(o) && Object.entries(o).every(([n, p]) => PACK.test(n) && pack(p));
205
+ if (!isObject(r) || r.v !== 2) return 'not version 2';
206
+ if (!isObject(r.runtime) || !versions(r.runtime.versions)) return 'runtime';
207
+ if (r.release != null && !(isObject(r.release) && (r.release.version == null || (typeof r.release.version === 'string' && VERSION.test(r.release.version))) &&
208
+ (r.release.security == null || (isObject(r.release.security) && typeof r.release.security.fixes === 'string')))) return 'release';
209
+ if (r.unreleased !== undefined && typeof r.unreleased !== 'boolean') return 'unreleased';
210
+ if (!packs(r.packs)) return 'packs';
211
+ if (r.held !== undefined && !packs(r.held)) return 'held';
212
+ if (r.held !== undefined && Object.keys(r.held).some((n) => own(r.packs, n))) return 'a pack both installed and held';
213
+ if (!isObject(r.modules) || !Object.entries(r.modules).every(([n, m]) => PACKAGE.test(n) && isObject(m) && storeVersion(m.version) && ROLES.has(m.role))) return 'modules';
214
+ // modules is what packs give: the same names, each at its active version
215
+ // (the live packs' highest: activeVersions)
216
+ const want = activeVersions(r.packs, Array.isArray(r.withdrawn) ? r.withdrawn : []);
217
+ const names = Object.keys(r.modules).sort();
218
+ if (names.join('\n') !== Object.keys(want).sort().join('\n') || names.some((n) => r.modules[n].version !== want[n])) return 'modules is not what packs give';
219
+ if (!Array.isArray(r.withdrawn) || !r.withdrawn.every((m) => typeof m === 'string' && own(want, m)) || new Set(r.withdrawn).size !== r.withdrawn.length) return 'withdrawn';
220
+ if (r.shim !== undefined && !(isObject(r.shim) && typeof r.shim.package === 'string' && PACKAGE.test(r.shim.package) && typeof r.shim.version === 'string' && VERSION.test(r.shim.version))) return 'shim';
221
+ return null;
222
+ }
223
+
224
+ // Writes the record with its derived fields made here: modules from packs
225
+ // (roleOf as derive's), withdrawn from `release` (the operation's own pins).
226
+ // record: {runtime, release, unreleased, packs, held?, shim?}. -> what was written.
227
+ function writeModulesRecord(where, record, opts = {}) {
228
+ const out = buildModulesRecord(record, opts);
229
+ writeAtomic(recordOf(where), JSON.stringify(out, null, 2) + '\n');
230
+ return out;
231
+ }
232
+
233
+ // The record with its derived fields, checked as the reader checks, not
234
+ // written: install builds it before it swaps the app, so a record that
235
+ // would not be valid stops the install with nothing changed (the medium
236
+ // review of L1a-2, 4). Throws.
237
+ function buildModulesRecord(record, {roleOf, release} = {}) {
238
+ if (typeof roleOf !== 'function') throw new Error('writeModulesRecord: roleOf is required');
239
+ // with no release every module would read as withdrawn (medium review, 2)
240
+ if (record.unreleased !== true && (release == null || release.packs == null || typeof release.packs !== 'object')) {
241
+ throw new Error('writeModulesRecord: a released record is written with its release\'s pins');
242
+ }
243
+ const out = {
244
+ v: 2,
245
+ runtime: record.runtime,
246
+ release: record.release != null ? record.release : null,
247
+ unreleased: record.unreleased === true,
248
+ // (maps with no prototype, as a record read back has them: the record
249
+ // written is handed on too)
250
+ packs: bare(record.packs, barePack),
251
+ withdrawn: withdrawnOf({unreleased: record.unreleased === true, packs: record.packs}, release),
252
+ modules: null,
253
+ ...(record.held != null && Object.keys(record.held).length > 0 ? {held: bare(record.held, barePack)} : {}),
254
+ ...(record.shim !== undefined ? {shim: record.shim} : {}),
255
+ at: new Date().toISOString()
256
+ };
257
+ out.modules = derive(record.packs, roleOf, out.withdrawn);
258
+ const problem = shapeProblem(out);
259
+ if (problem != null) throw new Error(`the record to write is not valid (${problem})`);
260
+ return out;
261
+ }
262
+
263
+ // A record written as it is, its derived fields kept: what the release
264
+ // rollback swaps (lib/rollback.js). Each record's modules and withdrawn were
265
+ // derived by the release that wrote it, from its own pins, which this one
266
+ // cannot re-derive. Checked as the reader checks. file: where to write.
267
+ function writeRecordAsIs(file, record) {
268
+ const out = {...record, v: 2, at: new Date().toISOString()};
269
+ if (out.held != null && Object.keys(out.held).length === 0) delete out.held;
270
+ const problem = shapeProblem(out);
271
+ if (problem != null) throw new Error(`the record to write is not valid (${problem})`);
272
+ writeAtomic(file, JSON.stringify(out, null, 2) + '\n');
273
+ return out;
274
+ }
275
+
276
+ // What an upgrade judged a home by (the Reviewer's high on #101, round 2):
277
+ // its packs with each module's version, every module's recorded version,
278
+ // the withdrawn list, and the runtime, release, unreleased and held packs (a
279
+ // rollback that moves no module still changes these: its medium, 1). upgrade and the automatic upgrade pass it to
280
+ // install, which refuses when the record under its lock is another: the
281
+ // preview, additions and moves were made on this record, not that one.
282
+ // -> a hex digest, or null for no record.
283
+ function judgedDigest(record) {
284
+ if (record == null) return null;
285
+ const sorted = (o) => Object.entries(o || {}).sort(([a], [b]) => (a < b ? -1 : 1));
286
+ const shape = {
287
+ packs: sorted(record.packs).map(([p, e]) => [p, sorted(e && e.modules)]),
288
+ modules: sorted(record.modules).map(([m, e]) => [m, e != null ? e.version : null]),
289
+ withdrawn: [...(Array.isArray(record.withdrawn) ? record.withdrawn : [])].sort(),
290
+ runtime: sorted(record.runtime && record.runtime.versions),
291
+ release: record.release != null ? record.release : null,
292
+ unreleased: record.unreleased === true,
293
+ held: sorted(record.held).map(([p, e]) => [p, sorted(e && e.modules)])
294
+ };
295
+ return require('node:crypto').createHash('sha256').update(JSON.stringify(shape)).digest('hex');
296
+ }
297
+
298
+ module.exports = {ioAdvice, judgedDigest, own, bare, readModulesRecord, writeModulesRecord, buildModulesRecord, writeRecordAsIs, derive, activeVersions, livePacks, withdrawnOf, activeVersion, compareVersions, shapeProblem, earlierLine};
@@ -0,0 +1,44 @@
1
+ 'use strict';
2
+ // Which installed modules are top-level and which are parts (#413 section
3
+ // 5.1), by the rule availability uses (lib/availability.js): a module that is
4
+ // some pack's scenario (lib/packs.js packScenario) is top-level, whatever
5
+ // role it declares; every other module is a part.
6
+
7
+ // record: modules.json as read (lib/module-record.js), or null.
8
+ // -> Set of the top-level modules' package names
9
+ function topLevel(record) {
10
+ const {packScenario, entryOf} = require('./packs');
11
+ const out = new Set();
12
+ if (record == null || record.packs == null) return out;
13
+ for (const pack of Object.keys(record.packs)) {
14
+ const m = packScenario(record, pack);
15
+ // (the record's own entry only: #449's review)
16
+ if (m != null && entryOf(record, m) != null) out.add(m);
17
+ }
18
+ return out;
19
+ }
20
+
21
+ // The top-level modules a part runs for: the scenarios of the packs that
22
+ // record it. -> [package name], sorted
23
+ function callersOf(record, part) {
24
+ const {packScenario, holds} = require('./packs');
25
+ const out = new Set();
26
+ for (const [pack, p] of Object.entries((record && record.packs) || {})) {
27
+ if (p == null || !holds(p.modules, part)) continue;
28
+ const m = packScenario(record, pack);
29
+ if (m != null && m !== part) out.add(m);
30
+ }
31
+ return [...out].sort();
32
+ }
33
+
34
+ // The packs whose scenario a module is (a leftover pack.<name> is its
35
+ // entry: section 10). -> [pack name]
36
+ function packsOf(record, module) {
37
+ const {packScenario} = require('./packs');
38
+ return Object.keys((record && record.packs) || {}).filter((pack) => packScenario(record, pack) === module);
39
+ }
40
+
41
+ // A module is a part when the record has it and it is no pack's scenario.
42
+ const isPart = (record, module) => require('./packs').entryOf(record, module) != null && !topLevel(record).has(module);
43
+
44
+ module.exports = {topLevel, callersOf, packsOf, isPart};
@@ -0,0 +1,26 @@
1
+ 'use strict';
2
+ // The on/off and ceiling rules of what loads (lib/availability.js rules 3
3
+ // and 4), by module (#413 sections 5.1, 5.2 and 8; L2b):
4
+ // - the ceiling: the operator's `modules` list allows the module, a part
5
+ // included (a module that calls one not listed goes by rule 6); a
6
+ // ceiling that cannot be trusted allows none;
7
+ // - off: a top-level module whose enabled.<package> is off, or a leftover
8
+ // pack.<name> off for a pack whose scenario it is (off wins:
9
+ // lib/settings.js isOn).
10
+ const {moduleAllowed, modulesRefusal} = require('./ceiling');
11
+ const {isOn} = require('./settings');
12
+ const {chLocal} = require('./command-line');
13
+
14
+ // settings: the settings in effect; ceiling: ceilingFor()'s; record:
15
+ // modules.json; where: the home's layout, for the command a reason names
16
+ // (lib/command-line.js). -> seams for availability(): ceiling and off, each
17
+ // (module) -> null or the reason.
18
+ function moduleSeams({settings, ceiling, record, where = null}) {
19
+ return {
20
+ ceiling: (m) => (moduleAllowed(ceiling, m) ? null
21
+ : ceiling != null && ceiling.state === 'trusted' ? 'it is not on the operator\'s list' : modulesRefusal(ceiling, [m])),
22
+ off: (m) => (isOn(settings, record, m) ? null : `it is turned off (\`${chLocal(where, `settings set enabled.${m} on`)}\`)`)
23
+ };
24
+ }
25
+
26
+ module.exports = {moduleSeams};
@@ -0,0 +1,202 @@
1
+ 'use strict';
2
+ // The module store (module-level install, #413 section 9.1): one directory
3
+ // per module version, replacing a tree per pack version (an earlier
4
+ // ch-local's <home>/packs/<pack>/<key>/),
5
+ // where each pack had its own copy of every part.
6
+ //
7
+ // <home>/module-store/
8
+ // @countinghouse/ch-access-github/0.2.0/ the package, as unpacked
9
+ // @countinghouse/ch-access-github/0.2.0.json {name, version, integrity, placedAt}
10
+ // weather-tool/1.2.0/ weather-tool/1.2.0.json
11
+ //
12
+ // A module's package has no npm dependencies (lib/unpack.js checkManifest),
13
+ // so a version directory is complete by itself.
14
+ // - Placing a version: its tarball, already checked against its pin, is
15
+ // unpacked into <version>.new-<random> beside it and its manifest checked;
16
+ // the directory is renamed into place, then its marker is written. A
17
+ // version directory with no marker is incomplete: never loaded, and
18
+ // collected (lib/gc.js).
19
+ // - Skipping: a version there with a marker whose integrity is the pin's is
20
+ // neither fetched nor unpacked again ("a module already installed is not
21
+ // installed again").
22
+ // - A marker with another integrity comes only from a development install
23
+ // (--unreleased-pins builds one version twice): the version is replaced
24
+ // when no running start uses it, refused otherwise.
25
+ // The store is inside ch-local's home, which the file broker denies to every
26
+ // module; a module reads its own directory only. Every change here is made
27
+ // under the home's lock (the caller's).
28
+ const crypto = require('node:crypto');
29
+ const fs = require('node:fs');
30
+ const path = require('node:path');
31
+ const {writeAtomic} = require('./atomic');
32
+ const {unpackOne} = require('./unpack');
33
+
34
+ const {VERSION, PACKAGE, SCOPE, storeVersion} = require('./names');
35
+ const {removeAside} = require('./aside');
36
+ const INTEGRITY = /^sha512-[A-Za-z0-9+/]{86}==$/;
37
+
38
+ const {versionDir, markerFile} = require('./store-paths');
39
+
40
+ const {integrityOf} = require('./integrity');
41
+ const {chLocal} = require('./command-line');
42
+
43
+
44
+ // The error for what could not be read: neither there nor not there. A
45
+ // reader that gets it keeps (collection) or refuses (placing): unknown is
46
+ // never taken for missing (#82's high review, 2).
47
+ const unknown = (what, err) => Object.assign(new Error(`${what} could not be read (${err.code || err.message})`), {code: err.code || 'EUNKNOWN', unknown: true});
48
+
49
+ // -> the version's marker {name, version, integrity, placedAt}, or null when
50
+ // there is none: no file (ENOENT), not a regular file (a link is no marker:
51
+ // #82's high review, 6), not JSON, or not this version's. Throws (unknown)
52
+ // on any other error.
53
+ // opts.noFollow: the open flag, the platform's by default (a test gives none,
54
+ // as Windows has).
55
+ function readMarker(where, name, version, opts = {}) {
56
+ const file = markerFile(where, name, version);
57
+ // opened without following a link where the platform can (O_NOFOLLOW),
58
+ // and judged on what was opened, so nothing swapped in between is read
59
+ // (#82's medium, 6); Windows has no O_NOFOLLOW: lstat first there
60
+ // Windows: no O_NOFOLLOW (undefined there, never passed into the flags);
61
+ // lstat, open, then fstat the opened file, and its device and inode must
62
+ // be the lstat's, or what was opened is not what was checked: unknown
63
+ const given = Object.prototype.hasOwnProperty.call(opts, 'noFollow') ? opts.noFollow : fs.constants.O_NOFOLLOW;
64
+ const noFollow = typeof given === 'number' ? given : null;
65
+ let fd;
66
+ let checked = null;
67
+ try {
68
+ if (noFollow == null) {
69
+ checked = fs.lstatSync(file, {bigint: true});
70
+ if (!checked.isFile()) return null;
71
+ }
72
+ fd = fs.openSync(file, noFollow == null ? fs.constants.O_RDONLY : (fs.constants.O_RDONLY | noFollow));
73
+ } catch (err) {
74
+ if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return null;
75
+ if (err.code === 'ELOOP') return null; // a link: no marker
76
+ throw unknown(file, err);
77
+ }
78
+ let raw;
79
+ try {
80
+ const opened = fs.fstatSync(fd, {bigint: true});
81
+ if (!opened.isFile()) return null;
82
+ if (checked != null && (opened.dev !== checked.dev || opened.ino !== checked.ino)) {
83
+ throw Object.assign(new Error('it changed while being read'), {code: 'ECHANGED'});
84
+ }
85
+ raw = fs.readFileSync(fd, 'utf8');
86
+ } catch (err) {
87
+ throw unknown(file, err);
88
+ } finally {
89
+ fs.closeSync(fd);
90
+ }
91
+ let m;
92
+ try { m = JSON.parse(raw); } catch (err) { return null; }
93
+ if (m == null || typeof m !== 'object' || m.name !== name || m.version !== version || typeof m.integrity !== 'string' ||
94
+ !INTEGRITY.test(m.integrity) || typeof m.placedAt !== 'string') return null;
95
+ return {name: m.name, version: m.version, integrity: m.integrity, placedAt: m.placedAt};
96
+ }
97
+
98
+ // The version's directory: {there: whether anything is at its path, dir:
99
+ // whether that is a directory (never a link)}. Throws (unknown) on an error
100
+ // other than not there.
101
+ function dirState(where, name, version) {
102
+ const dir = versionDir(where, name, version);
103
+ try {
104
+ return {there: true, dir: fs.lstatSync(dir).isDirectory()};
105
+ } catch (err) {
106
+ if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return {there: false, dir: false};
107
+ throw unknown(dir, err);
108
+ }
109
+ }
110
+
111
+ // Whether the version is whole: its directory there, its marker this
112
+ // version's. Throws (unknown) when either cannot be read.
113
+ function isComplete(where, name, version) {
114
+ const {marker, dir} = versionState(where, name, version);
115
+ return dir && marker != null;
116
+ }
117
+
118
+ // One module version into the store, under the home's lock (the caller's).
119
+ // bytes: its tarball, read once; pin: {version, integrity}, which the bytes
120
+ // must match. inUse(name, version), required: whether a running start uses
121
+ // that version (lib/gc.js's liveness), asked only when a version there holds
122
+ // other contents. A start writes its run.json under the same lock
123
+ // (lib/start.js), so none can begin between that answer and the swap.
124
+ // -> {dir, placed: true when unpacked now, false when skipped}. Throws with
125
+ // a message naming the module; a failure leaves the store as it was, or the
126
+ // version incomplete (no marker), which is never loaded and is collected.
127
+ function placeModule(where, name, bytes, pin, {inUse, now = () => new Date()} = {}) {
128
+ // required, so a caller that forgets it never replaces a version in use
129
+ if (typeof inUse !== 'function') throw new Error('placeModule: inUse is required');
130
+ const version = pin != null ? pin.version : undefined;
131
+ const dir = versionDir(where, name, version);
132
+ if (typeof pin.integrity !== 'string' || !INTEGRITY.test(pin.integrity)) throw new Error(`${name}@${version}: its pin has no integrity`);
133
+ if (!Buffer.isBuffer(bytes) || integrityOf(bytes) !== pin.integrity) throw new Error(`${name}@${version}: the tarball's integrity is not the pinned one`);
134
+ // one look at each (#82's high review, 9); unknown refuses (2)
135
+ const state = dirState(where, name, version);
136
+ const marker = readMarker(where, name, version);
137
+ const whole = state.dir && marker != null;
138
+ const there = state.there;
139
+ if (whole && marker.integrity === pin.integrity) return {dir, placed: false};
140
+ // anything at the path may be in use, whole or not (a failed earlier swap
141
+ // leaves it incomplete): asked whenever it is there (#82's high review, 4)
142
+ if (there && inUse(name, version)) {
143
+ throw new Error(whole
144
+ ? `${name} ${version} is installed with other contents and a running client uses it; stop it and run this again`
145
+ : `${name} ${version} is incomplete in the module store and a running client uses it; stop it and run this again`);
146
+ }
147
+ swapIn(where, name, version, pin.integrity, (stage) => unpackOne(stage, bytes, name, version), {there, now});
148
+ return {dir, placed: true};
149
+ }
150
+
151
+ // The version made in a stage beside it by make(stage), then swapped in:
152
+ // the old one (other contents, or incomplete) made incomplete first, then
153
+ // set aside whole, never half of one under its name; the marker last.
154
+ function swapIn(where, name, version, integrity, make, {there, now = () => new Date()}) {
155
+ const dir = versionDir(where, name, version);
156
+ const stage = `${dir}.new-${crypto.randomBytes(4).toString('hex')}`;
157
+ fs.mkdirSync(path.dirname(dir), {recursive: true});
158
+ try {
159
+ make(stage);
160
+ fs.rmSync(markerFile(where, name, version), {force: true});
161
+ if (there) removeAside(dir);
162
+ fs.renameSync(stage, dir);
163
+ } finally {
164
+ fs.rmSync(stage, {recursive: true, force: true});
165
+ }
166
+ writeAtomic(markerFile(where, name, version), JSON.stringify({name, version, integrity, placedAt: now().toISOString()}) + '\n');
167
+ }
168
+
169
+ // A module version's manifest from the store (its role, its calls, its
170
+ // remotes). -> the parsed package.json. Throws when the version is not whole
171
+ // or its package.json cannot be read.
172
+ function readStoredManifest(where, name, version) {
173
+ if (!isComplete(where, name, version)) throw new Error(`${name} ${version} is not in the module store; run \`${chLocal(where, 'install')}\` again`);
174
+ try {
175
+ return JSON.parse(fs.readFileSync(path.join(versionDir(where, name, version), 'package.json'), 'utf8'));
176
+ } catch (err) {
177
+ throw new Error(`${name} ${version}: its package.json in the module store is not readable`);
178
+ }
179
+ }
180
+
181
+ // -> the version's countinghouse.role: 'scenario', 'part', or null
182
+ function roleOf(where, name, version) {
183
+ const m = readStoredManifest(where, name, version);
184
+ const role = m.countinghouse != null && typeof m.countinghouse === 'object' ? m.countinghouse.role : undefined;
185
+ return role === 'scenario' || role === 'part' ? role : null;
186
+ }
187
+
188
+ // Whether the store holds the version whole at its pin's integrity: what
189
+ // install and add-pack skip (the medium review of L1a-2, 8: one test). An
190
+ // unknown marker throws (unknown), never "not there".
191
+ function wholeAt(where, name, pin) {
192
+ const {marker, dir} = versionState(where, name, pin.version);
193
+ return dir && marker != null && marker.integrity === pin.integrity;
194
+ }
195
+
196
+ // One look at a version: its marker and whether its directory is one.
197
+ // -> {marker, dir}. Throws (unknown) as readMarker and dirState do.
198
+ function versionState(where, name, version) {
199
+ return {marker: readMarker(where, name, version), dir: dirState(where, name, version).dir};
200
+ }
201
+
202
+ module.exports = {versionDir, markerFile, readMarker, isComplete, wholeAt, versionState, placeModule, readStoredManifest, roleOf, storeVersion, VERSION, PACKAGE, SCOPE};