@travetto/manifest 3.0.0-rc.10

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020 ArcSine Technologies
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,14 @@
1
+ <!-- This file was generated by @travetto/doc and should not be modified directly -->
2
+ <!-- Please modify https://github.com/travetto/travetto/tree/main/module/manifest/DOC.ts and execute "npx trv doc" to rebuild -->
3
+ # Manifest
4
+ ## Manifest support
5
+
6
+ **Install: @travetto/manifest**
7
+ ```bash
8
+ npm install @travetto/manifest
9
+ ```
10
+
11
+ This module provides functionality for basic path functionality and common typings for manifests
12
+
13
+ ### Module Indexing
14
+ The bootstrap process will also produce an index of all source files, which allows for fast in-memory scanning. This allows for all the automatic discovery that is used within the framework.
package/__index__.ts ADDED
@@ -0,0 +1,11 @@
1
+ /// <reference path="./src/typings.d.ts" />
2
+
3
+ export * from './src/path';
4
+ export * from './src/module';
5
+ export * from './src/delta';
6
+ export * from './src/manifest-index';
7
+ export * from './src/root-index';
8
+ export * from './src/package';
9
+ export * from './src/util';
10
+ export * from './src/types';
11
+ export * from './src/watch';
@@ -0,0 +1,10 @@
1
+ import type { ManifestContext } from '../src/types';
2
+
3
+ declare namespace ManifestBootstrap {
4
+ /**
5
+ * Get Context for building
6
+ */
7
+ function getManifestContext(folder?: string): Promise<ManifestContext>;
8
+ }
9
+
10
+ export = ManifestBootstrap;
package/bin/context.js ADDED
@@ -0,0 +1,116 @@
1
+ // @ts-check
2
+
3
+ /**
4
+ * @typedef {import('../src/types').Package} Pkg
5
+ * @typedef {import('../src/types').ManifestContext} ManifestContext
6
+ */
7
+ import fs from 'fs/promises';
8
+ import path from 'path';
9
+ import { createRequire } from 'module';
10
+
11
+ /**
12
+ * Returns the package.json
13
+ * @param {string} inputFolder
14
+ * @returns {Promise<Pkg>}
15
+ */
16
+ async function $getPkg(inputFolder) {
17
+ if (!inputFolder.endsWith('.json')) {
18
+ inputFolder = path.resolve(inputFolder, 'package.json');
19
+ }
20
+ return JSON.parse(await fs.readFile(inputFolder, 'utf8'));
21
+ }
22
+
23
+ const WS_ROOT = {};
24
+
25
+ /**
26
+ * Get module name from a given file
27
+ * @param {string} file
28
+ * @return {Promise<string|void>}
29
+ */
30
+ async function $getModuleFromFile(file) {
31
+ let dir = path.dirname(file);
32
+ let prev;
33
+ while (dir !== prev && !(await fs.stat(path.resolve(dir, 'package.json')).catch(() => false))) {
34
+ prev = dir;
35
+ dir = path.dirname(dir);
36
+ }
37
+ try {
38
+ return (await $getPkg(dir)).name;
39
+ } catch { }
40
+ }
41
+
42
+ /**
43
+ * Get workspace root
44
+ * @return {Promise<string>}
45
+ */
46
+ async function $getWorkspaceRoot(base = process.cwd()) {
47
+ if (base in WS_ROOT) {
48
+ return WS_ROOT[base];
49
+ }
50
+
51
+ let folder = base;
52
+ let prevFolder = '';
53
+ while (folder !== prevFolder) {
54
+ try {
55
+ const pkg = await $getPkg(folder);
56
+ if (!!pkg.workspaces || !!pkg.travetto?.isolated) {
57
+ return (WS_ROOT[base] = folder);
58
+ }
59
+ } catch { }
60
+ if (await fs.stat(path.resolve(folder, '.git')).catch(() => { })) {
61
+ break;
62
+ }
63
+ prevFolder = folder;
64
+ folder = path.dirname(folder);
65
+ }
66
+ return WS_ROOT[base] = base;
67
+ }
68
+
69
+
70
+ /**
71
+ * Gets build context
72
+ * @param {string} [folder]
73
+ * @return {Promise<ManifestContext>}
74
+ */
75
+ export async function getManifestContext(folder) {
76
+ const workspacePath = path.resolve(await $getWorkspaceRoot(folder));
77
+
78
+ // If manifest specified via env var, and is a package name
79
+ if (!folder && process.env.TRV_MODULE) {
80
+ // If module is actually a file, try to detect
81
+ if (/[.](t|j)s$/.test(process.env.TRV_MODULE)) {
82
+ process.env.TRV_MODULE = await $getModuleFromFile(process.env.TRV_MODULE) ?? process.env.TRV_MODULE;
83
+ }
84
+ const req = createRequire(`${workspacePath}/node_modules`);
85
+ try {
86
+ folder = path.dirname(req.resolve(`${process.env.TRV_MODULE}/package.json`));
87
+ } catch {
88
+ const workspacePkg = JSON.parse(await fs.readFile(path.resolve(workspacePath, 'package.json'), 'utf8'));
89
+ if (workspacePkg.name === process.env.TRV_MODULE) {
90
+ folder = workspacePath;
91
+ } else {
92
+ throw new Error(`Unable to resolve location for ${folder}`);
93
+ }
94
+ }
95
+ }
96
+
97
+ const mainPath = path.resolve(folder ?? '.');
98
+ const { name: mainModule, workspaces, travetto } = (await $getPkg(mainPath));
99
+ const monoRepo = workspacePath !== mainPath || !!workspaces;
100
+ const outputFolder = travetto?.outputFolder ?? '.trv_output';
101
+
102
+ const moduleType = (await $getPkg(workspacePath)).type ?? 'commonjs';
103
+ const mainFolder = mainPath === workspacePath ? '' : mainPath.replace(`${workspacePath}/`, '');
104
+
105
+ const res = {
106
+ moduleType,
107
+ mainModule,
108
+ mainFolder,
109
+ workspacePath,
110
+ monoRepo,
111
+ outputFolder,
112
+ toolFolder: '.trv_build',
113
+ compilerFolder: '.trv_compiler'
114
+ };
115
+ return res;
116
+ }
package/package.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "name": "@travetto/manifest",
3
+ "version": "3.0.0-rc.10",
4
+ "description": "Manifest support",
5
+ "keywords": [
6
+ "path",
7
+ "package",
8
+ "manifest",
9
+ "travetto",
10
+ "typescript"
11
+ ],
12
+ "homepage": "https://travetto.io",
13
+ "license": "MIT",
14
+ "author": {
15
+ "email": "travetto.framework@gmail.com",
16
+ "name": "Travetto Framework"
17
+ },
18
+ "type": "module",
19
+ "files": [
20
+ "__index__.ts",
21
+ "bin",
22
+ "src",
23
+ "support"
24
+ ],
25
+ "main": "__index__.ts",
26
+ "engines": {
27
+ "node": ">=18.0.0"
28
+ },
29
+ "repository": {
30
+ "url": "https://github.com/travetto/travetto.git",
31
+ "directory": "module/manifest"
32
+ },
33
+ "peerDependencies": {
34
+ "@parcel/watcher": "^2.1.0"
35
+ },
36
+ "peerDependenciesMeta": {
37
+ "@parcel/watcher": {
38
+ "optional": true
39
+ }
40
+ },
41
+ "travetto": {
42
+ "displayName": "Manifest",
43
+ "docBaseUrl": "https://github.com/travetto/travetto/tree/main"
44
+ },
45
+ "publishConfig": {
46
+ "access": "public"
47
+ }
48
+ }
package/src/delta.ts ADDED
@@ -0,0 +1,104 @@
1
+ import fs from 'fs/promises';
2
+ import path from 'path';
3
+
4
+ import {
5
+ ManifestContext, ManifestModule, ManifestModuleCore, ManifestModuleFile,
6
+ ManifestModuleFileType, ManifestModuleFolderType, ManifestRoot
7
+ } from './types';
8
+
9
+ import { ManifestModuleUtil } from './module';
10
+
11
+ type DeltaEventType = 'added' | 'changed' | 'removed' | 'missing' | 'dirty';
12
+ type DeltaModule = ManifestModuleCore & { files: Record<string, ManifestModuleFile> };
13
+ export type DeltaEvent = { file: string, type: DeltaEventType, module: string };
14
+
15
+ const VALID_SOURCE_FOLDERS = new Set<ManifestModuleFolderType>(['bin', 'src', 'test', 'support', '$index', '$package', 'doc']);
16
+ const VALID_SOURCE_TYPE = new Set<ManifestModuleFileType>(['js', 'ts', 'package-json']);
17
+
18
+ /**
19
+ * Produce delta for the manifest
20
+ */
21
+ export class ManifestDeltaUtil {
22
+
23
+ static #getNewest(stat: { mtimeMs: number, ctimeMs: number }): number {
24
+ return Math.max(stat.mtimeMs, stat.ctimeMs);
25
+ }
26
+
27
+ /**
28
+ * Produce delta between two manifest modules, relative to an output folder
29
+ */
30
+ static async #deltaModules(ctx: ManifestContext, outputFolder: string, left: DeltaModule): Promise<DeltaEvent[]> {
31
+ const out: DeltaEvent[] = [];
32
+
33
+ const add = (file: string, type: DeltaEvent['type']): unknown =>
34
+ out.push({ file, module: left.name, type });
35
+
36
+ const root = `${ctx.workspacePath}/${ctx.outputFolder}/${left.outputFolder}`;
37
+ const right = new Set(
38
+ (await ManifestModuleUtil.scanFolder(root, left.main))
39
+ .filter(x => (x.endsWith('.ts') || x.endsWith('.js') || x.endsWith('package.json')))
40
+ .map(x => x.replace(`${root}/`, '').replace(/[.][tj]s$/, ''))
41
+ );
42
+
43
+ for (const el of Object.keys(left.files)) {
44
+ const output = `${outputFolder}/${left.outputFolder}/${el.replace(/[.]ts$/, '.js')}`;
45
+ const [, , leftTs] = left.files[el];
46
+ const stat = await fs.stat(output).catch(() => { });
47
+ right.delete(el.replace(/[.][tj]s$/, ''));
48
+
49
+ if (!stat) {
50
+ add(el, 'added');
51
+ } else {
52
+ const rightTs = this.#getNewest(stat);
53
+ if (leftTs > rightTs) {
54
+ add(el, 'changed');
55
+ }
56
+ }
57
+ }
58
+ // Deleted
59
+ for (const el of right) {
60
+ add(el, 'removed');
61
+ }
62
+ return out;
63
+ }
64
+
65
+ /**
66
+ * Collapse all files in a module
67
+ * @param {ManifestModule} m
68
+ * @returns {}
69
+ */
70
+ static #flattenModuleFiles(m: ManifestModule): Record<string, ManifestModuleFile> {
71
+ const out: Record<string, ManifestModuleFile> = {};
72
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
73
+ for (const key of Object.keys(m.files) as (ManifestModuleFolderType[])) {
74
+ if (!VALID_SOURCE_FOLDERS.has(key)) {
75
+ continue;
76
+ }
77
+ for (const [name, type, date] of m.files?.[key] ?? []) {
78
+ if (VALID_SOURCE_TYPE.has(type)) {
79
+ out[name] = [name, type, date];
80
+ }
81
+ }
82
+ }
83
+ return out;
84
+ }
85
+
86
+ /**
87
+ * Produce delta between manifest root and the output folder
88
+ */
89
+ static async produceDelta(ctx: ManifestContext, manifest: ManifestRoot): Promise<DeltaEvent[]> {
90
+ const deltaLeft = Object.fromEntries(
91
+ Object.values(manifest.modules)
92
+ .map(m => [m.name, { ...m, files: this.#flattenModuleFiles(m) }])
93
+ );
94
+
95
+ const out: DeltaEvent[] = [];
96
+ const outputFolder = path.resolve(ctx.workspacePath, ctx.outputFolder);
97
+
98
+ for (const lMod of Object.values(deltaLeft)) {
99
+ out.push(...await this.#deltaModules(manifest, outputFolder, lMod));
100
+ }
101
+
102
+ return out;
103
+ }
104
+ }
@@ -0,0 +1,163 @@
1
+ import { PackageUtil } from './package';
2
+ import { path } from './path';
3
+ import { ManifestContext, ManifestProfile, PackageRel, PackageVisitor, PackageVisitReq } from './types';
4
+
5
+ export type ModuleDep = {
6
+ version: string;
7
+ name: string;
8
+ main?: boolean;
9
+ mainSource?: boolean;
10
+ local?: boolean;
11
+ internal?: boolean;
12
+ sourcePath: string;
13
+ childSet: Map<string, Set<PackageRel>>;
14
+ parentSet: Set<string>;
15
+ profileSet: Set<ManifestProfile>;
16
+ };
17
+
18
+ /**
19
+ * Used for walking dependencies for collecting modules for the manifest
20
+ */
21
+ export class ModuleDependencyVisitor implements PackageVisitor<ModuleDep> {
22
+
23
+ /**
24
+ * Get main patterns for detecting if a module should be treated as main
25
+ */
26
+ static getMainPatterns(mainModule: string, mergeModules: string[]): RegExp[] {
27
+ const groups: Record<string, string[]> = { [mainModule]: [] };
28
+ for (const el of mergeModules) {
29
+ if (el.includes('/')) {
30
+ const [grp, sub] = el.split('/');
31
+ (groups[`${grp}/`] ??= []).push(sub);
32
+ } else {
33
+ (groups[el] ??= []);
34
+ }
35
+ }
36
+
37
+ return Object.entries(groups)
38
+ .map(([root, subs]) => subs.length ? `${root}(${subs.join('|')})` : root)
39
+ .map(x => new RegExp(`^${x.replace(/[*]/g, '.*?')}$`));
40
+ }
41
+
42
+ constructor(public ctx: ManifestContext) { }
43
+
44
+ #mainPatterns: RegExp[] = [];
45
+
46
+ /**
47
+ * Initialize visitor, and provide global dependencies
48
+ */
49
+ async init(req: PackageVisitReq<ModuleDep>): Promise<PackageVisitReq<ModuleDep>[]> {
50
+ const pkg = PackageUtil.readPackage(req.sourcePath);
51
+ const workspacePkg = PackageUtil.readPackage(this.ctx.workspacePath);
52
+ const workspaceModules = pkg.workspaces?.length ? (await PackageUtil.resolveWorkspaces(this.ctx, req.sourcePath)) : [];
53
+
54
+ this.#mainPatterns = ModuleDependencyVisitor.getMainPatterns(pkg.name, [
55
+ ...pkg.travetto?.mainSource ?? [],
56
+ // Add workspace folders, for tests and docs
57
+ ...workspaceModules.map(x => x.name)
58
+ ]);
59
+
60
+ const globals = [
61
+ ...(workspacePkg.travetto?.globalModules ?? []),
62
+ ...(pkg.travetto?.globalModules ?? [])
63
+ ]
64
+ .map(f => PackageUtil.resolvePackagePath(f));
65
+
66
+ const workspaceModuleDeps = workspaceModules
67
+ .map(entry => path.resolve(req.sourcePath, entry.sourcePath));
68
+
69
+ return [
70
+ ...globals,
71
+ ...workspaceModuleDeps
72
+ ].map(s => PackageUtil.packageReq(s, 'global'));
73
+ }
74
+
75
+ /**
76
+ * Is valid dependency for searching
77
+ */
78
+ valid(req: PackageVisitReq<ModuleDep>): boolean {
79
+ return req.sourcePath === path.cwd() || (
80
+ req.rel !== 'peer' &&
81
+ (!!req.pkg.travetto || req.pkg.private === true || !req.sourcePath.includes('node_modules') || req.rel === 'global')
82
+ );
83
+ }
84
+
85
+ /**
86
+ * Create dependency from request
87
+ */
88
+ create(req: PackageVisitReq<ModuleDep>): ModuleDep {
89
+ const { pkg: { name, version, travetto: { profiles = [] } = {}, ...pkg }, sourcePath } = req;
90
+ const profileSet = new Set<ManifestProfile>([
91
+ ...profiles ?? []
92
+ ]);
93
+ const main = name === this.ctx.mainModule;
94
+ const mainSource = main || this.#mainPatterns.some(x => x.test(name));
95
+ const internal = pkg.private === true;
96
+ const local = internal || mainSource || !sourcePath.includes('node_modules');
97
+
98
+ const dep = {
99
+ name, version, sourcePath, main, mainSource, local, internal,
100
+ parentSet: new Set([]), childSet: new Map(), profileSet
101
+ };
102
+
103
+ return dep;
104
+ }
105
+
106
+ /**
107
+ * Visit dependency
108
+ */
109
+ visit(req: PackageVisitReq<ModuleDep>, dep: ModuleDep): void {
110
+ const { parent } = req;
111
+ if (parent && dep.name !== this.ctx.mainModule) {
112
+ dep.parentSet.add(parent.name);
113
+ const set = parent.childSet.get(dep.name) ?? new Set();
114
+ parent.childSet.set(dep.name, set);
115
+ set.add(req.rel);
116
+ }
117
+ }
118
+
119
+ /**
120
+ * Propagate profile/relationship information through graph
121
+ */
122
+ complete(deps: Set<ModuleDep>): Set<ModuleDep> {
123
+ const mapping = new Map<string, { parent: Set<string>, child: Map<string, Set<PackageRel>>, el: ModuleDep }>();
124
+ for (const el of deps) {
125
+ mapping.set(el.name, { parent: new Set(el.parentSet), child: new Map(el.childSet), el });
126
+ }
127
+
128
+ const main = mapping.get(this.ctx.mainModule)!;
129
+
130
+ // Visit all direct dependencies and mark
131
+ for (const [name, relSet] of main.child) {
132
+ const childDep = mapping.get(name)!.el;
133
+ if (!relSet.has('dev')) {
134
+ childDep.profileSet.add('std');
135
+ }
136
+ }
137
+
138
+ while (mapping.size > 0) {
139
+ const toProcess = [...mapping.values()].filter(x => x.parent.size === 0);
140
+ if (!toProcess.length) {
141
+ throw new Error(`We have reached a cycle for ${[...mapping.keys()]}`);
142
+ }
143
+ // Propagate
144
+ for (const { el, child } of toProcess) {
145
+ for (const c of child.keys()) {
146
+ const { el: cDep, parent } = mapping.get(c)!;
147
+ parent.delete(el.name); // Remove from child
148
+ for (const prof of el.profileSet) {
149
+ cDep.profileSet.add(prof);
150
+ }
151
+ }
152
+ }
153
+ // Remove from mapping
154
+ for (const { el } of toProcess) {
155
+ mapping.delete(el.name);
156
+ }
157
+ }
158
+
159
+ // Color the main folder as std
160
+ main.el.profileSet.add('std');
161
+ return deps;
162
+ }
163
+ }