├── .gitignore ├── src ├── index.ts ├── partial.ts ├── undefined.ts ├── prebuilt.ts ├── watch-tree.ts └── context.ts ├── .vscode ├── extensions.json └── settings.json ├── tsconfig.json ├── LICENSE.md ├── package.json └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | lib 2 | node_modules 3 | *.tgz 4 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./prebuilt.js"; 2 | export * from "./watch-tree.js"; 3 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": [ 3 | "esbenp.prettier-vscode" 4 | ] 5 | } -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.formatOnSave": true, 3 | "editor.defaultFormatter": "esbenp.prettier-vscode" 4 | } -------------------------------------------------------------------------------- /src/partial.ts: -------------------------------------------------------------------------------- 1 | export const partial = 2 | ( 3 | fn: (arg1: TArg1, ...rest: TRest) => TReturn, 4 | arg1: TArg1, 5 | ): ((...rest: TRest) => TReturn) => 6 | (...rest) => 7 | fn(arg1, ...rest); 8 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "@tsconfig/strictest/tsconfig.json", 3 | "compilerOptions": { 4 | "declaration": true, 5 | "inlineSourceMap": true, 6 | "module": "NodeNext", 7 | "outDir": "lib" 8 | }, 9 | "include": [ 10 | "src/**/*" 11 | ], 12 | "exclude": [ 13 | "node_modules", 14 | "lib" 15 | ] 16 | } -------------------------------------------------------------------------------- /src/undefined.ts: -------------------------------------------------------------------------------- 1 | export const isDefined = (value: T | undefined): value is T => 2 | typeof value !== "undefined"; 3 | 4 | export const isUndefined = (value: any): value is undefined => 5 | typeof value === "undefined"; 6 | 7 | export const defined = (value: T | undefined) => { 8 | if (isUndefined(value)) throw new Error("undefined"); 9 | return value; 10 | }; 11 | -------------------------------------------------------------------------------- /src/prebuilt.ts: -------------------------------------------------------------------------------- 1 | import path from "node:path"; 2 | import { PackageInfo, WatchExpression } from "./watch-tree.js"; 3 | 4 | export const tsViteBuild = (p: PackageInfo): WatchExpression => [ 5 | "allof", 6 | [ 7 | "not", 8 | [ 9 | "anyof", 10 | ["dirname", "dist"], 11 | ["dirname", "node_modules"], 12 | ["dirname", "lib"], 13 | ], 14 | ], 15 | [ 16 | "anyof", 17 | [ 18 | "allof", 19 | ["dirname", p.root], 20 | ["anyof", ["match", "index.html", "wholename"]], 21 | ], 22 | [ 23 | "allof", 24 | ["dirname", path.join(p.root, "src")], 25 | ["anyof", ["match", "*.ts", "basename"], ["match", "*.css", "basename"]], 26 | ], 27 | ], 28 | ]; 29 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Copyright © 2023 Mattie Behrens. 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "turbotree", 3 | "type": "module", 4 | "version": "1.0.2-alpha.0", 5 | "description": "use turbo and turbowatch to intelligently watch your whole monorepo", 6 | "homepage": "https://github.com/mattieb/turbotree", 7 | "license": "MIT", 8 | "author": { 9 | "name": "Mattie Behrens", 10 | "email": "mattie@mattiebee.io", 11 | "url": "https://mattiebee.io" 12 | }, 13 | "files": [ 14 | "./lib" 15 | ], 16 | "main": "./lib/index.js", 17 | "types": "./lib/index.d.ts", 18 | "repository": { 19 | "type": "git", 20 | "url": "git+https://github.com/mattieb/turbotree.git" 21 | }, 22 | "scripts": { 23 | "build": "tsc", 24 | "bump:alpha": "npm version prerelease --no-git-tag-version --preid=alpha", 25 | "clean": "rimraf lib", 26 | "prepare": "npm run build", 27 | "watch": "tsc -w" 28 | }, 29 | "prettier": { 30 | "plugins": [ 31 | "prettier-plugin-organize-imports" 32 | ] 33 | }, 34 | "dependencies": { 35 | "supports-color": "^9.4.0", 36 | "turbowatch": "^2.29.4", 37 | "workspace-tools": "^0.36.3", 38 | "zx": "^7.2.3" 39 | }, 40 | "devDependencies": { 41 | "@tsconfig/strictest": "^2.0.2", 42 | "prettier": "^3.0.3", 43 | "prettier-plugin-organize-imports": "^3.2.3", 44 | "rimraf": "^5.0.5", 45 | "type-fest": "^4.5.0", 46 | "typescript": "^5.2.2" 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/watch-tree.ts: -------------------------------------------------------------------------------- 1 | import supportsColor from "supports-color"; 2 | import { watch } from "turbowatch"; 3 | import { TurbowatchConfigurationInput } from "turbowatch/dist/types.js"; 4 | import type { IterableElement } from "type-fest"; 5 | import { $, ProcessOutput, chalk } from "zx"; 6 | import { buildContext } from "./context.js"; 7 | import { defined, isDefined } from "./undefined.js"; 8 | 9 | export type PackageInfo = Readonly<{ 10 | $: typeof $; 11 | name: string; 12 | root: string; 13 | leaves: readonly string[]; 14 | turboFilterFlags: readonly string[]; 15 | }>; 16 | 17 | export type KickstartContext = Readonly<{ 18 | $: typeof $; 19 | turboFilterFlags: readonly string[]; 20 | }>; 21 | 22 | export type Trigger = IterableElement; 23 | 24 | export type WatchExpression = Trigger["expression"]; 25 | 26 | const message = (text: string) => { 27 | console.log(chalk.bold(`${chalk.green("==>")} ${text}`)); 28 | console.log(); 29 | }; 30 | 31 | export const watchTree = async ( 32 | root: string, 33 | makeTriggers: (p: PackageInfo) => readonly Trigger[], 34 | kickstartCommand?: (k: KickstartContext) => Promise, 35 | ) => { 36 | const ctx = buildContext(root); 37 | 38 | const triggers = ctx.packageGraph.packages 39 | .map((name) => { 40 | const leaves = defined(ctx.leavesByPackage[name]); 41 | const packageInfo: PackageInfo = { 42 | $, 43 | name, 44 | root: defined(ctx.relativePaths[name]), 45 | leaves, 46 | turboFilterFlags: ctx.turboFilterFlags(leaves), 47 | }; 48 | return makeTriggers(packageInfo); 49 | }) 50 | .reduce((a, t) => a.concat(t), []); 51 | 52 | if (supportsColor.stdout) { 53 | $.env["FORCE_COLOR"] = "1"; 54 | } 55 | 56 | if (isDefined(kickstartCommand)) { 57 | message("Kickstarting..."); 58 | 59 | const turboFilterFlags = ctx.turboFilterFlags(ctx.allLeaves); 60 | await kickstartCommand({ $, turboFilterFlags }); 61 | } 62 | 63 | message("Watching..."); 64 | 65 | watch({ project: ctx.projectRoot, triggers }); 66 | }; 67 | -------------------------------------------------------------------------------- /src/context.ts: -------------------------------------------------------------------------------- 1 | import path from "node:path"; 2 | import { 3 | createPackageGraph, 4 | getPackageInfos, 5 | getWorkspaceRoot, 6 | } from "workspace-tools"; 7 | import { partial } from "./partial.js"; 8 | import { defined, isUndefined } from "./undefined.js"; 9 | 10 | type Dependents = { [key: string]: string[] }; 11 | 12 | const getLeaves = (dependents: Dependents, node: string): string[] => { 13 | const dependent = dependents[node]; 14 | if (isUndefined(dependent)) return [node]; 15 | return dependent 16 | .map(partial(getLeaves, dependents)) 17 | .reduce((a, d) => a.concat(d), []) 18 | .reduce((a, d) => (a.includes(d) ? a : a.concat([d])), [] as string[]); 19 | }; 20 | 21 | const unboundTurboFilterFlags = ( 22 | relativePaths: { [key: string]: string }, 23 | leaves: string[], 24 | ) => leaves.map((l) => `--filter=./${relativePaths[l]}`); 25 | 26 | export const buildContext = (root: string) => { 27 | const projectRoot = defined(getWorkspaceRoot(root)); 28 | const packageInfos = getPackageInfos(projectRoot); 29 | const packageGraph = createPackageGraph(packageInfos); 30 | 31 | const dependents = packageGraph.dependencies.reduce( 32 | (a, d) => ({ 33 | ...a, 34 | [d.dependency]: (a[d.dependency] ?? []).concat([d.name]), 35 | }), 36 | {} as Dependents, 37 | ); 38 | 39 | const getLeavesFromDependents = partial(getLeaves, dependents); 40 | 41 | const leavesByPackage = Object.fromEntries( 42 | packageGraph.packages.map((p) => [p, getLeavesFromDependents(p)]), 43 | ); 44 | 45 | const allLeaves = Object.values(leavesByPackage) 46 | .reduce((a, d) => a.concat(d), []) 47 | .reduce((a, d) => (a.includes(d) ? a : a.concat([d])), [] as string[]); 48 | 49 | const relativePaths = Object.fromEntries( 50 | packageGraph.packages.map((p) => [ 51 | p, 52 | path.relative( 53 | projectRoot, 54 | path.dirname(defined(packageInfos[p]).packageJsonPath), 55 | ), 56 | ]), 57 | ); 58 | 59 | const turboFilterFlags = partial(unboundTurboFilterFlags, relativePaths); 60 | 61 | return { 62 | allLeaves, 63 | leavesByPackage, 64 | packageGraph, 65 | projectRoot, 66 | relativePaths, 67 | turboFilterFlags, 68 | }; 69 | }; 70 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # turbotree 2 | 3 | turbotree uses [turbowatch](https://github.com/gajus/turbowatch) and [turbo](https://turbo.build) to 4 | 5 | - determine the dependencies in your monorepo (using [workspace-tools](https://microsoft.github.io/workspace-tools/)), and 6 | - rebuild packages _and their dependents_ in the proper order when changes happen. 7 | 8 | turbotree works with monorepos based on [workspaces](https://docs.npmjs.com/cli/using-npm/workspaces). 9 | 10 | ## Getting started 11 | 12 | Here's a complete example "watch.ts" script: 13 | 14 | ```typescript 15 | import { KickstartContext, PackageInfo, Trigger, watchTree } from "turbotree"; 16 | 17 | const triggers = (p: PackageInfo): Trigger[] => [ 18 | { 19 | expression: tsViteBuild(p), 20 | name: `${p.name}:build`, 21 | initialRun: false, 22 | onChange: async ({ spawn, files }) => { 23 | console.log(`${p.root}: changes detected: ${files.map((f) => f.name)}`); 24 | await spawn`npx turbo build --output-logs=new-only ${p.turboFilterFlags}`; 25 | }, 26 | }, 27 | ]; 28 | 29 | const kickstartCommand = async (k: KickstartContext) => 30 | k.$`npx turbo build --output-logs=new-only ${k.turboFilterFlags}`; 31 | 32 | watchTree(__dirname, triggers, kickstartCommand); 33 | ``` 34 | 35 | With a "package.json" correctly set up with workspaces, this is all you need to watch your entire tree. 36 | 37 | ### Triggers 38 | 39 | The first argument to "watchTree" is a function that can generate triggers, which are [the same triggers turbowatch uses](https://github.com/gajus/turbowatch#api) (in fact, they're passed directly to turbowatch). 40 | 41 | That function is supplied a package info object which has things like the package name, its root directory, information about the dependency tree from that package's vantage point, and a set of filter flags for turbo. 42 | 43 | The filter flags are the most important part; they are used to construct a command that will tell turbo to rebuild the _leaves_ of the dependency tree when this package changes. turbo is then relied on to figure out what packages to (re)build and in what order. 44 | 45 | So, for example, given this dependency tree: 46 | 47 | ```mermaid 48 | graph LR; 49 | core-->server; 50 | core-->api; 51 | server-->api; 52 | core-->sdk; 53 | sdk-->client; 54 | ``` 55 | 56 | If changes are detected in "core", the filter flags ask turbo to build both "api" and "client". If changes are detected in "server", turbo will be asked to build only "api". 57 | 58 | In both cases, turbo will rebuild a package and all related packages under its control. So, for "core", it would rebuild all packages. For "api", it would build "core", "api", and "server". 59 | 60 | When turbo builds each package, it checks to see if anything has actually changed first. If it hasn't, it won't actually do the build. 61 | 62 | In short, we tell turbo exactly once when files change what the relevant parts of the tree are, and rely on turbo itself to determine what actually needs rebuilding. 63 | 64 | ### Kickstart 65 | 66 | Of course, triggers only fire when changes are detected. If the watch script isn't running, it can't detect changes. 67 | 68 | turbotree has optional support for a "kickstart" in this case. The kickstart context that is passed in to a kickstart function will contain turbo filter flags, as before, as well as a reference to [zx](https://github.com/google/zx) that can be used to execute a command. 69 | 70 | The filter flags will describe all leaves of the dependency tree. In this case, the kickstart will build everything (and, again, turbo will skip things that are already built) one time before the watcher takes over. 71 | 72 | ## Watch expressions 73 | 74 | turbowatch triggers have an "expression" property that describes the watch [expression](https://github.com/gajus/turbowatch#expressions) that will trigger that particular rule. (See that documentation for more information on how to build an expression.) 75 | 76 | In the [quick start](#quick-start) above, we use a prebuilt watch expression included with turbotree. This expression is designed for packages that 77 | 78 | - have TypeScript, CSS, and/or HTML source code in "src", 79 | - may have an "index.html" in the root of the project (such as with [Vite](https://vitejs.dev) projects) 80 | - build into "dist" and/or "lib" 81 | 82 | You can, of course, write any turbowatch-compatible watch expression you wish. 83 | 84 | ## Additional triggers 85 | 86 | The trigger builder function you pass to turbotree doesn't just take a single trigger, but allows you to pass an arbitrarily-sized list of triggers—even none at all. 87 | 88 | For example: 89 | 90 | ```typescript 91 | const START = ["client"]; 92 | 93 | const triggers = (p: PackageInfo): Trigger[] => { 94 | const build: Trigger = { 95 | expression: tsViteBuild(p), 96 | name: `${p.name}:build`, 97 | initialRun: false, 98 | onChange: async ({ spawn, files }) => { 99 | console.log(`${p.root}: changes detected: ${files.map((f) => f.name)}`); 100 | await spawn`npx turbo build --output-logs=new-only ${p.turboFilterFlags}`; 101 | }, 102 | }; 103 | 104 | const start: Trigger = { 105 | expression: ["dirname", "lib"], 106 | name: `${p.name}:start`, 107 | initialRun: true, 108 | interruptible: true, 109 | onChange: async ({ spawn }) => { 110 | await spawn`cd ${p.root} && npm start`; 111 | }, 112 | persistent: true, 113 | }; 114 | 115 | return START.includes(p.name) ? [build, start] : [build]; 116 | }; 117 | ``` 118 | 119 | In this example, all packages get the prebuilt watch expression we saw earlier, but a few also get another trigger that runs a persistent server, then restarts it when its code is rebuilt—e.g. after dependency packages have finished rebuilding. 120 | --------------------------------------------------------------------------------