@socketsecurity/lib 3.2.2 → 3.2.4

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 (307) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/dist/abort.js +1 -1
  3. package/dist/agent.js +1 -1
  4. package/dist/ansi.js +1 -1
  5. package/dist/argv/flags.js +1 -1
  6. package/dist/argv/parse.js +1 -1
  7. package/dist/arrays.js +1 -1
  8. package/dist/bin.js +1 -1
  9. package/dist/cacache.js +1 -1
  10. package/dist/cache-with-ttl.js +1 -1
  11. package/dist/constants/agents.js +1 -1
  12. package/dist/constants/core.js +1 -1
  13. package/dist/constants/encoding.js +1 -1
  14. package/dist/constants/github.js +1 -1
  15. package/dist/constants/licenses.js +1 -1
  16. package/dist/constants/node.js +1 -1
  17. package/dist/constants/packages.js +1 -1
  18. package/dist/constants/paths.js +1 -1
  19. package/dist/constants/platform.js +1 -1
  20. package/dist/constants/process.js +1 -1
  21. package/dist/constants/socket.js +1 -1
  22. package/dist/constants/testing.js +1 -1
  23. package/dist/constants/time.js +1 -1
  24. package/dist/constants/typescript.js +1 -1
  25. package/dist/cover/code.js +1 -1
  26. package/dist/cover/formatters.js +1 -1
  27. package/dist/cover/type.js +1 -1
  28. package/dist/cover/types.js +1 -1
  29. package/dist/debug.js +1 -1
  30. package/dist/dlx-binary.js +1 -1
  31. package/dist/dlx-manifest.js +1 -1
  32. package/dist/dlx-package.js +1 -1
  33. package/dist/dlx.js +1 -1
  34. package/dist/effects/pulse-frames.js +4 -4
  35. package/dist/effects/text-shimmer.js +1 -1
  36. package/dist/effects/types.js +1 -1
  37. package/dist/effects/ultra.js +1 -1
  38. package/dist/env/ci.js +1 -1
  39. package/dist/env/debug.js +1 -1
  40. package/dist/env/github.js +1 -1
  41. package/dist/env/helpers.js +1 -1
  42. package/dist/env/home.js +1 -1
  43. package/dist/env/locale.js +1 -1
  44. package/dist/env/node-auth-token.js +1 -1
  45. package/dist/env/node-env.js +1 -1
  46. package/dist/env/npm.js +1 -1
  47. package/dist/env/package-manager.js +1 -1
  48. package/dist/env/path.js +1 -1
  49. package/dist/env/pre-commit.js +1 -1
  50. package/dist/env/rewire.js +1 -1
  51. package/dist/env/shell.js +1 -1
  52. package/dist/env/socket-cli-shadow.js +1 -1
  53. package/dist/env/socket-cli.js +1 -1
  54. package/dist/env/socket.js +1 -1
  55. package/dist/env/temp-dir.js +1 -1
  56. package/dist/env/term.js +1 -1
  57. package/dist/env/test.js +1 -1
  58. package/dist/env/windows.js +1 -1
  59. package/dist/env/xdg.js +1 -1
  60. package/dist/env.js +1 -1
  61. package/dist/external/@inquirer/confirm.js +16 -15
  62. package/dist/external/@inquirer/input.js +16 -15
  63. package/dist/external/@inquirer/password.js +17 -16
  64. package/dist/external/@inquirer/search.js +18 -17
  65. package/dist/external/@inquirer/select.js +19 -18
  66. package/dist/external/@npmcli/package-json/lib/read-package.js +7 -1
  67. package/dist/external/@npmcli/package-json/lib/sort.js +6 -1
  68. package/dist/external/@npmcli/package-json.js +18 -0
  69. package/dist/external/@npmcli/promise-spawn.js +2 -1
  70. package/dist/external/@socketregistry/is-unicode-supported.js +2 -1
  71. package/dist/external/@socketregistry/packageurl-js.js +3 -2
  72. package/dist/external/@socketregistry/yocto-spinner.js +5 -4
  73. package/dist/external/@yarnpkg/extensions.js +2 -1
  74. package/dist/external/cacache.js +10 -9
  75. package/dist/external/debug.js +2 -5
  76. package/dist/external/del.js +3 -2
  77. package/dist/external/fast-glob.js +3 -2
  78. package/dist/external/fast-sort.js +2 -1
  79. package/dist/external/get-east-asian-width.js +2 -1
  80. package/dist/external/libnpmexec.js +6 -0
  81. package/dist/external/libnpmpack.js +68 -71
  82. package/dist/external/make-fetch-happen.js +17 -20
  83. package/dist/external/normalize-package-data.js +3 -2
  84. package/dist/external/npm-package-arg.js +3 -2
  85. package/dist/external/pacote.js +38 -41
  86. package/dist/external/picomatch.js +2 -1
  87. package/dist/external/semver.js +2 -1
  88. package/dist/external/spdx-correct.js +2 -1
  89. package/dist/external/spdx-expression-parse.js +2 -1
  90. package/dist/external/streaming-iterables.js +2 -1
  91. package/dist/external/validate-npm-package-name.js +2 -1
  92. package/dist/external/which.js +2 -1
  93. package/dist/external/yargs-parser.js +2 -1
  94. package/dist/external/yoctocolors-cjs.js +2 -1
  95. package/dist/external/zod.js +10 -9
  96. package/dist/fs.js +1 -1
  97. package/dist/functions.js +1 -1
  98. package/dist/git.js +1 -1
  99. package/dist/github.js +1 -1
  100. package/dist/globs.js +1 -1
  101. package/dist/http-request.js +1 -1
  102. package/dist/ipc.js +1 -1
  103. package/dist/json.js +1 -1
  104. package/dist/links/index.js +1 -1
  105. package/dist/logger.d.ts +29 -4
  106. package/dist/logger.js +34 -5
  107. package/dist/maintained-node-versions.js +1 -1
  108. package/dist/memoization.js +1 -1
  109. package/dist/objects.js +1 -1
  110. package/dist/packages/editable.js +1 -1
  111. package/dist/packages/exports.js +1 -1
  112. package/dist/packages/isolation.js +1 -1
  113. package/dist/packages/licenses.js +1 -1
  114. package/dist/packages/manifest.js +1 -1
  115. package/dist/packages/normalize.js +1 -1
  116. package/dist/packages/operations.js +1 -1
  117. package/dist/packages/paths.js +1 -1
  118. package/dist/packages/provenance.js +1 -1
  119. package/dist/packages/specs.js +1 -1
  120. package/dist/packages/validation.js +1 -1
  121. package/dist/packages.js +1 -1
  122. package/dist/path.js +1 -1
  123. package/dist/paths/rewire.js +1 -1
  124. package/dist/paths.js +1 -1
  125. package/dist/performance.js +1 -1
  126. package/dist/process-lock.js +1 -1
  127. package/dist/promise-queue.js +1 -1
  128. package/dist/promises.js +1 -1
  129. package/dist/regexps.js +1 -1
  130. package/dist/sea.js +1 -1
  131. package/dist/shadow.js +1 -1
  132. package/dist/signal-exit.js +1 -1
  133. package/dist/sorts.js +1 -1
  134. package/dist/spawn.js +1 -1
  135. package/dist/spinner.js +1 -1
  136. package/dist/ssri.js +1 -1
  137. package/dist/stdio/clear.js +1 -1
  138. package/dist/stdio/divider.js +1 -1
  139. package/dist/stdio/footer.js +1 -1
  140. package/dist/stdio/header.js +1 -1
  141. package/dist/stdio/mask.js +1 -1
  142. package/dist/stdio/progress.js +1 -1
  143. package/dist/stdio/prompts.js +1 -1
  144. package/dist/stdio/stderr.js +1 -1
  145. package/dist/stdio/stdout.js +1 -1
  146. package/dist/streams.js +1 -1
  147. package/dist/strings.js +1 -1
  148. package/dist/suppress-warnings.js +1 -1
  149. package/dist/tables.js +1 -1
  150. package/dist/temporary-executor.js +1 -1
  151. package/dist/themes/context.js +1 -1
  152. package/dist/themes/index.js +1 -1
  153. package/dist/themes/themes.js +1 -1
  154. package/dist/themes/types.js +1 -1
  155. package/dist/themes/utils.js +1 -1
  156. package/dist/types.js +1 -1
  157. package/dist/url.js +1 -1
  158. package/dist/utils/get-ipc.js +1 -1
  159. package/dist/validation/json-parser.js +1 -1
  160. package/dist/validation/types.js +1 -1
  161. package/dist/versions.js +1 -1
  162. package/dist/words.js +1 -1
  163. package/dist/zod.js +1 -1
  164. package/package.json +1 -1
  165. package/dist/abort.js.map +0 -7
  166. package/dist/agent.js.map +0 -7
  167. package/dist/ansi.js.map +0 -7
  168. package/dist/argv/flags.js.map +0 -7
  169. package/dist/argv/parse.js.map +0 -7
  170. package/dist/arrays.js.map +0 -7
  171. package/dist/bin.js.map +0 -7
  172. package/dist/cacache.js.map +0 -7
  173. package/dist/cache-with-ttl.js.map +0 -7
  174. package/dist/constants/agents.js.map +0 -7
  175. package/dist/constants/core.js.map +0 -7
  176. package/dist/constants/encoding.js.map +0 -7
  177. package/dist/constants/github.js.map +0 -7
  178. package/dist/constants/licenses.js.map +0 -7
  179. package/dist/constants/node.js.map +0 -7
  180. package/dist/constants/packages.js.map +0 -7
  181. package/dist/constants/paths.js.map +0 -7
  182. package/dist/constants/platform.js.map +0 -7
  183. package/dist/constants/process.js.map +0 -7
  184. package/dist/constants/socket.js.map +0 -7
  185. package/dist/constants/testing.js.map +0 -7
  186. package/dist/constants/time.js.map +0 -7
  187. package/dist/constants/typescript.js.map +0 -7
  188. package/dist/cover/code.js.map +0 -7
  189. package/dist/cover/formatters.js.map +0 -7
  190. package/dist/cover/type.js.map +0 -7
  191. package/dist/cover/types.js.map +0 -7
  192. package/dist/debug.js.map +0 -7
  193. package/dist/dlx-binary.js.map +0 -7
  194. package/dist/dlx-manifest.js.map +0 -7
  195. package/dist/dlx-package.js.map +0 -7
  196. package/dist/dlx.js.map +0 -7
  197. package/dist/effects/pulse-frames.js.map +0 -7
  198. package/dist/effects/text-shimmer.js.map +0 -7
  199. package/dist/effects/types.js.map +0 -7
  200. package/dist/effects/ultra.js.map +0 -7
  201. package/dist/env/ci.js.map +0 -7
  202. package/dist/env/debug.js.map +0 -7
  203. package/dist/env/github.js.map +0 -7
  204. package/dist/env/helpers.js.map +0 -7
  205. package/dist/env/home.js.map +0 -7
  206. package/dist/env/locale.js.map +0 -7
  207. package/dist/env/node-auth-token.js.map +0 -7
  208. package/dist/env/node-env.js.map +0 -7
  209. package/dist/env/npm.js.map +0 -7
  210. package/dist/env/package-manager.js.map +0 -7
  211. package/dist/env/path.js.map +0 -7
  212. package/dist/env/pre-commit.js.map +0 -7
  213. package/dist/env/rewire.js.map +0 -7
  214. package/dist/env/shell.js.map +0 -7
  215. package/dist/env/socket-cli-shadow.js.map +0 -7
  216. package/dist/env/socket-cli.js.map +0 -7
  217. package/dist/env/socket.js.map +0 -7
  218. package/dist/env/temp-dir.js.map +0 -7
  219. package/dist/env/term.js.map +0 -7
  220. package/dist/env/test.js.map +0 -7
  221. package/dist/env/windows.js.map +0 -7
  222. package/dist/env/xdg.js.map +0 -7
  223. package/dist/env.js.map +0 -7
  224. package/dist/external/@npmcli/package-json/index.js +0 -1
  225. package/dist/external/@socketregistry/is-unicode-supported.d.ts +0 -2
  226. package/dist/external/@socketregistry/yocto-spinner.d.ts +0 -12
  227. package/dist/external/@yarnpkg/extensions.d.ts +0 -4
  228. package/dist/external/cacache.d.ts +0 -86
  229. package/dist/external/debug.d.ts +0 -22
  230. package/dist/external/del.d.ts +0 -1
  231. package/dist/external/fast-sort.d.ts +0 -3
  232. package/dist/external/get-east-asian-width.d.ts +0 -5
  233. package/dist/external/libnpmexec.d.ts +0 -33
  234. package/dist/external/libnpmpack.d.ts +0 -2
  235. package/dist/external/make-fetch-happen.d.ts +0 -15
  236. package/dist/external/pacote.d.ts +0 -14
  237. package/dist/external/semver.d.ts +0 -2
  238. package/dist/external/yargs-parser.d.ts +0 -2
  239. package/dist/external/yoctocolors-cjs.d.ts +0 -52
  240. package/dist/external/zod.d.ts +0 -1
  241. package/dist/fs.js.map +0 -7
  242. package/dist/functions.js.map +0 -7
  243. package/dist/git.js.map +0 -7
  244. package/dist/github.js.map +0 -7
  245. package/dist/globs.js.map +0 -7
  246. package/dist/http-request.js.map +0 -7
  247. package/dist/ipc.js.map +0 -7
  248. package/dist/json.js.map +0 -7
  249. package/dist/links/index.js.map +0 -7
  250. package/dist/logger.js.map +0 -7
  251. package/dist/maintained-node-versions.js.map +0 -7
  252. package/dist/memoization.js.map +0 -7
  253. package/dist/objects.js.map +0 -7
  254. package/dist/packages/editable.js.map +0 -7
  255. package/dist/packages/exports.js.map +0 -7
  256. package/dist/packages/isolation.js.map +0 -7
  257. package/dist/packages/licenses.js.map +0 -7
  258. package/dist/packages/manifest.js.map +0 -7
  259. package/dist/packages/normalize.js.map +0 -7
  260. package/dist/packages/operations.js.map +0 -7
  261. package/dist/packages/paths.js.map +0 -7
  262. package/dist/packages/provenance.js.map +0 -7
  263. package/dist/packages/specs.js.map +0 -7
  264. package/dist/packages/validation.js.map +0 -7
  265. package/dist/packages.js.map +0 -7
  266. package/dist/path.js.map +0 -7
  267. package/dist/paths/rewire.js.map +0 -7
  268. package/dist/paths.js.map +0 -7
  269. package/dist/performance.js.map +0 -7
  270. package/dist/process-lock.js.map +0 -7
  271. package/dist/promise-queue.js.map +0 -7
  272. package/dist/promises.js.map +0 -7
  273. package/dist/regexps.js.map +0 -7
  274. package/dist/sea.js.map +0 -7
  275. package/dist/shadow.js.map +0 -7
  276. package/dist/signal-exit.js.map +0 -7
  277. package/dist/sorts.js.map +0 -7
  278. package/dist/spawn.js.map +0 -7
  279. package/dist/spinner.js.map +0 -7
  280. package/dist/ssri.js.map +0 -7
  281. package/dist/stdio/clear.js.map +0 -7
  282. package/dist/stdio/divider.js.map +0 -7
  283. package/dist/stdio/footer.js.map +0 -7
  284. package/dist/stdio/header.js.map +0 -7
  285. package/dist/stdio/mask.js.map +0 -7
  286. package/dist/stdio/progress.js.map +0 -7
  287. package/dist/stdio/prompts.js.map +0 -7
  288. package/dist/stdio/stderr.js.map +0 -7
  289. package/dist/stdio/stdout.js.map +0 -7
  290. package/dist/streams.js.map +0 -7
  291. package/dist/strings.js.map +0 -7
  292. package/dist/suppress-warnings.js.map +0 -7
  293. package/dist/tables.js.map +0 -7
  294. package/dist/temporary-executor.js.map +0 -7
  295. package/dist/themes/context.js.map +0 -7
  296. package/dist/themes/index.js.map +0 -7
  297. package/dist/themes/themes.js.map +0 -7
  298. package/dist/themes/types.js.map +0 -7
  299. package/dist/themes/utils.js.map +0 -7
  300. package/dist/types.js.map +0 -7
  301. package/dist/url.js.map +0 -7
  302. package/dist/utils/get-ipc.js.map +0 -7
  303. package/dist/validation/json-parser.js.map +0 -7
  304. package/dist/validation/types.js.map +0 -7
  305. package/dist/versions.js.map +0 -7
  306. package/dist/words.js.map +0 -7
  307. package/dist/zod.js.map +0 -7
package/dist/fs.js.map DELETED
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../src/fs.ts"],
4
- "sourcesContent": ["/**\n * @fileoverview File system utilities with cross-platform path handling.\n * Provides enhanced fs operations, glob matching, and directory traversal functions.\n */\n\nimport type { Abortable } from 'events'\n\nimport type {\n Dirent,\n MakeDirectoryOptions,\n ObjectEncodingOptions,\n OpenMode,\n PathLike,\n StatSyncOptions,\n WriteFileOptions,\n} from 'fs'\n\nimport { getAbortSignal } from '#constants/process'\n\nimport { isArray } from './arrays'\n\nconst abortSignal = getAbortSignal()\n\nimport { defaultIgnore, getGlobMatcher } from './globs'\nimport type { JsonReviver } from './json'\nimport { jsonParse } from './json'\nimport { objectFreeze, type Remap } from './objects'\nimport { normalizePath, pathLikeToString } from './path'\nimport { registerCacheInvalidation } from './paths/rewire'\nimport { naturalCompare } from './sorts'\n\n/**\n * Supported text encodings for Node.js Buffers.\n * Includes ASCII, UTF-8/16, base64, binary, and hexadecimal encodings.\n */\nexport type BufferEncoding =\n | 'ascii'\n | 'utf8'\n | 'utf-8'\n | 'utf16le'\n | 'ucs2'\n | 'ucs-2'\n | 'base64'\n | 'base64url'\n | 'latin1'\n | 'binary'\n | 'hex'\n\n/**\n * Represents any valid JSON content type.\n */\nexport type JsonContent = unknown\n\n/**\n * Options for asynchronous `findUp` operations.\n */\nexport interface FindUpOptions {\n /**\n * Starting directory for the search.\n * @default process.cwd()\n */\n cwd?: string | undefined\n /**\n * Only match directories, not files.\n * @default false\n */\n onlyDirectories?: boolean | undefined\n /**\n * Only match files, not directories.\n * @default true\n */\n onlyFiles?: boolean | undefined\n /**\n * Abort signal to cancel the search operation.\n */\n signal?: AbortSignal | undefined\n}\n\n/**\n * Options for synchronous `findUpSync` operations.\n */\nexport interface FindUpSyncOptions {\n /**\n * Starting directory for the search.\n * @default process.cwd()\n */\n cwd?: string | undefined\n /**\n * Directory to stop searching at (inclusive).\n * When provided, search will stop at this directory even if the root hasn't been reached.\n */\n stopAt?: string | undefined\n /**\n * Only match directories, not files.\n * @default false\n */\n onlyDirectories?: boolean | undefined\n /**\n * Only match files, not directories.\n * @default true\n */\n onlyFiles?: boolean | undefined\n}\n\n/**\n * Options for checking if a directory is empty.\n */\nexport interface IsDirEmptyOptions {\n /**\n * Glob patterns for files to ignore when checking emptiness.\n * Files matching these patterns are not counted.\n * @default defaultIgnore\n */\n ignore?: string[] | readonly string[] | undefined\n}\n\n/**\n * Options for read operations with abort support.\n */\nexport interface ReadOptions extends Abortable {\n /**\n * Character encoding to use for reading.\n * @default 'utf8'\n */\n encoding?: BufferEncoding | string | undefined\n /**\n * File system flag for reading behavior.\n * @default 'r'\n */\n flag?: string | undefined\n}\n\n/**\n * Options for reading directories with filtering and sorting.\n */\nexport interface ReadDirOptions {\n /**\n * Glob patterns for directories to ignore.\n * @default undefined\n */\n ignore?: string[] | readonly string[] | undefined\n /**\n * Include empty directories in results.\n * When `false`, empty directories are filtered out.\n * @default true\n */\n includeEmpty?: boolean | undefined\n /**\n * Sort directory names alphabetically using natural sort order.\n * @default true\n */\n sort?: boolean | undefined\n}\n\n/**\n * Options for reading files with encoding and abort support.\n * Can be either an options object, an encoding string, or null.\n */\nexport type ReadFileOptions =\n | Remap<\n ObjectEncodingOptions &\n Abortable & {\n flag?: OpenMode | undefined\n }\n >\n | BufferEncoding\n | null\n\n/**\n * Options for reading and parsing JSON files.\n */\nexport type ReadJsonOptions = Remap<\n ReadFileOptions & {\n /**\n * Whether to throw errors on parse failure.\n * When `false`, returns `undefined` on error instead of throwing.\n * @default true\n */\n throws?: boolean | undefined\n /**\n * JSON reviver function to transform parsed values.\n * Same as the second parameter to `JSON.parse()`.\n */\n reviver?: Parameters<typeof JSON.parse>[1] | undefined\n }\n>\n\n/**\n * Options for file/directory removal operations.\n */\nexport interface RemoveOptions {\n /**\n * Force deletion even outside normally safe directories.\n * When `false`, prevents deletion outside temp, cacache, and ~/.socket.\n * @default true for safe directories, false otherwise\n */\n force?: boolean | undefined\n /**\n * Maximum number of retry attempts on failure.\n * @default 3\n */\n maxRetries?: number | undefined\n /**\n * Recursively delete directories and contents.\n * @default true\n */\n recursive?: boolean | undefined\n /**\n * Delay in milliseconds between retry attempts.\n * @default 200\n */\n retryDelay?: number | undefined\n /**\n * Abort signal to cancel the operation.\n */\n signal?: AbortSignal | undefined\n}\n\n/**\n * Options for safe read operations that don't throw on errors.\n */\nexport interface SafeReadOptions extends ReadOptions {\n /**\n * Default value to return on read failure.\n * If not provided, `undefined` is returned on error.\n */\n defaultValue?: unknown | undefined\n}\n\n/**\n * Options for write operations with encoding and mode control.\n */\nexport interface WriteOptions extends Abortable {\n /**\n * Character encoding for writing.\n * @default 'utf8'\n */\n encoding?: BufferEncoding | string | undefined\n /**\n * File mode (permissions) to set.\n * Uses standard Unix permission bits (e.g., 0o644).\n * @default 0o666 (read/write for all, respecting umask)\n */\n mode?: number | undefined\n /**\n * File system flag for write behavior.\n * @default 'w' (create or truncate)\n */\n flag?: string | undefined\n}\n\n/**\n * Options for writing JSON files with formatting control.\n */\nexport interface WriteJsonOptions extends WriteOptions {\n /**\n * End-of-line sequence to use.\n * @default '\\n'\n * @example\n * ```ts\n * // Windows-style line endings\n * writeJson('data.json', data, { EOL: '\\r\\n' })\n * ```\n */\n EOL?: string | undefined\n /**\n * Whether to add a final newline at end of file.\n * @default true\n */\n finalEOL?: boolean | undefined\n /**\n * JSON replacer function to transform values during stringification.\n * Same as the second parameter to `JSON.stringify()`.\n */\n replacer?: JsonReviver | undefined\n /**\n * Number of spaces for indentation, or string to use for indentation.\n * @default 2\n * @example\n * ```ts\n * // Use tabs instead of spaces\n * writeJson('data.json', data, { spaces: '\\t' })\n *\n * // Use 4 spaces for indentation\n * writeJson('data.json', data, { spaces: 4 })\n * ```\n */\n spaces?: number | string | undefined\n}\n\nconst defaultRemoveOptions = objectFreeze({\n __proto__: null,\n force: true,\n maxRetries: 3,\n recursive: true,\n retryDelay: 200,\n})\n\nlet _fs: typeof import('fs') | undefined\n/**\n * Lazily load the fs module to avoid Webpack errors.\n * Uses non-'node:' prefixed require to prevent Webpack bundling issues.\n *\n * @returns The Node.js fs module\n * @private\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getFs() {\n if (_fs === undefined) {\n // Use non-'node:' prefixed require to avoid Webpack errors.\n _fs = /*@__PURE__*/ require('node:fs')\n }\n return _fs as typeof import('fs')\n}\n\nlet _path: typeof import('path') | undefined\n/**\n * Lazily load the path module to avoid Webpack errors.\n * Uses non-'node:' prefixed require to prevent Webpack bundling issues.\n *\n * @returns The Node.js path module\n * @private\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getPath() {\n if (_path === undefined) {\n // Use non-'node:' prefixed require to avoid Webpack errors.\n\n _path = /*@__PURE__*/ require('node:path')\n }\n return _path as typeof import('path')\n}\n\n/**\n * Process directory entries and filter for directories.\n * Filters entries to include only directories, optionally excluding empty ones.\n * Applies ignore patterns and natural sorting.\n *\n * @param dirents - Directory entries from readdir\n * @param dirname - Parent directory path\n * @param options - Filtering and sorting options\n * @returns Array of directory names, optionally sorted\n * @private\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction innerReadDirNames(\n dirents: Dirent[],\n dirname: string | undefined,\n options?: ReadDirOptions | undefined,\n): string[] {\n const {\n ignore,\n includeEmpty = true,\n sort = true,\n } = { __proto__: null, ...options } as ReadDirOptions\n const path = getPath()\n const names = dirents\n .filter(\n (d: Dirent) =>\n d.isDirectory() &&\n (includeEmpty ||\n !isDirEmptySync(path.join(dirname || d.parentPath, d.name), {\n ignore,\n })),\n )\n .map((d: Dirent) => d.name)\n return sort ? names.sort(naturalCompare) : names\n}\n\n/**\n * Stringify JSON with custom formatting options.\n * Formats JSON with configurable line endings and indentation.\n *\n * @param json - Value to stringify\n * @param EOL - End-of-line sequence\n * @param finalEOL - Whether to add final newline\n * @param replacer - JSON replacer function\n * @param spaces - Indentation spaces or string\n * @returns Formatted JSON string\n * @private\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction stringify(\n json: unknown,\n EOL: string,\n finalEOL: boolean,\n replacer: JsonReviver | undefined,\n spaces: number | string = 2,\n): string {\n const EOF = finalEOL ? EOL : ''\n const str = JSON.stringify(json, replacer, spaces)\n return `${str.replace(/\\n/g, EOL)}${EOF}`\n}\n\n/**\n * Find a file or directory by traversing up parent directories.\n * Searches from the starting directory upward to the filesystem root.\n * Useful for finding configuration files or project roots.\n *\n * @param name - Filename(s) to search for\n * @param options - Search options including cwd and type filters\n * @returns Normalized absolute path if found, undefined otherwise\n *\n * @example\n * ```ts\n * // Find package.json starting from current directory\n * const pkgPath = await findUp('package.json')\n *\n * // Find any of multiple config files\n * const configPath = await findUp(['.config.js', '.config.json'])\n *\n * // Find a directory instead of file\n * const nodeModules = await findUp('node_modules', { onlyDirectories: true })\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function findUp(\n name: string | string[] | readonly string[],\n options?: FindUpOptions | undefined,\n): Promise<string | undefined> {\n const { cwd = process.cwd(), signal = abortSignal } = {\n __proto__: null,\n ...options,\n } as FindUpOptions\n let { onlyDirectories = false, onlyFiles = true } = {\n __proto__: null,\n ...options,\n } as FindUpOptions\n if (onlyDirectories) {\n onlyFiles = false\n }\n if (onlyFiles) {\n onlyDirectories = false\n }\n const fs = getFs()\n const path = getPath()\n let dir = path.resolve(cwd)\n const { root } = path.parse(dir)\n const names = isArray(name) ? name : [name as string]\n while (dir && dir !== root) {\n for (const n of names) {\n if (signal?.aborted) {\n return undefined\n }\n const thePath = path.join(dir, n)\n try {\n // eslint-disable-next-line no-await-in-loop\n const stats = await fs.promises.stat(thePath)\n if (!onlyDirectories && stats.isFile()) {\n return normalizePath(thePath)\n }\n if (!onlyFiles && stats.isDirectory()) {\n return normalizePath(thePath)\n }\n } catch {}\n }\n dir = path.dirname(dir)\n }\n return undefined\n}\n\n/**\n * Synchronously find a file or directory by traversing up parent directories.\n * Searches from the starting directory upward to the filesystem root or `stopAt` directory.\n * Useful for finding configuration files or project roots in synchronous contexts.\n *\n * @param name - Filename(s) to search for\n * @param options - Search options including cwd, stopAt, and type filters\n * @returns Normalized absolute path if found, undefined otherwise\n *\n * @example\n * ```ts\n * // Find package.json starting from current directory\n * const pkgPath = findUpSync('package.json')\n *\n * // Find .git directory but stop at home directory\n * const gitPath = findUpSync('.git', {\n * onlyDirectories: true,\n * stopAt: process.env.HOME\n * })\n *\n * // Find any of multiple config files\n * const configPath = findUpSync(['.eslintrc.js', '.eslintrc.json'])\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function findUpSync(\n name: string | string[] | readonly string[],\n options?: FindUpSyncOptions | undefined,\n) {\n const { cwd = process.cwd(), stopAt } = {\n __proto__: null,\n ...options,\n } as FindUpSyncOptions\n let { onlyDirectories = false, onlyFiles = true } = {\n __proto__: null,\n ...options,\n } as FindUpSyncOptions\n if (onlyDirectories) {\n onlyFiles = false\n }\n if (onlyFiles) {\n onlyDirectories = false\n }\n const fs = getFs()\n const path = getPath()\n let dir = path.resolve(cwd)\n const { root } = path.parse(dir)\n const stopDir = stopAt ? path.resolve(stopAt) : undefined\n const names = isArray(name) ? name : [name as string]\n while (dir && dir !== root) {\n // Check if we should stop at this directory.\n if (stopDir && dir === stopDir) {\n // Check current directory but don't go up.\n for (const n of names) {\n const thePath = path.join(dir, n)\n try {\n const stats = fs.statSync(thePath)\n if (!onlyDirectories && stats.isFile()) {\n return normalizePath(thePath)\n }\n if (!onlyFiles && stats.isDirectory()) {\n return normalizePath(thePath)\n }\n } catch {}\n }\n return undefined\n }\n for (const n of names) {\n const thePath = path.join(dir, n)\n try {\n const stats = fs.statSync(thePath)\n if (!onlyDirectories && stats.isFile()) {\n return normalizePath(thePath)\n }\n if (!onlyFiles && stats.isDirectory()) {\n return normalizePath(thePath)\n }\n } catch {}\n }\n dir = path.dirname(dir)\n }\n return undefined\n}\n\n/**\n * Check if a path is a directory asynchronously.\n * Returns `true` for directories, `false` for files or non-existent paths.\n *\n * @param filepath - Path to check\n * @returns `true` if path is a directory, `false` otherwise\n *\n * @example\n * ```ts\n * if (await isDir('./src')) {\n * console.log('src is a directory')\n * }\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function isDir(filepath: PathLike) {\n return !!(await safeStats(filepath))?.isDirectory()\n}\n\n/**\n * Check if a path is a directory synchronously.\n * Returns `true` for directories, `false` for files or non-existent paths.\n *\n * @param filepath - Path to check\n * @returns `true` if path is a directory, `false` otherwise\n *\n * @example\n * ```ts\n * if (isDirSync('./src')) {\n * console.log('src is a directory')\n * }\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function isDirSync(filepath: PathLike) {\n return !!safeStatsSync(filepath)?.isDirectory()\n}\n\n/**\n * Check if a directory is empty synchronously.\n * A directory is considered empty if it contains no files after applying ignore patterns.\n * Uses glob patterns to filter ignored files.\n *\n * @param dirname - Directory path to check\n * @param options - Options including ignore patterns\n * @returns `true` if directory is empty (or doesn't exist), `false` otherwise\n *\n * @example\n * ```ts\n * // Check if directory is completely empty\n * isDirEmptySync('./build')\n *\n * // Check if directory is empty, ignoring .DS_Store files\n * isDirEmptySync('./cache', { ignore: ['.DS_Store'] })\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function isDirEmptySync(\n dirname: PathLike,\n options?: IsDirEmptyOptions | undefined,\n) {\n const { ignore = defaultIgnore } = {\n __proto__: null,\n ...options,\n } as IsDirEmptyOptions\n const fs = getFs()\n try {\n const files = fs.readdirSync(dirname)\n const { length } = files\n if (length === 0) {\n return true\n }\n const matcher = getGlobMatcher(\n ignore as string[],\n {\n cwd: pathLikeToString(dirname),\n } as { cwd?: string; dot?: boolean; ignore?: string[]; nocase?: boolean },\n )\n let ignoredCount = 0\n for (let i = 0; i < length; i += 1) {\n const file = files[i]\n if (file && matcher(file)) {\n ignoredCount += 1\n }\n }\n return ignoredCount === length\n } catch {\n // Return false for non-existent paths or other errors.\n return false\n }\n}\n\n/**\n * Check if a path is a symbolic link synchronously.\n * Uses `lstat` to check the link itself, not the target.\n *\n * @param filepath - Path to check\n * @returns `true` if path is a symbolic link, `false` otherwise\n *\n * @example\n * ```ts\n * if (isSymLinkSync('./my-link')) {\n * console.log('Path is a symbolic link')\n * }\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function isSymLinkSync(filepath: PathLike) {\n const fs = getFs()\n try {\n return fs.lstatSync(filepath).isSymbolicLink()\n } catch {}\n return false\n}\n\n/**\n * Result of file readability validation.\n * Contains lists of valid and invalid file paths.\n */\nexport interface ValidateFilesResult {\n /**\n * File paths that passed validation and are readable.\n */\n validPaths: string[]\n /**\n * File paths that failed validation (unreadable, permission denied, or non-existent).\n * Common with Yarn Berry PnP virtual filesystem, pnpm symlinks, or filesystem race conditions.\n */\n invalidPaths: string[]\n}\n\n/**\n * Validate that file paths are readable before processing.\n * Filters out files from glob results that cannot be accessed (common with\n * Yarn Berry PnP virtual filesystem, pnpm content-addressable store symlinks,\n * or filesystem race conditions in CI/CD environments).\n *\n * This defensive pattern prevents ENOENT errors when files exist in glob\n * results but are not accessible via standard filesystem operations.\n *\n * @param filepaths - Array of file paths to validate\n * @returns Object with `validPaths` (readable) and `invalidPaths` (unreadable)\n *\n * @example\n * ```ts\n * import { validateFiles } from '@socketsecurity/lib/fs'\n *\n * const files = ['package.json', '.pnp.cjs/virtual-file.json']\n * const { validPaths, invalidPaths } = validateFiles(files)\n *\n * console.log(`Valid: ${validPaths.length}`)\n * console.log(`Invalid: ${invalidPaths.length}`)\n * ```\n *\n * @example\n * ```ts\n * // Typical usage in Socket CLI commands\n * const packagePaths = await getPackageFilesForScan(targets)\n * const { validPaths } = validateFiles(packagePaths)\n * await sdk.uploadManifestFiles(orgSlug, validPaths)\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function validateFiles(\n filepaths: string[] | readonly string[],\n): ValidateFilesResult {\n const fs = getFs()\n const validPaths: string[] = []\n const invalidPaths: string[] = []\n const { R_OK } = fs.constants\n\n for (const filepath of filepaths) {\n try {\n fs.accessSync(filepath, R_OK)\n validPaths.push(filepath)\n } catch {\n invalidPaths.push(filepath)\n }\n }\n\n return { __proto__: null, validPaths, invalidPaths } as ValidateFilesResult\n}\n\n/**\n * Read directory names asynchronously with filtering and sorting.\n * Returns only directory names (not files), with optional filtering for empty directories\n * and glob-based ignore patterns. Results are naturally sorted by default.\n *\n * @param dirname - Directory path to read\n * @param options - Options for filtering and sorting\n * @returns Array of directory names, empty array on error\n *\n * @example\n * ```ts\n * // Get all subdirectories, sorted naturally\n * const dirs = await readDirNames('./packages')\n *\n * // Get non-empty directories only\n * const nonEmpty = await readDirNames('./cache', { includeEmpty: false })\n *\n * // Get directories without sorting\n * const unsorted = await readDirNames('./src', { sort: false })\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function readDirNames(\n dirname: PathLike,\n options?: ReadDirOptions | undefined,\n) {\n const fs = getFs()\n try {\n return innerReadDirNames(\n await fs.promises.readdir(dirname, {\n __proto__: null,\n encoding: 'utf8',\n withFileTypes: true,\n } as ObjectEncodingOptions & { withFileTypes: true }),\n String(dirname),\n options,\n )\n } catch {}\n return []\n}\n\n/**\n * Read directory names synchronously with filtering and sorting.\n * Returns only directory names (not files), with optional filtering for empty directories\n * and glob-based ignore patterns. Results are naturally sorted by default.\n *\n * @param dirname - Directory path to read\n * @param options - Options for filtering and sorting\n * @returns Array of directory names, empty array on error\n *\n * @example\n * ```ts\n * // Get all subdirectories, sorted naturally\n * const dirs = readDirNamesSync('./packages')\n *\n * // Get non-empty directories only, ignoring node_modules\n * const nonEmpty = readDirNamesSync('./src', {\n * includeEmpty: false,\n * ignore: ['node_modules']\n * })\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function readDirNamesSync(dirname: PathLike, options?: ReadDirOptions) {\n const fs = getFs()\n try {\n return innerReadDirNames(\n fs.readdirSync(dirname, {\n __proto__: null,\n encoding: 'utf8',\n withFileTypes: true,\n } as ObjectEncodingOptions & { withFileTypes: true }),\n String(dirname),\n options,\n )\n } catch {}\n return []\n}\n\n/**\n * Read a file as binary data asynchronously.\n * Returns a Buffer without encoding the contents.\n * Useful for reading images, archives, or other binary formats.\n *\n * @param filepath - Path to file\n * @param options - Read options (encoding is forced to null for binary)\n * @returns Promise resolving to Buffer containing file contents\n *\n * @example\n * ```ts\n * // Read an image file\n * const imageBuffer = await readFileBinary('./image.png')\n *\n * // Read with abort signal\n * const buffer = await readFileBinary('./data.bin', { signal: abortSignal })\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function readFileBinary(\n filepath: PathLike,\n options?: ReadFileOptions | undefined,\n) {\n // Don't specify encoding to get a Buffer.\n const opts = typeof options === 'string' ? { encoding: options } : options\n const fs = getFs()\n return await fs.promises.readFile(filepath, {\n signal: abortSignal,\n ...opts,\n encoding: null,\n })\n}\n\n/**\n * Read a file as UTF-8 text asynchronously.\n * Returns a string with the file contents decoded as UTF-8.\n * This is the most common way to read text files.\n *\n * @param filepath - Path to file\n * @param options - Read options including encoding and abort signal\n * @returns Promise resolving to string containing file contents\n *\n * @example\n * ```ts\n * // Read a text file\n * const content = await readFileUtf8('./README.md')\n *\n * // Read with custom encoding\n * const content = await readFileUtf8('./data.txt', { encoding: 'utf-8' })\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function readFileUtf8(\n filepath: PathLike,\n options?: ReadFileOptions | undefined,\n) {\n const opts = typeof options === 'string' ? { encoding: options } : options\n const fs = getFs()\n return await fs.promises.readFile(filepath, {\n signal: abortSignal,\n ...opts,\n encoding: 'utf8',\n })\n}\n\n/**\n * Read a file as binary data synchronously.\n * Returns a Buffer without encoding the contents.\n * Useful for reading images, archives, or other binary formats.\n *\n * @param filepath - Path to file\n * @param options - Read options (encoding is forced to null for binary)\n * @returns Buffer containing file contents\n *\n * @example\n * ```ts\n * // Read an image file\n * const imageBuffer = readFileBinarySync('./logo.png')\n *\n * // Read a compressed file\n * const gzipData = readFileBinarySync('./archive.gz')\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function readFileBinarySync(\n filepath: PathLike,\n options?: ReadFileOptions | undefined,\n) {\n // Don't specify encoding to get a Buffer\n const opts = typeof options === 'string' ? { encoding: options } : options\n const fs = getFs()\n return fs.readFileSync(filepath, {\n ...opts,\n encoding: null,\n } as ObjectEncodingOptions)\n}\n\n/**\n * Read a file as UTF-8 text synchronously.\n * Returns a string with the file contents decoded as UTF-8.\n * This is the most common way to read text files synchronously.\n *\n * @param filepath - Path to file\n * @param options - Read options including encoding\n * @returns String containing file contents\n *\n * @example\n * ```ts\n * // Read a configuration file\n * const config = readFileUtf8Sync('./config.txt')\n *\n * // Read with custom options\n * const data = readFileUtf8Sync('./data.txt', { encoding: 'utf8' })\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function readFileUtf8Sync(\n filepath: PathLike,\n options?: ReadFileOptions | undefined,\n) {\n const opts = typeof options === 'string' ? { encoding: options } : options\n const fs = getFs()\n return fs.readFileSync(filepath, {\n ...opts,\n encoding: 'utf8',\n } as ObjectEncodingOptions)\n}\n\n/**\n * Read and parse a JSON file asynchronously.\n * Reads the file as UTF-8 text and parses it as JSON.\n * Optionally accepts a reviver function to transform parsed values.\n *\n * @param filepath - Path to JSON file\n * @param options - Read and parse options\n * @returns Promise resolving to parsed JSON value, or undefined if throws is false and an error occurs\n *\n * @example\n * ```ts\n * // Read and parse package.json\n * const pkg = await readJson('./package.json')\n *\n * // Read JSON with custom reviver\n * const data = await readJson('./data.json', {\n * reviver: (key, value) => {\n * if (key === 'date') return new Date(value)\n * return value\n * }\n * })\n *\n * // Don't throw on parse errors\n * const config = await readJson('./config.json', { throws: false })\n * if (config === undefined) {\n * console.log('Failed to parse config')\n * }\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function readJson(\n filepath: PathLike,\n options?: ReadJsonOptions | string | undefined,\n) {\n const opts = typeof options === 'string' ? { encoding: options } : options\n const { reviver, throws, ...fsOptions } = {\n __proto__: null,\n ...opts,\n } as unknown as ReadJsonOptions\n const shouldThrow = throws === undefined || !!throws\n const fs = getFs()\n let content = ''\n try {\n content = await fs.promises.readFile(filepath, {\n __proto__: null,\n encoding: 'utf8',\n ...fsOptions,\n } as unknown as Parameters<typeof fs.promises.readFile>[1] & {\n encoding: string\n })\n } catch (e) {\n if (shouldThrow) {\n const code = (e as NodeJS.ErrnoException).code\n if (code === 'ENOENT') {\n throw new Error(\n `JSON file not found: ${filepath}\\n` +\n 'Ensure the file exists or create it with the expected structure.',\n { cause: e },\n )\n }\n if (code === 'EACCES' || code === 'EPERM') {\n throw new Error(\n `Permission denied reading JSON file: ${filepath}\\n` +\n 'Check file permissions or run with appropriate access.',\n { cause: e },\n )\n }\n throw e\n }\n return undefined\n }\n return jsonParse(content, {\n filepath: String(filepath),\n reviver,\n throws: shouldThrow,\n })\n}\n\n/**\n * Read and parse a JSON file synchronously.\n * Reads the file as UTF-8 text and parses it as JSON.\n * Optionally accepts a reviver function to transform parsed values.\n *\n * @param filepath - Path to JSON file\n * @param options - Read and parse options\n * @returns Parsed JSON value, or undefined if throws is false and an error occurs\n *\n * @example\n * ```ts\n * // Read and parse tsconfig.json\n * const tsconfig = readJsonSync('./tsconfig.json')\n *\n * // Read JSON with custom reviver\n * const data = readJsonSync('./data.json', {\n * reviver: (key, value) => {\n * if (typeof value === 'string' && /^\\d{4}-\\d{2}-\\d{2}/.test(value)) {\n * return new Date(value)\n * }\n * return value\n * }\n * })\n *\n * // Don't throw on parse errors\n * const config = readJsonSync('./config.json', { throws: false })\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function readJsonSync(\n filepath: PathLike,\n options?: ReadJsonOptions | string | undefined,\n) {\n const opts = typeof options === 'string' ? { encoding: options } : options\n const { reviver, throws, ...fsOptions } = {\n __proto__: null,\n ...opts,\n } as unknown as ReadJsonOptions\n const shouldThrow = throws === undefined || !!throws\n const fs = getFs()\n let content = ''\n try {\n content = fs.readFileSync(filepath, {\n __proto__: null,\n encoding: 'utf8',\n ...fsOptions,\n } as unknown as Parameters<typeof fs.readFileSync>[1] & {\n encoding: string\n })\n } catch (e) {\n if (shouldThrow) {\n const code = (e as NodeJS.ErrnoException).code\n if (code === 'ENOENT') {\n throw new Error(\n `JSON file not found: ${filepath}\\n` +\n 'Ensure the file exists or create it with the expected structure.',\n { cause: e },\n )\n }\n if (code === 'EACCES' || code === 'EPERM') {\n throw new Error(\n `Permission denied reading JSON file: ${filepath}\\n` +\n 'Check file permissions or run with appropriate access.',\n { cause: e },\n )\n }\n throw e\n }\n return undefined\n }\n return jsonParse(content, {\n filepath: String(filepath),\n reviver,\n throws: shouldThrow,\n })\n}\n\n// Cache for resolved allowed directories\nlet _cachedAllowedDirs: string[] | undefined\n\n/**\n * Get resolved allowed directories for safe deletion with lazy caching.\n * These directories are resolved once and cached for the process lifetime.\n */\nfunction getAllowedDirectories(): string[] {\n if (_cachedAllowedDirs === undefined) {\n const path = getPath()\n const {\n getOsTmpDir,\n getSocketCacacheDir,\n getSocketUserDir,\n } = /*@__PURE__*/ require('#lib/paths')\n\n _cachedAllowedDirs = [\n path.resolve(getOsTmpDir()),\n path.resolve(getSocketCacacheDir()),\n path.resolve(getSocketUserDir()),\n ]\n }\n return _cachedAllowedDirs\n}\n\n/**\n * Invalidate the cached allowed directories.\n * Called automatically by the paths/rewire module when paths are overridden in tests.\n *\n * @internal Used for test rewiring\n */\nexport function invalidatePathCache(): void {\n _cachedAllowedDirs = undefined\n}\n\n// Register cache invalidation with the rewire module\nregisterCacheInvalidation(invalidatePathCache)\n\n/**\n * Safely delete a file or directory asynchronously with built-in protections.\n * Uses `del` for safer deletion that prevents removing cwd and above by default.\n * Automatically uses force: true for temp directory, cacache, and ~/.socket subdirectories.\n *\n * @param filepath - Path or array of paths to delete (supports glob patterns)\n * @param options - Deletion options including force, retries, and recursion\n * @throws {Error} When attempting to delete protected paths without force option\n *\n * @example\n * ```ts\n * // Delete a single file\n * await safeDelete('./temp-file.txt')\n *\n * // Delete a directory recursively\n * await safeDelete('./build', { recursive: true })\n *\n * // Delete multiple paths\n * await safeDelete(['./dist', './coverage'])\n *\n * // Delete with custom retry settings\n * await safeDelete('./flaky-dir', { maxRetries: 5, retryDelay: 500 })\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function safeDelete(\n filepath: PathLike | PathLike[],\n options?: RemoveOptions | undefined,\n) {\n const del = /*@__PURE__*/ require('./external/del')\n const { deleteAsync } = del\n const opts = { __proto__: null, ...options } as RemoveOptions\n const patterns = isArray(filepath)\n ? filepath.map(pathLikeToString)\n : [pathLikeToString(filepath)]\n\n // Check if we're deleting within allowed directories.\n let shouldForce = opts.force !== false\n if (!shouldForce && patterns.length > 0) {\n const path = getPath()\n const allowedDirs = getAllowedDirectories()\n\n // Check if all patterns are within allowed directories.\n const allInAllowedDirs = patterns.every(pattern => {\n const resolvedPath = path.resolve(pattern)\n\n // Check each allowed directory\n for (const allowedDir of allowedDirs) {\n const isInAllowedDir =\n resolvedPath.startsWith(allowedDir + path.sep) ||\n resolvedPath === allowedDir\n const relativePath = path.relative(allowedDir, resolvedPath)\n const isGoingBackward = relativePath.startsWith('..')\n\n if (isInAllowedDir && !isGoingBackward) {\n return true\n }\n }\n\n return false\n })\n\n if (allInAllowedDirs) {\n shouldForce = true\n }\n }\n\n await deleteAsync(patterns, {\n concurrency: opts.maxRetries || defaultRemoveOptions.maxRetries,\n dryRun: false,\n force: shouldForce,\n onlyFiles: false,\n })\n}\n\n/**\n * Safely delete a file or directory synchronously with built-in protections.\n * Uses `del` for safer deletion that prevents removing cwd and above by default.\n * Automatically uses force: true for temp directory, cacache, and ~/.socket subdirectories.\n *\n * @param filepath - Path or array of paths to delete (supports glob patterns)\n * @param options - Deletion options including force, retries, and recursion\n * @throws {Error} When attempting to delete protected paths without force option\n *\n * @example\n * ```ts\n * // Delete a single file\n * safeDeleteSync('./temp-file.txt')\n *\n * // Delete a directory recursively\n * safeDeleteSync('./build', { recursive: true })\n *\n * // Delete multiple paths with globs\n * safeDeleteSync(['./dist/**', './coverage/**'])\n *\n * // Force delete a protected path (use with caution)\n * safeDeleteSync('./important', { force: true })\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function safeDeleteSync(\n filepath: PathLike | PathLike[],\n options?: RemoveOptions | undefined,\n) {\n const del = /*@__PURE__*/ require('./external/del')\n const { deleteSync } = del\n const opts = { __proto__: null, ...options } as RemoveOptions\n const patterns = isArray(filepath)\n ? filepath.map(pathLikeToString)\n : [pathLikeToString(filepath)]\n\n // Check if we're deleting within allowed directories.\n let shouldForce = opts.force !== false\n if (!shouldForce && patterns.length > 0) {\n const path = getPath()\n const allowedDirs = getAllowedDirectories()\n\n // Check if all patterns are within allowed directories.\n const allInAllowedDirs = patterns.every(pattern => {\n const resolvedPath = path.resolve(pattern)\n\n // Check each allowed directory\n for (const allowedDir of allowedDirs) {\n const isInAllowedDir =\n resolvedPath.startsWith(allowedDir + path.sep) ||\n resolvedPath === allowedDir\n const relativePath = path.relative(allowedDir, resolvedPath)\n const isGoingBackward = relativePath.startsWith('..')\n\n if (isInAllowedDir && !isGoingBackward) {\n return true\n }\n }\n\n return false\n })\n\n if (allInAllowedDirs) {\n shouldForce = true\n }\n }\n\n deleteSync(patterns, {\n concurrency: opts.maxRetries || defaultRemoveOptions.maxRetries,\n dryRun: false,\n force: shouldForce,\n onlyFiles: false,\n })\n}\n\n/**\n * Safely create a directory asynchronously, ignoring EEXIST errors.\n * This function wraps fs.promises.mkdir and handles the race condition where\n * the directory might already exist, which is common in concurrent code.\n *\n * Unlike fs.promises.mkdir with recursive:true, this function:\n * - Silently ignores EEXIST errors (directory already exists)\n * - Re-throws all other errors (permissions, invalid path, etc.)\n * - Works reliably in multi-process/concurrent scenarios\n * - Defaults to recursive: true for convenient nested directory creation\n *\n * @param path - Directory path to create\n * @param options - Options including recursive (default: true) and mode settings\n * @returns Promise that resolves when directory is created or already exists\n *\n * @example\n * ```ts\n * // Create a directory recursively by default, no error if it exists\n * await safeMkdir('./config')\n *\n * // Create nested directories (recursive: true is the default)\n * await safeMkdir('./data/cache/temp')\n *\n * // Create with specific permissions\n * await safeMkdir('./secure', { mode: 0o700 })\n *\n * // Explicitly disable recursive behavior\n * await safeMkdir('./single-level', { recursive: false })\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function safeMkdir(\n path: PathLike,\n options?: MakeDirectoryOptions | undefined,\n): Promise<void> {\n const fs = getFs()\n const opts = { __proto__: null, recursive: true, ...options }\n try {\n await fs.promises.mkdir(path, opts)\n } catch (e: unknown) {\n // Ignore EEXIST error - directory already exists.\n if (\n typeof e === 'object' &&\n e !== null &&\n 'code' in e &&\n e.code !== 'EEXIST'\n ) {\n throw e\n }\n }\n}\n\n/**\n * Safely create a directory synchronously, ignoring EEXIST errors.\n * This function wraps fs.mkdirSync and handles the race condition where\n * the directory might already exist, which is common in concurrent code.\n *\n * Unlike fs.mkdirSync with recursive:true, this function:\n * - Silently ignores EEXIST errors (directory already exists)\n * - Re-throws all other errors (permissions, invalid path, etc.)\n * - Works reliably in multi-process/concurrent scenarios\n * - Defaults to recursive: true for convenient nested directory creation\n *\n * @param path - Directory path to create\n * @param options - Options including recursive (default: true) and mode settings\n *\n * @example\n * ```ts\n * // Create a directory recursively by default, no error if it exists\n * safeMkdirSync('./config')\n *\n * // Create nested directories (recursive: true is the default)\n * safeMkdirSync('./data/cache/temp')\n *\n * // Create with specific permissions\n * safeMkdirSync('./secure', { mode: 0o700 })\n *\n * // Explicitly disable recursive behavior\n * safeMkdirSync('./single-level', { recursive: false })\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function safeMkdirSync(\n path: PathLike,\n options?: MakeDirectoryOptions | undefined,\n): void {\n const fs = getFs()\n const opts = { __proto__: null, recursive: true, ...options }\n try {\n fs.mkdirSync(path, opts)\n } catch (e: unknown) {\n // Ignore EEXIST error - directory already exists.\n if (\n typeof e === 'object' &&\n e !== null &&\n 'code' in e &&\n e.code !== 'EEXIST'\n ) {\n throw e\n }\n }\n}\n\n/**\n * Safely read a file asynchronously, returning undefined on error.\n * Useful when you want to attempt reading a file without handling errors explicitly.\n * Returns undefined for any error (file not found, permission denied, etc.).\n *\n * @param filepath - Path to file\n * @param options - Read options including encoding and default value\n * @returns Promise resolving to file contents, or undefined on error\n *\n * @example\n * ```ts\n * // Try to read a file, get undefined if it doesn't exist\n * const content = await safeReadFile('./optional-config.txt')\n * if (content) {\n * console.log('Config found:', content)\n * }\n *\n * // Read with specific encoding\n * const data = await safeReadFile('./data.txt', { encoding: 'utf8' })\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function safeReadFile(\n filepath: PathLike,\n options?: SafeReadOptions | undefined,\n) {\n const opts = typeof options === 'string' ? { encoding: options } : options\n const fs = getFs()\n try {\n return await fs.promises.readFile(filepath, {\n signal: abortSignal,\n ...opts,\n } as Abortable)\n } catch {}\n return undefined\n}\n\n/**\n * Safely read a file synchronously, returning undefined on error.\n * Useful when you want to attempt reading a file without handling errors explicitly.\n * Returns undefined for any error (file not found, permission denied, etc.).\n *\n * @param filepath - Path to file\n * @param options - Read options including encoding and default value\n * @returns File contents, or undefined on error\n *\n * @example\n * ```ts\n * // Try to read a config file\n * const config = safeReadFileSync('./config.txt')\n * if (config) {\n * console.log('Config loaded successfully')\n * }\n *\n * // Read binary file safely\n * const buffer = safeReadFileSync('./image.png', { encoding: null })\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function safeReadFileSync(\n filepath: PathLike,\n options?: SafeReadOptions | undefined,\n) {\n const opts = typeof options === 'string' ? { encoding: options } : options\n const fs = getFs()\n try {\n return fs.readFileSync(filepath, {\n __proto__: null,\n ...opts,\n } as ObjectEncodingOptions)\n } catch {}\n return undefined\n}\n\n/**\n * Safely get file stats asynchronously, returning undefined on error.\n * Useful for checking file existence and properties without error handling.\n * Returns undefined for any error (file not found, permission denied, etc.).\n *\n * @param filepath - Path to check\n * @returns Promise resolving to Stats object, or undefined on error\n *\n * @example\n * ```ts\n * // Check if file exists and get its stats\n * const stats = await safeStats('./file.txt')\n * if (stats) {\n * console.log('File size:', stats.size)\n * console.log('Modified:', stats.mtime)\n * }\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function safeStats(filepath: PathLike) {\n const fs = getFs()\n try {\n return await fs.promises.stat(filepath)\n } catch {}\n return undefined\n}\n\n/**\n * Safely get file stats synchronously, returning undefined on error.\n * Useful for checking file existence and properties without error handling.\n * Returns undefined for any error (file not found, permission denied, etc.).\n *\n * @param filepath - Path to check\n * @param options - Read options (currently unused but kept for API consistency)\n * @returns Stats object, or undefined on error\n *\n * @example\n * ```ts\n * // Check if file exists and get its size\n * const stats = safeStatsSync('./file.txt')\n * if (stats) {\n * console.log('File size:', stats.size)\n * console.log('Is directory:', stats.isDirectory())\n * }\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function safeStatsSync(\n filepath: PathLike,\n options?: ReadFileOptions | undefined,\n) {\n const opts = typeof options === 'string' ? { encoding: options } : options\n const fs = getFs()\n try {\n return fs.statSync(filepath, {\n __proto__: null,\n throwIfNoEntry: false,\n ...opts,\n } as StatSyncOptions)\n } catch {}\n return undefined\n}\n\n/**\n * Generate a unique filepath by adding number suffix if the path exists.\n * Appends `-1`, `-2`, etc. before the file extension until a non-existent path is found.\n * Useful for creating files without overwriting existing ones.\n *\n * @param filepath - Desired file path\n * @returns Normalized unique filepath (original if it doesn't exist, or with number suffix)\n *\n * @example\n * ```ts\n * // If 'report.pdf' exists, returns 'report-1.pdf'\n * const uniquePath = uniqueSync('./report.pdf')\n *\n * // If 'data.json' and 'data-1.json' exist, returns 'data-2.json'\n * const path = uniqueSync('./data.json')\n *\n * // If 'backup' doesn't exist, returns 'backup' unchanged\n * const backupPath = uniqueSync('./backup')\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function uniqueSync(filepath: PathLike): string {\n const fs = getFs()\n const path = getPath()\n const filepathStr = String(filepath)\n\n // If the file doesn't exist, return as is\n if (!fs.existsSync(filepathStr)) {\n return normalizePath(filepathStr)\n }\n\n const dirname = path.dirname(filepathStr)\n const ext = path.extname(filepathStr)\n const basename = path.basename(filepathStr, ext)\n\n let counter = 1\n let uniquePath: string\n do {\n uniquePath = path.join(dirname, `${basename}-${counter}${ext}`)\n counter++\n } while (fs.existsSync(uniquePath))\n\n return normalizePath(uniquePath)\n}\n\n/**\n * Write JSON content to a file asynchronously with formatting.\n * Stringifies the value with configurable indentation and line endings.\n * Automatically adds a final newline by default for POSIX compliance.\n *\n * @param filepath - Path to write to\n * @param jsonContent - Value to stringify and write\n * @param options - Write options including formatting and encoding\n * @returns Promise that resolves when write completes\n *\n * @example\n * ```ts\n * // Write formatted JSON with default 2-space indentation\n * await writeJson('./data.json', { name: 'example', version: '1.0.0' })\n *\n * // Write with custom indentation\n * await writeJson('./config.json', config, { spaces: 4 })\n *\n * // Write with tabs instead of spaces\n * await writeJson('./data.json', data, { spaces: '\\t' })\n *\n * // Write without final newline\n * await writeJson('./inline.json', obj, { finalEOL: false })\n *\n * // Write with Windows line endings\n * await writeJson('./win.json', data, { EOL: '\\r\\n' })\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport async function writeJson(\n filepath: PathLike,\n jsonContent: unknown,\n options?: WriteJsonOptions | string,\n): Promise<void> {\n const opts = typeof options === 'string' ? { encoding: options } : options\n const { EOL, finalEOL, replacer, spaces, ...fsOptions } = {\n __proto__: null,\n ...opts,\n } as WriteJsonOptions\n const fs = getFs()\n const jsonString = stringify(\n jsonContent,\n EOL || '\\n',\n finalEOL !== undefined ? finalEOL : true,\n replacer,\n spaces,\n )\n await fs.promises.writeFile(filepath, jsonString, {\n encoding: 'utf8',\n ...fsOptions,\n __proto__: null,\n } as ObjectEncodingOptions)\n}\n\n/**\n * Write JSON content to a file synchronously with formatting.\n * Stringifies the value with configurable indentation and line endings.\n * Automatically adds a final newline by default for POSIX compliance.\n *\n * @param filepath - Path to write to\n * @param jsonContent - Value to stringify and write\n * @param options - Write options including formatting and encoding\n *\n * @example\n * ```ts\n * // Write formatted JSON with default 2-space indentation\n * writeJsonSync('./package.json', pkg)\n *\n * // Write with custom indentation\n * writeJsonSync('./tsconfig.json', tsconfig, { spaces: 4 })\n *\n * // Write with tabs for indentation\n * writeJsonSync('./data.json', data, { spaces: '\\t' })\n *\n * // Write compacted (no indentation)\n * writeJsonSync('./compact.json', data, { spaces: 0 })\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function writeJsonSync(\n filepath: PathLike,\n jsonContent: unknown,\n options?: WriteJsonOptions | string | undefined,\n): void {\n const opts = typeof options === 'string' ? { encoding: options } : options\n const { EOL, finalEOL, replacer, spaces, ...fsOptions } = {\n __proto__: null,\n ...opts,\n }\n const fs = getFs()\n const jsonString = stringify(\n jsonContent,\n EOL || '\\n',\n finalEOL !== undefined ? finalEOL : true,\n replacer,\n spaces,\n )\n fs.writeFileSync(filepath, jsonString, {\n encoding: 'utf8',\n ...fsOptions,\n __proto__: null,\n } as WriteFileOptions)\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAiBA,qBAA+B;AAE/B,oBAAwB;AAIxB,mBAA8C;AAE9C,kBAA0B;AAC1B,qBAAyC;AACzC,kBAAgD;AAChD,oBAA0C;AAC1C,mBAA+B;AAR/B,MAAM,kBAAc,+BAAe;AA6QnC,MAAM,2BAAuB,6BAAa;AAAA,EACxC,WAAW;AAAA,EACX,OAAO;AAAA,EACP,YAAY;AAAA,EACZ,WAAW;AAAA,EACX,YAAY;AACd,CAAC;AAED,IAAI;AAAA;AASJ,SAAS,QAAQ;AACf,MAAI,QAAQ,QAAW;AAErB,UAAoB,QAAQ,SAAS;AAAA,EACvC;AACA,SAAO;AACT;AAEA,IAAI;AAAA;AASJ,SAAS,UAAU;AACjB,MAAI,UAAU,QAAW;AAGvB,YAAsB,QAAQ,WAAW;AAAA,EAC3C;AACA,SAAO;AACT;AAAA;AAcA,SAAS,kBACP,SACA,SACA,SACU;AACV,QAAM;AAAA,IACJ;AAAA,IACA,eAAe;AAAA,IACf,OAAO;AAAA,EACT,IAAI,EAAE,WAAW,MAAM,GAAG,QAAQ;AAClC,QAAM,OAAO,wBAAQ;AACrB,QAAM,QAAQ,QACX;AAAA,IACC,CAAC,MACC,EAAE,YAAY,MACb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O;AAAA,IACP,aAAa,SAAY,WAAW;AAAA,IACpC;AAAA,IACA;AAAA,EACF;AACA,KAAG,cAAc,UAAU,YAAY;AAAA,IACrC,UAAU;AAAA,IACV,GAAG;AAAA,IACH,WAAW;AAAA,EACb,CAAqB;AACvB;",
6
- "names": []
7
- }
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../src/functions.ts"],
4
- "sourcesContent": ["/**\n * @fileoverview Common function utilities for control flow and caching.\n * Provides noop, once, and other foundational function helpers.\n */\n\n// Type definitions\nexport type AsyncFunction<TArgs extends unknown[], TResult> = (\n ...args: TArgs\n) => Promise<TResult>\nexport type AnyFunction = (...args: unknown[]) => unknown\n\n/**\n * A no-op function that does nothing.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function noop(): void {}\n\n/**\n * Create a function that only executes once.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function once<T extends AnyFunction>(fn: T): T {\n let called = false\n let result: ReturnType<T>\n return function (\n this: ThisParameterType<T>,\n ...args: Parameters<T>\n ): ReturnType<T> {\n if (!called) {\n called = true\n result = fn.apply(this, args) as ReturnType<T>\n }\n return result as ReturnType<T>\n } as T\n}\n\n/**\n * Wrap an async function to silently catch and ignore errors.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function silentWrapAsync<TArgs extends unknown[], TResult>(\n fn: AsyncFunction<TArgs, TResult>,\n): (...args: TArgs) => Promise<TResult | undefined> {\n return async (...args: TArgs): Promise<TResult | undefined> => {\n try {\n const result = await fn(...args)\n return result === null ? undefined : result\n } catch {}\n return undefined\n }\n}\n\n/**\n * Execute a function with tail call optimization via trampoline.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function trampoline<T extends AnyFunction>(fn: T): T {\n return function (\n this: ThisParameterType<T>,\n ...args: Parameters<T>\n ): ReturnType<T> {\n let result: ReturnType<T> | (() => ReturnType<T>) = fn.apply(this, args) as\n | ReturnType<T>\n | (() => ReturnType<T>)\n while (typeof result === 'function') {\n result = (result as () => ReturnType<T> | (() => ReturnType<T>))() as\n | ReturnType<T>\n | (() => ReturnType<T>)\n }\n return result as ReturnType<T>\n } as T\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAeO,SAAS,OAAa;AAAC;AAAA;AAMvB,SAAS,KAA4B,IAAU;AACpD,MAAI,SAAS;AACb,MAAI;AACJ,SAAO,YAEF,MACY;AACf,QAAI,CAAC,QAAQ;AACX,eAAS;AACT,eAAS,GAAG,MAAM,MAAM,IAAI;AAAA,IAC9B;AACA,WAAO;AAAA,EACT;AACF;AAAA;AAMO,SAAS,gBACd,IACkD;AAClD,SAAO,UAAU,SAA8C;AAC7D,QAAI;AACF,YAAM,SAAS,MAAM,GAAG,GAAG,IAAI;AAC/B,aAAO,WAAW,OAAO,SAAY;AAAA,IACvC,QAAQ;AAAA,IAAC;AACT,WAAO;AAAA,EACT;AACF;AAAA;AAMO,SAAS,WAAkC,IAAU;AAC1D,SAAO,YAEF,MACY;AACf,QAAI,SAAgD,GAAG,MAAM,MAAM,IAAI;AAGvE,WAAO,OAAO,WAAW,YAAY;AACnC,eAAU,OAAuD;AAAA,IAGnE;AACA,WAAO;AAAA,EACT;AACF;",
6
- "names": []
7
- }
package/dist/git.js.map DELETED
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../src/git.ts"],
4
- "sourcesContent": ["import path from 'path'\n\nimport { WIN32 } from '#constants/platform'\nimport { debugNs } from './debug'\nimport { getGlobMatcher } from './globs'\nimport { normalizePath } from './path'\nimport { spawn, spawnSync } from './spawn'\nimport { stripAnsi } from './strings'\n\n/**\n * Options for git diff operations.\n *\n * Controls how git diff results are processed and returned.\n *\n * @example\n * ```typescript\n * // Get absolute file paths\n * const files = await getChangedFiles({ absolute: true })\n * // => ['/path/to/repo/src/file.ts']\n *\n * // Get relative paths with caching disabled\n * const files = await getChangedFiles({ cache: false })\n * // => ['src/file.ts']\n *\n * // Get files from specific directory\n * const files = await getChangedFiles({ cwd: '/path/to/repo/src' })\n * ```\n */\nexport interface GitDiffOptions {\n /**\n * Return absolute file paths instead of relative paths.\n *\n * @default false\n */\n absolute?: boolean | undefined\n /**\n * Cache git diff results to avoid repeated git subprocess calls.\n *\n * Caching is keyed by the git command and options used, so different\n * option combinations maintain separate cache entries.\n *\n * @default true\n */\n cache?: boolean | undefined\n /**\n * Working directory for git operations.\n *\n * Git operations will be run from this directory, and returned paths\n * will be relative to the git repository root. Symlinks are resolved\n * using `fs.realpathSync()`.\n *\n * @default process.cwd()\n */\n cwd?: string | undefined\n /**\n * Parse git porcelain format output (status codes like `M`, `A`, `??`).\n *\n * When `true`, strips the two-character status code and space from the\n * beginning of each line. Automatically enabled for `getChangedFiles()`.\n *\n * @default false\n */\n porcelain?: boolean | undefined\n /**\n * Return results as a `Set` instead of an array.\n *\n * @default false\n */\n asSet?: boolean | undefined\n /**\n * Additional options passed to glob matcher.\n *\n * Supports options like `dot`, `ignore`, `nocase` for filtering results.\n */\n [key: string]: unknown\n}\n\n/**\n * Options for filtering packages by git changes.\n *\n * Used to determine which packages in a monorepo have changed files.\n *\n * @example\n * ```typescript\n * // Filter packages with changes\n * const changed = filterPackagesByChanges(packages)\n *\n * // Force include all packages\n * const all = filterPackagesByChanges(packages, { force: true })\n *\n * // Use custom package key\n * const changed = filterPackagesByChanges(\n * packages,\n * { packageKey: 'directory' }\n * )\n * ```\n */\nexport interface FilterPackagesByChangesOptions {\n /**\n * Force include all packages regardless of changes.\n *\n * @default false\n */\n force?: boolean | undefined\n /**\n * Key to access package path in package objects.\n *\n * @default 'path'\n */\n packageKey?: string | undefined\n /**\n * Additional options for filtering.\n */\n [key: string]: unknown\n}\n\ntype SpawnArgs = [string, string[], Record<string, unknown>]\n\ninterface GitDiffSpawnArgs {\n all: SpawnArgs\n unstaged: SpawnArgs\n staged: SpawnArgs\n}\n\nconst gitDiffCache = new Map<string, string[]>()\n\nlet _fs: typeof import('fs') | undefined\n/**\n * Lazily load the `fs` module to avoid Webpack errors.\n *\n * Uses non-`node:` prefixed require internally to prevent Webpack from\n * attempting to bundle Node.js built-in modules.\n *\n * @returns The Node.js `fs` module.\n *\n * @example\n * ```typescript\n * const fs = getFs()\n * const exists = fs.existsSync('/path/to/file')\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getFs() {\n if (_fs === undefined) {\n // Use non-'node:' prefixed require to avoid Webpack errors.\n\n _fs = /*@__PURE__*/ require('node:fs')\n }\n return _fs as typeof import('fs')\n}\n\nlet _path: typeof import('path') | undefined\n/**\n * Lazily load the `path` module to avoid Webpack errors.\n *\n * Uses non-`node:` prefixed require internally to prevent Webpack from\n * attempting to bundle Node.js built-in modules.\n *\n * @returns The Node.js `path` module.\n *\n * @example\n * ```typescript\n * const path = getPath()\n * const joined = path.join('/foo', 'bar')\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getPath() {\n if (_path === undefined) {\n _path = /*@__PURE__*/ require('node:path')\n }\n return _path as typeof import('path')\n}\n\n/**\n * Get the git executable path.\n *\n * Currently always returns `'git'`, relying on the system PATH to resolve\n * the git binary location. This may be extended in the future to support\n * custom git paths.\n *\n * @returns The git executable name or path.\n *\n * @example\n * ```typescript\n * const git = getGitPath()\n * // => 'git'\n * ```\n */\nfunction getGitPath(): string {\n return 'git'\n}\n\n/**\n * Get the current working directory for git operations.\n *\n * Returns the real path to handle symlinks correctly. This is important\n * because symlinked directories like `/tmp -> /private/tmp` can cause\n * path mismatches when comparing git output.\n *\n * @returns The resolved real path of `process.cwd()`.\n *\n * @example\n * ```typescript\n * const cwd = getCwd()\n * // In /tmp (symlink to /private/tmp):\n * // => '/private/tmp'\n * ```\n */\nfunction getCwd(): string {\n return getFs().realpathSync(process.cwd())\n}\n\n/**\n * Get spawn arguments for different git diff operations.\n *\n * Prepares argument arrays for `spawn()`/`spawnSync()` calls that retrieve:\n * - `all`: All changed files (staged, unstaged, untracked) via `git status --porcelain`\n * - `unstaged`: Unstaged modifications via `git diff --name-only`\n * - `staged`: Staged changes via `git diff --cached --name-only`\n *\n * Automatically resolves symlinks in the provided `cwd` and enables shell\n * mode on Windows for proper command execution.\n *\n * @param cwd - Working directory for git operations, defaults to `process.cwd()`.\n * @returns Object containing spawn arguments for all, unstaged, and staged operations.\n */\nfunction getGitDiffSpawnArgs(cwd?: string | undefined): GitDiffSpawnArgs {\n const resolvedCwd = cwd ? getFs().realpathSync(cwd) : getCwd()\n return {\n all: [\n getGitPath(),\n ['status', '--porcelain'],\n {\n cwd: resolvedCwd,\n shell: WIN32,\n },\n ],\n unstaged: [\n getGitPath(),\n ['diff', '--name-only'],\n {\n cwd: resolvedCwd,\n },\n ],\n staged: [\n getGitPath(),\n ['diff', '--cached', '--name-only'],\n {\n cwd: resolvedCwd,\n shell: WIN32,\n },\n ],\n }\n}\n\n/**\n * Execute git diff command asynchronously and parse results.\n *\n * Internal helper for async git operations. Handles caching, command execution,\n * and result parsing. Returns empty array on git command failure.\n *\n * @param args - Spawn arguments tuple `[command, args, options]`.\n * @param options - Git diff options for caching and parsing.\n * @returns Promise resolving to array of file paths.\n */\nasync function innerDiff(\n args: SpawnArgs,\n options?: GitDiffOptions | undefined,\n): Promise<string[]> {\n const { cache = true, ...parseOptions } = { __proto__: null, ...options }\n const cacheKey = cache ? JSON.stringify({ args, parseOptions }) : undefined\n if (cache && cacheKey) {\n const result = gitDiffCache.get(cacheKey)\n if (result) {\n return result\n }\n }\n let result: string[]\n try {\n // Use stdioString: false to get raw Buffer, then convert ourselves to preserve exact output.\n const spawnResult = await spawn(args[0], args[1], {\n ...args[2],\n stdioString: false,\n })\n const stdout = Buffer.isBuffer(spawnResult.stdout)\n ? spawnResult.stdout.toString('utf8')\n : String(spawnResult.stdout)\n // Extract spawn cwd from args to pass to parser\n const spawnCwd =\n typeof args[2]['cwd'] === 'string' ? args[2]['cwd'] : undefined\n result = parseGitDiffStdout(stdout, parseOptions, spawnCwd)\n } catch (e) {\n // Git command failed. This is expected if:\n // - Not in a git repository\n // - Git is not installed\n // - Permission issues accessing .git directory\n // Log warning in debug mode for troubleshooting.\n debugNs(\n 'git',\n `Git command failed (${args[0]} ${args[1].join(' ')}): ${(e as Error).message}`,\n )\n return []\n }\n if (cache && cacheKey) {\n gitDiffCache.set(cacheKey, result)\n }\n return result\n}\n\n/**\n * Execute git diff command synchronously and parse results.\n *\n * Internal helper for sync git operations. Handles caching, command execution,\n * and result parsing. Returns empty array on git command failure.\n *\n * @param args - Spawn arguments tuple `[command, args, options]`.\n * @param options - Git diff options for caching and parsing.\n * @returns Array of file paths.\n */\nfunction innerDiffSync(\n args: SpawnArgs,\n options?: GitDiffOptions | undefined,\n): string[] {\n const { cache = true, ...parseOptions } = { __proto__: null, ...options }\n const cacheKey = cache ? JSON.stringify({ args, parseOptions }) : undefined\n if (cache && cacheKey) {\n const result = gitDiffCache.get(cacheKey)\n if (result) {\n return result\n }\n }\n let result: string[]\n try {\n // Use stdioString: false to get raw Buffer, then convert ourselves to preserve exact output.\n const spawnResult = spawnSync(args[0], args[1], {\n ...args[2],\n stdioString: false,\n })\n const stdout = Buffer.isBuffer(spawnResult.stdout)\n ? spawnResult.stdout.toString('utf8')\n : String(spawnResult.stdout)\n // Extract spawn cwd from args to pass to parser\n const spawnCwd =\n typeof args[2]['cwd'] === 'string' ? args[2]['cwd'] : undefined\n result = parseGitDiffStdout(stdout, parseOptions, spawnCwd)\n } catch (e) {\n // Git command failed. This is expected if:\n // - Not in a git repository\n // - Git is not installed\n // - Permission issues accessing .git directory\n // Log warning in debug mode for troubleshooting.\n debugNs(\n 'git',\n `Git command failed (${args[0]} ${args[1].join(' ')}): ${(e as Error).message}`,\n )\n return []\n }\n if (cache && cacheKey) {\n gitDiffCache.set(cacheKey, result)\n }\n return result\n}\n\n/**\n * Find git repository root by walking up from the given directory.\n *\n * Searches for a `.git` directory or file by traversing parent directories\n * upward until found or filesystem root is reached. Returns the original path\n * if no git repository is found.\n *\n * This function is exported primarily for testing purposes.\n *\n * @param startPath - Directory path to start searching from.\n * @returns Git repository root path, or `startPath` if not found.\n *\n * @example\n * ```typescript\n * const root = findGitRoot('/path/to/repo/src/subdir')\n * // => '/path/to/repo'\n *\n * const notFound = findGitRoot('/not/a/repo')\n * // => '/not/a/repo'\n * ```\n */\nexport function findGitRoot(startPath: string): string {\n const fs = getFs()\n const path = getPath()\n let currentPath = startPath\n // Walk up the directory tree looking for .git\n while (true) {\n try {\n const gitPath = path.join(currentPath, '.git')\n if (fs.existsSync(gitPath)) {\n return currentPath\n }\n } catch {\n // Ignore errors and continue walking up\n }\n const parentPath = path.dirname(currentPath)\n // Stop if we've reached the root or can't go up anymore\n if (parentPath === currentPath) {\n // Return original path if no .git found\n return startPath\n }\n currentPath = parentPath\n }\n}\n\n/**\n * Parse git diff stdout output into file path array.\n *\n * Internal helper that processes raw git command output by:\n * 1. Finding git repository root from spawn cwd\n * 2. Stripping ANSI codes and splitting into lines\n * 3. Parsing porcelain format status codes if requested\n * 4. Normalizing and optionally making paths absolute\n * 5. Filtering paths based on cwd and glob options\n *\n * Git always returns paths relative to the repository root, regardless of\n * where the command was executed. This function handles the path resolution\n * correctly by finding the repo root and adjusting paths accordingly.\n *\n * @param stdout - Raw stdout from git command.\n * @param options - Git diff options for path processing.\n * @param spawnCwd - Working directory where git command was executed.\n * @returns Array of processed file paths.\n */\nfunction parseGitDiffStdout(\n stdout: string,\n options?: GitDiffOptions | undefined,\n spawnCwd?: string | undefined,\n): string[] {\n // Find git repo root from spawnCwd. Git always returns paths relative to the repo root,\n // not the cwd where it was run. So we need to find the repo root to correctly parse paths.\n const defaultRoot = spawnCwd ? findGitRoot(spawnCwd) : getCwd()\n const {\n absolute = false,\n cwd: cwdOption = defaultRoot,\n porcelain = false,\n ...matcherOptions\n } = { __proto__: null, ...options }\n // Resolve cwd to handle symlinks.\n const cwd =\n cwdOption === defaultRoot ? defaultRoot : getFs().realpathSync(cwdOption)\n const rootPath = defaultRoot\n // Split into lines without trimming to preserve leading spaces in porcelain format.\n let rawFiles = stdout\n ? stripAnsi(stdout)\n .split('\\n')\n .map(line => line.trimEnd())\n .filter(line => line)\n : []\n // Parse porcelain format: strip status codes.\n // Git status --porcelain format is: XY filename\n // where X and Y are single characters and there's a space before the filename.\n if (porcelain) {\n rawFiles = rawFiles.map(line => {\n // Status is first 2 chars, then space, then filename.\n return line.length > 3 ? line.substring(3) : line\n })\n }\n const files = absolute\n ? rawFiles.map(relPath => normalizePath(path.join(rootPath, relPath)))\n : rawFiles.map(relPath => normalizePath(relPath))\n if (cwd === rootPath) {\n return files\n }\n const relPath = normalizePath(path.relative(rootPath, cwd))\n const matcher = getGlobMatcher([`${relPath}/**`], {\n ...(matcherOptions as {\n dot?: boolean\n ignore?: string[]\n nocase?: boolean\n }),\n absolute,\n cwd: rootPath,\n } as {\n absolute?: boolean\n cwd?: string\n dot?: boolean\n ignore?: string[]\n nocase?: boolean\n })\n const filtered: string[] = []\n for (const filepath of files) {\n if (matcher(filepath)) {\n filtered.push(filepath)\n }\n }\n return filtered\n}\n\n/**\n * Get all changed files including staged, unstaged, and untracked files.\n *\n * Uses `git status --porcelain` which returns the full working tree status\n * with status codes:\n * - `M` - Modified\n * - `A` - Added\n * - `D` - Deleted\n * - `??` - Untracked\n * - `R` - Renamed\n * - `C` - Copied\n *\n * This is the most comprehensive check - captures everything that differs\n * from the last commit, including:\n * - Files modified and staged with `git add`\n * - Files modified but not staged\n * - New files not yet tracked by git\n *\n * Status codes are automatically stripped from the output.\n *\n * @param options - Options controlling path format and filtering.\n * @returns Promise resolving to array of changed file paths.\n *\n * @example\n * ```typescript\n * // Get all changed files as relative paths\n * const files = await getChangedFiles()\n * // => ['src/foo.ts', 'src/bar.ts', 'newfile.ts']\n *\n * // Get absolute paths\n * const files = await getChangedFiles({ absolute: true })\n * // => ['/path/to/repo/src/foo.ts', ...]\n *\n * // Get changed files in specific directory\n * const files = await getChangedFiles({ cwd: '/path/to/repo/src' })\n * // => ['foo.ts', 'bar.ts']\n * ```\n */\nexport async function getChangedFiles(\n options?: GitDiffOptions | undefined,\n): Promise<string[]> {\n const args = getGitDiffSpawnArgs(options?.cwd).all\n return await innerDiff(args, {\n __proto__: null,\n ...options,\n porcelain: true,\n })\n}\n\n/**\n * Get all changed files including staged, unstaged, and untracked files.\n *\n * Synchronous version of `getChangedFiles()`. Uses `git status --porcelain`\n * which returns the full working tree status with status codes:\n * - `M` - Modified\n * - `A` - Added\n * - `D` - Deleted\n * - `??` - Untracked\n * - `R` - Renamed\n * - `C` - Copied\n *\n * This is the most comprehensive check - captures everything that differs\n * from the last commit, including:\n * - Files modified and staged with `git add`\n * - Files modified but not staged\n * - New files not yet tracked by git\n *\n * Status codes are automatically stripped from the output.\n *\n * @param options - Options controlling path format and filtering.\n * @returns Array of changed file paths.\n *\n * @example\n * ```typescript\n * // Get all changed files as relative paths\n * const files = getChangedFilesSync()\n * // => ['src/foo.ts', 'src/bar.ts', 'newfile.ts']\n *\n * // Get absolute paths\n * const files = getChangedFilesSync({ absolute: true })\n * // => ['/path/to/repo/src/foo.ts', ...]\n *\n * // Get changed files in specific directory\n * const files = getChangedFilesSync({ cwd: '/path/to/repo/src' })\n * // => ['foo.ts', 'bar.ts']\n * ```\n */\nexport function getChangedFilesSync(\n options?: GitDiffOptions | undefined,\n): string[] {\n const args = getGitDiffSpawnArgs(options?.cwd).all\n return innerDiffSync(args, {\n __proto__: null,\n ...options,\n porcelain: true,\n })\n}\n\n/**\n * Get unstaged modified files (changes not yet staged for commit).\n *\n * Uses `git diff --name-only` which returns only unstaged modifications\n * to tracked files. Does NOT include:\n * - Untracked files (new files not added to git)\n * - Staged changes (files added with `git add`)\n *\n * This is a focused check for uncommitted changes to existing tracked files.\n * Useful for detecting work-in-progress modifications before staging.\n *\n * @param options - Options controlling path format and filtering.\n * @returns Promise resolving to array of unstaged file paths.\n *\n * @example\n * ```typescript\n * // Get unstaged files\n * const files = await getUnstagedFiles()\n * // => ['src/foo.ts', 'src/bar.ts']\n *\n * // After staging some files\n * await spawn('git', ['add', 'src/foo.ts'])\n * const files = await getUnstagedFiles()\n * // => ['src/bar.ts'] (foo.ts no longer included)\n *\n * // Get absolute paths\n * const files = await getUnstagedFiles({ absolute: true })\n * // => ['/path/to/repo/src/bar.ts']\n * ```\n */\nexport async function getUnstagedFiles(\n options?: GitDiffOptions | undefined,\n): Promise<string[]> {\n const args = getGitDiffSpawnArgs(options?.cwd).unstaged\n return await innerDiff(args, options)\n}\n\n/**\n * Get unstaged modified files (changes not yet staged for commit).\n *\n * Synchronous version of `getUnstagedFiles()`. Uses `git diff --name-only`\n * which returns only unstaged modifications to tracked files. Does NOT include:\n * - Untracked files (new files not added to git)\n * - Staged changes (files added with `git add`)\n *\n * This is a focused check for uncommitted changes to existing tracked files.\n * Useful for detecting work-in-progress modifications before staging.\n *\n * @param options - Options controlling path format and filtering.\n * @returns Array of unstaged file paths.\n *\n * @example\n * ```typescript\n * // Get unstaged files\n * const files = getUnstagedFilesSync()\n * // => ['src/foo.ts', 'src/bar.ts']\n *\n * // After staging some files\n * spawnSync('git', ['add', 'src/foo.ts'])\n * const files = getUnstagedFilesSync()\n * // => ['src/bar.ts'] (foo.ts no longer included)\n *\n * // Get absolute paths\n * const files = getUnstagedFilesSync({ absolute: true })\n * // => ['/path/to/repo/src/bar.ts']\n * ```\n */\nexport function getUnstagedFilesSync(\n options?: GitDiffOptions | undefined,\n): string[] {\n const args = getGitDiffSpawnArgs(options?.cwd).unstaged\n return innerDiffSync(args, options)\n}\n\n/**\n * Get staged files ready for commit (changes added with `git add`).\n *\n * Uses `git diff --cached --name-only` which returns only staged changes.\n * Does NOT include:\n * - Unstaged modifications (changes not added with `git add`)\n * - Untracked files (new files not added to git)\n *\n * This is a focused check for what will be included in the next commit.\n * Useful for validating changes before committing or running pre-commit hooks.\n *\n * @param options - Options controlling path format and filtering.\n * @returns Promise resolving to array of staged file paths.\n *\n * @example\n * ```typescript\n * // Get currently staged files\n * const files = await getStagedFiles()\n * // => ['src/foo.ts']\n *\n * // Stage more files\n * await spawn('git', ['add', 'src/bar.ts'])\n * const files = await getStagedFiles()\n * // => ['src/foo.ts', 'src/bar.ts']\n *\n * // Get absolute paths\n * const files = await getStagedFiles({ absolute: true })\n * // => ['/path/to/repo/src/foo.ts', ...]\n * ```\n */\nexport async function getStagedFiles(\n options?: GitDiffOptions | undefined,\n): Promise<string[]> {\n const args = getGitDiffSpawnArgs(options?.cwd).staged\n return await innerDiff(args, options)\n}\n\n/**\n * Get staged files ready for commit (changes added with `git add`).\n *\n * Synchronous version of `getStagedFiles()`. Uses `git diff --cached --name-only`\n * which returns only staged changes. Does NOT include:\n * - Unstaged modifications (changes not added with `git add`)\n * - Untracked files (new files not added to git)\n *\n * This is a focused check for what will be included in the next commit.\n * Useful for validating changes before committing or running pre-commit hooks.\n *\n * @param options - Options controlling path format and filtering.\n * @returns Array of staged file paths.\n *\n * @example\n * ```typescript\n * // Get currently staged files\n * const files = getStagedFilesSync()\n * // => ['src/foo.ts']\n *\n * // Stage more files\n * spawnSync('git', ['add', 'src/bar.ts'])\n * const files = getStagedFilesSync()\n * // => ['src/foo.ts', 'src/bar.ts']\n *\n * // Get absolute paths\n * const files = getStagedFilesSync({ absolute: true })\n * // => ['/path/to/repo/src/foo.ts', ...]\n * ```\n */\nexport function getStagedFilesSync(\n options?: GitDiffOptions | undefined,\n): string[] {\n const args = getGitDiffSpawnArgs(options?.cwd).staged\n return innerDiffSync(args, options)\n}\n\n/**\n * Check if a file or directory has any git changes.\n *\n * Checks if the given pathname has any changes including:\n * - Staged modifications (added with `git add`)\n * - Unstaged modifications (not yet staged)\n * - Untracked status (new file/directory not in git)\n *\n * For directories, returns `true` if ANY file within the directory has changes.\n *\n * Symlinks in the pathname and cwd are automatically resolved using\n * `fs.realpathSync()` before comparison.\n *\n * @param pathname - File or directory path to check.\n * @param options - Options for the git status check.\n * @returns Promise resolving to `true` if path has any changes, `false` otherwise.\n *\n * @example\n * ```typescript\n * // Check if file is changed\n * const changed = await isChanged('src/foo.ts')\n * // => true\n *\n * // Check if directory has any changes\n * const changed = await isChanged('src/')\n * // => true (if any file in src/ is changed)\n *\n * // Check from different cwd\n * const changed = await isChanged(\n * '/path/to/repo/src/foo.ts',\n * { cwd: '/path/to/repo' }\n * )\n * ```\n */\nexport async function isChanged(\n pathname: string,\n options?: GitDiffOptions | undefined,\n): Promise<boolean> {\n const files = await getChangedFiles({\n __proto__: null,\n ...options,\n absolute: false,\n })\n // Resolve pathname to handle symlinks before computing relative path.\n const resolvedPathname = getFs().realpathSync(pathname)\n const baseCwd = options?.cwd ? getFs().realpathSync(options['cwd']) : getCwd()\n const relativePath = normalizePath(path.relative(baseCwd, resolvedPathname))\n return files.includes(relativePath)\n}\n\n/**\n * Check if a file or directory has any git changes.\n *\n * Synchronous version of `isChanged()`. Checks if the given pathname has\n * any changes including:\n * - Staged modifications (added with `git add`)\n * - Unstaged modifications (not yet staged)\n * - Untracked status (new file/directory not in git)\n *\n * For directories, returns `true` if ANY file within the directory has changes.\n *\n * Symlinks in the pathname and cwd are automatically resolved using\n * `fs.realpathSync()` before comparison.\n *\n * @param pathname - File or directory path to check.\n * @param options - Options for the git status check.\n * @returns `true` if path has any changes, `false` otherwise.\n *\n * @example\n * ```typescript\n * // Check if file is changed\n * const changed = isChangedSync('src/foo.ts')\n * // => true\n *\n * // Check if directory has any changes\n * const changed = isChangedSync('src/')\n * // => true (if any file in src/ is changed)\n *\n * // Check from different cwd\n * const changed = isChangedSync(\n * '/path/to/repo/src/foo.ts',\n * { cwd: '/path/to/repo' }\n * )\n * ```\n */\nexport function isChangedSync(\n pathname: string,\n options?: GitDiffOptions | undefined,\n): boolean {\n const files = getChangedFilesSync({\n __proto__: null,\n ...options,\n absolute: false,\n })\n // Resolve pathname to handle symlinks before computing relative path.\n const resolvedPathname = getFs().realpathSync(pathname)\n const baseCwd = options?.cwd ? getFs().realpathSync(options['cwd']) : getCwd()\n const relativePath = normalizePath(path.relative(baseCwd, resolvedPathname))\n return files.includes(relativePath)\n}\n\n/**\n * Check if a file or directory has unstaged changes.\n *\n * Checks if the given pathname has modifications that are not yet staged\n * for commit (changes not added with `git add`). Does NOT include:\n * - Staged changes (already added with `git add`)\n * - Untracked files (new files not in git)\n *\n * For directories, returns `true` if ANY file within the directory has\n * unstaged changes.\n *\n * Symlinks in the pathname and cwd are automatically resolved using\n * `fs.realpathSync()` before comparison.\n *\n * @param pathname - File or directory path to check.\n * @param options - Options for the git diff check.\n * @returns Promise resolving to `true` if path has unstaged changes, `false` otherwise.\n *\n * @example\n * ```typescript\n * // Check if file has unstaged changes\n * const unstaged = await isUnstaged('src/foo.ts')\n * // => true\n *\n * // After staging the file\n * await spawn('git', ['add', 'src/foo.ts'])\n * const unstaged = await isUnstaged('src/foo.ts')\n * // => false\n *\n * // Check directory\n * const unstaged = await isUnstaged('src/')\n * // => true (if any file in src/ has unstaged changes)\n * ```\n */\nexport async function isUnstaged(\n pathname: string,\n options?: GitDiffOptions | undefined,\n): Promise<boolean> {\n const files = await getUnstagedFiles({\n __proto__: null,\n ...options,\n absolute: false,\n })\n // Resolve pathname to handle symlinks before computing relative path.\n const resolvedPathname = getFs().realpathSync(pathname)\n const baseCwd = options?.cwd ? getFs().realpathSync(options['cwd']) : getCwd()\n const relativePath = normalizePath(path.relative(baseCwd, resolvedPathname))\n return files.includes(relativePath)\n}\n\n/**\n * Check if a file or directory has unstaged changes.\n *\n * Synchronous version of `isUnstaged()`. Checks if the given pathname has\n * modifications that are not yet staged for commit (changes not added with\n * `git add`). Does NOT include:\n * - Staged changes (already added with `git add`)\n * - Untracked files (new files not in git)\n *\n * For directories, returns `true` if ANY file within the directory has\n * unstaged changes.\n *\n * Symlinks in the pathname and cwd are automatically resolved using\n * `fs.realpathSync()` before comparison.\n *\n * @param pathname - File or directory path to check.\n * @param options - Options for the git diff check.\n * @returns `true` if path has unstaged changes, `false` otherwise.\n *\n * @example\n * ```typescript\n * // Check if file has unstaged changes\n * const unstaged = isUnstagedSync('src/foo.ts')\n * // => true\n *\n * // After staging the file\n * spawnSync('git', ['add', 'src/foo.ts'])\n * const unstaged = isUnstagedSync('src/foo.ts')\n * // => false\n *\n * // Check directory\n * const unstaged = isUnstagedSync('src/')\n * // => true (if any file in src/ has unstaged changes)\n * ```\n */\nexport function isUnstagedSync(\n pathname: string,\n options?: GitDiffOptions | undefined,\n): boolean {\n const files = getUnstagedFilesSync({\n __proto__: null,\n ...options,\n absolute: false,\n })\n // Resolve pathname to handle symlinks before computing relative path.\n const resolvedPathname = getFs().realpathSync(pathname)\n const baseCwd = options?.cwd ? getFs().realpathSync(options['cwd']) : getCwd()\n const relativePath = normalizePath(path.relative(baseCwd, resolvedPathname))\n return files.includes(relativePath)\n}\n\n/**\n * Check if a file or directory is staged for commit.\n *\n * Checks if the given pathname has changes staged with `git add` that will\n * be included in the next commit. Does NOT include:\n * - Unstaged modifications (changes not added with `git add`)\n * - Untracked files (new files not in git)\n *\n * For directories, returns `true` if ANY file within the directory is staged.\n *\n * Symlinks in the pathname and cwd are automatically resolved using\n * `fs.realpathSync()` before comparison.\n *\n * @param pathname - File or directory path to check.\n * @param options - Options for the git diff check.\n * @returns Promise resolving to `true` if path is staged, `false` otherwise.\n *\n * @example\n * ```typescript\n * // Check if file is staged\n * const staged = await isStaged('src/foo.ts')\n * // => false\n *\n * // Stage the file\n * await spawn('git', ['add', 'src/foo.ts'])\n * const staged = await isStaged('src/foo.ts')\n * // => true\n *\n * // Check directory\n * const staged = await isStaged('src/')\n * // => true (if any file in src/ is staged)\n * ```\n */\nexport async function isStaged(\n pathname: string,\n options?: GitDiffOptions | undefined,\n): Promise<boolean> {\n const files = await getStagedFiles({\n __proto__: null,\n ...options,\n absolute: false,\n })\n // Resolve pathname to handle symlinks before computing relative path.\n const resolvedPathname = getFs().realpathSync(pathname)\n const baseCwd = options?.cwd ? getFs().realpathSync(options['cwd']) : getCwd()\n const relativePath = normalizePath(path.relative(baseCwd, resolvedPathname))\n return files.includes(relativePath)\n}\n\n/**\n * Check if a file or directory is staged for commit.\n *\n * Synchronous version of `isStaged()`. Checks if the given pathname has\n * changes staged with `git add` that will be included in the next commit.\n * Does NOT include:\n * - Unstaged modifications (changes not added with `git add`)\n * - Untracked files (new files not in git)\n *\n * For directories, returns `true` if ANY file within the directory is staged.\n *\n * Symlinks in the pathname and cwd are automatically resolved using\n * `fs.realpathSync()` before comparison.\n *\n * @param pathname - File or directory path to check.\n * @param options - Options for the git diff check.\n * @returns `true` if path is staged, `false` otherwise.\n *\n * @example\n * ```typescript\n * // Check if file is staged\n * const staged = isStagedSync('src/foo.ts')\n * // => false\n *\n * // Stage the file\n * spawnSync('git', ['add', 'src/foo.ts'])\n * const staged = isStagedSync('src/foo.ts')\n * // => true\n *\n * // Check directory\n * const staged = isStagedSync('src/')\n * // => true (if any file in src/ is staged)\n * ```\n */\nexport function isStagedSync(\n pathname: string,\n options?: GitDiffOptions | undefined,\n): boolean {\n const files = getStagedFilesSync({\n __proto__: null,\n ...options,\n absolute: false,\n })\n // Resolve pathname to handle symlinks before computing relative path.\n const resolvedPathname = getFs().realpathSync(pathname)\n const baseCwd = options?.cwd ? getFs().realpathSync(options['cwd']) : getCwd()\n const relativePath = normalizePath(path.relative(baseCwd, resolvedPathname))\n return files.includes(relativePath)\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,kBAAiB;AAEjB,sBAAsB;AACtB,mBAAwB;AACxB,mBAA+B;AAC/B,IAAAA,eAA8B;AAC9B,mBAAiC;AACjC,qBAA0B;AAqH1B,MAAM,eAAe,oBAAI,IAAsB;AAE/C,IAAI;AAAA;AAgBJ,SAAS,QAAQ;AACf,MAAI,QAAQ,QAAW;AAGrB,UAAoB,QAAQ,SAAS;AAAA,EACvC;AACA,SAAO;AACT;AAEA,IAAI;AAAA;AAgBJ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AAI,OAAO;AAC7E,QAAM,mBAAe,4BAAc,YAAAA,QAAK,SAAS,SAAS,gBAAgB,CAAC;AAC3E,SAAO,MAAM,SAAS,YAAY;AACpC;AAmCA,eAAsB,SACpB,UACA,SACkB;AAClB,QAAM,QAAQ,MAAM,eAAe;AAAA,IACjC,WAAW;AAAA,IACX,GAAG;AAAA,IACH,UAAU;AAAA,EACZ,CAAC;AAED,QAAM,oBAAmB,sBAAM,GAAE,aAAa,QAAQ;AACtD,QAAM,UAAU,SAAS,OAAM,sBAAM,GAAE,aAAa,QAAQ,KAAK,CAAC,IAAI,OAAO;AAC7E,QAAM,mBAAe,4BAAc,YAAAA,QAAK,SAAS,SAAS,gBAAgB,CAAC;AAC3E,SAAO,MAAM,SAAS,YAAY;AACpC;AAoCO,SAAS,aACd,UACA,SACS;AACT,QAAM,QAAQ,mBAAmB;AAAA,IAC/B,WAAW;AAAA,IACX,GAAG;AAAA,IACH,UAAU;AAAA,EACZ,CAAC;AAED,QAAM,oBAAmB,sBAAM,GAAE,aAAa,QAAQ;AACtD,QAAM,UAAU,SAAS,OAAM,sBAAM,GAAE,aAAa,QAAQ,KAAK,CAAC,IAAI,OAAO;AAC7E,QAAM,mBAAe,4BAAc,YAAAA,QAAK,SAAS,SAAS,gBAAgB,CAAC;AAC3E,SAAO,MAAM,SAAS,YAAY;AACpC;",
6
- "names": ["import_path", "result", "path", "relPath"]
7
- }
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../src/github.ts"],
4
- "sourcesContent": ["/**\n * @fileoverview GitHub utilities for Socket projects.\n * Provides GitHub API integration for repository operations.\n *\n * Authentication:\n * - getGitHubToken: Retrieve GitHub token from environment variables\n * - fetchGitHub: Authenticated GitHub API requests with rate limit handling\n *\n * Ref Resolution:\n * - resolveRefToSha: Convert tags/branches to commit SHAs (with memoization and persistent cache)\n * - clearRefCache: Clear the in-memory memoization cache\n *\n * Caching:\n * - Uses cacache for persistent storage with in-memory memoization\n * - Two-tier caching: in-memory (Map) for hot data, persistent (cacache) for durability\n * - Default TTL: 5 minutes\n * - Disable with DISABLE_GITHUB_CACHE env var\n *\n * Rate Limiting:\n * - Automatic rate limit detection and error messages\n * - Cache to minimize API calls\n */\n\nimport type { TtlCache } from './cache-with-ttl'\nimport { createTtlCache } from './cache-with-ttl'\nimport { getGhToken, getGithubToken } from '#env/github'\nimport { getSocketCliGithubToken } from '#env/socket-cli'\nimport { httpRequest } from './http-request'\nimport type { SpawnOptions } from './spawn'\nimport { spawn } from './spawn'\n\n// GitHub API base URL constant (inlined for coverage mode compatibility).\nconst GITHUB_API_BASE_URL = 'https://api.github.com'\n\n// 5 minutes.\nconst DEFAULT_CACHE_TTL_MS = 5 * 60 * 1000\n\n// Create TTL cache instance for GitHub ref resolution.\n// Uses cacache for persistent storage with in-memory memoization.\nlet _githubCache: TtlCache | undefined\n\n/**\n * Get or create the GitHub cache instance.\n * Lazy initializes the cache with default TTL and memoization enabled.\n * Used internally for caching GitHub API responses.\n *\n * @returns The singleton cache instance\n */\nfunction getGithubCache(): TtlCache {\n if (_githubCache === undefined) {\n _githubCache = createTtlCache({\n memoize: true,\n prefix: 'github-refs',\n ttl: DEFAULT_CACHE_TTL_MS,\n })\n }\n return _githubCache\n}\n\n/**\n * Options for GitHub API fetch requests.\n */\nexport interface GitHubFetchOptions {\n /**\n * GitHub authentication token.\n * If not provided, will attempt to use token from environment variables.\n */\n token?: string | undefined\n /**\n * Additional HTTP headers to include in the request.\n * Will be merged with default headers (Accept, User-Agent, Authorization).\n */\n headers?: Record<string, string> | undefined\n}\n\n/**\n * Error thrown when GitHub API rate limit is exceeded.\n * Extends the standard Error with additional rate limit information.\n */\nexport interface GitHubRateLimitError extends Error {\n /** HTTP status code (always 403 for rate limit errors) */\n status: number\n /**\n * Date when the rate limit will reset.\n * Undefined if reset time is not available in response headers.\n */\n resetTime?: Date | undefined\n}\n\n/**\n * Get GitHub authentication token from environment variables.\n * Checks multiple environment variable names in priority order.\n *\n * Environment variables checked (in order):\n * 1. `GITHUB_TOKEN` - Standard GitHub token variable\n * 2. `GH_TOKEN` - Alternative GitHub CLI token variable\n * 3. `SOCKET_CLI_GITHUB_TOKEN` - Socket-specific token variable\n *\n * @returns The first available GitHub token, or `undefined` if none found\n *\n * @example\n * ```ts\n * const token = getGitHubToken()\n * if (!token) {\n * console.warn('No GitHub token found')\n * }\n * ```\n */\nexport function getGitHubToken(): string | undefined {\n return (\n getGithubToken() || getGhToken() || getSocketCliGithubToken() || undefined\n )\n}\n\n/**\n * Fetch data from GitHub API with automatic authentication and rate limit handling.\n * Makes authenticated requests to the GitHub REST API with proper error handling.\n *\n * Features:\n * - Automatic token injection from environment if not provided\n * - Rate limit detection with helpful error messages\n * - Standard GitHub API headers (Accept, User-Agent)\n * - JSON response parsing\n *\n * @template T - Expected response type (defaults to `unknown`)\n * @param url - Full GitHub API URL (e.g., 'https://api.github.com/repos/owner/repo')\n * @param options - Fetch options including token and custom headers\n * @returns Parsed JSON response of type `T`\n *\n * @throws {GitHubRateLimitError} When API rate limit is exceeded (status 403)\n * @throws {Error} For other API errors with status code and message\n *\n * @example\n * ```ts\n * // Fetch repository information\n * interface Repo {\n * name: string\n * full_name: string\n * default_branch: string\n * }\n * const repo = await fetchGitHub<Repo>(\n * 'https://api.github.com/repos/owner/repo'\n * )\n * console.log(`Default branch: ${repo.default_branch}`)\n * ```\n *\n * @example\n * ```ts\n * // With custom token and headers\n * const data = await fetchGitHub(\n * 'https://api.github.com/user',\n * {\n * token: 'ghp_customtoken',\n * headers: { 'X-Custom-Header': 'value' }\n * }\n * )\n * ```\n *\n * @example\n * ```ts\n * // Handle rate limit errors\n * try {\n * await fetchGitHub('https://api.github.com/repos/owner/repo')\n * } catch (error) {\n * if (error.status === 403 && error.resetTime) {\n * console.error(`Rate limited until ${error.resetTime}`)\n * }\n * }\n * ```\n */\nexport async function fetchGitHub<T = unknown>(\n url: string,\n options?: GitHubFetchOptions | undefined,\n): Promise<T> {\n const opts = { __proto__: null, ...options } as GitHubFetchOptions\n const token = opts.token || getGitHubToken()\n\n const headers: Record<string, string> = {\n Accept: 'application/vnd.github.v3+json',\n 'User-Agent': 'socket-registry-github-client',\n ...opts.headers,\n }\n\n if (token) {\n headers['Authorization'] = `Bearer ${token}`\n }\n\n const response = await httpRequest(url, { headers })\n\n if (!response.ok) {\n if (response.status === 403) {\n const rateLimit = response.headers['x-ratelimit-remaining']\n const rateLimitStr =\n typeof rateLimit === 'string' ? rateLimit : rateLimit?.[0]\n if (rateLimitStr === '0') {\n const resetTime = response.headers['x-ratelimit-reset']\n const resetTimeStr =\n typeof resetTime === 'string' ? resetTime : resetTime?.[0]\n const resetDate = resetTimeStr\n ? new Date(Number(resetTimeStr) * 1000)\n : undefined\n const error = new Error(\n `GitHub API rate limit exceeded${resetDate ? `. Resets at ${resetDate.toLocaleString()}` : ''}. Use GITHUB_TOKEN environment variable to increase rate limit.`,\n ) as GitHubRateLimitError\n error.status = 403\n error.resetTime = resetDate\n throw error\n }\n }\n throw new Error(\n `GitHub API error ${response.status}: ${response.statusText}`,\n )\n }\n\n return JSON.parse(response.body.toString('utf8')) as T\n}\n\n/**\n * GitHub ref object returned by the API.\n * Represents a git reference (tag or branch).\n */\nexport interface GitHubRef {\n /** The object this ref points to */\n object: {\n /** SHA of the commit or tag object */\n sha: string\n /** Type of object ('commit' or 'tag') */\n type: string\n /** API URL to fetch the full object details */\n url: string\n }\n /** Full ref path (e.g., 'refs/tags/v1.0.0' or 'refs/heads/main') */\n ref: string\n /** API URL for this ref */\n url: string\n}\n\n/**\n * GitHub annotated tag object returned by the API.\n * Represents a git tag with metadata.\n */\nexport interface GitHubTag {\n /** Tag annotation message */\n message: string\n /** The commit this tag points to */\n object: {\n /** SHA of the commit */\n sha: string\n /** Type of object (usually 'commit') */\n type: string\n /** API URL to fetch the commit details */\n url: string\n }\n /** SHA of this tag object itself */\n sha: string\n /** Tag name (e.g., 'v1.0.0') */\n tag: string\n /**\n * Information about who created the tag.\n * Undefined for lightweight tags.\n */\n tagger?: {\n /** Tag creation date in ISO 8601 format */\n date: string\n /** Tagger's email address */\n email: string\n /** Tagger's name */\n name: string\n }\n /** API URL for this tag object */\n url: string\n}\n\n/**\n * GitHub commit object returned by the API.\n * Represents a git commit with metadata.\n */\nexport interface GitHubCommit {\n /** Full commit SHA */\n sha: string\n /** API URL for this commit */\n url: string\n /** Commit details */\n commit: {\n /** Commit message */\n message: string\n /** Author information */\n author: {\n /** Commit author date in ISO 8601 format */\n date: string\n /** Author's email address */\n email: string\n /** Author's name */\n name: string\n }\n }\n}\n\n/**\n * Options for resolving git refs to commit SHAs.\n */\nexport interface ResolveRefOptions {\n /**\n * GitHub authentication token.\n * If not provided, will attempt to use token from environment variables.\n */\n token?: string | undefined\n}\n\n/**\n * Resolve a git ref (tag, branch, or commit SHA) to its full commit SHA.\n * Handles tags (annotated and lightweight), branches, and commit SHAs.\n * Results are cached in-memory and on disk (with TTL) to minimize API calls.\n *\n * Resolution strategy:\n * 1. Try as a tag (refs/tags/{ref})\n * 2. If tag is annotated, dereference to get the commit SHA\n * 3. If not a tag, try as a branch (refs/heads/{ref})\n * 4. If not a branch, try as a commit SHA directly\n *\n * Caching behavior:\n * - In-memory cache (Map) for immediate lookups\n * - Persistent disk cache (cacache) for durability across runs\n * - Default TTL: 5 minutes\n * - Disable caching with `DISABLE_GITHUB_CACHE` env var\n *\n * @param owner - Repository owner (user or organization name)\n * @param repo - Repository name\n * @param ref - Git reference to resolve (tag name, branch name, or commit SHA)\n * @param options - Resolution options including authentication token\n * @returns The full commit SHA (40-character hex string)\n *\n * @throws {Error} When ref cannot be resolved after trying all strategies\n * @throws {GitHubRateLimitError} When API rate limit is exceeded\n *\n * @example\n * ```ts\n * // Resolve a tag to commit SHA\n * const sha = await resolveRefToSha('owner', 'repo', 'v1.0.0')\n * console.log(sha) // 'a1b2c3d4e5f6...'\n * ```\n *\n * @example\n * ```ts\n * // Resolve a branch to latest commit SHA\n * const sha = await resolveRefToSha('owner', 'repo', 'main')\n * console.log(sha) // Latest commit on main branch\n * ```\n *\n * @example\n * ```ts\n * // Resolve with custom token\n * const sha = await resolveRefToSha(\n * 'owner',\n * 'repo',\n * 'develop',\n * { token: 'ghp_customtoken' }\n * )\n * ```\n *\n * @example\n * ```ts\n * // Commit SHA passes through unchanged (but validates it exists)\n * const sha = await resolveRefToSha('owner', 'repo', 'a1b2c3d4')\n * console.log(sha) // Full 40-char SHA\n * ```\n */\nexport async function resolveRefToSha(\n owner: string,\n repo: string,\n ref: string,\n options?: ResolveRefOptions | undefined,\n): Promise<string> {\n const opts = {\n __proto__: null,\n ...options,\n } as ResolveRefOptions\n\n const cacheKey = `${owner}/${repo}@${ref}`\n\n // Optionally disable cache.\n if (process.env['DISABLE_GITHUB_CACHE']) {\n return await fetchRefSha(owner, repo, ref, opts)\n }\n\n // Use TTL cache for persistent storage and in-memory memoization.\n const cache = getGithubCache()\n return await cache.getOrFetch(cacheKey, async () => {\n return await fetchRefSha(owner, repo, ref, opts)\n })\n}\n\n/**\n * Fetch the SHA for a git ref from GitHub API.\n * Internal helper that implements the multi-strategy ref resolution logic.\n * Tries tags, branches, and direct commit lookups in sequence.\n *\n * @param owner - Repository owner\n * @param repo - Repository name\n * @param ref - Git reference to resolve\n * @param options - Resolution options with authentication token\n * @returns The full commit SHA\n *\n * @throws {Error} When ref cannot be resolved after all strategies fail\n */\nasync function fetchRefSha(\n owner: string,\n repo: string,\n ref: string,\n options: ResolveRefOptions,\n): Promise<string> {\n const fetchOptions: GitHubFetchOptions = {\n token: options.token,\n }\n\n try {\n // Try as a tag first.\n const tagUrl = `${GITHUB_API_BASE_URL}/repos/${owner}/${repo}/git/refs/tags/${ref}`\n const tagData = await fetchGitHub<GitHubRef>(tagUrl, fetchOptions)\n\n // Tag might point to a tag object or directly to a commit.\n if (tagData.object.type === 'tag') {\n // Dereference the tag object to get the commit.\n const tagObject = await fetchGitHub<GitHubTag>(\n tagData.object.url,\n fetchOptions,\n )\n return tagObject.object.sha\n }\n return tagData.object.sha\n } catch {\n // Not a tag, try as a branch.\n try {\n const branchUrl = `${GITHUB_API_BASE_URL}/repos/${owner}/${repo}/git/refs/heads/${ref}`\n const branchData = await fetchGitHub<GitHubRef>(branchUrl, fetchOptions)\n return branchData.object.sha\n } catch {\n // Try without refs/ prefix (for commit SHAs or other refs).\n try {\n const commitUrl = `${GITHUB_API_BASE_URL}/repos/${owner}/${repo}/commits/${ref}`\n const commitData = await fetchGitHub<GitHubCommit>(\n commitUrl,\n fetchOptions,\n )\n return commitData.sha\n } catch (e) {\n throw new Error(\n `failed to resolve ref \"${ref}\" for ${owner}/${repo}: ${e instanceof Error ? e.message : String(e)}`,\n )\n }\n }\n }\n}\n\n/**\n * Clear the ref resolution cache (in-memory only).\n * Clears the in-memory memoization cache without affecting the persistent disk cache.\n * Useful for testing or when you need fresh data from the API.\n *\n * Note: This only clears the in-memory cache. The persistent cacache storage\n * remains intact and will be used to rebuild the in-memory cache on next access.\n *\n * @returns Promise that resolves when cache is cleared\n *\n * @example\n * ```ts\n * // Clear cache to force fresh API calls\n * await clearRefCache()\n * const sha = await resolveRefToSha('owner', 'repo', 'main')\n * // This will hit the persistent cache or API, not in-memory cache\n * ```\n */\nexport async function clearRefCache(): Promise<void> {\n if (_githubCache) {\n await _githubCache.clear({ memoOnly: true })\n }\n}\n\n/**\n * Get GitHub authentication token from git config.\n * Reads the `github.token` configuration value from git config.\n * This is a fallback method when environment variables don't contain a token.\n *\n * @param options - Spawn options for git command execution\n * @returns GitHub token from git config, or `undefined` if not configured\n *\n * @example\n * ```ts\n * const token = await getGitHubTokenFromGitConfig()\n * if (token) {\n * console.log('Found token in git config')\n * }\n * ```\n *\n * @example\n * ```ts\n * // With custom working directory\n * const token = await getGitHubTokenFromGitConfig({\n * cwd: '/path/to/repo'\n * })\n * ```\n */\nexport async function getGitHubTokenFromGitConfig(\n options?: SpawnOptions | undefined,\n): Promise<string | undefined> {\n try {\n const result = await spawn('git', ['config', 'github.token'], {\n ...options,\n stdio: 'pipe',\n })\n if (result.code === 0 && result.stdout) {\n return result.stdout.toString().trim()\n }\n } catch {\n // Ignore errors - git config may not have token.\n }\n return undefined\n}\n\n/**\n * Get GitHub authentication token from all available sources.\n * Checks environment variables first, then falls back to git config.\n * This is the recommended way to get a GitHub token with maximum compatibility.\n *\n * Priority order:\n * 1. Environment variables (GITHUB_TOKEN, GH_TOKEN, SOCKET_CLI_GITHUB_TOKEN)\n * 2. Git config (github.token)\n *\n * @returns GitHub token from first available source, or `undefined` if none found\n *\n * @example\n * ```ts\n * const token = await getGitHubTokenWithFallback()\n * if (!token) {\n * throw new Error('GitHub token required')\n * }\n * ```\n */\nexport async function getGitHubTokenWithFallback(): Promise<\n string | undefined\n> {\n return getGitHubToken() || (await getGitHubTokenFromGitConfig())\n}\n\n/**\n * GitHub Security Advisory (GHSA) details.\n * Represents a complete security advisory from GitHub's database.\n */\nexport interface GhsaDetails {\n /** GHSA identifier (e.g., 'GHSA-xxxx-yyyy-zzzz') */\n ghsaId: string\n /** Short summary of the vulnerability */\n summary: string\n /** Detailed description of the vulnerability */\n details: string\n /** Severity level ('low', 'moderate', 'high', 'critical') */\n severity: string\n /** Alternative identifiers (CVE IDs, etc.) */\n aliases: string[]\n /** ISO 8601 timestamp when advisory was published */\n publishedAt: string\n /** ISO 8601 timestamp when advisory was last updated */\n updatedAt: string\n /**\n * ISO 8601 timestamp when advisory was withdrawn.\n * `null` if advisory is still active.\n */\n withdrawnAt: string | null\n /** External reference URLs for more information */\n references: Array<{ url: string }>\n /** Affected packages and version ranges */\n vulnerabilities: Array<{\n /** Package information */\n package: {\n /** Ecosystem (e.g., 'npm', 'pip', 'maven') */\n ecosystem: string\n /** Package name */\n name: string\n }\n /** Version range expression for vulnerable versions */\n vulnerableVersionRange: string\n /**\n * First patched version that fixes the vulnerability.\n * `null` if no patched version exists yet.\n */\n firstPatchedVersion: { identifier: string } | null\n }>\n /**\n * CVSS (Common Vulnerability Scoring System) information.\n * `null` if CVSS score is not available.\n */\n cvss: {\n /** CVSS score (0.0-10.0) */\n score: number\n /** CVSS vector string describing the vulnerability characteristics */\n vectorString: string\n } | null\n /** CWE (Common Weakness Enumeration) categories */\n cwes: Array<{\n /** CWE identifier (e.g., 'CWE-79') */\n cweId: string\n /** Human-readable CWE name */\n name: string\n /** Description of the weakness category */\n description: string\n }>\n}\n\n/**\n * Generate GitHub Security Advisory URL from GHSA ID.\n * Constructs the public advisory URL for a given GHSA identifier.\n *\n * @param ghsaId - GHSA identifier (e.g., 'GHSA-xxxx-yyyy-zzzz')\n * @returns Full URL to the advisory page\n *\n * @example\n * ```ts\n * const url = getGhsaUrl('GHSA-1234-5678-90ab')\n * console.log(url) // 'https://github.com/advisories/GHSA-1234-5678-90ab'\n * ```\n */\nexport function getGhsaUrl(ghsaId: string): string {\n return `https://github.com/advisories/${ghsaId}`\n}\n\n/**\n * Fetch GitHub Security Advisory details from the API.\n * Retrieves complete advisory information including severity, affected packages,\n * CVSS scores, and CWE classifications.\n *\n * @param ghsaId - GHSA identifier to fetch (e.g., 'GHSA-xxxx-yyyy-zzzz')\n * @param options - Fetch options including authentication token\n * @returns Complete advisory details with normalized field names\n *\n * @throws {Error} If advisory cannot be found or API request fails\n * @throws {GitHubRateLimitError} When API rate limit is exceeded\n *\n * @example\n * ```ts\n * const advisory = await fetchGhsaDetails('GHSA-1234-5678-90ab')\n * console.log(`Severity: ${advisory.severity}`)\n * console.log(`Affects: ${advisory.vulnerabilities.length} packages`)\n * if (advisory.cvss) {\n * console.log(`CVSS Score: ${advisory.cvss.score}`)\n * }\n * ```\n *\n * @example\n * ```ts\n * // Check if vulnerability is patched\n * const advisory = await fetchGhsaDetails('GHSA-xxxx-yyyy-zzzz')\n * for (const vuln of advisory.vulnerabilities) {\n * if (vuln.firstPatchedVersion) {\n * console.log(\n * `Patched in ${vuln.package.name}@${vuln.firstPatchedVersion.identifier}`\n * )\n * }\n * }\n * ```\n */\nexport async function fetchGhsaDetails(\n ghsaId: string,\n options?: GitHubFetchOptions | undefined,\n): Promise<GhsaDetails> {\n const url = `https://api.github.com/advisories/${ghsaId}`\n const data = await fetchGitHub<{\n aliases?: string[]\n cvss: unknown\n cwes?: Array<{ cweId: string; name: string; description: string }>\n details: string\n ghsa_id: string\n published_at: string\n references?: Array<{ url: string }>\n severity: string\n summary: string\n updated_at: string\n vulnerabilities?: Array<{\n package: { ecosystem: string; name: string }\n vulnerableVersionRange: string\n firstPatchedVersion: { identifier: string } | null\n }>\n withdrawn_at: string\n }>(url, options)\n\n return {\n ghsaId: data.ghsa_id,\n summary: data.summary,\n details: data.details,\n severity: data.severity,\n aliases: data.aliases || [],\n publishedAt: data.published_at,\n updatedAt: data.updated_at,\n withdrawnAt: data.withdrawn_at,\n references: data.references || [],\n vulnerabilities: data.vulnerabilities || [],\n cvss: data.cvss as { score: number; vectorString: string } | null,\n cwes: data.cwes || [],\n }\n}\n\n/**\n * Fetch GitHub Security Advisory details with caching.\n * Retrieves advisory information with two-tier caching (in-memory + persistent).\n * Cached results are stored with the default TTL (5 minutes).\n *\n * Caching behavior:\n * - Checks in-memory cache first for immediate response\n * - Falls back to persistent disk cache if not in memory\n * - Fetches from API only if not cached\n * - Stores result in both cache tiers\n * - Respects `DISABLE_GITHUB_CACHE` env var\n *\n * @param ghsaId - GHSA identifier to fetch\n * @param options - Fetch options including authentication token\n * @returns Complete advisory details\n *\n * @throws {Error} If advisory cannot be found or API request fails\n * @throws {GitHubRateLimitError} When API rate limit is exceeded\n *\n * @example\n * ```ts\n * // First call hits API\n * const advisory = await cacheFetchGhsa('GHSA-1234-5678-90ab')\n *\n * // Second call within 5 minutes returns cached data\n * const cached = await cacheFetchGhsa('GHSA-1234-5678-90ab')\n * ```\n *\n * @example\n * ```ts\n * // Disable caching for fresh data\n * process.env.DISABLE_GITHUB_CACHE = '1'\n * const advisory = await cacheFetchGhsa('GHSA-xxxx-yyyy-zzzz')\n * ```\n */\nexport async function cacheFetchGhsa(\n ghsaId: string,\n options?: GitHubFetchOptions | undefined,\n): Promise<GhsaDetails> {\n const cache = getGithubCache()\n const key = `ghsa:${ghsaId}`\n\n // Check cache first.\n if (!process.env['DISABLE_GITHUB_CACHE']) {\n const cached = await cache.get(key)\n if (cached) {\n return JSON.parse(cached as string) as GhsaDetails\n }\n }\n\n // Fetch and cache.\n const data = await fetchGhsaDetails(ghsaId, options)\n await cache.set(key, JSON.stringify(data))\n return data\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAwBA,4BAA+B;AAC/B,oBAA2C;AAC3C,wBAAwC;AACxC,0BAA4B;AAE5B,mBAAsB;AAGtB,MAAM,sBAAsB;AAG5B,MAAM,uBAAuB,IAAI,KAAK;AAItC,IAAI;AASJ,SAAS,iBAA2B;AAClC,MAAI,iBAAiB,QAAW;AAC9B,uBAAe,sCAAe;AAAA,MAC5B,SAAS;AAAA,MACT,QAAQ;AAAA,MACR,KAAK;AAAA,IACP,CAAC;AAAA,EACH;AACA,SAAO;AACT;AAmDO,SAAS,iBAAqC;AACnD,aACE,8BAAe,SAAK,0BAAW,SAAK,2CAAwB,KAAK;AAErE;AA0DA,eAAsB,YACpB,KACA,SACY;AACZ,QAAM,OAAO,EAAE,WAAW,MAAM,GAAG,QAAQ;AAC3C,QAAM,QAAQ,KAAK,SAAS,eAAe;AAE3C,QAAM,UAAkC;AAAA,IACtC,QAAQ;AAAA,IACR,cAAc;AAAA,IACd,GAAG,KAAK;AAAA,EACV;AAEA,MAAI,OAAO;AACT,YAAQ,eAAe,IAAI,UAAU,KAAK;AAAA,EAC5C;AAEA,QAAM,WAAW,UAAM,iCAAY,KAAK,EAAE,QAAQ,CAAC;AAEnD,MAAI,CAAC,SAAS,IAAI;AAChB,QAAI,SAAS,WAAW,KAAK;AAC3B,YAAM,YAAY,SAAS,QAAQ,uBAAuB;AAC1D,YAAM,eACJ,OAAO,cAAc,WAAW,YAAY,YAAY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KAAK,OAAO;AAEf,SAAO;AAAA,IACL,QAAQ,KAAK;AAAA,IACb,SAAS,KAAK;AAAA,IACd,SAAS,KAAK;AAAA,IACd,UAAU,KAAK;AAAA,IACf,SAAS,KAAK,WAAW,CAAC;AAAA,IAC1B,aAAa,KAAK;AAAA,IAClB,WAAW,KAAK;AAAA,IAChB,aAAa,KAAK;AAAA,IAClB,YAAY,KAAK,cAAc,CAAC;AAAA,IAChC,iBAAiB,KAAK,mBAAmB,CAAC;AAAA,IAC1C,MAAM,KAAK;AAAA,IACX,MAAM,KAAK,QAAQ,CAAC;AAAA,EACtB;AACF;AAqCA,eAAsB,eACpB,QACA,SACsB;AACtB,QAAM,QAAQ,eAAe;AAC7B,QAAM,MAAM,QAAQ,MAAM;AAG1B,MAAI,CAAC,QAAQ,IAAI,sBAAsB,GAAG;AACxC,UAAM,SAAS,MAAM,MAAM,IAAI,GAAG;AAClC,QAAI,QAAQ;AACV,aAAO,KAAK,MAAM,MAAgB;AAAA,IACpC;AAAA,EACF;AAGA,QAAM,OAAO,MAAM,iBAAiB,QAAQ,OAAO;AACnD,QAAM,MAAM,IAAI,KAAK,KAAK,UAAU,IAAI,CAAC;AACzC,SAAO;AACT;",
6
- "names": []
7
- }
package/dist/globs.js.map DELETED
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../src/globs.ts"],
4
- "sourcesContent": ["/**\n * @fileoverview Glob pattern matching utilities with default ignore patterns.\n * Provides file filtering and glob matcher functions for npm-like behavior.\n */\n\n// IMPORTANT: Do not use destructuring here - use direct assignment instead.\nimport { objectFreeze as ObjectFreeze } from './objects'\n\n// Type definitions\ntype Pattern = string\n\ninterface FastGlobOptions {\n absolute?: boolean\n baseNameMatch?: boolean\n braceExpansion?: boolean\n caseSensitiveMatch?: boolean\n concurrency?: number\n cwd?: string\n deep?: number\n dot?: boolean\n extglob?: boolean\n followSymbolicLinks?: boolean\n fs?: unknown\n globstar?: boolean\n ignore?: string[]\n ignoreFiles?: string[]\n markDirectories?: boolean\n objectMode?: boolean\n onlyDirectories?: boolean\n onlyFiles?: boolean\n stats?: boolean\n suppressErrors?: boolean\n throwErrorOnBrokenSymbolicLink?: boolean\n unique?: boolean\n}\n\nexport interface GlobOptions extends FastGlobOptions {\n ignoreOriginals?: boolean\n recursive?: boolean\n}\n\nexport type { Pattern, FastGlobOptions }\n\nexport const defaultIgnore = ObjectFreeze([\n // Most of these ignored files can be included specifically if included in the\n // files globs. Exceptions to this are:\n // https://docs.npmjs.com/cli/v10/configuring-npm/package-json#files\n // These can NOT be included.\n // https://github.com/npm/npm-packlist/blob/v10.0.0/lib/index.js#L280\n '**/.git',\n '**/.npmrc',\n // '**/bun.lockb?',\n '**/node_modules',\n // '**/package-lock.json',\n // '**/pnpm-lock.ya?ml',\n // '**/yarn.lock',\n // Include npm-packlist defaults:\n // https://github.com/npm/npm-packlist/blob/v10.0.0/lib/index.js#L15-L38\n '**/.DS_Store',\n '**/.gitignore',\n '**/.hg',\n '**/.lock-wscript',\n '**/.npmignore',\n '**/.svn',\n '**/.wafpickle-*',\n '**/.*.swp',\n '**/._*/**',\n '**/archived-packages/**',\n '**/build/config.gypi',\n '**/CVS',\n '**/npm-debug.log',\n '**/*.orig',\n // Inline generic socket-registry .gitignore entries.\n '**/.env',\n '**/.eslintcache',\n '**/.nvm',\n '**/.tap',\n '**/.vscode',\n '**/*.tsbuildinfo',\n '**/Thumbs.db',\n // Inline additional ignores.\n '**/bower_components',\n])\n\nlet _picomatch: typeof import('picomatch') | undefined\n/**\n * Lazily load the picomatch module.\n * @private\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getPicomatch() {\n if (_picomatch === undefined) {\n // The 'picomatch' package is browser safe.\n _picomatch = /*@__PURE__*/ require('./external/picomatch')\n }\n return _picomatch as typeof import('picomatch')\n}\n\nlet _fastGlob: typeof import('fast-glob') | undefined\n/**\n * Lazily load the fast-glob module.\n * @private\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getFastGlob() {\n if (_fastGlob === undefined) {\n const globExport = /*@__PURE__*/ require('./external/fast-glob') as\n | (typeof import('fast-glob') & { default?: typeof import('fast-glob') })\n | typeof import('fast-glob')\n _fastGlob = (\n 'default' in globExport ? globExport.default : globExport\n ) as typeof import('fast-glob')\n }\n return _fastGlob as typeof import('fast-glob')\n}\n\n/**\n * Create a stream of license file paths matching glob patterns.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function globStreamLicenses(\n dirname: string,\n options?: GlobOptions,\n): NodeJS.ReadableStream {\n const {\n ignore: ignoreOpt,\n ignoreOriginals,\n recursive,\n ...globOptions\n } = { __proto__: null, ...options } as GlobOptions\n const ignore = [\n ...(Array.isArray(ignoreOpt) ? ignoreOpt : defaultIgnore),\n '**/*.{cjs,cts,js,json,mjs,mts,ts}',\n ]\n if (ignoreOriginals) {\n const { LICENSE_ORIGINAL_GLOB_RECURSIVE } =\n /*@__INLINE__*/ require('#constants/paths') as typeof import('#constants/paths')\n ignore.push(LICENSE_ORIGINAL_GLOB_RECURSIVE)\n }\n const fastGlob = getFastGlob()\n const paths =\n /*@__INLINE__*/ require('#constants/paths') as typeof import('#constants/paths')\n return fastGlob.globStream(\n [recursive ? paths.LICENSE_GLOB_RECURSIVE : paths.LICENSE_GLOB],\n {\n __proto__: null,\n absolute: true,\n caseSensitiveMatch: false,\n cwd: dirname,\n ...globOptions,\n ...(ignore ? { ignore } : {}),\n } as import('fast-glob').Options,\n )\n}\n\nconst matcherCache = new Map<string, (path: string) => boolean>()\n/**\n * Get a cached glob matcher function.\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function getGlobMatcher(\n glob: Pattern | Pattern[],\n options?: { dot?: boolean; nocase?: boolean; ignore?: string[] },\n): (path: string) => boolean {\n const patterns = Array.isArray(glob) ? glob : [glob]\n const key = JSON.stringify({ patterns, options })\n let matcher: ((path: string) => boolean) | undefined = matcherCache.get(key)\n if (matcher) {\n return matcher\n }\n\n // Separate positive and negative patterns.\n const positivePatterns = patterns.filter(p => !p.startsWith('!'))\n const negativePatterns = patterns\n .filter(p => p.startsWith('!'))\n .map(p => p.slice(1))\n\n const picomatch = getPicomatch()\n\n // Use ignore option for negation patterns.\n const matchOptions = {\n dot: true,\n nocase: true,\n ...options,\n ...(negativePatterns.length > 0 ? { ignore: negativePatterns } : {}),\n }\n\n matcher = picomatch(\n positivePatterns.length > 0 ? positivePatterns : patterns,\n matchOptions,\n ) as (path: string) => boolean\n\n matcherCache.set(key, matcher)\n return matcher\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAMA,qBAA6C;AAqCtC,MAAM,oBAAgB,eAAAA,cAAa;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMxC;AAAA,EACA;AAAA;AAAA,EAEA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AACF,CAAC;AAED,IAAI;AAAA;AAMJ,SAAS,eAAe;AACtB,MAAI,eAAe,QAAW;AAE5B,iBAA2B,QAAQ,sBAAsB;AAAA,EAC3D;AACA,SAAO;AACT;AAEA,IAAI;AAAA;AAMJ,SAAS,cAAc;AACrB,MAAI,cAAc,QAAW;AAC3B,UAAM,aAA2B,QAAQ,sBAAsB;AAG/D,gBACE,aAAa,aAAa,WAAW,UAAU;AAAA,EAEnD;AACA,SAAO;AACT;AAAA;AAMO,SAAS,mBACd,SACA,SACuB;AACvB,QAAM;AAAA,IACJ,QAAQ;AAAA,IACR;AAAA,IACA;AAAA,IACA,GAAG;AAAA,EACL,IAAI,EAAE,WAAW,MAAM,GAAG,Q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A,EACF;AAEA,eAAa,IAAI,KAAK,OAAO;AAC7B,SAAO;AACT;",
6
- "names": ["ObjectFreeze"]
7
- }
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../src/http-request.ts"],
4
- "sourcesContent": ["/**\n * @fileoverview HTTP/HTTPS request utilities using Node.js built-in modules with retry logic, redirects, and download support.\n *\n * This module provides a fetch-like API built on top of Node.js native `http` and `https` modules.\n * It supports automatic retries with exponential backoff, redirect following, streaming downloads,\n * and provides a familiar fetch-style response interface.\n *\n * Key Features:\n * - Automatic retries with exponential backoff for failed requests.\n * - Redirect following with configurable max redirects.\n * - Streaming downloads with progress callbacks.\n * - Fetch-like response interface (`.json()`, `.text()`, `.arrayBuffer()`).\n * - Timeout support for all operations.\n * - Zero dependencies on external HTTP libraries.\n */\n\nimport { createWriteStream } from 'fs'\n\nimport type { IncomingMessage } from 'http'\n\nlet _http: typeof import('http') | undefined\nlet _https: typeof import('https') | undefined\n/**\n * Lazily load http and https modules to avoid Webpack errors.\n * @private\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction getHttp() {\n if (_http === undefined) {\n // Use non-'node:' prefixed require to avoid Webpack errors.\n\n _http = /*@__PURE__*/ require('node:http')\n }\n return _http as typeof import('http')\n}\n\n/*@__NO_SIDE_EFFECTS__*/\nfunction getHttps() {\n if (_https === undefined) {\n // Use non-'node:' prefixed require to avoid Webpack errors.\n\n _https = /*@__PURE__*/ require('node:https')\n }\n return _https as typeof import('https')\n}\n\n/**\n * Configuration options for HTTP/HTTPS requests.\n */\nexport interface HttpRequestOptions {\n /**\n * Request body to send.\n * Can be a string (e.g., JSON) or Buffer (e.g., binary data).\n *\n * @example\n * ```ts\n * // Send JSON data\n * await httpRequest('https://api.example.com/data', {\n * method: 'POST',\n * body: JSON.stringify({ name: 'Alice' }),\n * headers: { 'Content-Type': 'application/json' }\n * })\n *\n * // Send binary data\n * const buffer = Buffer.from([0x00, 0x01, 0x02])\n * await httpRequest('https://api.example.com/upload', {\n * method: 'POST',\n * body: buffer\n * })\n * ```\n */\n body?: Buffer | string | undefined\n /**\n * Whether to automatically follow HTTP redirects (3xx status codes).\n *\n * @default true\n *\n * @example\n * ```ts\n * // Follow redirects (default)\n * await httpRequest('https://example.com/redirect')\n *\n * // Don't follow redirects\n * const response = await httpRequest('https://example.com/redirect', {\n * followRedirects: false\n * })\n * console.log(response.status) // 301 or 302\n * ```\n */\n followRedirects?: boolean | undefined\n /**\n * HTTP headers to send with the request.\n * A `User-Agent` header is automatically added if not provided.\n *\n * @example\n * ```ts\n * await httpRequest('https://api.example.com/data', {\n * headers: {\n * 'Authorization': 'Bearer token123',\n * 'Content-Type': 'application/json',\n * 'Accept': 'application/json'\n * }\n * })\n * ```\n */\n headers?: Record<string, string> | undefined\n /**\n * Maximum number of redirects to follow before throwing an error.\n * Only relevant when `followRedirects` is `true`.\n *\n * @default 5\n *\n * @example\n * ```ts\n * // Allow up to 10 redirects\n * await httpRequest('https://example.com/many-redirects', {\n * maxRedirects: 10\n * })\n * ```\n */\n maxRedirects?: number | undefined\n /**\n * HTTP method to use for the request.\n *\n * @default 'GET'\n *\n * @example\n * ```ts\n * // GET request (default)\n * await httpRequest('https://api.example.com/data')\n *\n * // POST request\n * await httpRequest('https://api.example.com/data', {\n * method: 'POST',\n * body: JSON.stringify({ name: 'Alice' })\n * })\n *\n * // DELETE request\n * await httpRequest('https://api.example.com/data/123', {\n * method: 'DELETE'\n * })\n * ```\n */\n method?: string | undefined\n /**\n * Number of retry attempts for failed requests.\n * Uses exponential backoff: delay = `retryDelay` * 2^attempt.\n *\n * @default 0\n *\n * @example\n * ```ts\n * // Retry up to 3 times with exponential backoff\n * await httpRequest('https://api.example.com/data', {\n * retries: 3,\n * retryDelay: 1000 // 1s, then 2s, then 4s\n * })\n * ```\n */\n retries?: number | undefined\n /**\n * Initial delay in milliseconds before first retry.\n * Subsequent retries use exponential backoff.\n *\n * @default 1000\n *\n * @example\n * ```ts\n * // Start with 2 second delay, then 4s, 8s, etc.\n * await httpRequest('https://api.example.com/data', {\n * retries: 3,\n * retryDelay: 2000\n * })\n * ```\n */\n retryDelay?: number | undefined\n /**\n * Request timeout in milliseconds.\n * If the request takes longer than this, it will be aborted.\n *\n * @default 30000\n *\n * @example\n * ```ts\n * // 60 second timeout\n * await httpRequest('https://api.example.com/slow-endpoint', {\n * timeout: 60000\n * })\n * ```\n */\n timeout?: number | undefined\n}\n\n/**\n * HTTP response object with fetch-like interface.\n * Provides multiple ways to access the response body.\n */\nexport interface HttpResponse {\n /**\n * Get response body as ArrayBuffer.\n * Useful for binary data or when you need compatibility with browser APIs.\n *\n * @returns The response body as an ArrayBuffer\n *\n * @example\n * ```ts\n * const response = await httpRequest('https://example.com/image.png')\n * const arrayBuffer = response.arrayBuffer()\n * console.log(arrayBuffer.byteLength)\n * ```\n */\n arrayBuffer(): ArrayBuffer\n /**\n * Raw response body as Buffer.\n * Direct access to the underlying Node.js Buffer.\n *\n * @example\n * ```ts\n * const response = await httpRequest('https://example.com/data')\n * console.log(response.body.length) // Size in bytes\n * console.log(response.body.toString('hex')) // View as hex\n * ```\n */\n body: Buffer\n /**\n * HTTP response headers.\n * Keys are lowercase header names, values can be strings or string arrays.\n *\n * @example\n * ```ts\n * const response = await httpRequest('https://example.com')\n * console.log(response.headers['content-type'])\n * console.log(response.headers['set-cookie']) // May be string[]\n * ```\n */\n headers: Record<string, string | string[] | undefined>\n /**\n * Parse response body as JSON.\n * Type parameter `T` allows specifying the expected JSON structure.\n *\n * @template T - Expected JSON type (defaults to `unknown`)\n * @returns Parsed JSON data\n * @throws {SyntaxError} When response body is not valid JSON\n *\n * @example\n * ```ts\n * interface User { name: string; id: number }\n * const response = await httpRequest('https://api.example.com/user')\n * const user = response.json<User>()\n * console.log(user.name, user.id)\n * ```\n */\n json<T = unknown>(): T\n /**\n * Whether the request was successful (status code 200-299).\n *\n * @example\n * ```ts\n * const response = await httpRequest('https://example.com/data')\n * if (response.ok) {\n * console.log('Success:', response.json())\n * } else {\n * console.error('Failed:', response.status, response.statusText)\n * }\n * ```\n */\n ok: boolean\n /**\n * HTTP status code (e.g., 200, 404, 500).\n *\n * @example\n * ```ts\n * const response = await httpRequest('https://example.com')\n * console.log(response.status) // 200, 404, etc.\n * ```\n */\n status: number\n /**\n * HTTP status message (e.g., \"OK\", \"Not Found\", \"Internal Server Error\").\n *\n * @example\n * ```ts\n * const response = await httpRequest('https://example.com')\n * console.log(response.statusText) // \"OK\"\n * ```\n */\n statusText: string\n /**\n * Get response body as UTF-8 text string.\n *\n * @returns The response body as a string\n *\n * @example\n * ```ts\n * const response = await httpRequest('https://example.com')\n * const html = response.text()\n * console.log(html.includes('<html>'))\n * ```\n */\n text(): string\n}\n\n/**\n * Configuration options for file downloads.\n */\nexport interface HttpDownloadOptions {\n /**\n * HTTP headers to send with the download request.\n * A `User-Agent` header is automatically added if not provided.\n *\n * @example\n * ```ts\n * await httpDownload('https://example.com/file.zip', '/tmp/file.zip', {\n * headers: {\n * 'Authorization': 'Bearer token123'\n * }\n * })\n * ```\n */\n headers?: Record<string, string> | undefined\n /**\n * Callback for tracking download progress.\n * Called periodically as data is received.\n *\n * @param downloaded - Number of bytes downloaded so far\n * @param total - Total file size in bytes (from Content-Length header)\n *\n * @example\n * ```ts\n * await httpDownload('https://example.com/large-file.zip', '/tmp/file.zip', {\n * onProgress: (downloaded, total) => {\n * const percent = ((downloaded / total) * 100).toFixed(1)\n * console.log(`Progress: ${percent}%`)\n * }\n * })\n * ```\n */\n onProgress?: ((downloaded: number, total: number) => void) | undefined\n /**\n * Number of retry attempts for failed downloads.\n * Uses exponential backoff: delay = `retryDelay` * 2^attempt.\n *\n * @default 0\n *\n * @example\n * ```ts\n * // Retry up to 3 times for unreliable connections\n * await httpDownload('https://example.com/file.zip', '/tmp/file.zip', {\n * retries: 3,\n * retryDelay: 2000\n * })\n * ```\n */\n retries?: number | undefined\n /**\n * Initial delay in milliseconds before first retry.\n * Subsequent retries use exponential backoff.\n *\n * @default 1000\n */\n retryDelay?: number | undefined\n /**\n * Download timeout in milliseconds.\n * If the download takes longer than this, it will be aborted.\n *\n * @default 120000\n *\n * @example\n * ```ts\n * // 5 minute timeout for large files\n * await httpDownload('https://example.com/huge-file.zip', '/tmp/file.zip', {\n * timeout: 300000\n * })\n * ```\n */\n timeout?: number | undefined\n}\n\n/**\n * Result of a successful file download.\n */\nexport interface HttpDownloadResult {\n /**\n * Absolute path where the file was saved.\n *\n * @example\n * ```ts\n * const result = await httpDownload('https://example.com/file.zip', '/tmp/file.zip')\n * console.log(`Downloaded to: ${result.path}`)\n * ```\n */\n path: string\n /**\n * Total size of downloaded file in bytes.\n *\n * @example\n * ```ts\n * const result = await httpDownload('https://example.com/file.zip', '/tmp/file.zip')\n * console.log(`Downloaded ${result.size} bytes`)\n * ```\n */\n size: number\n}\n\n/**\n * Make an HTTP/HTTPS request with retry logic and redirect support.\n * Provides a fetch-like API using Node.js native http/https modules.\n *\n * This is the main entry point for making HTTP requests. It handles retries,\n * redirects, timeouts, and provides a fetch-compatible response interface.\n *\n * @param url - The URL to request (must start with http:// or https://)\n * @param options - Request configuration options\n * @returns Promise resolving to response object with `.json()`, `.text()`, etc.\n * @throws {Error} When all retries are exhausted, timeout occurs, or non-retryable error happens\n *\n * @example\n * ```ts\n * // Simple GET request\n * const response = await httpRequest('https://api.example.com/data')\n * const data = response.json()\n *\n * // POST with JSON body\n * const response = await httpRequest('https://api.example.com/users', {\n * method: 'POST',\n * headers: { 'Content-Type': 'application/json' },\n * body: JSON.stringify({ name: 'Alice', email: 'alice@example.com' })\n * })\n *\n * // With retries and timeout\n * const response = await httpRequest('https://api.example.com/data', {\n * retries: 3,\n * retryDelay: 1000,\n * timeout: 60000\n * })\n *\n * // Don't follow redirects\n * const response = await httpRequest('https://example.com/redirect', {\n * followRedirects: false\n * })\n * console.log(response.status) // 301, 302, etc.\n * ```\n */\nexport async function httpRequest(\n url: string,\n options?: HttpRequestOptions | undefined,\n): Promise<HttpResponse> {\n const {\n body,\n followRedirects = true,\n headers = {},\n maxRedirects = 5,\n method = 'GET',\n retries = 0,\n retryDelay = 1000,\n timeout = 30_000,\n } = { __proto__: null, ...options } as HttpRequestOptions\n\n // Retry logic with exponential backoff\n let lastError: Error | undefined\n for (let attempt = 0; attempt <= retries; attempt++) {\n try {\n // eslint-disable-next-line no-await-in-loop\n return await httpRequestAttempt(url, {\n body,\n followRedirects,\n headers,\n maxRedirects,\n method,\n timeout,\n })\n } catch (e) {\n lastError = e as Error\n\n // Last attempt - throw error\n if (attempt === retries) {\n break\n }\n\n // Retry with exponential backoff\n const delayMs = retryDelay * 2 ** attempt\n // eslint-disable-next-line no-await-in-loop\n await new Promise(resolve => setTimeout(resolve, delayMs))\n }\n }\n\n throw lastError || new Error('Request failed after retries')\n}\n\n/**\n * Single HTTP request attempt (used internally by httpRequest with retry logic).\n * @private\n */\nasync function httpRequestAttempt(\n url: string,\n options: HttpRequestOptions,\n): Promise<HttpResponse> {\n const {\n body,\n followRedirects = true,\n headers = {},\n maxRedirects = 5,\n method = 'GET',\n timeout = 30_000,\n } = { __proto__: null, ...options } as HttpRequestOptions\n\n return await new Promise((resolve, reject) => {\n const parsedUrl = new URL(url)\n const isHttps = parsedUrl.protocol === 'https:'\n const httpModule = isHttps ? getHttps() : getHttp()\n\n const requestOptions = {\n headers: {\n 'User-Agent': 'socket-registry/1.0',\n ...headers,\n },\n hostname: parsedUrl.hostname,\n method,\n path: parsedUrl.pathname + parsedUrl.search,\n port: parsedUrl.port,\n timeout,\n }\n\n const request = httpModule.request(\n requestOptions,\n (res: IncomingMessage) => {\n // Handle redirects\n if (\n followRedirects &&\n res.statusCode &&\n res.statusCode >= 300 &&\n res.statusCode < 400 &&\n res.headers.location\n ) {\n if (maxRedirects <= 0) {\n reject(\n new Error(\n `Too many redirects (exceeded maximum: ${maxRedirects})`,\n ),\n )\n return\n }\n\n // Follow redirect\n const redirectUrl = res.headers.location.startsWith('http')\n ? res.headers.location\n : new URL(res.headers.location, url).toString()\n\n resolve(\n httpRequestAttempt(redirectUrl, {\n body,\n followRedirects,\n headers,\n maxRedirects: maxRedirects - 1,\n method,\n timeout,\n }),\n )\n return\n }\n\n // Collect response data\n const chunks: Buffer[] = []\n res.on('data', (chunk: Buffer) => {\n chunks.push(chunk)\n })\n\n res.on('end', () => {\n const responseBody = Buffer.concat(chunks)\n const ok =\n res.statusCode !== undefined &&\n res.statusCode >= 200 &&\n res.statusCode < 300\n\n const response: HttpResponse = {\n arrayBuffer(): ArrayBuffer {\n return responseBody.buffer.slice(\n responseBody.byteOffset,\n responseBody.byteOffset + responseBody.byteLength,\n )\n },\n body: responseBody,\n headers: res.headers as Record<\n string,\n string | string[] | undefined\n >,\n json<T = unknown>(): T {\n return JSON.parse(responseBody.toString('utf8')) as T\n },\n ok,\n status: res.statusCode || 0,\n statusText: res.statusMessage || '',\n text(): string {\n return responseBody.toString('utf8')\n },\n }\n\n resolve(response)\n })\n },\n )\n\n request.on('error', (error: Error) => {\n const code = (error as NodeJS.ErrnoException).code\n let message = `HTTP request failed for ${url}: ${error.message}\\n`\n\n if (code === 'ENOTFOUND') {\n message +=\n 'DNS lookup failed. Check the hostname and your network connection.'\n } else if (code === 'ECONNREFUSED') {\n message +=\n 'Connection refused. Verify the server is running and accessible.'\n } else if (code === 'ETIMEDOUT') {\n message +=\n 'Request timed out. Check your network or increase the timeout value.'\n } else if (code === 'ECONNRESET') {\n message +=\n 'Connection reset. The server may have closed the connection unexpectedly.'\n } else {\n message +=\n 'Check your network connection and verify the URL is correct.'\n }\n\n reject(new Error(message, { cause: error }))\n })\n\n request.on('timeout', () => {\n request.destroy()\n reject(new Error(`Request timed out after ${timeout}ms`))\n })\n\n // Send body if present\n if (body) {\n request.write(body)\n }\n\n request.end()\n })\n}\n\n/**\n * Download a file from a URL to a local path with retry logic and progress callbacks.\n * Uses streaming to avoid loading entire file in memory.\n *\n * The download is streamed directly to disk, making it memory-efficient even for\n * large files. Progress callbacks allow for real-time download status updates.\n *\n * @param url - The URL to download from (must start with http:// or https://)\n * @param destPath - Absolute path where the file should be saved\n * @param options - Download configuration options\n * @returns Promise resolving to download result with path and size\n * @throws {Error} When all retries are exhausted, download fails, or file cannot be written\n *\n * @example\n * ```ts\n * // Simple download\n * const result = await httpDownload(\n * 'https://example.com/file.zip',\n * '/tmp/file.zip'\n * )\n * console.log(`Downloaded ${result.size} bytes to ${result.path}`)\n *\n * // With progress tracking\n * await httpDownload(\n * 'https://example.com/large-file.zip',\n * '/tmp/file.zip',\n * {\n * onProgress: (downloaded, total) => {\n * const percent = ((downloaded / total) * 100).toFixed(1)\n * console.log(`Progress: ${percent}% (${downloaded}/${total} bytes)`)\n * }\n * }\n * )\n *\n * // With retries and custom timeout\n * await httpDownload(\n * 'https://example.com/file.zip',\n * '/tmp/file.zip',\n * {\n * retries: 3,\n * retryDelay: 2000,\n * timeout: 300000, // 5 minutes\n * headers: { 'Authorization': 'Bearer token123' }\n * }\n * )\n * ```\n */\nexport async function httpDownload(\n url: string,\n destPath: string,\n options?: HttpDownloadOptions | undefined,\n): Promise<HttpDownloadResult> {\n const {\n headers = {},\n onProgress,\n retries = 0,\n retryDelay = 1000,\n timeout = 120_000,\n } = { __proto__: null, ...options } as HttpDownloadOptions\n\n // Retry logic with exponential backoff\n let lastError: Error | undefined\n for (let attempt = 0; attempt <= retries; attempt++) {\n try {\n // eslint-disable-next-line no-await-in-loop\n return await httpDownloadAttempt(url, destPath, {\n headers,\n onProgress,\n timeout,\n })\n } catch (e) {\n lastError = e as Error\n\n // Last attempt - throw error\n if (attempt === retries) {\n break\n }\n\n // Retry with exponential backoff\n const delayMs = retryDelay * 2 ** attempt\n // eslint-disable-next-line no-await-in-loop\n await new Promise(resolve => setTimeout(resolve, delayMs))\n }\n }\n\n throw lastError || new Error('Download failed after retries')\n}\n\n/**\n * Single download attempt (used internally by httpDownload with retry logic).\n * @private\n */\nasync function httpDownloadAttempt(\n url: string,\n destPath: string,\n options: HttpDownloadOptions,\n): Promise<HttpDownloadResult> {\n const {\n headers = {},\n onProgress,\n timeout = 120_000,\n } = { __proto__: null, ...options } as HttpDownloadOptions\n\n return await new Promise((resolve, reject) => {\n const parsedUrl = new URL(url)\n const isHttps = parsedUrl.protocol === 'https:'\n const httpModule = isHttps ? getHttps() : getHttp()\n\n const requestOptions = {\n headers: {\n 'User-Agent': 'socket-registry/1.0',\n ...headers,\n },\n hostname: parsedUrl.hostname,\n method: 'GET',\n path: parsedUrl.pathname + parsedUrl.search,\n port: parsedUrl.port,\n timeout,\n }\n\n let fileStream: ReturnType<typeof createWriteStream> | undefined\n let streamClosed = false\n\n const closeStream = () => {\n if (!streamClosed && fileStream) {\n streamClosed = true\n fileStream.close()\n }\n }\n\n const request = httpModule.request(\n requestOptions,\n (res: IncomingMessage) => {\n // Check status code\n if (!res.statusCode || res.statusCode < 200 || res.statusCode >= 300) {\n closeStream()\n reject(\n new Error(\n `Download failed: HTTP ${res.statusCode} ${res.statusMessage}`,\n ),\n )\n return\n }\n\n const totalSize = Number.parseInt(\n res.headers['content-length'] || '0',\n 10,\n )\n let downloadedSize = 0\n\n // Create write stream\n fileStream = createWriteStream(destPath)\n\n fileStream.on('error', (error: Error) => {\n closeStream()\n const err = new Error(`Failed to write file: ${error.message}`, {\n cause: error,\n })\n reject(err)\n })\n\n res.on('data', (chunk: Buffer) => {\n downloadedSize += chunk.length\n if (onProgress && totalSize > 0) {\n onProgress(downloadedSize, totalSize)\n }\n })\n\n res.on('end', () => {\n fileStream?.close(() => {\n streamClosed = true\n resolve({\n path: destPath,\n size: downloadedSize,\n })\n })\n })\n\n res.on('error', (error: Error) => {\n closeStream()\n reject(error)\n })\n\n // Pipe response to file\n res.pipe(fileStream)\n },\n )\n\n request.on('error', (error: Error) => {\n closeStream()\n const code = (error as NodeJS.ErrnoException).code\n let message = `HTTP download failed for ${url}: ${error.message}\\n`\n\n if (code === 'ENOTFOUND') {\n message +=\n 'DNS lookup failed. Check the hostname and your network connection.'\n } else if (code === 'ECONNREFUSED') {\n message +=\n 'Connection refused. Verify the server is running and accessible.'\n } else if (code === 'ETIMEDOUT') {\n message +=\n 'Request timed out. Check your network or increase the timeout value.'\n } else if (code === 'ECONNRESET') {\n message +=\n 'Connection reset. The server may have closed the connection unexpectedly.'\n } else {\n message +=\n 'Check your network connection and verify the URL is correct.'\n }\n\n reject(new Error(message, { cause: error }))\n })\n\n request.on('timeout', () => {\n request.destroy()\n closeStream()\n reject(new Error(`Download timed out after ${timeout}ms`))\n })\n\n request.end()\n })\n}\n\n/**\n * Perform a GET request and parse JSON response.\n * Convenience wrapper around `httpRequest` for common JSON API calls.\n *\n * @template T - Expected JSON response type (defaults to `unknown`)\n * @param url - The URL to request (must start with http:// or https://)\n * @param options - Request configuration options\n * @returns Promise resolving to parsed JSON data\n * @throws {Error} When request fails, response is not ok (status < 200 or >= 300), or JSON parsing fails\n *\n * @example\n * ```ts\n * // Simple JSON GET\n * const data = await httpGetJson('https://api.example.com/data')\n * console.log(data)\n *\n * // With type safety\n * interface User { id: number; name: string; email: string }\n * const user = await httpGetJson<User>('https://api.example.com/user/123')\n * console.log(user.name, user.email)\n *\n * // With custom headers\n * const data = await httpGetJson('https://api.example.com/data', {\n * headers: {\n * 'Authorization': 'Bearer token123',\n * 'Accept': 'application/json'\n * }\n * })\n *\n * // With retries\n * const data = await httpGetJson('https://api.example.com/data', {\n * retries: 3,\n * retryDelay: 1000\n * })\n * ```\n */\nexport async function httpGetJson<T = unknown>(\n url: string,\n options?: HttpRequestOptions | undefined,\n): Promise<T> {\n const response = await httpRequest(url, { ...options, method: 'GET' })\n\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`)\n }\n\n try {\n return response.json<T>()\n } catch (e) {\n throw new Error('Failed to parse JSON response', { cause: e })\n }\n}\n\n/**\n * Perform a GET request and return text response.\n * Convenience wrapper around `httpRequest` for fetching text content.\n *\n * @param url - The URL to request (must start with http:// or https://)\n * @param options - Request configuration options\n * @returns Promise resolving to response body as UTF-8 string\n * @throws {Error} When request fails or response is not ok (status < 200 or >= 300)\n *\n * @example\n * ```ts\n * // Fetch HTML\n * const html = await httpGetText('https://example.com')\n * console.log(html.includes('<!DOCTYPE html>'))\n *\n * // Fetch plain text\n * const text = await httpGetText('https://example.com/file.txt')\n * console.log(text)\n *\n * // With custom headers\n * const text = await httpGetText('https://example.com/data.txt', {\n * headers: {\n * 'Authorization': 'Bearer token123'\n * }\n * })\n *\n * // With timeout\n * const text = await httpGetText('https://example.com/large-file.txt', {\n * timeout: 60000 // 1 minute\n * })\n * ```\n */\nexport async function httpGetText(\n url: string,\n options?: HttpRequestOptions | undefined,\n): Promise<string> {\n const response = await httpRequest(url, { ...options, method: 'GET' })\n\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`)\n }\n\n return response.text()\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAgBA,gBAAkC;AAIlC,IAAI;AACJ,IAAI;AAAA;AAMJ,SAAS,UAAU;AACjB,MAAI,UAAU,QAAW;AAGvB,YAAsB,QAAQ,WAAW;AAAA,EAC3C;AACA,SAAO;AACT;AAAA;AAGA,SAAS,WAAW;AAClB,MAAI,WAAW,QAAW;AAGxB,aAAuB,QAAQ,YAAY;AAAA,EAC7C;AACA,SAAO;AACT;AA+YA,eAAsB,YACpB,KACA,SACuB;AACvB,QAAM;AAAA,IACJ;AAAA,IACA,kBAAkB;AAAA,IAClB,UAAU,CAAC;AAAA,IACX,eAAe;AAAA,IACf,SAAS;AAAA,IACT,UAAU;AAAA,IACV,aAAa;AAAA,IACb,UAAU;AAAA,EACZ,IAAI,EAAE,WAAW,MAAM,GAAG,QAAQ;AAGlC,MAAI;AACJ,WAAS,UAAU,GAAG,WAAW,SAAS,WAAW;AACnD,QAAI;AAEF,aAAO,MAAM,mBAAmB,KAAK;AAAA,QACnC;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF,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7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../src/ipc.ts"],
4
- "sourcesContent": ["/**\n * IPC (Inter-Process Communication) Module\n * ==========================================\n *\n * This module provides secure inter-process communication utilities for Socket CLI\n * and related tools. It replaces environment variable passing with more secure and\n * scalable alternatives.\n *\n * ## Key Features:\n * - File-based stub communication for initial data handoff\n * - Node.js IPC channel support for real-time bidirectional messaging\n * - Automatic cleanup of temporary files\n * - Type-safe message validation with Zod schemas\n * - Timeout handling for reliability\n *\n * ## Use Cases:\n * 1. Passing API tokens between processes without exposing them in env vars\n * 2. Transferring large configuration objects that exceed env var size limits\n * 3. Bidirectional communication between parent and child processes\n * 4. Secure handshake protocols between Socket CLI components\n *\n * ## Security Considerations:\n * - Stub files are created with restricted permissions in OS temp directory\n * - Messages include timestamps for freshness validation\n * - Automatic cleanup prevents sensitive data persistence\n * - Unique IDs prevent message replay attacks\n *\n * @module ipc\n */\n\nimport crypto from 'crypto'\n\nimport { promises as fs } from 'fs'\n\nimport path from 'path'\n\nimport { safeDeleteSync } from './fs'\nimport { getOsTmpDir } from './paths'\nimport { z } from './zod'\n\n// Define BufferEncoding type for TypeScript compatibility.\ntype BufferEncoding = globalThis.BufferEncoding\n\n/**\n * Zod Schemas for Runtime Validation\n * ====================================\n * These schemas provide runtime type safety for IPC messages,\n * ensuring data integrity across process boundaries.\n */\n\n/**\n * Base IPC message schema - validates the core message structure.\n * All IPC messages must conform to this schema.\n */\nconst IpcMessageSchema = z.object({\n /** Unique identifier for message tracking and response correlation. */\n id: z.string().min(1),\n /** Unix timestamp for freshness validation and replay prevention. */\n timestamp: z.number().positive(),\n /** Message type identifier for routing and handling. */\n type: z.string().min(1),\n /** Payload data - can be any JSON-serializable value. */\n data: z.unknown(),\n})\n\n/**\n * IPC handshake schema - used for initial connection establishment.\n * The handshake includes version info and authentication tokens.\n * @internal Exported for testing purposes.\n */\nexport const IpcHandshakeSchema = IpcMessageSchema.extend({\n type: z.literal('handshake'),\n data: z.object({\n /** Protocol version for compatibility checking. */\n version: z.string(),\n /** Process ID for identification. */\n pid: z.number().int().positive(),\n /** Optional API token for authentication. */\n apiToken: z.string().optional(),\n /** Application name for multi-app support. */\n appName: z.string(),\n }),\n})\n\n/**\n * IPC stub file schema - validates the structure of stub files.\n * Stub files are used for passing data between processes via filesystem.\n */\nconst IpcStubSchema = z.object({\n /** Process ID that created the stub. */\n pid: z.number().int().positive(),\n /** Creation timestamp for age validation. */\n timestamp: z.number().positive(),\n /** The actual data payload. */\n data: z.unknown(),\n})\n\n/**\n * TypeScript interfaces for IPC communication.\n * These types ensure type consistency across the IPC module.\n */\n\n/**\n * Base IPC message interface.\n * All IPC messages must conform to this structure.\n */\nexport interface IpcMessage<T = unknown> {\n /** Unique identifier for message tracking and response correlation. */\n id: string\n /** Unix timestamp for freshness validation and replay prevention. */\n timestamp: number\n /** Message type identifier for routing and handling. */\n type: string\n /** Payload data - can be any JSON-serializable value. */\n data: T\n}\n\n/**\n * IPC handshake message interface.\n * Used for initial connection establishment.\n */\nexport interface IpcHandshake\n extends IpcMessage<{\n /** Protocol version for compatibility checking. */\n version: string\n /** Process ID for identification. */\n pid: number\n /** Optional API token for authentication. */\n apiToken?: string\n /** Application name for multi-app support. */\n appName: string\n }> {\n type: 'handshake'\n}\n\n/**\n * IPC stub file interface.\n * Represents the structure of stub files used for filesystem-based IPC.\n */\nexport interface IpcStub {\n /** Process ID that created the stub. */\n pid: number\n /** Creation timestamp for age validation. */\n timestamp: number\n /** The actual data payload. */\n data: unknown\n}\n\n/**\n * Options for IPC communication\n */\nexport interface IpcOptions {\n /** Timeout in milliseconds for async operations. */\n timeout?: number\n /** Text encoding for message serialization. */\n encoding?: BufferEncoding\n}\n\n/**\n * Create a unique IPC channel identifier for message correlation.\n *\n * Generates a unique identifier that combines:\n * - A prefix for namespacing (defaults to 'socket')\n * - The current process ID for process identification\n * - A random hex string for uniqueness\n *\n * @param prefix - Optional prefix to namespace the channel ID\n * @returns A unique channel identifier string\n *\n * @example\n * ```typescript\n * const channelId = createIpcChannelId('socket-cli')\n * // Returns: 'socket-cli-12345-a1b2c3d4e5f6g7h8'\n * ```\n */\nexport function createIpcChannelId(prefix = 'socket'): string {\n return `${prefix}-${process.pid}-${crypto.randomBytes(8).toString('hex')}`\n}\n\n/**\n * Get the IPC stub path for a given application.\n *\n * This function generates a unique file path for IPC stub files that are used\n * to pass data between processes. The stub files are stored in a hidden directory\n * within the system's temporary folder.\n *\n * ## Path Structure:\n * - Base: System temp directory (e.g., /tmp on Unix, %TEMP% on Windows)\n * - Directory: `.socket-ipc/{appName}/`\n * - Filename: `stub-{pid}.json`\n *\n * ## Security Features:\n * - Files are isolated per application via appName parameter\n * - Process ID in filename prevents collisions between concurrent processes\n * - Temporary directory location ensures automatic cleanup on system restart\n *\n * @param appName - The application identifier (e.g., 'socket-cli', 'socket-dlx')\n * @returns Full path to the IPC stub file\n *\n * @example\n * ```typescript\n * const stubPath = getIpcStubPath('socket-cli')\n * // Returns: '/tmp/.socket-ipc/socket-cli/stub-12345.json' (Unix)\n * // Returns: 'C:\\\\Users\\\\Name\\\\AppData\\\\Local\\\\Temp\\\\.socket-ipc\\\\socket-cli\\\\stub-12345.json' (Windows)\n * ```\n *\n * @used Currently used by socket-cli for self-update and inter-process communication\n */\nexport function getIpcStubPath(appName: string): string {\n // Get the system's temporary directory - this is platform-specific.\n const tempDir = getOsTmpDir()\n\n // Create a hidden directory structure for Socket IPC files.\n // The dot prefix makes it hidden on Unix-like systems.\n const stubDir = path.join(tempDir, '.socket-ipc', appName)\n\n // Generate filename with process ID to ensure uniqueness.\n // The PID prevents conflicts when multiple processes run simultaneously.\n return path.join(stubDir, `stub-${process.pid}.json`)\n}\n\n/**\n * Ensure IPC directory exists for stub file creation.\n *\n * This helper function creates the directory structure needed for IPC stub files.\n * It's called before writing stub files to ensure the parent directories exist.\n *\n * @param filePath - Full path to the file that needs its directory created\n * @returns Promise that resolves when directory is created\n *\n * @internal Helper function used by writeIpcStub\n */\nasync function ensureIpcDirectory(filePath: string): Promise<void> {\n const dir = path.dirname(filePath)\n // Create directory recursively if it doesn't exist.\n await fs.mkdir(dir, { recursive: true })\n}\n\n/**\n * Write IPC data to a stub file for inter-process data transfer.\n *\n * This function creates a stub file containing data that needs to be passed\n * between processes. The stub file includes metadata like process ID and\n * timestamp for validation.\n *\n * ## File Structure:\n * ```json\n * {\n * \"pid\": 12345,\n * \"timestamp\": 1699564234567,\n * \"data\": { ... }\n * }\n * ```\n *\n * ## Use Cases:\n * - Passing API tokens to child processes\n * - Transferring configuration between Socket CLI components\n * - Sharing large data that exceeds environment variable limits\n *\n * @param appName - The application identifier\n * @param data - The data to write to the stub file\n * @returns Promise resolving to the stub file path\n *\n * @example\n * ```typescript\n * const stubPath = await writeIpcStub('socket-cli', {\n * apiToken: 'secret-token',\n * config: { ... }\n * })\n * // Pass stubPath to child process for reading\n * ```\n */\nexport async function writeIpcStub(\n appName: string,\n data: unknown,\n): Promise<string> {\n const stubPath = getIpcStubPath(appName)\n await ensureIpcDirectory(stubPath)\n\n // Create stub data with validation metadata.\n const ipcData: IpcStub = {\n data,\n pid: process.pid,\n timestamp: Date.now(),\n }\n\n // Validate data structure with Zod schema.\n const validated = IpcStubSchema.parse(ipcData)\n\n // Write with pretty printing for debugging.\n await fs.writeFile(stubPath, JSON.stringify(validated, null, 2), 'utf8')\n return stubPath\n}\n\n/**\n * Read IPC data from a stub file with automatic cleanup.\n *\n * This function reads data from an IPC stub file and validates its freshness.\n * Stale files (older than 5 minutes) are automatically cleaned up to prevent\n * accumulation of temporary files.\n *\n * ## Validation Steps:\n * 1. Read and parse JSON file\n * 2. Validate structure with Zod schema\n * 3. Check timestamp freshness\n * 4. Clean up if stale\n * 5. Return data if valid\n *\n * @param stubPath - Path to the stub file to read\n * @returns Promise resolving to the data or null if invalid/stale\n *\n * @example\n * ```typescript\n * const data = await readIpcStub('/tmp/.socket-ipc/socket-cli/stub-12345.json')\n * if (data) {\n * console.log('Received:', data)\n * }\n * ```\n *\n * @unused Reserved for future implementation\n */\nexport async function readIpcStub(stubPath: string): Promise<unknown> {\n try {\n const content = await fs.readFile(stubPath, 'utf8')\n const parsed = JSON.parse(content)\n // Validate structure with Zod schema.\n const validated = IpcStubSchema.parse(parsed)\n // Check age for freshness validation.\n const ageMs = Date.now() - validated.timestamp\n // 5 minutes.\n const maxAgeMs = 5 * 60 * 1000\n if (ageMs > maxAgeMs) {\n // Clean up stale file. IPC stubs are always in tmpdir, so use force: true.\n try {\n safeDeleteSync(stubPath, { force: true })\n } catch {\n // Ignore deletion errors\n }\n return null\n }\n return validated.data\n } catch {\n // Return null for any errors (file not found, invalid JSON, validation failure).\n return null\n }\n}\n\n/**\n * Clean up IPC stub files for an application.\n *\n * This maintenance function removes stale IPC stub files to prevent\n * accumulation in the temporary directory. It's designed to be called\n * periodically or on application startup.\n *\n * ## Cleanup Rules:\n * - Files older than 5 minutes are removed (checked via both filesystem mtime and JSON timestamp)\n * - Only stub files (stub-*.json) are processed\n * - Errors are silently ignored (best-effort cleanup)\n *\n * @param appName - The application identifier\n * @returns Promise that resolves when cleanup is complete\n *\n * @example\n * ```typescript\n * // Clean up on application startup\n * await cleanupIpcStubs('socket-cli')\n * ```\n *\n * @unused Reserved for future implementation\n */\nexport async function cleanupIpcStubs(appName: string): Promise<void> {\n const tempDir = getOsTmpDir()\n const stubDir = path.join(tempDir, '.socket-ipc', appName)\n try {\n const files = await fs.readdir(stubDir)\n const now = Date.now()\n // 5 minutes.\n const maxAgeMs = 5 * 60 * 1000\n // Process each file in parallel for efficiency.\n await Promise.allSettled(\n files.map(async file => {\n if (file.startsWith('stub-') && file.endsWith('.json')) {\n const filePath = path.join(stubDir, file)\n try {\n // Check both filesystem mtime and JSON timestamp for more reliable detection\n const stats = await fs.stat(filePath)\n const mtimeAge = now - stats.mtimeMs\n let isStale = mtimeAge > maxAgeMs\n\n // Always check the timestamp inside the JSON file for accuracy\n // This is more reliable than filesystem mtime in some environments\n try {\n const content = await fs.readFile(filePath, 'utf8')\n const parsed = JSON.parse(content)\n const validated = IpcStubSchema.parse(parsed)\n const contentAge = now - validated.timestamp\n // File is stale if EITHER check indicates staleness\n isStale = isStale || contentAge > maxAgeMs\n } catch {\n // If we can't read/parse the file, rely on mtime check\n }\n\n if (isStale) {\n // IPC stubs are always in tmpdir, so we can use force: true to skip path checks\n safeDeleteSync(filePath, { force: true })\n }\n } catch {\n // Ignore errors for individual files.\n }\n }\n }),\n )\n } catch {\n // Directory might not exist, that's ok.\n }\n}\n\n/**\n * Send data through Node.js IPC channel.\n *\n * This function sends structured messages through the Node.js IPC channel\n * when available. The IPC channel must be established with stdio: ['pipe', 'pipe', 'pipe', 'ipc'].\n *\n * ## Requirements:\n * - Process must have been spawned with IPC channel enabled\n * - Message must be serializable to JSON\n * - Process.send() must be available\n *\n * @param process - The process object with IPC channel\n * @param message - The IPC message to send\n * @returns true if message was sent, false otherwise\n *\n * @example\n * ```typescript\n * const message = createIpcMessage('handshake', { version: '1.0.0' })\n * const sent = sendIpc(childProcess, message)\n * ```\n *\n * @unused Reserved for bidirectional communication implementation\n */\nexport function sendIpc(\n process: NodeJS.Process | unknown,\n message: IpcMessage,\n): boolean {\n if (\n process &&\n typeof process === 'object' &&\n 'send' in process &&\n typeof process.send === 'function'\n ) {\n try {\n // Validate message structure before sending.\n const validated = IpcMessageSchema.parse(message)\n return process.send(validated)\n } catch {\n return false\n }\n }\n return false\n}\n\n/**\n * Receive data through Node.js IPC channel.\n *\n * Sets up a listener for IPC messages with automatic validation and parsing.\n * Returns a cleanup function to remove the listener when no longer needed.\n *\n * ## Message Flow:\n * 1. Receive raw message from IPC channel\n * 2. Validate with parseIpcMessage\n * 3. Call handler if valid\n * 4. Ignore invalid messages\n *\n * @param handler - Function to call with valid IPC messages\n * @returns Cleanup function to remove the listener\n *\n * @example\n * ```typescript\n * const cleanup = onIpc((message) => {\n * console.log('Received:', message.type, message.data)\n * })\n * // Later...\n * cleanup() // Remove listener\n * ```\n *\n * @unused Reserved for bidirectional communication\n */\nexport function onIpc(handler: (message: IpcMessage) => void): () => void {\n const listener = (message: unknown) => {\n const parsed = parseIpcMessage(message)\n if (parsed) {\n handler(parsed)\n }\n }\n process.on('message', listener)\n // Return cleanup function for proper resource management.\n return () => {\n process.off('message', listener)\n }\n}\n\n/**\n * Create a promise that resolves when a specific IPC message is received.\n *\n * This utility function provides async/await support for IPC communication,\n * allowing you to wait for specific message types with timeout support.\n *\n * ## Features:\n * - Automatic timeout handling\n * - Type-safe message data\n * - Resource cleanup on completion\n * - Promise-based API\n *\n * @param messageType - The message type to wait for\n * @param options - Options including timeout configuration\n * @returns Promise resolving to the message data\n *\n * @example\n * ```typescript\n * try {\n * const response = await waitForIpc<ConfigData>('config-response', {\n * timeout: 5000 // 5 seconds\n * })\n * console.log('Config received:', response)\n * } catch (error) {\n * console.error('Timeout waiting for config')\n * }\n * ```\n *\n * @unused Reserved for request-response pattern implementation\n */\nexport function waitForIpc<T = unknown>(\n messageType: string,\n options: IpcOptions = {},\n): Promise<T> {\n const { timeout = 30_000 } = options\n return new Promise((resolve, reject) => {\n let cleanup: (() => void) | null = null\n let timeoutId: NodeJS.Timeout | null = null\n const handleTimeout = () => {\n if (cleanup) {\n cleanup()\n }\n reject(new Error(`IPC timeout waiting for message type: ${messageType}`))\n }\n const handleMessage = (message: IpcMessage) => {\n if (message.type === messageType) {\n if (timeoutId) {\n clearTimeout(timeoutId)\n }\n if (cleanup) {\n cleanup()\n }\n resolve(message.data as T)\n }\n }\n cleanup = onIpc(handleMessage)\n if (timeout > 0) {\n timeoutId = setTimeout(handleTimeout, timeout)\n }\n })\n}\n\n/**\n * Create an IPC message with proper structure and metadata.\n *\n * This factory function creates properly structured IPC messages with:\n * - Unique ID for tracking\n * - Timestamp for freshness\n * - Type for routing\n * - Data payload\n *\n * @param type - The message type identifier\n * @param data - The message payload\n * @returns A properly structured IPC message\n *\n * @example\n * ```typescript\n * const handshake = createIpcMessage('handshake', {\n * version: '1.0.0',\n * pid: process.pid,\n * appName: 'socket-cli'\n * })\n * ```\n *\n * @unused Reserved for future message creation needs\n */\nexport function createIpcMessage<T = unknown>(\n type: string,\n data: T,\n): IpcMessage<T> {\n return {\n id: crypto.randomBytes(16).toString('hex'),\n timestamp: Date.now(),\n type,\n data,\n }\n}\n\n/**\n * Check if process has IPC channel available.\n *\n * This utility checks whether a process object has the necessary\n * properties for IPC communication. Used to determine if IPC\n * messaging is possible before attempting to send.\n *\n * @param process - The process object to check\n * @returns true if IPC is available, false otherwise\n *\n * @example\n * ```typescript\n * if (hasIpcChannel(childProcess)) {\n * sendIpc(childProcess, message)\n * } else {\n * // Fall back to alternative communication method\n * }\n * ```\n *\n * @unused Reserved for IPC availability detection\n */\nexport function hasIpcChannel(process: unknown): boolean {\n return Boolean(\n process &&\n typeof process === 'object' &&\n 'send' in process &&\n typeof process.send === 'function' &&\n 'channel' in process &&\n process.channel !== undefined,\n )\n}\n\n/**\n * Safely parse and validate IPC messages.\n *\n * This function performs runtime validation of incoming messages\n * to ensure they conform to the IPC message structure. It uses\n * Zod schemas for robust validation.\n *\n * ## Validation Steps:\n * 1. Check if message is an object\n * 2. Validate required fields exist\n * 3. Validate field types\n * 4. Return typed message or null\n *\n * @param message - The raw message to parse\n * @returns Parsed IPC message or null if invalid\n *\n * @example\n * ```typescript\n * const parsed = parseIpcMessage(rawMessage)\n * if (parsed) {\n * handleMessage(parsed)\n * }\n * ```\n *\n * @unused Reserved for message validation needs\n */\nexport function parseIpcMessage(message: unknown): IpcMessage | null {\n try {\n // Use Zod schema for comprehensive validation.\n const validated = IpcMessageSchema.parse(message)\n return validated as IpcMessage\n } catch {\n // Return null for any validation failure.\n return null\n }\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA8BA,oBAAmB;AAEnB,gBAA+B;AAE/B,kBAAiB;AAEj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ACA,aAAO,IAAI,MAAM,yCAAyC,WAAW,EAAE,CAAC;AAAA,IAC1E;AACA,UAAM,gBAAgB,CAAC,YAAwB;AAC7C,UAAI,QAAQ,SAAS,aAAa;AAChC,YAAI,WAAW;AACb,uBAAa,SAAS;AAAA,QACxB;AACA,YAAI,SAAS;AACX,kBAAQ;AAAA,QACV;AACA,gBAAQ,QAAQ,IAAS;AAAA,MAC3B;AAAA,IACF;AACA,cAAU,MAAM,aAAa;AAC7B,QAAI,UAAU,GAAG;AACf,kBAAY,WAAW,eAAe,OAAO;AAAA,IAC/C;AAAA,EACF,CAAC;AACH;AA0BO,SAAS,iBACd,MACA,MACe;AACf,SAAO;AAAA,IACL,IAAI,cAAAH,QAAO,YAAY,EAAE,EAAE,SAAS,KAAK;AAAA,IACzC,WAAW,KAAK,IAAI;AAAA,IACpB;AAAA,IACA;AAAA,EACF;AACF;AAuBO,SAAS,cAAcG,UAA2B;AACvD,SAAO;AAAA,IACLA,YACE,OAAOA,aAAY,YACnB,UAAUA,YACV,OAAOA,SAAQ,SAAS,cACxB,aAAaA,YACbA,SAAQ,YAAY;AAAA,EACxB;AACF;AA4BO,SAAS,gBAAgB,SAAqC;AACnE,MAAI;AAEF,UAAM,YAAY,iBAAiB,MAAM,OAAO;AAChD,WAAO;AAAA,EACT,QAAQ;AAEN,WAAO;AAAA,EACT;AACF;",
6
- "names": ["import_fs", "crypto", "path", "fs", "process"]
7
- }
package/dist/json.js.map DELETED
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../src/json.ts"],
4
- "sourcesContent": ["/**\n * @fileoverview JSON parsing utilities with Buffer detection and BOM stripping.\n * Provides safe JSON parsing with automatic encoding handling.\n */\n\nimport { stripBom } from './strings'\n\n/**\n * JSON primitive types: `null`, `boolean`, `number`, or `string`.\n *\n * @example\n * ```ts\n * const primitives: JsonPrimitive[] = [null, true, 42, 'hello']\n * ```\n */\nexport type JsonPrimitive = null | boolean | number | string\n\n/**\n * Any valid JSON value: primitive, object, or array.\n *\n * @example\n * ```ts\n * const values: JsonValue[] = [\n * null,\n * true,\n * 42,\n * 'hello',\n * { key: 'value' },\n * [1, 2, 3]\n * ]\n * ```\n */\nexport type JsonValue = JsonPrimitive | JsonObject | JsonArray\n\n/**\n * A JSON object with string keys and JSON values.\n *\n * @example\n * ```ts\n * const obj: JsonObject = {\n * name: 'example',\n * count: 42,\n * active: true,\n * nested: { key: 'value' }\n * }\n * ```\n */\nexport interface JsonObject {\n [key: string]: JsonValue\n}\n\n/**\n * A JSON array containing JSON values.\n *\n * @example\n * ```ts\n * const arr: JsonArray = [1, 'two', { three: 3 }, [4, 5]]\n * ```\n */\nexport interface JsonArray extends Array<JsonValue> {}\n\n/**\n * Reviver function for transforming parsed JSON values.\n * Called for each key-value pair during parsing.\n *\n * @param key - The object key or array index being parsed\n * @param value - The parsed value\n * @returns The transformed value (or original if no transform needed)\n *\n * @example\n * ```ts\n * // Convert date strings to Date objects\n * const reviver: JsonReviver = (key, value) => {\n * if (typeof value === 'string' && /^\\d{4}-\\d{2}-\\d{2}/.test(value)) {\n * return new Date(value)\n * }\n * return value\n * }\n * ```\n */\nexport type JsonReviver = (key: string, value: unknown) => unknown\n\n/**\n * Options for JSON parsing operations.\n */\nexport interface JsonParseOptions {\n /**\n * Optional filepath for improved error messages.\n * When provided, errors will be prefixed with the filepath.\n *\n * @example\n * ```ts\n * // Error message will be: \"config.json: Unexpected token } in JSON\"\n * jsonParse('invalid', { filepath: 'config.json' })\n * ```\n */\n filepath?: string | undefined\n /**\n * Optional reviver function to transform parsed values.\n * Called for each key-value pair during parsing.\n *\n * @example\n * ```ts\n * // Convert ISO date strings to Date objects\n * const options = {\n * reviver: (key, value) => {\n * if (typeof value === 'string' && /^\\d{4}-\\d{2}-\\d{2}/.test(value)) {\n * return new Date(value)\n * }\n * return value\n * }\n * }\n * ```\n */\n reviver?: JsonReviver | undefined\n /**\n * Whether to throw on parse errors.\n * When `false`, returns `undefined` instead of throwing.\n *\n * @default true\n *\n * @example\n * ```ts\n * // Throws error\n * jsonParse('invalid', { throws: true })\n *\n * // Returns undefined\n * const result = jsonParse('invalid', { throws: false })\n * ```\n */\n throws?: boolean | undefined\n}\n\n// IMPORTANT: Do not use destructuring here - use direct assignment instead.\n// tsgo has a bug that incorrectly transpiles destructured exports, resulting in\n// `exports.SomeName = void 0;` which causes runtime errors.\n// See: https://github.com/SocketDev/socket-packageurl-js/issues/3\nconst JSONParse = JSON.parse\n\n/**\n * Check if a value is a Buffer instance.\n * Uses duck-typing to detect Buffer without requiring Node.js Buffer in type system.\n *\n * @param x - Value to check\n * @returns `true` if value is a Buffer, `false` otherwise\n *\n * @example\n * ```ts\n * isBuffer(Buffer.from('hello')) // => true\n * isBuffer('hello') // => false\n * isBuffer({ length: 5 }) // => false\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction isBuffer(x: unknown): x is Buffer {\n if (!x || typeof x !== 'object') {\n return false\n }\n const obj = x as Record<string | number, unknown>\n if (typeof obj['length'] !== 'number') {\n return false\n }\n if (typeof obj['copy'] !== 'function' || typeof obj['slice'] !== 'function') {\n return false\n }\n if (\n typeof obj['length'] === 'number' &&\n obj['length'] > 0 &&\n typeof obj[0] !== 'number'\n ) {\n return false\n }\n\n const Ctor = (x as { constructor?: unknown }).constructor as\n | { isBuffer?: unknown }\n | undefined\n return !!(typeof Ctor?.isBuffer === 'function' && Ctor.isBuffer(x))\n}\n\n/**\n * Check if a value is a JSON primitive type.\n * JSON primitives are: `null`, `boolean`, `number`, or `string`.\n *\n * @param value - Value to check\n * @returns `true` if value is a JSON primitive, `false` otherwise\n *\n * @example\n * ```ts\n * isJsonPrimitive(null) // => true\n * isJsonPrimitive(true) // => true\n * isJsonPrimitive(42) // => true\n * isJsonPrimitive('hello') // => true\n * isJsonPrimitive({}) // => false\n * isJsonPrimitive([]) // => false\n * isJsonPrimitive(undefined) // => false\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function isJsonPrimitive(value: unknown): value is JsonPrimitive {\n return (\n value === null ||\n typeof value === 'boolean' ||\n typeof value === 'number' ||\n typeof value === 'string'\n )\n}\n\n/**\n * Parse JSON content with automatic Buffer handling and BOM stripping.\n * Provides safer JSON parsing with helpful error messages and optional error suppression.\n *\n * Features:\n * - Automatic UTF-8 Buffer conversion\n * - BOM (Byte Order Mark) stripping for cross-platform compatibility\n * - Enhanced error messages with filepath context\n * - Optional error suppression (returns `undefined` instead of throwing)\n * - Optional reviver for transforming parsed values\n *\n * @param content - JSON string or Buffer to parse\n * @param options - Optional parsing configuration\n * @returns Parsed JSON value, or `undefined` if parsing fails and `throws` is `false`\n *\n * @throws {SyntaxError} When JSON is invalid and `throws` is `true` (default)\n *\n * @example\n * ```ts\n * // Basic usage\n * const data = jsonParse('{\"name\":\"example\"}')\n * console.log(data.name) // => 'example'\n *\n * // Parse Buffer with UTF-8 BOM\n * const buffer = Buffer.from('\\uFEFF{\"value\":42}')\n * const data = jsonParse(buffer)\n * console.log(data.value) // => 42\n *\n * // Enhanced error messages with filepath\n * try {\n * jsonParse('invalid', { filepath: 'config.json' })\n * } catch (err) {\n * console.error(err.message)\n * // => \"config.json: Unexpected token i in JSON at position 0\"\n * }\n *\n * // Suppress errors\n * const result = jsonParse('invalid', { throws: false })\n * console.log(result) // => undefined\n *\n * // Transform values with reviver\n * const json = '{\"created\":\"2024-01-15T10:30:00Z\"}'\n * const data = jsonParse(json, {\n * reviver: (key, value) => {\n * if (key === 'created' && typeof value === 'string') {\n * return new Date(value)\n * }\n * return value\n * }\n * })\n * console.log(data.created instanceof Date) // => true\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function jsonParse(\n content: string | Buffer,\n options?: JsonParseOptions | undefined,\n): JsonValue | undefined {\n const { filepath, reviver, throws } = {\n __proto__: null,\n ...options,\n } as JsonParseOptions\n const shouldThrow = throws === undefined || !!throws\n const jsonStr = isBuffer(content) ? content.toString('utf8') : content\n try {\n return JSONParse(stripBom(jsonStr), reviver)\n } catch (e) {\n if (shouldThrow) {\n const error = e as Error\n if (error && typeof filepath === 'string') {\n error.message = `${filepath}: ${error.message}`\n }\n throw error\n }\n }\n return undefined\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAKA,qBAAyB;AAoIzB,MAAM,YAAY,KAAK;AAAA;AAiBvB,SAAS,SAAS,GAAyB;AACzC,MAAI,CAAC,KAAK,OAAO,MAAM,UAAU;AAC/B,WAAO;AAAA,EACT;AACA,QAAM,MAAM;AACZ,MAAI,OAAO,IAAI,QAAQ,MAAM,UAAU;AACrC,WAAO;AAAA,EACT;AACA,MAAI,OAAO,IAAI,MAAM,MAAM,cAAc,OAAO,IAAI,OAAO,MAAM,YAAY;AAC3E,WAAO;AAAA,EACT;AACA,MACE,OAAO,IAAI,QAAQ,MAAM,YACzB,IAAI,QAAQ,IAAI,KAChB,OAAO,IAAI,CAAC,MAAM,UAClB;AACA,WAAO;AAAA,EACT;AAEA,QAAM,OAAQ,EAAgC;AAG9C,SAAO,CAAC,EAAE,OAAO,MAAM,aAAa,cAAc,KAAK,SAAS,CAAC;AACnE;AAAA;AAqBO,SAAS,gBAAgB,OAAwC;AACtE,SACE,UAAU,QACV,OAAO,UAAU,aACjB,OAAO,UAAU,YACjB,OAAO,UAAU;AAErB;AAAA;AAwDO,SAAS,UACd,SACA,SACuB;AACvB,QAAM,EAAE,UAAU,SAAS,OAAO,IAAI;AAAA,IACpC,WAAW;AAAA,IACX,GAAG;AAAA,EACL;AACA,QAAM,cAAc,WAAW,UAAa,CAAC,CAAC;AAC9C,QAAM,UAAU,yBAAS,OAAO,IAAI,QAAQ,SAAS,MAAM,IAAI;AAC/D,MAAI;AACF,WAAO,cAAU,yBAAS,OAAO,GAAG,OAAO;AAAA,EAC7C,SAAS,GAAG;AACV,QAAI,aAAa;AACf,YAAM,QAAQ;AACd,UAAI,SAAS,OAAO,aAAa,UAAU;AACzC,cAAM,UAAU,GAAG,QAAQ,KAAK,MAAM,OAAO;AAAA,MAC/C;AACA,YAAM;AAAA,IACR;AAAA,EACF;AACA,SAAO;AACT;",
6
- "names": []
7
- }
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/links/index.ts"],
4
- "sourcesContent": ["/**\n * @fileoverview Themed hyperlink utilities for terminal output.\n * Provides colored hyperlinks using theme configuration.\n */\n\nimport yoctocolorsCjs from '../external/yoctocolors-cjs'\nimport type { ColorName } from '../spinner'\nimport { getTheme } from '../themes/context'\nimport { THEMES } from '../themes/themes'\nimport { resolveColor } from '../themes/utils'\nimport type { Theme } from '../themes/types'\nimport type { ThemeName } from '../themes/themes'\n\n/**\n * Options for creating themed links.\n */\nexport type LinkOptions = {\n /** Theme to use (overrides global) */\n theme?: Theme | ThemeName | undefined\n /** Show URL as fallback if terminal doesn't support links */\n fallback?: boolean | undefined\n}\n\n/**\n * Create a themed hyperlink for terminal output.\n * The link text is colored using the theme's link color.\n *\n * Note: Most terminals support ANSI color codes but not clickable links.\n * This function colors the text but does not create clickable hyperlinks.\n * For clickable links, use a library like 'terminal-link' separately.\n *\n * @param text - Link text to display\n * @param url - URL (included in fallback mode)\n * @param options - Link configuration options\n * @returns Colored link text\n *\n * @example\n * ```ts\n * import { link } from '@socketsecurity/lib/links'\n *\n * // Use current theme\n * console.log(link('Documentation', 'https://socket.dev'))\n *\n * // Override theme\n * console.log(link('API Docs', 'https://api.socket.dev', {\n * theme: 'coana'\n * }))\n *\n * // Show URL as fallback\n * console.log(link('GitHub', 'https://github.com', {\n * fallback: true\n * }))\n * // Output: \"GitHub (https://github.com)\"\n * ```\n */\nexport function link(text: string, url: string, options?: LinkOptions): string {\n const opts = { __proto__: null, fallback: false, ...options } as LinkOptions\n\n // Resolve theme\n const theme =\n typeof opts.theme === 'string'\n ? THEMES[opts.theme]\n : (opts.theme ?? getTheme())\n\n // Resolve link color\n const linkColor = resolveColor(theme.colors.link, theme.colors)\n\n // Apply color - for now just use cyan as a simple fallback\n // Note: RGB color support to be added in yoctocolors wrapper\n const colors = yoctocolorsCjs\n let colored: string\n if (typeof linkColor === 'string' && linkColor !== 'inherit') {\n // Use named color method if available\n const colorMethod = colors[linkColor as ColorName]\n colored = colorMethod ? colorMethod(text) : colors.cyan(text)\n } else if (Array.isArray(linkColor)) {\n // RGB color - for now fallback to cyan\n // Note: RGB color support to be implemented\n colored = colors.cyan(text)\n } else {\n colored = colors.cyan(text)\n }\n\n // Return with or without URL fallback\n return opts.fallback ? `${colored} (${url})` : colored\n}\n\n/**\n * Create multiple themed links from an array of link specifications.\n *\n * @param links - Array of [text, url] pairs\n * @param options - Link configuration options\n * @returns Array of colored link texts\n *\n * @example\n * ```ts\n * import { links } from '@socketsecurity/lib/links'\n *\n * const formatted = links([\n * ['Documentation', 'https://socket.dev'],\n * ['API Reference', 'https://api.socket.dev'],\n * ['GitHub', 'https://github.com/SocketDev']\n * ])\n *\n * formatted.forEach(link => console.log(link))\n * ```\n */\nexport function links(\n linkSpecs: Array<[text: string, url: string]>,\n options?: LinkOptions,\n): string[] {\n return linkSpecs.map(([text, url]) => link(text, url, options))\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAKA,6BAA2B;AAE3B,qBAAyB;AACzB,oBAAuB;AACvB,mBAA6B;AA8CtB,SAAS,KAAK,MAAc,KAAa,SAA+B;AAC7E,QAAM,OAAO,EAAE,WAAW,MAAM,UAAU,OAAO,GAAG,QAAQ;AAG5D,QAAM,QACJ,OAAO,KAAK,UAAU,WAClB,qBAAO,KAAK,KAAK,IAChB,KAAK,aAAS,yBAAS;AAG9B,QAAM,gBAAY,2BAAa,MAAM,OAAO,MAAM,MAAM,MAAM;AAI9D,QAAM,SAAS,uBAAAA;AACf,MAAI;AACJ,MAAI,OAAO,cAAc,YAAY,cAAc,WAAW;AAE5D,UAAM,cAAc,OAAO,SAAsB;AACjD,cAAU,cAAc,YAAY,IAAI,IAAI,OAAO,KAAK,IAAI;AAAA,EAC9D,WAAW,MAAM,QAAQ,SAAS,GAAG;AAGnC,cAAU,OAAO,KAAK,IAAI;AAAA,EAC5B,OAAO;AACL,cAAU,OAAO,KAAK,IAAI;AAAA,EAC5B;AAGA,SAAO,KAAK,WAAW,GAAG,OAAO,KAAK,GAAG,MAAM;AACjD;AAsBO,SAAS,MACd,WACA,SACU;AACV,SAAO,UAAU,IAAI,CAAC,CAAC,MAAM,GAAG,MAAM,KAAK,MAAM,KAAK,OAAO,CAAC;AAChE;",
6
- "names": ["yoctocolorsCjs"]
7
- }