Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

workspace.ts

297 lines9.6 KB

1import { posix } from 'node:path'
2import { SchematicsException } from '@angular-devkit/schematics'
3import { getWorkspace } from '@schematics/angular/utility/workspace'
4import ts from 'typescript'
5import type { Tree } from '@angular-devkit/schematics'
6​
7// cspell:ignore subdirs
8​
9const ignoredDirectories = new Set([
10 'node_modules',
11 'dist',
12 'build',
13 '.git',
14 '.angular',
15 '.nx',
16 '.cache',
17 'coverage',
18])
19​
20function isSource(path: string) {
21 return /\.[cm]?tsx?$/.test(path) && !/\.d\.[cm]?ts$/.test(path)
23​
24/** Visit files without descending into dependencies or generated output. */
25function filesUnder(tree: Tree, root: string): Array<string> {
26 const files: Array<string> = []
27 const visit = (path: string) => {
28 const directory = tree.getDir(path)
29 for (const name of directory.subfiles) {
30 const file = posix.join(path, name)
31 files.push(file)
32 }
33 for (const name of directory.subdirs) {
34 if (!ignoredDirectories.has(name)) visit(posix.join(path, name))
35 }
36 }
37 visit(root)
38 return files
40​
41function sourcesUnder(tree: Tree, root: string) {
42 return filesUnder(tree, root).filter(isSource)
44​
45/** Include declarations, JavaScript, and component files when checking dependency references. */
46export function packageReferenceFiles(tree: Tree, packageName: string) {
47 return filesUnder(tree, '/').filter((path) => {
48 const isComponent = /\.(vue|svelte|astro)$/.test(path)
49 if (!isComponent && !/\.[cm]?[jt]sx?$/.test(path)) return false
50 const text = tree.readText(path)
51 if (!text.includes(packageName)) return false
52 if (isComponent) return true
53 const containsReference = (node: ts.Node): boolean => {
54 if (ts.isStringLiteralLike(node) || ts.isTemplateHead(node))
55 return (
56 node.text === packageName || node.text.startsWith(`${packageName}/`)
57 )
58 return ts.forEachChild(node, containsReference) ?? false
59 }
60 return containsReference(
61 ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true),
62 )
63 })
65​
66/** TypeScript config patterns support *, ? and **; a bare directory includes its descendants. */
67function configPattern(root: string, pattern: string): RegExp {
68 let path = posix.resolve(root, pattern)
69 if (!/[?*]/.test(path) && !posix.extname(path)) path += '/**/*'
70 const segments = path.split('/')
71 const expression = segments
72 .map((segment, index) => {
73 if (segment === '**')
74 return index === segments.length - 1 ? '.*' : '(?:[^/]+/)*'
75 const value = segment
76 .split('')
77 .map((character) => {
78 if (character === '*') return '[^/]*'
79 if (character === '?') return '[^/]'
80 return character.replace(/[\\^$.*+?()[\]{}|]/g, '\\$&')
81 })
82 .join('')
83 return value + (index < segments.length - 1 ? '/' : '')
84 })
85 .join('')
86 return new RegExp(`^${expression}$`)
88​
89function configuredSources(
90 tree: Tree,
91 configPath: string,
92 visited = new Set<string>(),
93): Array<string> {
94 if (visited.has(configPath)) return []
95 visited.add(configPath)
96 const readFile = (path: string) =>
97 tree.exists(path) ? tree.readText(path) : undefined
98 const config = ts.getParsedCommandLineOfConfigFile(
99 configPath,
100 { noLib: true },
101 {
102 useCaseSensitiveFileNames: true,
103 getCurrentDirectory: () => '/',
104 fileExists: (path) => tree.exists(path),
105 readFile,
106 readDirectory: (root, extensions, excludes, includes) => {
107 const patterns = includes
108 const roots = new Set([root])
109 for (const pattern of patterns) {
110 const prefix = posix.resolve(root, pattern).split(/[?*]/)[0]!
111 roots.add(prefix.endsWith('/') ? prefix : posix.dirname(prefix))
112 }
113 const candidates = new Set(
114 [...roots].flatMap((path) => sourcesUnder(tree, path)),
115 )
116 return [...candidates].filter(
117 (path) =>
118 extensions.some((extension) => path.endsWith(extension)) &&
119 patterns.some((pattern) =>
120 configPattern(root, pattern).test(path),
121 ) &&
122 !(excludes ?? []).some((pattern) =>
123 configPattern(root, pattern).test(path),
124 ),
125 )
126 },
127 onUnRecoverableConfigFileDiagnostic: (diagnostic) => {
128 throw new SchematicsException(
129 ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'),
130 )
131 },
132 },
133 )
134 if (!config) return []
135 const host = ts.createCompilerHost(config.options)
136 host.getCurrentDirectory = () => '/'
137 host.fileExists = (path) => tree.exists(path)
138 host.readFile = readFile
139 host.realpath = (path) => path
140 host.directoryExists = (path) => {
141 // TypeScript also probes file paths here; `getDir` throws on those.
142 if (tree.exists(path)) return false
143 const directory = tree.getDir(path)
144 return directory.subfiles.length > 0 || directory.subdirs.length > 0
145 }
146 host.getSourceFile = (path) => {
147 if (path.split('/').some((part) => ignoredDirectories.has(part)))
148 return undefined
149 const text = readFile(path)
150 return text === undefined
151 ? undefined
152 : ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true)
153 }
154 const sources = ts
155 .createProgram(config.fileNames, config.options, host)
156 .getSourceFiles()
157 .map((source) => source.fileName)
158 .filter(isSource)
159 return [
160 ...sources,
161 ...(config.projectReferences ?? []).flatMap((reference) =>
162 configuredSources(
163 tree,
164 ts.resolveProjectReferencePath(reference),
165 visited,
166 ),
167 ),
168 ]
170​
171type Target = {
172 options?: Record<string, unknown>
173 configurations?: Record<string, Record<string, unknown> | undefined>
175type ProjectConfig = {
176 root?: string
177 sourceRoot?: string
178 targets?: Record<string, Target>
180​
181/** Use Angular/Nx projects and their declared configs, including inherited configs and local imports. */
182export async function migrationWorkspace(tree: Tree) {
183 const manifests = new Set<string>()
184 if (tree.exists('/package.json')) manifests.add('/package.json')
185 const projects = new Map<
186 string,
187 {
188 sourceRoot?: string
189 configs: Set<string>
190 hasExplicitTestConfig: boolean
191 }
192 >()
193 const addProject = (
194 root: string,
195 sourceRoot: string | undefined,
196 targets: Iterable<[string, Target]>,
197 ) => {
198 root = posix.resolve('/', root)
199 const project = projects.get(root) ?? {
200 sourceRoot,
201 configs: new Set<string>(),
202 hasExplicitTestConfig: false,
203 }
204 project.sourceRoot ??= sourceRoot
205 projects.set(root, project)
206 const manifest = posix.join(root, 'package.json')
207 if (tree.exists(manifest)) manifests.add(manifest)
208 for (const [name, target] of targets) {
209 for (const options of [
210 target.options,
211 ...Object.values(target.configurations ?? {}),
212 ]) {
213 const tsConfig = options?.tsConfig
214 if (typeof tsConfig !== 'string') continue
215 if (name === 'test' || name.startsWith('test:'))
216 project.hasExplicitTestConfig = true
217 const config = posix.resolve('/', tsConfig)
218 if (tree.exists(config)) project.configs.add(config)
219 }
220 }
221 }
222 if (tree.exists('/angular.json') || tree.exists('/.angular.json')) {
223 const workspace = await getWorkspace(
224 tree,
225 tree.exists('/angular.json') ? '/angular.json' : '/.angular.json',
226 )
227 for (const project of workspace.projects.values())
228 addProject(project.root, project.sourceRoot, project.targets.entries())
229 }
230 if (tree.exists('/nx.json')) {
231 for (const path of filesUnder(tree, '/')) {
232 if (posix.basename(path) === 'project.json') {
233 const project = tree.readJson(path) as ProjectConfig
234 addProject(
235 project.root ?? posix.dirname(path),
236 project.sourceRoot,
237 Object.entries(project.targets ?? {}),
238 )
239 } else if (posix.basename(path) === 'package.json') {
240 const pkg = tree.readJson(path) as { nx?: ProjectConfig }
241 if (pkg.nx)
242 addProject(
243 posix.dirname(path),
244 pkg.nx.sourceRoot,
245 Object.entries(pkg.nx.targets ?? {}),
246 )
247 }
248 }
249 }
250 if (!projects.size) addProject('/', undefined, [])
251 const files = new Set<string>()
252 for (const [root, project] of projects) {
253 // Infer defaults only after Angular and Nx declarations have been merged.
254 if (!project.configs.size) {
255 for (const name of [
256 'tsconfig.json',
257 'tsconfig.app.json',
258 'tsconfig.lib.json',
259 ]) {
260 const config = posix.join(root, name)
261 if (tree.exists(config)) project.configs.add(config)
262 }
263 }
264 const testConfigs = project.hasExplicitTestConfig
265 ? []
266 : ['tsconfig.spec.json', 'tsconfig.test.json']
267 .map((name) => posix.join(root, name))
268 .filter((path) => tree.exists(path))
269​
270 const sources = project.configs.size
271 ? [...project.configs].flatMap((path) => configuredSources(tree, path))
272 : sourcesUnder(
273 tree,
274 posix.resolve('/', project.sourceRoot ?? root),
275 ).filter(
276 (path) =>
277 !testConfigs.length || !/\.(spec|test)\.[cm]?tsx?$/.test(path),
278 )
279 for (const path of [
280 ...sources,
281 ...testConfigs.flatMap((configPath) =>
282 configuredSources(tree, configPath),
283 ),
284 ])
285 files.add(path)
286 }
287 return { files: [...files], manifests: [...manifests] }
289​
290/** Associate each source with its closest declared workspace package. */
291export function sourceManifest(path: string, manifests: Array<string>) {
292 return [...manifests]
293 .sort((a, b) => b.length - a.length)
294 .find((manifest) =>
295 path.startsWith(`${posix.dirname(manifest).replace(/\/$/, '')}/`),
296 )