@decohere/workspace 0.0.1-dev.116

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +81 -0
  2. package/commonjs/src/const.js +69 -0
  3. package/commonjs/src/errors.js +12 -0
  4. package/commonjs/src/factories/config.factory.js +90 -0
  5. package/commonjs/src/factories/find-workspace-root.js +37 -0
  6. package/commonjs/src/factories/project.factory.js +72 -0
  7. package/commonjs/src/factories/workspace.factory.js +50 -0
  8. package/commonjs/src/index.js +74 -0
  9. package/commonjs/src/models/has-package-json.mixin.js +50 -0
  10. package/commonjs/src/models/has-tsconfig.mixin.js +75 -0
  11. package/commonjs/src/models/package-aliases.js +112 -0
  12. package/commonjs/src/models/package-json.model.js +196 -0
  13. package/commonjs/src/models/project-file-event.js +4 -0
  14. package/commonjs/src/models/project.model.js +316 -0
  15. package/commonjs/src/models/source-extensions.js +81 -0
  16. package/commonjs/src/models/tsconfig.model.js +97 -0
  17. package/commonjs/src/models/workspace-config.type.js +7 -0
  18. package/commonjs/src/models/workspace.model.js +153 -0
  19. package/es6/src/const.js +36 -0
  20. package/es6/src/errors.js +2 -0
  21. package/es6/src/factories/config.factory.js +34 -0
  22. package/es6/src/factories/find-workspace-root.js +26 -0
  23. package/es6/src/factories/project.factory.js +57 -0
  24. package/es6/src/factories/workspace.factory.js +35 -0
  25. package/es6/src/index.js +14 -0
  26. package/es6/src/models/has-package-json.mixin.js +35 -0
  27. package/es6/src/models/has-tsconfig.mixin.js +60 -0
  28. package/es6/src/models/package-aliases.js +97 -0
  29. package/es6/src/models/package-json.model.js +186 -0
  30. package/es6/src/models/project-file-event.js +1 -0
  31. package/es6/src/models/project.model.js +301 -0
  32. package/es6/src/models/source-extensions.js +66 -0
  33. package/es6/src/models/tsconfig.model.js +74 -0
  34. package/es6/src/models/workspace-config.type.js +4 -0
  35. package/es6/src/models/workspace.model.js +143 -0
  36. package/package.json +34 -0
  37. package/types/src/const.d.ts +8 -0
  38. package/types/src/errors.d.ts +2 -0
  39. package/types/src/factories/config.factory.d.ts +6 -0
  40. package/types/src/factories/find-workspace-root.d.ts +6 -0
  41. package/types/src/factories/project.factory.d.ts +8 -0
  42. package/types/src/factories/workspace.factory.d.ts +9 -0
  43. package/types/src/index.d.ts +18 -0
  44. package/types/src/models/has-package-json.mixin.d.ts +9 -0
  45. package/types/src/models/has-tsconfig.mixin.d.ts +11 -0
  46. package/types/src/models/package-aliases.d.ts +28 -0
  47. package/types/src/models/package-json.model.d.ts +39 -0
  48. package/types/src/models/project-file-event.d.ts +8 -0
  49. package/types/src/models/project.model.d.ts +64 -0
  50. package/types/src/models/source-extensions.d.ts +22 -0
  51. package/types/src/models/tsconfig.model.d.ts +11 -0
  52. package/types/src/models/workspace-config.type.d.ts +52 -0
  53. package/types/src/models/workspace.model.d.ts +40 -0
@@ -0,0 +1,97 @@
1
+ import { existsSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { sourceExtensions } from "./source-extensions.js";
4
+ /**
5
+ * Convention aliases from workspace packages, then tsconfig `paths` for the same keys.
6
+ * Prefer `Workspace.getPackageAliases` when a workspace is available.
7
+ */ function build(projects, options) {
8
+ const baseUrl = path.resolve(options.baseUrl);
9
+ const paths = {
10
+ ...conventionAliasPaths(projects, baseUrl),
11
+ ...options.tsconfigPaths
12
+ };
13
+ return {
14
+ baseUrl,
15
+ paths
16
+ };
17
+ }
18
+ /** Bare import specifier that is not relative, absolute, or a node/file URL. */ function isBareSpecifier(specifier) {
19
+ return specifier.length > 0 && !specifier.startsWith(".") && !specifier.startsWith("/") && !specifier.startsWith("node:") && !specifier.startsWith("file:") && !specifier.startsWith("data:") && !specifier.startsWith("#");
20
+ }
21
+ /**
22
+ * Resolve a bare specifier through package aliases (SWC-style `paths`
23
+ * relative to `baseUrl`) to an absolute `.ts` path. Longest key wins.
24
+ */ function resolvePath(specifier, paths, baseUrl) {
25
+ if (!isBareSpecifier(specifier)) return null;
26
+ const resolvedBase = path.resolve(baseUrl);
27
+ const keys = Object.keys(paths).sort((a, b)=>b.length - a.length);
28
+ for (const key of keys){
29
+ const target = paths[key]?.[0];
30
+ if (target == null) continue;
31
+ if (key.endsWith("/*")) {
32
+ const prefix = key.slice(0, -1);
33
+ if (!specifier.startsWith(prefix)) continue;
34
+ const mappedRoot = target.endsWith("/*") ? target.slice(0, -2) : target;
35
+ const subpath = specifier.slice(prefix.length);
36
+ return subpathSource(path.resolve(resolvedBase, mappedRoot, subpath));
37
+ }
38
+ if (specifier === key) {
39
+ return toTsSourcePath(path.resolve(resolvedBase, target.replace(/\*$/, "")));
40
+ }
41
+ }
42
+ return null;
43
+ }
44
+ function conventionAliasPaths(projects, baseUrl) {
45
+ const aliases = {};
46
+ for (const project of projects){
47
+ const name = project.name;
48
+ if (name.length === 0) continue;
49
+ const entry = path.resolve(project.getSourceEntryPath());
50
+ // A package with no root entry (only subpaths, like core) gets no bare alias, and its
51
+ // subpaths resolve under `src/`.
52
+ const hasEntry = existsSync(entry);
53
+ if (hasEntry) aliases[name] = [
54
+ toPosixRelative(baseUrl, entry)
55
+ ];
56
+ const subpathRoot = hasEntry ? path.dirname(entry) : path.resolve(project.rootDir, project.projectDirectory, "src");
57
+ if (existsSync(subpathRoot)) {
58
+ aliases[`${name}/*`] = [
59
+ `${toPosixRelative(baseUrl, subpathRoot)}/*`
60
+ ];
61
+ }
62
+ // Subpaths the package exports, mapped to their sources (#518): these can name any file,
63
+ // not just `<sub>.ts` or `<sub>/index.ts` under the entry's directory.
64
+ for (const [subpath, source] of Object.entries(project.getSourceExports())){
65
+ aliases[`${name}/${subpath.slice(2)}`] = [
66
+ toPosixRelative(baseUrl, source)
67
+ ];
68
+ }
69
+ }
70
+ return aliases;
71
+ }
72
+ function toPosixRelative(from, to) {
73
+ const relative = path.relative(from, to);
74
+ if (relative === "") return ".";
75
+ return relative.split(path.sep).join("/");
76
+ }
77
+ /**
78
+ * The source file a wildcard subpath names: `<sub>` with a source extension (`.ts`, `.tsx`, or
79
+ * `.mts`/`.cts` for `.mjs`/`.cjs`), else the `index` source of the directory it names (as
80
+ * `@pkg/models` is `src/models/index.ts`), else `<sub>.ts` for the caller to report missing.
81
+ */ function subpathSource(candidate) {
82
+ const files = sourceExtensions.candidates(candidate);
83
+ const directory = candidate.replace(/\.([mc]?[jt]sx?)$/, "");
84
+ const indexes = sourceExtensions.candidates(path.join(directory, "index"));
85
+ return [
86
+ ...files,
87
+ ...indexes
88
+ ].find((file)=>existsSync(file)) ?? toTsSourcePath(candidate);
89
+ }
90
+ /** A target as a source path: itself when it is one, else its first source candidate. */ function toTsSourcePath(candidate) {
91
+ return sourceExtensions.candidates(candidate)[0] ?? `${candidate}.ts`;
92
+ }
93
+ export const packageAliases = {
94
+ build,
95
+ isBareSpecifier,
96
+ resolvePath
97
+ };
@@ -0,0 +1,186 @@
1
+ export class PackageJson {
2
+ static PACKAGE_JSON_KEY_ORDER = [
3
+ "$schema",
4
+ "name",
5
+ "displayName",
6
+ "version",
7
+ "description",
8
+ "keywords",
9
+ "homepage",
10
+ "bugs",
11
+ "repository",
12
+ "license",
13
+ "author",
14
+ "contributors",
15
+ "funding",
16
+ "type",
17
+ "main",
18
+ "module",
19
+ "types",
20
+ "exports",
21
+ "files",
22
+ "bin",
23
+ "man",
24
+ "directories",
25
+ "scripts",
26
+ "dependencies",
27
+ "devDependencies",
28
+ "peerDependencies",
29
+ "peerDependenciesMeta",
30
+ "optionalDependencies",
31
+ "bundledDependencies",
32
+ "engines",
33
+ "os",
34
+ "cpu",
35
+ "private",
36
+ "publishConfig",
37
+ "workspaces",
38
+ "packageManager",
39
+ "forge"
40
+ ];
41
+ constructor(data){
42
+ Object.assign(this, data);
43
+ this.dependencies = this.dependencies ?? {};
44
+ this.devDependencies = this.devDependencies ?? {};
45
+ }
46
+ sort() {
47
+ const sorted = this.toSortedPackageJsonRecord();
48
+ Object.assign(this, sorted);
49
+ return this;
50
+ }
51
+ withVersion(version) {
52
+ return new PackageJson({
53
+ ...this,
54
+ version
55
+ });
56
+ }
57
+ withDependencies(dependencies) {
58
+ return new PackageJson({
59
+ ...this,
60
+ dependencies
61
+ });
62
+ }
63
+ withDevDependencies(devDependencies) {
64
+ return new PackageJson({
65
+ ...this,
66
+ devDependencies
67
+ });
68
+ }
69
+ toJSON() {
70
+ return `${JSON.stringify(this.toSortedPackageJsonRecord(), null, 2)}\n`;
71
+ }
72
+ getRepositoryOwner() {
73
+ return this.parseRepository()?.owner;
74
+ }
75
+ getRepositoryName() {
76
+ return this.parseRepository()?.name;
77
+ }
78
+ getRepositoryFullName() {
79
+ const parsed = this.parseRepository();
80
+ if (parsed == null) {
81
+ return undefined;
82
+ }
83
+ return `${parsed.owner}/${parsed.name}`;
84
+ }
85
+ sortDependencyMap(input) {
86
+ return Object.fromEntries(Object.entries(input).sort(([left], [right])=>left.localeCompare(right, "en")));
87
+ }
88
+ sortPackageJsonKeys(source) {
89
+ const sorted = Object.create(null);
90
+ for (const key of PackageJson.PACKAGE_JSON_KEY_ORDER){
91
+ if (key in source) {
92
+ sorted[key] = source[key];
93
+ }
94
+ }
95
+ const remainingKeys = Object.keys(source).filter((key)=>!PackageJson.PACKAGE_JSON_KEY_ORDER.includes(key)).sort();
96
+ for (const key of remainingKeys){
97
+ sorted[key] = source[key];
98
+ }
99
+ return sorted;
100
+ }
101
+ toSortedPackageJsonRecord() {
102
+ const clone = {
103
+ ...this
104
+ };
105
+ if (clone.dependencies) {
106
+ clone.dependencies = this.sortDependencyMap(clone.dependencies);
107
+ }
108
+ if (clone.devDependencies) {
109
+ clone.devDependencies = this.sortDependencyMap(clone.devDependencies);
110
+ }
111
+ return this.sortPackageJsonKeys(clone);
112
+ }
113
+ repositoryReferenceToString(repository) {
114
+ if (typeof repository === "string") {
115
+ return repository;
116
+ }
117
+ if (repository == null) {
118
+ return "";
119
+ }
120
+ return String(repository.url ?? "");
121
+ }
122
+ parseRepository() {
123
+ const repositoryValue = this.repositoryReferenceToString(this.repository);
124
+ if (repositoryValue === "") {
125
+ return undefined;
126
+ }
127
+ const trimmed = repositoryValue.trim();
128
+ if (!trimmed.includes("://") && !trimmed.startsWith("git@")) {
129
+ const shorthand = /^(?:[a-z0-9-]+:)?([^/\s]+)\/([^\s]+)$/i.exec(trimmed);
130
+ if (shorthand) {
131
+ return {
132
+ owner: shorthand[1].toLowerCase(),
133
+ name: this.sanitizeRepositoryName(shorthand[2])
134
+ };
135
+ }
136
+ }
137
+ const ssh = /^git@[^:]+:([^/\s]+)\/([^\s]+)$/i.exec(trimmed);
138
+ if (ssh) {
139
+ return {
140
+ owner: ssh[1].toLowerCase(),
141
+ name: this.sanitizeRepositoryName(ssh[2])
142
+ };
143
+ }
144
+ const urlRepository = this.parseRepositoryFromUrl(trimmed);
145
+ if (urlRepository != null) {
146
+ return urlRepository;
147
+ }
148
+ return undefined;
149
+ }
150
+ parseRepositoryFromUrl(repository) {
151
+ const normalized = repository.replace(/^git\+/, "");
152
+ let url;
153
+ try {
154
+ url = new URL(normalized);
155
+ } catch {
156
+ return undefined;
157
+ }
158
+ const segments = url.pathname.split("/").filter(Boolean);
159
+ if (segments.length < 2) {
160
+ return undefined;
161
+ }
162
+ const owner = segments[0]?.toLowerCase();
163
+ const name = this.sanitizeRepositoryName(segments[1] ?? "");
164
+ if (owner == null || owner === "" || name === "") {
165
+ return undefined;
166
+ }
167
+ return {
168
+ owner,
169
+ name
170
+ };
171
+ }
172
+ sanitizeRepositoryName(name) {
173
+ return name.replace(/\.git$/i, "").toLowerCase();
174
+ }
175
+ name;
176
+ version;
177
+ repository;
178
+ main;
179
+ /** `exports` as written in package.json: a path, or a map of subpaths (values may be condition maps). */ exports;
180
+ peerDependencies;
181
+ optionalDependencies;
182
+ scripts;
183
+ dependencies = {};
184
+ devDependencies = {};
185
+ private;
186
+ }
@@ -0,0 +1 @@
1
+ export { };
@@ -0,0 +1,301 @@
1
+ function _ts_decorate(decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ }
7
+ function _ts_metadata(k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ }
10
+ import { existsSync } from "node:fs";
11
+ import path from "node:path";
12
+ import { cache, memoize } from "@decohere/core/caching";
13
+ import { mixwith } from "@decohere/core/extensibility";
14
+ import { io } from "@decohere/core/io";
15
+ import picomatch from "picomatch";
16
+ import { Subject } from "rxjs";
17
+ import { WorkspaceConfigurationError } from "../errors.js";
18
+ import { HasPackageJson } from "./has-package-json.mixin.js";
19
+ import { HasTsConfig } from "./has-tsconfig.mixin.js";
20
+ import { PackageJson } from "./package-json.model.js";
21
+ import { sourceExtensions } from "./source-extensions.js";
22
+ export class Project extends mixwith(HasPackageJson, HasTsConfig) {
23
+ packageJson;
24
+ #projectFileChangedSubject = new Subject();
25
+ #sourceFiles = new Map();
26
+ #projectConfig;
27
+ #name;
28
+ #projectDirectory;
29
+ #selectedConfiguration;
30
+ #hasLoadedSourceFiles = false;
31
+ #watcher;
32
+ constructor(name, config = {}, selectedConfigurationName){
33
+ super();
34
+ this.#name = name;
35
+ this.#projectDirectory = config?.projectDir ?? name;
36
+ this.#projectConfig = config;
37
+ this.#selectedConfiguration = this.resolveConfiguration(selectedConfigurationName);
38
+ this.packageJson = config.packageJson ?? new PackageJson();
39
+ }
40
+ get name() {
41
+ return this.#name;
42
+ }
43
+ get isPrivate() {
44
+ return this.packageJson?.private === true;
45
+ }
46
+ toString() {
47
+ return `Project(${this.#name})`;
48
+ }
49
+ get projectDirectory() {
50
+ return this.#projectDirectory;
51
+ }
52
+ get projectRoot() {
53
+ return path.resolve(this.#projectConfig.rootDir ?? "./", this.#projectDirectory);
54
+ }
55
+ get configuration() {
56
+ return this.#selectedConfiguration;
57
+ }
58
+ get packageJsonDirectory() {
59
+ return this.#absoluteProjectDir;
60
+ }
61
+ get tsConfigDirectory() {
62
+ return this.#absoluteProjectDir;
63
+ }
64
+ get fallbackTsConfigDirectory() {
65
+ return this.#projectConfig.rootDir;
66
+ }
67
+ get rootDir() {
68
+ return this.#projectConfig.rootDir ?? "./";
69
+ }
70
+ get #absoluteProjectDir() {
71
+ return this.projectRoot;
72
+ }
73
+ get include() {
74
+ return this.#selectedConfiguration.include ?? this.#projectConfig.include ?? [];
75
+ }
76
+ get ignore() {
77
+ const baseIgnore = this.#projectConfig.ignore ?? [];
78
+ const selectedIgnore = this.#selectedConfiguration.ignore ?? [];
79
+ return [
80
+ ...baseIgnore,
81
+ ...selectedIgnore
82
+ ];
83
+ }
84
+ get copyFiles() {
85
+ const base = this.#projectConfig.copyFiles ?? [];
86
+ const selected = this.#selectedConfiguration.copyFiles ?? [];
87
+ return [
88
+ ...base,
89
+ ...selected
90
+ ];
91
+ }
92
+ get dockerConfig() {
93
+ return this.#projectConfig.docker;
94
+ }
95
+ get uiConfig() {
96
+ return this.#projectConfig.ui;
97
+ }
98
+ get configurations() {
99
+ return this.#projectConfig.configurations ?? [];
100
+ }
101
+ get projectFileChanged$() {
102
+ return this.#projectFileChangedSubject.asObservable();
103
+ }
104
+ async getAllFiles() {
105
+ const files = await io.findFiles(this.include, {
106
+ cwd: this.#absoluteProjectDir,
107
+ ignore: this.ignore
108
+ });
109
+ this.#sourceFiles.clear();
110
+ for (const file of files){
111
+ this.#sourceFiles.set(file.relativePath, file);
112
+ }
113
+ this.#hasLoadedSourceFiles = true;
114
+ return files;
115
+ }
116
+ isSourceFile(file) {
117
+ return this.#sourceFiles.has(file.relativePath);
118
+ }
119
+ async watch(configuration) {
120
+ if (this.#watcher != null) {
121
+ return this.#watcher;
122
+ }
123
+ if (!this.#hasLoadedSourceFiles) {
124
+ await this.getAllFiles();
125
+ }
126
+ const watcher = io.watch(this.#absoluteProjectDir, {
127
+ ignoreInitial: true
128
+ });
129
+ this.#watcher = watcher;
130
+ watcher.on(io.WatchEvents.add, (file)=>{
131
+ const fileEx = file;
132
+ this.updateSourceFileCache(io.WatchEvents.add, fileEx);
133
+ this.#projectFileChangedSubject.next({
134
+ project: this,
135
+ configuration,
136
+ eventName: io.WatchEvents.add,
137
+ file: fileEx
138
+ });
139
+ });
140
+ watcher.on(io.WatchEvents.change, (file)=>{
141
+ const fileEx = file;
142
+ this.updateSourceFileCache(io.WatchEvents.change, fileEx);
143
+ this.#projectFileChangedSubject.next({
144
+ project: this,
145
+ configuration,
146
+ eventName: io.WatchEvents.change,
147
+ file: fileEx
148
+ });
149
+ });
150
+ watcher.on(io.WatchEvents.unlink, (file)=>{
151
+ const fileEx = file;
152
+ this.updateSourceFileCache(io.WatchEvents.unlink, fileEx);
153
+ this.#projectFileChangedSubject.next({
154
+ project: this,
155
+ configuration,
156
+ eventName: io.WatchEvents.unlink,
157
+ file: fileEx
158
+ });
159
+ });
160
+ return watcher;
161
+ }
162
+ stopWatching() {
163
+ this.#watcher?.close();
164
+ this.#watcher = undefined;
165
+ }
166
+ getRootOut() {
167
+ return path.join(this.getWorkspaceOut(), this.#selectedConfiguration.name);
168
+ }
169
+ getOutDir(target = "") {
170
+ const targetDir = this.#selectedConfiguration.pack ? path.join(this.projectDirectory, target) : path.join(this.projectDirectory);
171
+ const out = path.join(this.getRootOut(), targetDir);
172
+ return out;
173
+ }
174
+ getConfiguration(name) {
175
+ return this.configurations.find((b)=>b.name === name);
176
+ }
177
+ /**
178
+ * The package's entry source file. A TypeScript `main` (the workspace convention,
179
+ * `src/index.ts`) is used as written. A `main` or `exports["."]` that describes the published
180
+ * layout (`index.js`, `./es6/src/index.js`) is mapped back to the source it was built from,
181
+ * falling back to `src/index.ts` (#518).
182
+ */ getSourceEntryPath() {
183
+ const projectRoot = path.join(this.rootDir, this.projectDirectory);
184
+ const main = this.packageJson?.main;
185
+ if (main != null && sourceExtensions.isSource(main)) {
186
+ return path.join(projectRoot, main);
187
+ }
188
+ const exports = this.packageJson?.exports;
189
+ const root = exports == null ? undefined : typeof exports === "string" ? exports : exports["."] ?? (Object.keys(exports).some((k)=>k.startsWith(".")) ? undefined : exports);
190
+ for (const built of [
191
+ root == null ? undefined : firstExportTarget(root),
192
+ main
193
+ ]){
194
+ const fromSrc = built?.match(/(?:^|\/)(src\/.+)$/)?.[1];
195
+ const source = fromSrc == null ? undefined : sourceFileFor(path.join(projectRoot, fromSrc));
196
+ if (source != null) return source;
197
+ }
198
+ const conventional = path.join(projectRoot, "src/index.ts");
199
+ if (main == null || existsSync(conventional)) return conventional;
200
+ return path.join(projectRoot, main);
201
+ }
202
+ /**
203
+ * The source file each subpath in package.json `exports` names, such as `./auth` →
204
+ * `<project>/src/auth/auth.extensions.ts` (#518). Exports point at the release layout
205
+ * (`./es6/src/auth/auth.extensions.js`); the source is the part from `src/`, with its
206
+ * TypeScript extension. Wildcard subpaths, and targets with no such source file, are left out.
207
+ */ getSourceExports() {
208
+ const exports = this.packageJson?.exports;
209
+ if (exports == null || typeof exports === "string") return {};
210
+ const projectRoot = path.join(this.rootDir, this.projectDirectory);
211
+ const sources = {};
212
+ for (const [subpath, target] of Object.entries(exports)){
213
+ if (!subpath.startsWith("./") || subpath.includes("*")) continue;
214
+ const built = firstExportTarget(target);
215
+ const fromSrc = built?.match(/(?:^|\/)(src\/.+)$/)?.[1];
216
+ if (fromSrc == null) continue;
217
+ const source = sourceFileFor(path.join(projectRoot, fromSrc));
218
+ if (source != null) sources[subpath] = source;
219
+ }
220
+ return sources;
221
+ }
222
+ [Symbol.dispose]() {
223
+ this.stopWatching();
224
+ }
225
+ getWorkspaceOut() {
226
+ const out = path.join(this.#projectConfig.rootDir ?? "./", this.#projectConfig.outDir);
227
+ return out;
228
+ }
229
+ updateSourceFileCache(eventName, file) {
230
+ if (!this.#hasLoadedSourceFiles) {
231
+ return;
232
+ }
233
+ switch(eventName){
234
+ case io.WatchEvents.unlink:
235
+ this.#sourceFiles.delete(file.relativePath);
236
+ return;
237
+ case io.WatchEvents.add:
238
+ case io.WatchEvents.change:
239
+ if (this.matchesSourcePattern(file.relativePath)) {
240
+ this.#sourceFiles.set(file.relativePath, file);
241
+ return;
242
+ }
243
+ this.#sourceFiles.delete(file.relativePath);
244
+ return;
245
+ }
246
+ }
247
+ matchesSourcePattern(relativePath) {
248
+ if (picomatch.isMatch(relativePath, this.ignore)) {
249
+ return false;
250
+ }
251
+ return picomatch.isMatch(relativePath, this.include);
252
+ }
253
+ resolveConfiguration(configurationName) {
254
+ const resolvedConfigurationName = configurationName ?? "debug";
255
+ const configuration = this.configurations.find((c)=>c.name === resolvedConfigurationName);
256
+ if (configuration == null) {
257
+ throw new WorkspaceConfigurationError(`Configuration "${resolvedConfigurationName}" was not found for project "${this.name}"`);
258
+ }
259
+ return configuration;
260
+ }
261
+ }
262
+ _ts_decorate([
263
+ memoize(),
264
+ _ts_metadata("design:type", Function),
265
+ _ts_metadata("design:paramtypes", []),
266
+ _ts_metadata("design:returntype", Promise)
267
+ ], Project.prototype, "getAllFiles", null);
268
+ _ts_decorate([
269
+ cache(),
270
+ _ts_metadata("design:type", Function),
271
+ _ts_metadata("design:paramtypes", []),
272
+ _ts_metadata("design:returntype", void 0)
273
+ ], Project.prototype, "getRootOut", null);
274
+ _ts_decorate([
275
+ cache(),
276
+ _ts_metadata("design:type", Function),
277
+ _ts_metadata("design:paramtypes", [
278
+ void 0
279
+ ]),
280
+ _ts_metadata("design:returntype", void 0)
281
+ ], Project.prototype, "getOutDir", null);
282
+ /** The first path an exports value gives, preferring the conditions that name runtime code. */ function firstExportTarget(value) {
283
+ if (typeof value === "string") return value;
284
+ for (const condition of [
285
+ "import",
286
+ "default",
287
+ "require",
288
+ "node",
289
+ "types"
290
+ ]){
291
+ const nested = value[condition];
292
+ if (nested != null) return firstExportTarget(nested);
293
+ }
294
+ return undefined;
295
+ }
296
+ /** The TypeScript source a built or declaration path came from, if it exists. */ function sourceFileFor(builtPath) {
297
+ // A declaration names the file its JavaScript sits next to: `x.d.ts` is `x.js`.
298
+ const declaration = builtPath.match(/^(.*)\.d\.([mc]?)ts$/);
299
+ const built = declaration == null ? builtPath : `${declaration[1]}.${declaration[2]}js`;
300
+ return sourceExtensions.candidates(built).find((candidate)=>existsSync(candidate));
301
+ }
@@ -0,0 +1,66 @@
1
+ import path from "node:path";
2
+ /** TypeScript source extensions a workspace compiles (#518). */ const SOURCE = [
3
+ ".ts",
4
+ ".tsx",
5
+ ".mts",
6
+ ".cts"
7
+ ];
8
+ /** The sources an import's extension can name: `./a.js` is `a.ts` or `a.tsx`, `./a.mjs` is `a.mts`. */ const SOURCES_FOR = {
9
+ ".js": [
10
+ ".ts",
11
+ ".tsx"
12
+ ],
13
+ ".jsx": [
14
+ ".tsx"
15
+ ],
16
+ ".mjs": [
17
+ ".mts"
18
+ ],
19
+ ".cjs": [
20
+ ".cts"
21
+ ],
22
+ "": [
23
+ ".ts",
24
+ ".tsx"
25
+ ]
26
+ };
27
+ /** Whether a path is a TypeScript source (not a declaration file). */ function isSource(file) {
28
+ return SOURCE.some((ext)=>file.endsWith(ext)) && !/\.d\.[mc]?ts$/.test(file);
29
+ }
30
+ /**
31
+ * The source files a path written in an import (or a built path) could name, most likely first:
32
+ * itself when it is already a source, else the same stem with each matching source extension.
33
+ */ function candidates(file) {
34
+ if (isSource(file)) return [
35
+ file
36
+ ];
37
+ const ext = path.extname(file);
38
+ const known = SOURCES_FOR[ext];
39
+ if (known == null) return [
40
+ `${file}.ts`,
41
+ `${file}.tsx`
42
+ ];
43
+ const stem = ext === "" ? file : file.slice(0, -ext.length);
44
+ return known.map((sourceExt)=>`${stem}${sourceExt}`);
45
+ }
46
+ /** The extension a source builds to: `.mts` to `.mjs`, `.cts` to `.cjs`, the rest to `.js`. */ function outputExtension(file) {
47
+ if (file.endsWith(".mts")) return ".mjs";
48
+ if (file.endsWith(".cts")) return ".cjs";
49
+ return ".js";
50
+ }
51
+ /** The path a source builds to: `a.mts` to `a.mjs`, `a.cts` to `a.cjs`, `a.ts` and `a.tsx` to `a.js`. */ function outputPath(file) {
52
+ const ext = path.extname(file);
53
+ const stem = ext === "" ? file : file.slice(0, -ext.length);
54
+ return `${stem}${outputExtension(file)}`;
55
+ }
56
+ /** Whether a source is CommonJS (`.cts`); everything else compiles as an ES module. */ function isCommonJs(file) {
57
+ return file.endsWith(".cts");
58
+ }
59
+ export const sourceExtensions = {
60
+ SOURCE,
61
+ isSource,
62
+ candidates,
63
+ outputExtension,
64
+ outputPath,
65
+ isCommonJs
66
+ };