TExcelTAD

JS Packages & Bundlers Exercises

The first four exercises are small pieces of the logic that package managers and bundlers run on every install and build, written as pure functions with the tests already in place. Run the starter first: it prints wrong answers, which shows what the tests expect. Complete the code marked TODO until the output matches the expected output, then compare with the solution. The last exercise is a real pnpm workspace to repair.

Exercise 1: maxSatisfying

Topics: Semver & Version Ranges

Implement satisfies(version, range) for exact versions, ^ and ~ ranges (including the 0.x caret rules), then maxSatisfying returns the highest matching version or null. Compare versions numerically: 1.10.2 is newer than 1.4.0.

js · try it yourself
const parse = (v) => v.split('.').map(Number);
const cmp = (a, b) => { for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] - b[i]; return 0; };

function satisfies(version, range) {
  // TODO: exact match, ~x.y.z (< x.(y+1).0), ^x.y.z (first non-zero part fixed)
  return false;
}

function maxSatisfying(versions, range) {
  // TODO: the highest version for which satisfies() is true, or null
  return null;
}

const versions = ['1.2.3', '1.4.0', '1.10.2', '2.0.0', '0.3.1', '0.3.9', '0.4.0'];
for (const r of ['^1.2.0', '~1.4.0', '^0.3.2', '2.0.0', '^3.0.0']) console.log(r.padEnd(7), '->', maxSatisfying(versions, r));
^1.2.0  -> null
~1.4.0  -> null
^0.3.2  -> null
2.0.0   -> null
^3.0.0  -> null

Expected output:

text
^1.2.0  -> 1.10.2
~1.4.0  -> 1.4.0
^0.3.2  -> 0.3.9
2.0.0   -> 2.0.0
^3.0.0  -> null
Show solution
js
function satisfies(version, range) {
  const v = parse(version);
  if (range[0] === '^' || range[0] === '~') {
    const lo = parse(range.slice(1));
    let hi;
    if (range[0] === '~') hi = [lo[0], lo[1] + 1, 0];
    else if (lo[0] > 0) hi = [lo[0] + 1, 0, 0];
    else if (lo[1] > 0) hi = [0, lo[1] + 1, 0];
    else hi = [0, 0, lo[2] + 1];
    return cmp(v, lo) >= 0 && cmp(v, hi) < 0;
  }
  return cmp(v, parse(range)) === 0;
}

function maxSatisfying(versions, range) {
  return versions.filter((v) => satisfies(v, range)).sort((a, b) => cmp(parse(b), parse(a)))[0] ?? null;
}

Exercise 2: Would npm ci accept this lockfile?

Topics: package-lock.json, npm ci vs npm install

checkSync(manifest, lock) compares package.json dependencies with a v3 lockfile and returns a list of problems, or ['in sync']. Report, in this order: each manifest dependency that is missing from the lock or whose locked version doesn't satisfy its range (invalid), then each dependency in the lock's root entry that the manifest no longer has (extraneous). A caret(version, range) helper is provided.

js · try it yourself
const caret = (v, r) => { const [a, b] = [v.split('.').map(Number), r.slice(1).split('.').map(Number)];
  return a[0] === b[0] && (a[1] > b[1] || (a[1] === b[1] && a[2] >= b[2])); };

function checkSync(manifest, lock) {
  const problems = [];
  // TODO: Missing / Invalid for each manifest dependency (look up lock.packages[`node_modules/${name}`])
  // TODO: Extraneous for each name in lock.packages[''].dependencies not in the manifest
  return problems.length ? problems : ['in sync'];
}

const lock = { packages: { '': { dependencies: { lodash: '^4.17.21', ms: '^2.1.3' } },
  'node_modules/lodash': { version: '4.17.21' }, 'node_modules/ms': { version: '2.1.3' } } };
console.log(checkSync({ dependencies: { lodash: '^4.17.21', ms: '^2.1.3' } }, lock));
console.log(checkSync({ dependencies: { lodash: '^4.18.0', ms: '^2.1.3', chalk: '^4.1.2' } }, lock));
console.log(checkSync({ dependencies: { lodash: '^4.17.21' } }, lock));
[ 'in sync' ]
[ 'in sync' ]
[ 'in sync' ]

Expected output:

text
[ 'in sync' ]
[
  "Invalid: lock file's lodash@4.17.21 does not satisfy lodash@^4.18.0",
  'Missing: chalk@^4.1.2 from lock file'
]
[ 'Extraneous: ms is in the lock file but not in package.json' ]
Show solution
js
function checkSync(manifest, lock) {
  const problems = [];
  for (const [name, range] of Object.entries(manifest.dependencies)) {
    const entry = lock.packages[`node_modules/${name}`];
    if (!entry) problems.push(`Missing: ${name}@${range} from lock file`);
    else if (!caret(entry.version, range)) problems.push(`Invalid: lock file's ${name}@${entry.version} does not satisfy ${name}@${range}`);
  }
  for (const name of Object.keys(lock.packages[''].dependencies ?? {})) {
    if (!(name in manifest.dependencies)) problems.push(`Extraneous: ${name} is in the lock file but not in package.json`);
  }
  return problems.length ? problems : ['in sync'];
}

Exercise 3: Workspace build order

Topics: pnpm -r, --filter & Publishing, Turborepo & Nx

buildOrder(pkgs) returns the workspace packages in an order where every package comes after its dependencies (visit packages and dependencies in alphabetical order, so the answer is unique). If the graph has a cycle, throw Error('cycle: a -> b -> c -> a').

js · try it yourself
function buildOrder(pkgs) {
  const order = [];
  // TODO: depth-first search; mark packages 'visiting' / 'done'; push a package after its dependencies
  return order;
}

const ws = { app: ['ui', 'api-client'], ui: ['core'], 'api-client': ['core'], core: [], docs: [] };
console.log(buildOrder(ws).join(' '));
try { console.log(buildOrder({ a: ['b'], b: ['c'], c: ['a'] }).join(' ') || '(no cycle detected)'); } catch (e) { console.log(e.message); }

(no cycle detected)

Expected output:

text
core api-client ui app docs
cycle: a -> b -> c -> a
Show solution
js
function buildOrder(pkgs) {
  const order = [], state = {};
  const visit = (name, path) => {
    if (state[name] === 'done') return;
    if (state[name] === 'visiting') throw new Error(`cycle: ${[...path, name].join(' -> ')}`);
    state[name] = 'visiting';
    for (const d of [...pkgs[name]].sort()) visit(d, [...path, name]);
    state[name] = 'done';
    order.push(name);
  };
  for (const name of Object.keys(pkgs).sort()) visit(name, []);
  return order;
}

Exercise 4: Resolve an exports map

Topics: How Node Resolves Packages, TypeScript Libraries

resolveExport(pkg, subpath, conditions) returns the file a consumer gets. Rules: without exports, '.' maps to main (or index.js) and other subpaths to themselves (without ./). With exports, an unknown subpath is ERR_PACKAGE_PATH_NOT_EXPORTED. A condition object is searched in its own key order; take the first key that is default or in conditions, and keep descending while the target is an object.

js · try it yourself
function resolveExport(pkg, subpath, conditions) {
  // TODO
  return undefined;
}

const pkg = { name: 'units', main: './dist/index.cjs', exports: {
  '.': { import: { types: './dist/index.d.ts', default: './dist/index.js' }, require: { types: './dist/index.d.cts', default: './dist/index.cjs' } },
  './package.json': './package.json' } };
console.log(resolveExport(pkg, '.', ['import']));
console.log(resolveExport(pkg, '.', ['require']));
console.log(resolveExport(pkg, '.', ['types', 'import']));
console.log(resolveExport(pkg, './package.json', ['require']));
console.log(resolveExport(pkg, './dist/secret.js', ['import']));
console.log(resolveExport({ main: 'lib/main.js' }, '.', ['import']));
undefined
undefined
undefined
undefined
undefined
undefined

Expected output:

text
./dist/index.js
./dist/index.cjs
./dist/index.d.ts
./package.json
ERR_PACKAGE_PATH_NOT_EXPORTED
lib/main.js
Show solution
js
function resolveExport(pkg, subpath, conditions) {
  const exp = pkg.exports;
  if (!exp) return subpath === '.' ? pkg.main ?? 'index.js' : subpath.slice(2);
  const map = typeof exp === 'string' || !Object.keys(exp).some((k) => k.startsWith('.')) ? { '.': exp } : exp;
  let target = map[subpath];
  if (target === undefined) return 'ERR_PACKAGE_PATH_NOT_EXPORTED';
  while (target && typeof target === 'object') {
    const key = Object.keys(target).find((k) => k === 'default' || conditions.includes(k));
    if (key === undefined) return 'ERR_PACKAGE_PATH_NOT_EXPORTED';
    target = target[key];
  }
  return target;
}

Note the third case: with both types and import active, the nested object's first matching key wins, which is why types must come first in each branch.

Exercise 5: Repair a pnpm workspace

Topics: Strictness & Phantom Dependencies, pnpm Workspaces, pnpm -r

This workspace was migrated from npm and no longer works. The session peels off the problems one at a time: a typo, an internal dependency that pnpm looks up on the registry, and then a third failure once that's fixed. Repair the workspace without shamefully-hoist: every package must declare what it uses, internal dependencies must never resolve from the registry, and both packages should share one lodash version definition.

bash · try it yourself
mkdir -p shop/packages/{money,web} && cd shop
echo '{ "name": "shop", "private": true }' > package.json
printf 'packages:\n  - packages/*\n' > pnpm-workspace.yaml
echo '{ "name": "@shop/money", "version": "1.0.0", "main": "index.js", "dependencies": { "lodash": "^4.18.1" } }' > packages/money/package.json
echo 'exports.format = (n) => "
quot; + require("lodash").round(n, 2).toFixed(2);' > packages/money/index.js echo '{ "name": "@shop/web", "version": "1.0.0", "dependencies": { "@shop/mony": "^1.0.0" } }' > packages/web/package.json cat > packages/web/index.js <<'JS' const { format } = require('@shop/money'); const { sumBy } = require('lodash'); console.log('total', format(sumBy([{ p: 9.99 }, { p: 5.5 }], 'p'))); JS pnpm install 2>&1 | grep -E 'ERR_PNPM|404' | head -2 echo '--- after fixing the typo:' sed -i 's/@shop\/mony/@shop\/money/' packages/web/package.json pnpm install 2>&1 | grep -E 'ERR_PNPM|404' | head -2 echo '--- after switching to workspace:^' sed -i 's/"@shop\/money": "^1.0.0"/"@shop\/money": "workspace:^"/' packages/web/package.json pnpm install > /dev/null 2>&1 node packages/web/index.js 2>&1 | grep -m1 Error
 ERR_PNPM_FETCH_404  GET http://localhost:4873/@shop%2Fmony: Not Found - 404
--- after fixing the typo:
 ERR_PNPM_FETCH_404  GET http://localhost:4873/@shop%2Fmoney: Not Found - 404
--- after switching to workspace:^
Error: Cannot find module 'lodash'
Show solution

Three problems. The typo was sent to the registry. Even spelled correctly, "^1.0.0" is a registry range: pnpm 10 doesn't link a workspace package for a plain range unless link-workspace-packages is enabled, so it asked the registry for @shop/money too. workspace:^ fixes both, and would have turned the typo into a local error. Finally, web uses lodash without declaring it, which only worked under npm's hoisting.

bash · try it yourself
mkdir -p shop/packages/{money,web} && cd shop
echo '{ "name": "shop", "private": true }' > package.json
printf 'packages:\n  - packages/*\ncatalog:\n  lodash: ^4.18.1\n' > pnpm-workspace.yaml
echo '{ "name": "@shop/money", "version": "1.0.0", "main": "index.js", "dependencies": { "lodash": "catalog:" } }' > packages/money/package.json
echo 'exports.format = (n) => "
quot; + require("lodash").round(n, 2).toFixed(2);' > packages/money/index.js echo '{ "name": "@shop/web", "version": "1.0.0", "dependencies": { "@shop/money": "workspace:^", "lodash": "catalog:" } }' > packages/web/package.json cat > packages/web/index.js <<'JS' const { format } = require('@shop/money'); const { sumBy } = require('lodash'); console.log('total', format(sumBy([{ p: 9.99 }, { p: 5.5 }], 'p'))); JS pnpm install > /dev/null 2>&1 node packages/web/index.js pnpm -r list lodash --depth 0 | grep -E '^@shop|lodash'
total $15.49
@shop/money@1.0.0 /home/learner/shop/packages/money
└── lodash@4.18.1
@shop/web@1.0.0 /home/learner/shop/packages/web
└── lodash@4.18.1

Both packages now take lodash from the catalog, so they can't drift apart, and the internal dependency uses workspace:^.

Test yourself

In Exercise 2, why is ms reported as extraneous?

  1. Its version is wrong
  2. The lockfile's root entry lists it, but package.json no longer does
  3. It has no integrity hash
  4. It's a dev dependency

In Exercise 5, why did the misspelled @shop/mony produce a registry error rather than a local one?

  1. pnpm always uses the registry
  2. A plain semver range can be satisfied from the registry; only workspace: forces a local package
  3. The workspace file was wrong
  4. Because of the catalog