Order package builds depth-first, throwing on cycles or unknowns
A monorepo holds many packages that depend on each other. When a developer runs build web, the tool must build only what web needs, and every package must be built after the packages it depends on. Implement planBuild(workspace, targets), which returns that build plan.
planBuild(workspace, targets) // => string[]
workspace is an object whose keys are package names and whose values are arrays of the package names each package depends on, in the order they are declared.targets is an array of package names to build.targets or in a dependency list count once.Use this depth-first order so the plan is predictable:
targets in order.workspace, throw an Error whose message contains unknown (any case) and the package name. Names such as toString are unknown unless they are real keys.Error whose message contains cycle (any case) and the cycle written as package names joined by ' -> '. The cycle starts and ends with the package that repeats, following the order the walk above discovers it. For example, if the walk goes web, ui, theme and theme depends on ui, the message contains ui -> theme -> ui. A package that lists itself gives pkg -> pkg.workspace or its arrays. An empty targets array returns [].const workspace = {
web: ['ui', 'api-client'],
admin: ['ui', 'auth'],
ui: ['tokens', 'utils'],
'api-client': ['utils'],
auth: ['api-client'],
tokens: [],
utils: [],
docs: ['missing-pkg'],
};
planBuild(workspace, ['web']);
// => ['tokens', 'utils', 'ui', 'api-client', 'web']
planBuild(workspace, ['admin', 'web']);
// => ['tokens', 'utils', 'ui', 'api-client', 'auth', 'admin', 'web']
planBuild(workspace, ['docs']);
// throws Error: Unknown package: missing-pkg
planBuild({ app: ['ui'], ui: ['theme'], theme: ['ui'] }, ['app']);
// throws Error: Cycle: ui -> theme -> ui