|
| 1 | +/** |
| 2 | + * Rewrites lockfiles to use a custom npm registry. |
| 3 | + * |
| 4 | + * Purpose |
| 5 | + * - Some lockfiles contain hardcoded references to public registries. |
| 6 | + * - In Azure Pipelines, we want installs and npx to consistently resolve from a |
| 7 | + * configured private/custom registry feed. |
| 8 | + * |
| 9 | + * Inputs |
| 10 | + * - Environment variable: NPM_CONFIG_REGISTRY (required) |
| 11 | + * |
| 12 | + * Behavior |
| 13 | + * - Recursively scans the repo (excluding node_modules and .git) for: |
| 14 | + * - package-lock.json |
| 15 | + * - yarn.lock |
| 16 | + * - Replaces URLs matching: https://registry.<something>.(com|org)/ |
| 17 | + * with the provided registry URL. |
| 18 | + */ |
| 19 | +const fs = require('fs').promises; |
| 20 | +const path = require('path'); |
| 21 | + |
| 22 | +async function* getLockFiles(dir) { |
| 23 | + const files = await fs.readdir(dir); |
| 24 | + |
| 25 | + for (const file of files) { |
| 26 | + const fullPath = path.join(dir, file); |
| 27 | + const stat = await fs.stat(fullPath); |
| 28 | + |
| 29 | + if (stat.isDirectory()) { |
| 30 | + if (file === 'node_modules' || file === '.git') { |
| 31 | + continue; |
| 32 | + } |
| 33 | + yield* getLockFiles(fullPath); |
| 34 | + continue; |
| 35 | + } |
| 36 | + |
| 37 | + if (file === 'yarn.lock' || file === 'package-lock.json') { |
| 38 | + yield fullPath; |
| 39 | + } |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +async function rewrite(file, registry) { |
| 44 | + let contents = await fs.readFile(file, 'utf8'); |
| 45 | + const re = /https:\/\/registry\.[^.]+\.(com|org)\//g; |
| 46 | + contents = contents.replace(re, registry); |
| 47 | + await fs.writeFile(file, contents); |
| 48 | +} |
| 49 | + |
| 50 | +async function main() { |
| 51 | + let registry = process.env.NPM_CONFIG_REGISTRY; |
| 52 | + if (!registry) { |
| 53 | + throw new Error('NPM_CONFIG_REGISTRY is not set'); |
| 54 | + } |
| 55 | + |
| 56 | + if (!registry.endsWith('/')) { |
| 57 | + registry += '/'; |
| 58 | + } |
| 59 | + |
| 60 | + const root = process.cwd(); |
| 61 | + for await (const file of getLockFiles(root)) { |
| 62 | + await rewrite(file, registry); |
| 63 | + console.log('Updated node registry:', file); |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +main().catch((err) => { |
| 68 | + console.error(err); |
| 69 | + process.exit(1); |
| 70 | +}); |
0 commit comments