@seasb/metafab 0.0.1 → 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 (369) hide show
  1. package/README.md +46 -1
  2. package/dist/cli.d.ts +11 -0
  3. package/dist/cli.js +317 -0
  4. package/dist/cli.js.map +1 -0
  5. package/dist/commands/build.d.ts +2 -0
  6. package/dist/commands/build.js +70 -0
  7. package/dist/commands/build.js.map +1 -0
  8. package/dist/commands/check.d.ts +2 -0
  9. package/dist/commands/check.js +41 -0
  10. package/dist/commands/check.js.map +1 -0
  11. package/dist/commands/create.d.ts +2 -0
  12. package/dist/commands/create.js +74 -0
  13. package/dist/commands/create.js.map +1 -0
  14. package/dist/commands/detach.d.ts +2 -0
  15. package/dist/commands/detach.js +24 -0
  16. package/dist/commands/detach.js.map +1 -0
  17. package/dist/commands/diff.d.ts +2 -0
  18. package/dist/commands/diff.js +35 -0
  19. package/dist/commands/diff.js.map +1 -0
  20. package/dist/commands/import.d.ts +2 -0
  21. package/dist/commands/import.js +107 -0
  22. package/dist/commands/import.js.map +1 -0
  23. package/dist/commands/init.d.ts +2 -0
  24. package/dist/commands/init.js +77 -0
  25. package/dist/commands/init.js.map +1 -0
  26. package/dist/commands/map.d.ts +2 -0
  27. package/dist/commands/map.js +43 -0
  28. package/dist/commands/map.js.map +1 -0
  29. package/dist/commands/not-implemented.d.ts +2 -0
  30. package/dist/commands/not-implemented.js +19 -0
  31. package/dist/commands/not-implemented.js.map +1 -0
  32. package/dist/commands/pipeline-add.d.ts +2 -0
  33. package/dist/commands/pipeline-add.js +67 -0
  34. package/dist/commands/pipeline-add.js.map +1 -0
  35. package/dist/commands/pipeline-remove.d.ts +2 -0
  36. package/dist/commands/pipeline-remove.js +44 -0
  37. package/dist/commands/pipeline-remove.js.map +1 -0
  38. package/dist/commands/publish.d.ts +2 -0
  39. package/dist/commands/publish.js +147 -0
  40. package/dist/commands/publish.js.map +1 -0
  41. package/dist/commands/types.d.ts +45 -0
  42. package/dist/commands/types.js +2 -0
  43. package/dist/commands/types.js.map +1 -0
  44. package/dist/commands/update.d.ts +2 -0
  45. package/dist/commands/update.js +97 -0
  46. package/dist/commands/update.js.map +1 -0
  47. package/dist/core/adopt.d.ts +53 -0
  48. package/dist/core/adopt.js +676 -0
  49. package/dist/core/adopt.js.map +1 -0
  50. package/dist/core/build/agents.d.ts +23 -0
  51. package/dist/core/build/agents.js +60 -0
  52. package/dist/core/build/agents.js.map +1 -0
  53. package/dist/core/build/index.d.ts +4 -0
  54. package/dist/core/build/index.js +5 -0
  55. package/dist/core/build/index.js.map +1 -0
  56. package/dist/core/build/markers.d.ts +34 -0
  57. package/dist/core/build/markers.js +97 -0
  58. package/dist/core/build/markers.js.map +1 -0
  59. package/dist/core/build/plan.d.ts +48 -0
  60. package/dist/core/build/plan.js +792 -0
  61. package/dist/core/build/plan.js.map +1 -0
  62. package/dist/core/build/skill.d.ts +60 -0
  63. package/dist/core/build/skill.js +275 -0
  64. package/dist/core/build/skill.js.map +1 -0
  65. package/dist/core/check/drift.d.ts +13 -0
  66. package/dist/core/check/drift.js +205 -0
  67. package/dist/core/check/drift.js.map +1 -0
  68. package/dist/core/check/index.d.ts +12 -0
  69. package/dist/core/check/index.js +78 -0
  70. package/dist/core/check/index.js.map +1 -0
  71. package/dist/core/check/markers.d.ts +9 -0
  72. package/dist/core/check/markers.js +220 -0
  73. package/dist/core/check/markers.js.map +1 -0
  74. package/dist/core/config/destinations.d.ts +5 -0
  75. package/dist/core/config/destinations.js +20 -0
  76. package/dist/core/config/destinations.js.map +1 -0
  77. package/dist/core/config/load.d.ts +4 -0
  78. package/dist/core/config/load.js +41 -0
  79. package/dist/core/config/load.js.map +1 -0
  80. package/dist/core/config/parse.d.ts +8 -0
  81. package/dist/core/config/parse.js +198 -0
  82. package/dist/core/config/parse.js.map +1 -0
  83. package/dist/core/config/source.d.ts +14 -0
  84. package/dist/core/config/source.js +44 -0
  85. package/dist/core/config/source.js.map +1 -0
  86. package/dist/core/config/types.d.ts +48 -0
  87. package/dist/core/config/types.js +2 -0
  88. package/dist/core/config/types.js.map +1 -0
  89. package/dist/core/config/validate.d.ts +11 -0
  90. package/dist/core/config/validate.js +351 -0
  91. package/dist/core/config/validate.js.map +1 -0
  92. package/dist/core/config/writers.d.ts +14 -0
  93. package/dist/core/config/writers.js +261 -0
  94. package/dist/core/config/writers.js.map +1 -0
  95. package/dist/core/config.d.ts +7 -0
  96. package/dist/core/config.js +8 -0
  97. package/dist/core/config.js.map +1 -0
  98. package/dist/core/discovery.d.ts +34 -0
  99. package/dist/core/discovery.js +272 -0
  100. package/dist/core/discovery.js.map +1 -0
  101. package/dist/core/edit/create.d.ts +18 -0
  102. package/dist/core/edit/create.js +190 -0
  103. package/dist/core/edit/create.js.map +1 -0
  104. package/dist/core/edit/document.d.ts +4 -0
  105. package/dist/core/edit/document.js +16 -0
  106. package/dist/core/edit/document.js.map +1 -0
  107. package/dist/core/edit/factory-yaml.d.ts +17 -0
  108. package/dist/core/edit/factory-yaml.js +211 -0
  109. package/dist/core/edit/factory-yaml.js.map +1 -0
  110. package/dist/core/edit/files.d.ts +6 -0
  111. package/dist/core/edit/files.js +47 -0
  112. package/dist/core/edit/files.js.map +1 -0
  113. package/dist/core/edit/index.d.ts +9 -0
  114. package/dist/core/edit/index.js +10 -0
  115. package/dist/core/edit/index.js.map +1 -0
  116. package/dist/core/edit/map.d.ts +24 -0
  117. package/dist/core/edit/map.js +82 -0
  118. package/dist/core/edit/map.js.map +1 -0
  119. package/dist/core/edit/names.d.ts +2 -0
  120. package/dist/core/edit/names.js +17 -0
  121. package/dist/core/edit/names.js.map +1 -0
  122. package/dist/core/edit/paths.d.ts +8 -0
  123. package/dist/core/edit/paths.js +76 -0
  124. package/dist/core/edit/paths.js.map +1 -0
  125. package/dist/core/edit/pipeline.d.ts +19 -0
  126. package/dist/core/edit/pipeline.js +146 -0
  127. package/dist/core/edit/pipeline.js.map +1 -0
  128. package/dist/core/edit/skill.d.ts +1 -0
  129. package/dist/core/edit/skill.js +10 -0
  130. package/dist/core/edit/skill.js.map +1 -0
  131. package/dist/core/factory/discovery.d.ts +9 -0
  132. package/dist/core/factory/discovery.js +139 -0
  133. package/dist/core/factory/discovery.js.map +1 -0
  134. package/dist/core/factory/factory-yaml.d.ts +16 -0
  135. package/dist/core/factory/factory-yaml.js +375 -0
  136. package/dist/core/factory/factory-yaml.js.map +1 -0
  137. package/dist/core/factory/index.d.ts +5 -0
  138. package/dist/core/factory/index.js +6 -0
  139. package/dist/core/factory/index.js.map +1 -0
  140. package/dist/core/factory/lines.d.ts +8 -0
  141. package/dist/core/factory/lines.js +11 -0
  142. package/dist/core/factory/lines.js.map +1 -0
  143. package/dist/core/factory/load.d.ts +4 -0
  144. package/dist/core/factory/load.js +81 -0
  145. package/dist/core/factory/load.js.map +1 -0
  146. package/dist/core/factory/requires.d.ts +9 -0
  147. package/dist/core/factory/requires.js +123 -0
  148. package/dist/core/factory/requires.js.map +1 -0
  149. package/dist/core/factory/types.d.ts +45 -0
  150. package/dist/core/factory/types.js +2 -0
  151. package/dist/core/factory/types.js.map +1 -0
  152. package/dist/core/factory/validate.d.ts +41 -0
  153. package/dist/core/factory/validate.js +441 -0
  154. package/dist/core/factory/validate.js.map +1 -0
  155. package/dist/core/hooks/index.d.ts +8 -0
  156. package/dist/core/hooks/index.js +15 -0
  157. package/dist/core/hooks/index.js.map +1 -0
  158. package/dist/core/hooks/script.d.ts +21 -0
  159. package/dist/core/hooks/script.js +34 -0
  160. package/dist/core/hooks/script.js.map +1 -0
  161. package/dist/core/hooks/sync.d.ts +17 -0
  162. package/dist/core/hooks/sync.js +262 -0
  163. package/dist/core/hooks/sync.js.map +1 -0
  164. package/dist/core/import/conflicts.d.ts +82 -0
  165. package/dist/core/import/conflicts.js +256 -0
  166. package/dist/core/import/conflicts.js.map +1 -0
  167. package/dist/core/import/copy.d.ts +10 -0
  168. package/dist/core/import/copy.js +76 -0
  169. package/dist/core/import/copy.js.map +1 -0
  170. package/dist/core/import/file-tree.d.ts +43 -0
  171. package/dist/core/import/file-tree.js +107 -0
  172. package/dist/core/import/file-tree.js.map +1 -0
  173. package/dist/core/import/index.d.ts +5 -0
  174. package/dist/core/import/index.js +6 -0
  175. package/dist/core/import/index.js.map +1 -0
  176. package/dist/core/import/pipeline-changes.d.ts +8 -0
  177. package/dist/core/import/pipeline-changes.js +89 -0
  178. package/dist/core/import/pipeline-changes.js.map +1 -0
  179. package/dist/core/import/run.d.ts +76 -0
  180. package/dist/core/import/run.js +258 -0
  181. package/dist/core/import/run.js.map +1 -0
  182. package/dist/core/init/gitattributes.d.ts +20 -0
  183. package/dist/core/init/gitattributes.js +89 -0
  184. package/dist/core/init/gitattributes.js.map +1 -0
  185. package/dist/core/init/index.d.ts +4 -0
  186. package/dist/core/init/index.js +5 -0
  187. package/dist/core/init/index.js.map +1 -0
  188. package/dist/core/init/name.d.ts +1 -0
  189. package/dist/core/init/name.js +4 -0
  190. package/dist/core/init/name.js.map +1 -0
  191. package/dist/core/init/run.d.ts +51 -0
  192. package/dist/core/init/run.js +261 -0
  193. package/dist/core/init/run.js.map +1 -0
  194. package/dist/core/init/targets.d.ts +17 -0
  195. package/dist/core/init/targets.js +87 -0
  196. package/dist/core/init/targets.js.map +1 -0
  197. package/dist/core/merge.d.ts +88 -0
  198. package/dist/core/merge.js +239 -0
  199. package/dist/core/merge.js.map +1 -0
  200. package/dist/core/publish/exclude.d.ts +9 -0
  201. package/dist/core/publish/exclude.js +32 -0
  202. package/dist/core/publish/exclude.js.map +1 -0
  203. package/dist/core/publish/git-target.d.ts +32 -0
  204. package/dist/core/publish/git-target.js +447 -0
  205. package/dist/core/publish/git-target.js.map +1 -0
  206. package/dist/core/publish/index.d.ts +10 -0
  207. package/dist/core/publish/index.js +11 -0
  208. package/dist/core/publish/index.js.map +1 -0
  209. package/dist/core/publish/npm-target.d.ts +15 -0
  210. package/dist/core/publish/npm-target.js +170 -0
  211. package/dist/core/publish/npm-target.js.map +1 -0
  212. package/dist/core/publish/package-json.d.ts +31 -0
  213. package/dist/core/publish/package-json.js +74 -0
  214. package/dist/core/publish/package-json.js.map +1 -0
  215. package/dist/core/publish/prepare.d.ts +24 -0
  216. package/dist/core/publish/prepare.js +93 -0
  217. package/dist/core/publish/prepare.js.map +1 -0
  218. package/dist/core/publish/provenance.d.ts +1 -0
  219. package/dist/core/publish/provenance.js +20 -0
  220. package/dist/core/publish/provenance.js.map +1 -0
  221. package/dist/core/publish/publish.d.ts +13 -0
  222. package/dist/core/publish/publish.js +130 -0
  223. package/dist/core/publish/publish.js.map +1 -0
  224. package/dist/core/publish/readme.d.ts +22 -0
  225. package/dist/core/publish/readme.js +112 -0
  226. package/dist/core/publish/readme.js.map +1 -0
  227. package/dist/core/publish/stage.d.ts +19 -0
  228. package/dist/core/publish/stage.js +333 -0
  229. package/dist/core/publish/stage.js.map +1 -0
  230. package/dist/core/publish/types.d.ts +71 -0
  231. package/dist/core/publish/types.js +2 -0
  232. package/dist/core/publish/types.js.map +1 -0
  233. package/dist/core/requires/check.d.ts +15 -0
  234. package/dist/core/requires/check.js +83 -0
  235. package/dist/core/requires/check.js.map +1 -0
  236. package/dist/core/requires/index.d.ts +4 -0
  237. package/dist/core/requires/index.js +5 -0
  238. package/dist/core/requires/index.js.map +1 -0
  239. package/dist/core/requires/inspect.d.ts +44 -0
  240. package/dist/core/requires/inspect.js +114 -0
  241. package/dist/core/requires/inspect.js.map +1 -0
  242. package/dist/core/requires/paths.d.ts +29 -0
  243. package/dist/core/requires/paths.js +83 -0
  244. package/dist/core/requires/paths.js.map +1 -0
  245. package/dist/core/requires/setup.d.ts +37 -0
  246. package/dist/core/requires/setup.js +147 -0
  247. package/dist/core/requires/setup.js.map +1 -0
  248. package/dist/core/setup.d.ts +27 -0
  249. package/dist/core/setup.js +84 -0
  250. package/dist/core/setup.js.map +1 -0
  251. package/dist/core/sources/cache.d.ts +38 -0
  252. package/dist/core/sources/cache.js +200 -0
  253. package/dist/core/sources/cache.js.map +1 -0
  254. package/dist/core/sources/containment.d.ts +21 -0
  255. package/dist/core/sources/containment.js +50 -0
  256. package/dist/core/sources/containment.js.map +1 -0
  257. package/dist/core/sources/env.d.ts +12 -0
  258. package/dist/core/sources/env.js +28 -0
  259. package/dist/core/sources/env.js.map +1 -0
  260. package/dist/core/sources/extract.d.ts +25 -0
  261. package/dist/core/sources/extract.js +676 -0
  262. package/dist/core/sources/extract.js.map +1 -0
  263. package/dist/core/sources/git-process.d.ts +26 -0
  264. package/dist/core/sources/git-process.js +51 -0
  265. package/dist/core/sources/git-process.js.map +1 -0
  266. package/dist/core/sources/git.d.ts +41 -0
  267. package/dist/core/sources/git.js +511 -0
  268. package/dist/core/sources/git.js.map +1 -0
  269. package/dist/core/sources/https.d.ts +21 -0
  270. package/dist/core/sources/https.js +208 -0
  271. package/dist/core/sources/https.js.map +1 -0
  272. package/dist/core/sources/index.d.ts +13 -0
  273. package/dist/core/sources/index.js +14 -0
  274. package/dist/core/sources/index.js.map +1 -0
  275. package/dist/core/sources/npm-cli.d.ts +19 -0
  276. package/dist/core/sources/npm-cli.js +43 -0
  277. package/dist/core/sources/npm-cli.js.map +1 -0
  278. package/dist/core/sources/npm.d.ts +29 -0
  279. package/dist/core/sources/npm.js +386 -0
  280. package/dist/core/sources/npm.js.map +1 -0
  281. package/dist/core/sources/parse.d.ts +32 -0
  282. package/dist/core/sources/parse.js +389 -0
  283. package/dist/core/sources/parse.js.map +1 -0
  284. package/dist/core/sources/path.d.ts +10 -0
  285. package/dist/core/sources/path.js +316 -0
  286. package/dist/core/sources/path.js.map +1 -0
  287. package/dist/core/sources/redact.d.ts +2 -0
  288. package/dist/core/sources/redact.js +70 -0
  289. package/dist/core/sources/redact.js.map +1 -0
  290. package/dist/core/sources/resolve.d.ts +9 -0
  291. package/dist/core/sources/resolve.js +29 -0
  292. package/dist/core/sources/resolve.js.map +1 -0
  293. package/dist/core/sources/types.d.ts +86 -0
  294. package/dist/core/sources/types.js +2 -0
  295. package/dist/core/sources/types.js.map +1 -0
  296. package/dist/core/sources/validate.d.ts +9 -0
  297. package/dist/core/sources/validate.js +111 -0
  298. package/dist/core/sources/validate.js.map +1 -0
  299. package/dist/core/summary.d.ts +77 -0
  300. package/dist/core/summary.js +405 -0
  301. package/dist/core/summary.js.map +1 -0
  302. package/dist/core/update/clashes.d.ts +63 -0
  303. package/dist/core/update/clashes.js +192 -0
  304. package/dist/core/update/clashes.js.map +1 -0
  305. package/dist/core/update/detach.d.ts +21 -0
  306. package/dist/core/update/detach.js +38 -0
  307. package/dist/core/update/detach.js.map +1 -0
  308. package/dist/core/update/diff.d.ts +58 -0
  309. package/dist/core/update/diff.js +180 -0
  310. package/dist/core/update/diff.js.map +1 -0
  311. package/dist/core/update/fetch.d.ts +34 -0
  312. package/dist/core/update/fetch.js +73 -0
  313. package/dist/core/update/fetch.js.map +1 -0
  314. package/dist/core/update/index.d.ts +6 -0
  315. package/dist/core/update/index.js +7 -0
  316. package/dist/core/update/index.js.map +1 -0
  317. package/dist/core/update/restore.d.ts +20 -0
  318. package/dist/core/update/restore.js +195 -0
  319. package/dist/core/update/restore.js.map +1 -0
  320. package/dist/core/update/run.d.ts +113 -0
  321. package/dist/core/update/run.js +1132 -0
  322. package/dist/core/update/run.js.map +1 -0
  323. package/dist/core/update/select.d.ts +39 -0
  324. package/dist/core/update/select.js +157 -0
  325. package/dist/core/update/select.js.map +1 -0
  326. package/dist/core/update/spelling.d.ts +51 -0
  327. package/dist/core/update/spelling.js +185 -0
  328. package/dist/core/update/spelling.js.map +1 -0
  329. package/dist/core/update/trees.d.ts +24 -0
  330. package/dist/core/update/trees.js +72 -0
  331. package/dist/core/update/trees.js.map +1 -0
  332. package/dist/errors.d.ts +29 -0
  333. package/dist/errors.js +24 -0
  334. package/dist/errors.js.map +1 -0
  335. package/dist/help.d.ts +46 -0
  336. package/dist/help.js +103 -0
  337. package/dist/help.js.map +1 -0
  338. package/dist/input.d.ts +25 -0
  339. package/dist/input.js +173 -0
  340. package/dist/input.js.map +1 -0
  341. package/dist/output.d.ts +21 -0
  342. package/dist/output.js +37 -0
  343. package/dist/output.js.map +1 -0
  344. package/dist/util/frontmatter.d.ts +12 -0
  345. package/dist/util/frontmatter.js +58 -0
  346. package/dist/util/frontmatter.js.map +1 -0
  347. package/dist/util/fs.d.ts +32 -0
  348. package/dist/util/fs.js +126 -0
  349. package/dist/util/fs.js.map +1 -0
  350. package/dist/util/git-names.d.ts +8 -0
  351. package/dist/util/git-names.js +25 -0
  352. package/dist/util/git-names.js.map +1 -0
  353. package/dist/util/git.d.ts +12 -0
  354. package/dist/util/git.js +33 -0
  355. package/dist/util/git.js.map +1 -0
  356. package/dist/util/suggest.d.ts +6 -0
  357. package/dist/util/suggest.js +48 -0
  358. package/dist/util/suggest.js.map +1 -0
  359. package/dist/util/text.d.ts +8 -0
  360. package/dist/util/text.js +19 -0
  361. package/dist/util/text.js.map +1 -0
  362. package/dist/util/version.d.ts +7 -0
  363. package/dist/util/version.js +13 -0
  364. package/dist/util/version.js.map +1 -0
  365. package/dist/util/yaml.d.ts +30 -0
  366. package/dist/util/yaml.js +201 -0
  367. package/dist/util/yaml.js.map +1 -0
  368. package/package.json +50 -3
  369. package/resources/metafab-skill/SKILL.md +99 -0
@@ -0,0 +1,676 @@
1
+ import { createReadStream } from "node:fs";
2
+ import { link, mkdir, realpath, rm, stat, symlink } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import * as tar from "tar";
5
+ import { ExitCode, MetafabError } from "../../errors.js";
6
+ import { containmentRootAbsolute, isInsideAbsolute } from "./containment.js";
7
+ export const MAX_FAB_FILE_SIZE = 1024 * 1024;
8
+ export const MAX_FAB_TOTAL_SIZE = 64 * 1024 * 1024;
9
+ export const MAX_FAB_ENTRIES = 10_000;
10
+ const BLOCK_SIZE = 512;
11
+ const FACTORY_DIRECTORY = ".factory";
12
+ const CACHE_WRITE_CODES = new Set(["EACCES", "EPERM", "ENOSPC", "EROFS", "EDQUOT"]);
13
+ /**
14
+ * True when a filesystem failure means the destination could not be written,
15
+ * rather than the archive being bad: permissions, a full disk or a read-only
16
+ * filesystem.
17
+ */
18
+ export function isCacheWriteFailure(error) {
19
+ if (typeof error !== "object" || error === null || !("code" in error))
20
+ return false;
21
+ const code = error.code;
22
+ return typeof code === "string" && CACHE_WRITE_CODES.has(code);
23
+ }
24
+ const FILE_TYPES = new Set(["File", "OldFile", "ContiguousFile"]);
25
+ const DIRECTORY_TYPES = new Set(["Directory"]);
26
+ const METADATA_TYPES = new Set(["ExtendedHeader", "GlobalExtendedHeader"]);
27
+ const LINK_TYPES = new Set(["SymbolicLink", "Link"]);
28
+ // Every file, directory and link is one entry. Metadata headers and unsupported
29
+ // entry types are not, so the cap counts the same things as a local-path copy.
30
+ const COUNTED_TYPES = new Set([...FILE_TYPES, ...DIRECTORY_TYPES, ...LINK_TYPES]);
31
+ function unsafePathReason(entryPath) {
32
+ if (entryPath === "")
33
+ return "the entry has an empty path";
34
+ const normalized = entryPath.replace(/\\/g, "/");
35
+ if (normalized.startsWith("/") ||
36
+ /^[A-Za-z]:\//.test(normalized) ||
37
+ entryPath.startsWith("\\")) {
38
+ return "absolute paths are not allowed";
39
+ }
40
+ if (normalized.split("/").includes(".."))
41
+ return "paths that contain .. are not allowed";
42
+ return undefined;
43
+ }
44
+ function collidesWithFactory(segment) {
45
+ if (segment === FACTORY_DIRECTORY)
46
+ return false;
47
+ return segment.replace(/[. ]+$/g, "").toLowerCase() === FACTORY_DIRECTORY;
48
+ }
49
+ function factoryCollisionReason(entryPath) {
50
+ for (const segment of entryPath.replace(/\\/g, "/").split("/")) {
51
+ if (collidesWithFactory(segment)) {
52
+ return "paths that collide with .factory are not allowed in a fab";
53
+ }
54
+ }
55
+ return undefined;
56
+ }
57
+ function entryProblem(entry, maxFileSize) {
58
+ if (entry.type === "BlockDevice" || entry.type === "CharacterDevice" || entry.type === "FIFO") {
59
+ return "device files and FIFOs are not allowed in a fab";
60
+ }
61
+ if (FILE_TYPES.has(entry.type) && entry.size > maxFileSize) {
62
+ return `files larger than ${maxFileSize} bytes are not allowed in a fab`;
63
+ }
64
+ return undefined;
65
+ }
66
+ function isAllowedType(entry) {
67
+ return FILE_TYPES.has(entry.type) || DIRECTORY_TYPES.has(entry.type) || METADATA_TYPES.has(entry.type);
68
+ }
69
+ function normalizePrefix(prefix) {
70
+ const normalized = prefix.replace(/\\/g, "/").replace(/^\.\//, "");
71
+ return normalized.endsWith("/") ? normalized : `${normalized}/`;
72
+ }
73
+ function cleanEntryPath(entryPath) {
74
+ const parts = entryPath.replace(/\\/g, "/").split("/");
75
+ let index = 0;
76
+ while (index < parts.length && parts[index] === ".")
77
+ index += 1;
78
+ return parts.slice(index).join("/");
79
+ }
80
+ function stripSegments(entryPath, count) {
81
+ const parts = entryPath.replace(/\\/g, "/").split("/").filter((part) => part !== "");
82
+ return parts.slice(count).join("/");
83
+ }
84
+ function stripEntryPath(entryPath, count) {
85
+ const parts = cleanEntryPath(entryPath).split("/");
86
+ if (parts.length < count)
87
+ return "";
88
+ return parts.slice(count).join("/");
89
+ }
90
+ /**
91
+ * Header and padding blocks are read for every entry too, so a tar full of
92
+ * padding or metadata cannot hide behind the declared file sizes.
93
+ */
94
+ function blockBytes(size) {
95
+ return BLOCK_SIZE + Math.ceil(size / BLOCK_SIZE) * BLOCK_SIZE;
96
+ }
97
+ function listingReadCap(limits) {
98
+ return limits.maxTotalSize + limits.maxEntries * 2 * BLOCK_SIZE + 2 * BLOCK_SIZE;
99
+ }
100
+ function listingProblem(entries, declaredBytes, readBytes, limits) {
101
+ if (entries > limits.maxEntries) {
102
+ return `archives with more than ${limits.maxEntries} entries are not allowed in a fab`;
103
+ }
104
+ if (declaredBytes > limits.maxTotalSize) {
105
+ return `extracted files larger than ${limits.maxTotalSize} bytes in total are not allowed in a fab`;
106
+ }
107
+ if (readBytes > listingReadCap(limits)) {
108
+ return `archives that expand to more than ${listingReadCap(limits)} bytes are not allowed in a fab`;
109
+ }
110
+ return undefined;
111
+ }
112
+ async function readEntries(tarball, limits) {
113
+ const entries = [];
114
+ let countedEntries = 0;
115
+ let declaredBytes = 0;
116
+ let readBytes = 0;
117
+ let failure;
118
+ const parser = tar.list({
119
+ onentry: (entry) => {
120
+ entries.push({
121
+ path: entry.path,
122
+ type: entry.type,
123
+ ...(entry.linkpath === undefined || entry.linkpath === null
124
+ ? {}
125
+ : { linkpath: String(entry.linkpath) }),
126
+ size: entry.size,
127
+ });
128
+ readBytes += blockBytes(entry.size);
129
+ if (FILE_TYPES.has(entry.type))
130
+ declaredBytes += entry.size;
131
+ if (COUNTED_TYPES.has(entry.type))
132
+ countedEntries += 1;
133
+ const problem = listingProblem(countedEntries, declaredBytes, readBytes, limits);
134
+ if (problem === undefined) {
135
+ entry.resume();
136
+ return;
137
+ }
138
+ failure = unsafeArchive(problem);
139
+ parser.abort(failure);
140
+ },
141
+ });
142
+ const stream = createReadStream(tarball);
143
+ try {
144
+ await new Promise((resolve, reject) => {
145
+ let settled = false;
146
+ const fail = (error) => {
147
+ if (settled)
148
+ return;
149
+ settled = true;
150
+ stream.destroy();
151
+ reject(error);
152
+ };
153
+ parser.on("end", () => {
154
+ if (settled)
155
+ return;
156
+ settled = true;
157
+ resolve();
158
+ });
159
+ parser.on("error", fail);
160
+ stream.on("error", fail);
161
+ stream.pipe(parser);
162
+ });
163
+ }
164
+ catch (error) {
165
+ if (failure !== undefined)
166
+ throw failure;
167
+ throw error;
168
+ }
169
+ finally {
170
+ // An aborted listing stops at a header, so the rest of the archive is never
171
+ // read. Closing the descriptor here keeps a rejected archive from leaving a
172
+ // stream running (and erroring) after the promise has settled.
173
+ stream.destroy();
174
+ }
175
+ if (failure !== undefined)
176
+ throw failure;
177
+ return entries;
178
+ }
179
+ async function singleTopDirectory(entries, prefix, strip) {
180
+ const cleaned = entries.map((entry) => cleanEntryPath(entry.path));
181
+ const relative = cleaned
182
+ .filter((entryPath) => prefix === undefined || entryPath.startsWith(prefix))
183
+ .map((entryPath) => stripSegments(prefixedPath(entryPath, prefix), strip))
184
+ .filter((entryPath) => entryPath !== "");
185
+ const segments = relative.map((entryPath) => entryPath.split("/").filter((part) => part !== ""));
186
+ if (segments.length === 0)
187
+ return undefined;
188
+ const first = segments[0]?.[0];
189
+ if (first === undefined || first === ".factory")
190
+ return undefined;
191
+ if (!segments.every((parts) => parts[0] === first))
192
+ return undefined;
193
+ if (!segments.some((parts) => parts.length >= 2))
194
+ return undefined;
195
+ return first;
196
+ }
197
+ function prefixedPath(entryPath, prefix) {
198
+ return prefix === undefined ? entryPath : entryPath.slice(prefix.length);
199
+ }
200
+ function isAbsoluteLinkTarget(target) {
201
+ const normalized = target.replace(/\\/g, "/");
202
+ return normalized.startsWith("/") || /^[A-Za-z]:\//.test(normalized);
203
+ }
204
+ function containmentRoot(finalPath) {
205
+ return finalPath === ".factory" || finalPath.startsWith(".factory/") ? ".factory" : "";
206
+ }
207
+ function isWithin(root, target) {
208
+ if (target === "" || target === ".." || target.startsWith("../"))
209
+ return false;
210
+ if (root === "")
211
+ return true;
212
+ return target === root || target.startsWith(`${root}/`);
213
+ }
214
+ function symlinkTarget(finalPath, linkpath) {
215
+ if (linkpath === "" || isAbsoluteLinkTarget(linkpath))
216
+ return undefined;
217
+ const resolved = path.posix.normalize(path.posix.join(path.posix.dirname(finalPath), linkpath.replace(/\\/g, "/")));
218
+ const root = containmentRoot(finalPath);
219
+ if (!isWithin(root, resolved))
220
+ return undefined;
221
+ return resolved;
222
+ }
223
+ function hardLinkTarget(finalPath, linkpath, strip) {
224
+ if (linkpath === "" || isAbsoluteLinkTarget(linkpath))
225
+ return undefined;
226
+ if (linkpath.replace(/\\/g, "/").split("/").includes(".."))
227
+ return undefined;
228
+ const resolved = path.posix.normalize(stripEntryPath(linkpath, strip));
229
+ const root = containmentRoot(finalPath);
230
+ if (!isWithin(root, resolved))
231
+ return undefined;
232
+ return resolved;
233
+ }
234
+ function finalPath(entryPath, strip) {
235
+ return path.posix.normalize(stripEntryPath(entryPath, strip));
236
+ }
237
+ /**
238
+ * Reject an archive that would overwrite earlier content or turn a directory
239
+ * into a file or link. Extraction must never have to delete a path to make
240
+ * room: `..notes.md` is a harmless file name, but `.factory/dir` as both a
241
+ * directory and a link is not.
242
+ */
243
+ function pathCollisionProblems(entries, strip, linkDirectories) {
244
+ const problems = [];
245
+ const categories = new Map();
246
+ const directories = new Set();
247
+ for (const entry of entries) {
248
+ if (!COUNTED_TYPES.has(entry.type))
249
+ continue;
250
+ if (unsafePathReason(entry.path) !== undefined)
251
+ continue;
252
+ if (factoryCollisionReason(entry.path) !== undefined)
253
+ continue;
254
+ const entryPath = finalPath(cleanEntryPath(entry.path), strip);
255
+ if (entryPath === "" || entryPath === ".")
256
+ continue;
257
+ // A symlink and everything below it is rejected by the filter with its own
258
+ // message; do not report the same entries as a directory collision here.
259
+ if (linkDirectories.has(entryPath) || writtenThroughLink(entryPath, linkDirectories))
260
+ continue;
261
+ const category = DIRECTORY_TYPES.has(entry.type)
262
+ ? "directory"
263
+ : LINK_TYPES.has(entry.type)
264
+ ? "link"
265
+ : "file";
266
+ const previous = categories.get(entryPath);
267
+ if (previous !== undefined && !(previous === "directory" && category === "directory")) {
268
+ problems.push({
269
+ level: "error",
270
+ file: entry.path,
271
+ message: `duplicate archive entry "${entryPath}" would replace earlier content`,
272
+ });
273
+ continue;
274
+ }
275
+ if (previous === undefined)
276
+ categories.set(entryPath, category);
277
+ let parent = path.posix.dirname(entryPath);
278
+ while (parent !== "." && parent !== "/" && parent !== "") {
279
+ directories.add(parent);
280
+ const next = path.posix.dirname(parent);
281
+ if (next === parent)
282
+ break;
283
+ parent = next;
284
+ }
285
+ if (category === "directory")
286
+ directories.add(entryPath);
287
+ }
288
+ for (const [entryPath, category] of categories) {
289
+ if (category === "directory")
290
+ continue;
291
+ if (directories.has(entryPath)) {
292
+ problems.push({
293
+ level: "error",
294
+ file: entryPath,
295
+ message: "an entry whose path is an existing directory is not allowed",
296
+ });
297
+ }
298
+ }
299
+ return problems;
300
+ }
301
+ function symlinkDirectories(entries, strip) {
302
+ const directories = new Set();
303
+ for (const entry of entries) {
304
+ if (entry.type !== "SymbolicLink")
305
+ continue;
306
+ if (unsafePathReason(entry.path) !== undefined)
307
+ continue;
308
+ const entryPath = finalPath(entry.path, strip);
309
+ if (entryPath === "")
310
+ continue;
311
+ directories.add(entryPath);
312
+ }
313
+ return directories;
314
+ }
315
+ function writtenThroughLink(entryPath, directories) {
316
+ let current = path.posix.dirname(entryPath);
317
+ while (current !== "." && current !== "/" && current !== "") {
318
+ if (directories.has(current))
319
+ return true;
320
+ current = path.posix.dirname(current);
321
+ }
322
+ return false;
323
+ }
324
+ function linkPath(destination, relativePath) {
325
+ return path.join(destination, ...relativePath.split("/"));
326
+ }
327
+ async function targetExists(target) {
328
+ try {
329
+ await stat(target);
330
+ return true;
331
+ }
332
+ catch {
333
+ return false;
334
+ }
335
+ }
336
+ async function linkTargetType(target) {
337
+ try {
338
+ return (await stat(target)).isDirectory() ? "dir" : "file";
339
+ }
340
+ catch {
341
+ return "file";
342
+ }
343
+ }
344
+ function linkProblem(task, error) {
345
+ const message = error instanceof Error ? error.message : String(error);
346
+ return {
347
+ level: "error",
348
+ file: task.path,
349
+ message: `links could not be created: ${message}`,
350
+ };
351
+ }
352
+ async function createSymbolicLink(destination, task, type) {
353
+ const target = linkPath(destination, task.path);
354
+ await mkdir(path.dirname(target), { recursive: true });
355
+ await symlink(task.target, target, type);
356
+ }
357
+ async function createHardLink(destination, task) {
358
+ const target = linkPath(destination, task.path);
359
+ await mkdir(path.dirname(target), { recursive: true });
360
+ // Never remove whatever is already at the path: a directory here holds files
361
+ // that earlier entries extracted. A collision is rejected before extraction.
362
+ await link(linkPath(destination, task.target), target);
363
+ }
364
+ async function createLinks(destination, tasks) {
365
+ const problems = [];
366
+ const failed = new Set();
367
+ const symbolic = tasks.filter((task) => task.kind === "symbolic");
368
+ const hard = tasks.filter((task) => task.kind === "hard");
369
+ let pending = symbolic;
370
+ while (pending.length > 0) {
371
+ const remaining = [];
372
+ let progress = false;
373
+ for (const task of pending) {
374
+ const target = linkPath(destination, task.path);
375
+ const absoluteTarget = path.resolve(path.dirname(target), task.target);
376
+ if (!(await targetExists(absoluteTarget))) {
377
+ remaining.push(task);
378
+ continue;
379
+ }
380
+ try {
381
+ await createSymbolicLink(destination, task, await linkTargetType(absoluteTarget));
382
+ progress = true;
383
+ }
384
+ catch (error) {
385
+ problems.push(linkProblem(task, error));
386
+ failed.add(task.path);
387
+ progress = true;
388
+ }
389
+ }
390
+ if (!progress) {
391
+ for (const task of remaining) {
392
+ try {
393
+ await createSymbolicLink(destination, task, "file");
394
+ }
395
+ catch (error) {
396
+ problems.push(linkProblem(task, error));
397
+ failed.add(task.path);
398
+ }
399
+ }
400
+ break;
401
+ }
402
+ pending = remaining;
403
+ }
404
+ for (const task of hard) {
405
+ const source = linkPath(destination, task.target);
406
+ const target = linkPath(destination, task.path);
407
+ await mkdir(path.dirname(target), { recursive: true });
408
+ let resolved;
409
+ try {
410
+ resolved = await realpath(source);
411
+ }
412
+ catch {
413
+ problems.push({
414
+ level: "error",
415
+ file: task.path,
416
+ message: "links whose target does not exist are not allowed",
417
+ });
418
+ failed.add(task.path);
419
+ continue;
420
+ }
421
+ if (!isInsideAbsolute(await containmentRootAbsolute(target, destination), resolved)) {
422
+ problems.push({
423
+ level: "error",
424
+ file: task.path,
425
+ message: "links that point outside the extraction root are not allowed",
426
+ });
427
+ failed.add(task.path);
428
+ continue;
429
+ }
430
+ try {
431
+ await createHardLink(destination, task);
432
+ }
433
+ catch (error) {
434
+ problems.push(linkProblem(task, error));
435
+ failed.add(task.path);
436
+ }
437
+ }
438
+ return { problems, failed };
439
+ }
440
+ async function verifyLinks(destination, tasks) {
441
+ const problems = [];
442
+ for (const task of tasks) {
443
+ const target = linkPath(destination, task.path);
444
+ let resolved;
445
+ try {
446
+ resolved = await realpath(target);
447
+ }
448
+ catch {
449
+ problems.push({
450
+ level: "error",
451
+ file: task.path,
452
+ message: "links whose target does not exist are not allowed",
453
+ });
454
+ continue;
455
+ }
456
+ if (!isInsideAbsolute(await containmentRootAbsolute(target, destination), resolved)) {
457
+ problems.push({
458
+ level: "error",
459
+ file: task.path,
460
+ message: "links that point outside the extraction root are not allowed",
461
+ });
462
+ }
463
+ }
464
+ return problems;
465
+ }
466
+ function tarballError(tarball, cause) {
467
+ const message = cause instanceof Error ? cause.message : String(cause);
468
+ return new MetafabError(`Cannot extract ${tarball}: ${message}`, {
469
+ exitCode: ExitCode.InvalidFab,
470
+ code: "invalid-fab",
471
+ cause,
472
+ });
473
+ }
474
+ function unsafeArchive(message, cause) {
475
+ return new MetafabError("The archive is not a safe fab", {
476
+ exitCode: ExitCode.InvalidFab,
477
+ code: "invalid-fab",
478
+ problems: [{ level: "error", file: ".", message }],
479
+ ...(cause === undefined ? {} : { cause }),
480
+ });
481
+ }
482
+ export async function extractTarball(tarball, destination, options = {}) {
483
+ const maxFileSize = options.maxFileSize ?? MAX_FAB_FILE_SIZE;
484
+ const maxTotalSize = options.maxTotalSize ?? MAX_FAB_TOTAL_SIZE;
485
+ const maxEntries = options.maxEntries ?? MAX_FAB_ENTRIES;
486
+ const prefix = options.stripPrefix === undefined ? undefined : normalizePrefix(options.stripPrefix);
487
+ let strip = (options.strip ?? 0) + (prefix === undefined ? 0 : prefix.split("/").filter((part) => part !== "").length);
488
+ let entries;
489
+ try {
490
+ entries = await readEntries(tarball, { maxEntries, maxTotalSize });
491
+ if (options.flattenSingleDirectory === true) {
492
+ // `singleTopDirectory` strips the prefix itself, and `strip` already
493
+ // counts the prefix segments, so only the caller's own count goes in.
494
+ const top = await singleTopDirectory(entries, prefix, options.strip ?? 0);
495
+ if (top !== undefined)
496
+ strip += 1;
497
+ }
498
+ }
499
+ catch (error) {
500
+ if (error instanceof MetafabError)
501
+ throw error;
502
+ throw tarballError(tarball, error);
503
+ }
504
+ const relevant = entries.filter((entry) => prefix === undefined || cleanEntryPath(entry.path).startsWith(prefix));
505
+ const linkDirectories = symlinkDirectories(relevant, strip);
506
+ const collisions = pathCollisionProblems(relevant, strip, linkDirectories);
507
+ if (collisions.length > 0) {
508
+ throw new MetafabError("The archive is not a safe fab", {
509
+ exitCode: ExitCode.InvalidFab,
510
+ code: "invalid-fab",
511
+ problems: collisions,
512
+ });
513
+ }
514
+ try {
515
+ await mkdir(destination, { recursive: true });
516
+ }
517
+ catch (error) {
518
+ if (options.writeError !== undefined)
519
+ throw options.writeError(destination, error);
520
+ throw tarballError(tarball, error);
521
+ }
522
+ const problems = [];
523
+ const links = [];
524
+ const filter = (entryPath, entry) => {
525
+ const rawEntry = entry;
526
+ const reason = unsafePathReason(entryPath);
527
+ if (reason !== undefined) {
528
+ problems.push({ level: "error", file: entryPath, message: reason });
529
+ return false;
530
+ }
531
+ const collision = factoryCollisionReason(entryPath);
532
+ if (collision !== undefined) {
533
+ problems.push({ level: "error", file: entryPath, message: collision });
534
+ return false;
535
+ }
536
+ const normalizedEntryPath = cleanEntryPath(entryPath);
537
+ if (prefix !== undefined && !normalizedEntryPath.startsWith(prefix))
538
+ return false;
539
+ const entryFinalPath = finalPath(normalizedEntryPath, strip);
540
+ if (LINK_TYPES.has(rawEntry.type)) {
541
+ const linkpath = rawEntry.linkpath === undefined || rawEntry.linkpath === null
542
+ ? ""
543
+ : String(rawEntry.linkpath);
544
+ if (entryFinalPath === "" || entryFinalPath === "." || entryFinalPath.startsWith("../")) {
545
+ problems.push({
546
+ level: "error",
547
+ file: entryPath,
548
+ message: "links are not allowed at the extraction root",
549
+ });
550
+ return false;
551
+ }
552
+ if (writtenThroughLink(entryFinalPath, linkDirectories)) {
553
+ problems.push({
554
+ level: "error",
555
+ file: entryPath,
556
+ message: "entries written through a symbolic link are not allowed",
557
+ });
558
+ return false;
559
+ }
560
+ if (rawEntry.type === "SymbolicLink") {
561
+ const target = symlinkTarget(entryFinalPath, linkpath);
562
+ if (target === undefined) {
563
+ problems.push({
564
+ level: "error",
565
+ file: entryPath,
566
+ message: "links that point outside the extraction root are not allowed",
567
+ });
568
+ return false;
569
+ }
570
+ links.push({ kind: "symbolic", target: linkpath, path: entryFinalPath });
571
+ return false;
572
+ }
573
+ const target = hardLinkTarget(entryFinalPath, linkpath, strip);
574
+ if (target === undefined) {
575
+ problems.push({
576
+ level: "error",
577
+ file: entryPath,
578
+ message: "links that point outside the extraction root are not allowed",
579
+ });
580
+ return false;
581
+ }
582
+ links.push({ kind: "hard", target, path: entryFinalPath });
583
+ return false;
584
+ }
585
+ const problem = entryProblem(rawEntry, maxFileSize);
586
+ if (problem !== undefined) {
587
+ problems.push({ level: "error", file: entryPath, message: problem });
588
+ return false;
589
+ }
590
+ if (!isAllowedType(rawEntry)) {
591
+ problems.push({
592
+ level: "error",
593
+ file: entryPath,
594
+ message: `unsupported archive entry type "${rawEntry.type}"`,
595
+ });
596
+ return false;
597
+ }
598
+ if (writtenThroughLink(entryFinalPath, linkDirectories)) {
599
+ problems.push({
600
+ level: "error",
601
+ file: entryPath,
602
+ message: "entries written through a symbolic link are not allowed",
603
+ });
604
+ return false;
605
+ }
606
+ if (entryFinalPath === "" || entryFinalPath === ".")
607
+ return false;
608
+ rawEntry.path = entryFinalPath;
609
+ return true;
610
+ };
611
+ let failure;
612
+ const unpack = tar.x({ cwd: destination, filter, strict: true });
613
+ const stream = createReadStream(tarball);
614
+ try {
615
+ await new Promise((resolve, reject) => {
616
+ let settled = false;
617
+ const fail = (error) => {
618
+ if (settled)
619
+ return;
620
+ settled = true;
621
+ stream.destroy();
622
+ reject(error);
623
+ };
624
+ unpack.on("end", () => {
625
+ if (settled)
626
+ return;
627
+ settled = true;
628
+ resolve();
629
+ });
630
+ unpack.on("error", fail);
631
+ stream.on("error", fail);
632
+ stream.pipe(unpack);
633
+ });
634
+ }
635
+ catch (error) {
636
+ failure = error;
637
+ }
638
+ finally {
639
+ // A failed extraction aborts before the end of the archive. Tear both
640
+ // streams down so nothing writes into a finished stream and no descriptor
641
+ // or zlib handle outlives this call. `abort` is tar's own way to stop a
642
+ // parser: it closes the decompressor it opened.
643
+ stream.destroy();
644
+ if (failure !== undefined) {
645
+ unpack.abort(failure instanceof Error ? failure : new Error(String(failure)));
646
+ }
647
+ }
648
+ if (problems.length > 0) {
649
+ throw new MetafabError("The archive is not a safe fab", {
650
+ exitCode: ExitCode.InvalidFab,
651
+ code: "invalid-fab",
652
+ problems,
653
+ cause: failure,
654
+ });
655
+ }
656
+ if (failure !== undefined) {
657
+ if (options.writeError !== undefined && isCacheWriteFailure(failure)) {
658
+ throw options.writeError(destination, failure);
659
+ }
660
+ throw tarballError(tarball, failure);
661
+ }
662
+ const created = await createLinks(destination, links);
663
+ // A link whose creation already failed keeps its creation message: the
664
+ // realpath check would only repeat it as "target does not exist".
665
+ const stillValid = links.filter((task) => !created.failed.has(task.path));
666
+ const verificationProblems = await verifyLinks(destination, stillValid);
667
+ const allLinkProblems = [...created.problems, ...verificationProblems];
668
+ if (allLinkProblems.length > 0) {
669
+ throw new MetafabError("The archive is not a safe fab", {
670
+ exitCode: ExitCode.InvalidFab,
671
+ code: "invalid-fab",
672
+ problems: allLinkProblems,
673
+ });
674
+ }
675
+ }
676
+ //# sourceMappingURL=extract.js.map