@nestjs/observe 0.3.15 → 0.3.17
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/README.md +10 -8
- package/dist/cli/link.d.ts +15 -0
- package/dist/cli/link.js +95 -1
- package/dist/cli/observe-cli.js +21 -1
- package/dist/cli/package-manager.d.ts +13 -0
- package/dist/cli/package-manager.js +54 -0
- package/dist/cli/project-setup.d.ts +43 -0
- package/dist/cli/project-setup.js +249 -0
- package/dist/cli/wire-application.d.ts +29 -0
- package/dist/cli/wire-application.js +390 -0
- package/dist/interfaces/observe-options.interface.d.ts +13 -8
- package/dist/protocols/http-observe-agent.service.d.ts +3 -4
- package/dist/protocols/http-observe-agent.service.js +7 -5
- package/dist/services/operation-trace.registry.d.ts +6 -0
- package/dist/services/operation-trace.registry.js +21 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -79,6 +79,13 @@ adds `--env-file .env` to every script that runs `nest start` (`start`,
|
|
|
79
79
|
`start:dev` and `start:debug` in a `nest new` project). `ObserveModule` reads those two variables whenever `appKey` and
|
|
80
80
|
`appSecret` are left out or still hold the `nest new` placeholders.
|
|
81
81
|
|
|
82
|
+
In an app that does not use the SDK yet, the same command also installs
|
|
83
|
+
`@nestjs/observe` with the project's package manager and wires it in -
|
|
84
|
+
`ObserveModule.forRoot()` first in the root module's imports, `ObserveInstrument`
|
|
85
|
+
passed to `NestFactory.create()` - so the app reports from its next start. It
|
|
86
|
+
says so before you approve, and leaves a workspace with several applications
|
|
87
|
+
for you to wire by hand, as the [Quick start](#quick-start) shows.
|
|
88
|
+
|
|
82
89
|
Or sign up at **[observe.nestjs.com](https://observe.nestjs.com)** and create a
|
|
83
90
|
service by hand. The dashboard issues an **app key** and an **app secret**,
|
|
84
91
|
which the agent sends on every ingest request.
|
|
@@ -107,8 +114,6 @@ agent off rather than supplying fake credentials, which are sent and refused:
|
|
|
107
114
|
```ts
|
|
108
115
|
ObserveModule.forRoot({
|
|
109
116
|
enabled: process.env.NODE_ENV === "production",
|
|
110
|
-
appKey: process.env.OBSERVE_APP_KEY ?? "",
|
|
111
|
-
appSecret: process.env.OBSERVE_APP_SECRET ?? "",
|
|
112
117
|
serviceId: "my-service",
|
|
113
118
|
});
|
|
114
119
|
```
|
|
@@ -136,11 +141,8 @@ import { ObserveModule } from "./observe";
|
|
|
136
141
|
|
|
137
142
|
@Module({
|
|
138
143
|
imports: [
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
appSecret: process.env.OBSERVE_APP_SECRET!,
|
|
142
|
-
serviceId: "my-service",
|
|
143
|
-
}),
|
|
144
|
+
// appKey and appSecret default to OBSERVE_APP_KEY and OBSERVE_APP_SECRET.
|
|
145
|
+
ObserveModule.forRoot({ serviceId: "my-service" }),
|
|
144
146
|
],
|
|
145
147
|
})
|
|
146
148
|
export class AppModule {}
|
|
@@ -471,7 +473,7 @@ The MSSQL unit suite uses the real driver's public request APIs with stubbed tra
|
|
|
471
473
|
$ docker run -d -p 6379:6379 redis:7-alpine
|
|
472
474
|
$ docker run -d -p 54321:5432 -e POSTGRES_PASSWORD=postgres-whisprr postgres:16-alpine
|
|
473
475
|
$ docker run -d -p 3306:3306 -e MYSQL_ROOT_PASSWORD=root -e MYSQL_DATABASE=test mysql:8
|
|
474
|
-
$ docker run -d -p 27027:27017 mongo:
|
|
476
|
+
$ docker run -d -p 27027:27017 mongo:7
|
|
475
477
|
```
|
|
476
478
|
|
|
477
479
|
To point them elsewhere, set `REDIS_HOST`/`REDIS_PORT`, `PGHOST`/`PGPORT`/`PGUSER`/`PGPASSWORD`/`PGDATABASE`, `MYSQL_HOST`/`MYSQL_PORT`/`MYSQL_USER`/`MYSQL_PASSWORD`/`MYSQL_DATABASE` or `MONGO_HOST`/`MONGO_PORT`.
|
package/dist/cli/link.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { TypeScript } from "./project-setup.js";
|
|
1
2
|
export interface LinkOptions {
|
|
2
3
|
/** The project directory: where `package.json` and `.env` live. */
|
|
3
4
|
cwd: string;
|
|
@@ -5,6 +6,8 @@ export interface LinkOptions {
|
|
|
5
6
|
endpoint: string;
|
|
6
7
|
/** Whether to try opening the link page in a browser. */
|
|
7
8
|
openBrowser: boolean;
|
|
9
|
+
/** This package's version: what a project without the SDK gets. */
|
|
10
|
+
version: string;
|
|
8
11
|
}
|
|
9
12
|
export interface LinkDependencies {
|
|
10
13
|
fetch: typeof fetch;
|
|
@@ -13,12 +16,24 @@ export interface LinkDependencies {
|
|
|
13
16
|
log: (line: string) => void;
|
|
14
17
|
hostname: () => string;
|
|
15
18
|
now: () => number;
|
|
19
|
+
/**
|
|
20
|
+
* Runs a command in the project with the terminal attached - the package
|
|
21
|
+
* manager's output is the progress - and resolves to its exit code.
|
|
22
|
+
*/
|
|
23
|
+
run: (command: string, args: string[], cwd: string) => Promise<number>;
|
|
24
|
+
/** The project's own TypeScript, or undefined when it has none. */
|
|
25
|
+
loadTypeScript: (cwd: string) => TypeScript | undefined;
|
|
16
26
|
}
|
|
17
27
|
/**
|
|
18
28
|
* `npx @nestjs/observe link`: asks the API for a code, has the person type it
|
|
19
29
|
* into the dashboard and approve, then writes the key pair it receives into
|
|
20
30
|
* `.env` and makes the start scripts load it.
|
|
21
31
|
*
|
|
32
|
+
* In a project that does not use the SDK yet, it also installs it with the
|
|
33
|
+
* project's package manager and wires it into the root module and `main.ts`
|
|
34
|
+
* (see `wireApplication`) - so an existing app is set up by the one command,
|
|
35
|
+
* as a `nest new` one is. The person is told before they approve.
|
|
36
|
+
*
|
|
22
37
|
* Returns the process exit code. Nothing is written until the key pair has
|
|
23
38
|
* arrived, so an interrupted, denied or expired link leaves the project as it
|
|
24
39
|
* was.
|
package/dist/cli/link.js
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
|
+
import { addDependencyCommand, detectPackageManager, } from "./package-manager.js";
|
|
1
2
|
import { addEnvFileToStartScripts, ensureEnvIgnored, readPackageName, writeEnvFile, } from "./project-files.js";
|
|
3
|
+
import { findEntryFiles, inspectProject, QUICK_START_URL, SDK_PACKAGE, serviceIdFor, } from "./project-setup.js";
|
|
4
|
+
import { wireApplication } from "./wire-application.js";
|
|
2
5
|
/** Extra seconds `slow_down` adds to the interval, as RFC 8628 says. */
|
|
3
6
|
const SLOW_DOWN_SECONDS = 5;
|
|
4
7
|
/**
|
|
@@ -6,6 +9,11 @@ const SLOW_DOWN_SECONDS = 5;
|
|
|
6
9
|
* into the dashboard and approve, then writes the key pair it receives into
|
|
7
10
|
* `.env` and makes the start scripts load it.
|
|
8
11
|
*
|
|
12
|
+
* In a project that does not use the SDK yet, it also installs it with the
|
|
13
|
+
* project's package manager and wires it into the root module and `main.ts`
|
|
14
|
+
* (see `wireApplication`) - so an existing app is set up by the one command,
|
|
15
|
+
* as a `nest new` one is. The person is told before they approve.
|
|
16
|
+
*
|
|
9
17
|
* Returns the process exit code. Nothing is written until the key pair has
|
|
10
18
|
* arrived, so an interrupted, denied or expired link leaves the project as it
|
|
11
19
|
* was.
|
|
@@ -16,6 +24,12 @@ export async function link(options, deps) {
|
|
|
16
24
|
deps.log(`No package.json in ${options.cwd}. Run this in your NestJS project's directory.`);
|
|
17
25
|
return 1;
|
|
18
26
|
}
|
|
27
|
+
const setup = inspectProject(options.cwd, options.version, deps.loadTypeScript(options.cwd));
|
|
28
|
+
if (setup.unsupported) {
|
|
29
|
+
deps.log(`${setup.unsupported}. Nothing was written.`);
|
|
30
|
+
return 1;
|
|
31
|
+
}
|
|
32
|
+
const manager = detectPackageManager(options.cwd);
|
|
19
33
|
let started;
|
|
20
34
|
try {
|
|
21
35
|
started = await post(deps, options.endpoint, "sessions", {
|
|
@@ -32,6 +46,10 @@ export async function link(options, deps) {
|
|
|
32
46
|
deps.log(` and type ${started.userCode}`);
|
|
33
47
|
deps.log("");
|
|
34
48
|
deps.log(`Waiting for you to approve it in the dashboard. The code expires in ${Math.round(started.expiresIn / 60)} minutes.`);
|
|
49
|
+
const plan = describePlan(setup, manager);
|
|
50
|
+
if (plan) {
|
|
51
|
+
deps.log(plan);
|
|
52
|
+
}
|
|
35
53
|
if (options.openBrowser) {
|
|
36
54
|
// The page only, never the code: the code is typed, so a link that
|
|
37
55
|
// carries it cannot approve anything on its own.
|
|
@@ -56,9 +74,85 @@ export async function link(options, deps) {
|
|
|
56
74
|
if (scripts.skipped.length) {
|
|
57
75
|
deps.log(` ${listScripts(scripts.skipped)} do${scripts.skipped.length === 1 ? "es" : ""} not run nest start, so load .env there yourself (node --env-file=.env).`);
|
|
58
76
|
}
|
|
59
|
-
|
|
77
|
+
if (setup.install) {
|
|
78
|
+
const spec = `${SDK_PACKAGE}@^${options.version}`;
|
|
79
|
+
const [command, args] = addDependencyCommand(manager, spec);
|
|
80
|
+
deps.log("");
|
|
81
|
+
deps.log(`Installing ${spec} with ${manager}...`);
|
|
82
|
+
const exitCode = await deps.run(command, args, options.cwd).catch(() => -1);
|
|
83
|
+
if (exitCode !== 0) {
|
|
84
|
+
deps.log(`✖ ${[command, ...args].join(" ")} did not finish. Run it yourself, then add the SDK to the app: ${QUICK_START_URL}`);
|
|
85
|
+
return 1;
|
|
86
|
+
}
|
|
87
|
+
deps.log(`✔ Installed ${spec}.`);
|
|
88
|
+
}
|
|
89
|
+
let wired = true;
|
|
90
|
+
if (setup.wire) {
|
|
91
|
+
const result = wire(deps, options.cwd, serviceIdFor(credentials.applicationName, applicationName));
|
|
92
|
+
if (result.kind === "wired") {
|
|
93
|
+
deps.log("✔ Wired it into the app:");
|
|
94
|
+
const width = Math.max(...result.files.map((file) => file.path.length));
|
|
95
|
+
for (const file of result.files) {
|
|
96
|
+
deps.log(` ${file.path.padEnd(width)} ${file.change}`);
|
|
97
|
+
}
|
|
98
|
+
deps.log(" Review the changes with git diff.");
|
|
99
|
+
}
|
|
100
|
+
else {
|
|
101
|
+
wired = false;
|
|
102
|
+
deps.log(`! Not wired into the app: ${result.reason}.`);
|
|
103
|
+
deps.log(` Add it by hand - three edits: ${QUICK_START_URL}`);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
deps.log(` ${wired ? "Start the app" : "Once it is wired, start the app"} and it reports to NestJS Observe. In production, set OBSERVE_APP_KEY and OBSERVE_APP_SECRET in the environment instead.`);
|
|
60
107
|
return 0;
|
|
61
108
|
}
|
|
109
|
+
/**
|
|
110
|
+
* What else the link will change, said while the person can still decide not
|
|
111
|
+
* to approve. Nothing for a project that already uses the SDK.
|
|
112
|
+
*/
|
|
113
|
+
function describePlan(setup, manager) {
|
|
114
|
+
const wiring = "wires it into the app's root module and main.ts";
|
|
115
|
+
if (setup.install && setup.wire) {
|
|
116
|
+
return `This project does not use NestJS Observe yet: once you approve, link also installs ${SDK_PACKAGE} with ${manager} and ${wiring}.`;
|
|
117
|
+
}
|
|
118
|
+
if (setup.wire) {
|
|
119
|
+
return `The app does not use ${SDK_PACKAGE} yet: once you approve, link also ${wiring}.`;
|
|
120
|
+
}
|
|
121
|
+
if (setup.install) {
|
|
122
|
+
return `Once you approve, link also installs ${SDK_PACKAGE} with ${manager}.`;
|
|
123
|
+
}
|
|
124
|
+
return undefined;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Wires the SDK into the project's one application. Asked for TypeScript
|
|
128
|
+
* again rather than reusing what the inspection had: an install has just
|
|
129
|
+
* run, and may have been what brought it.
|
|
130
|
+
*/
|
|
131
|
+
function wire(deps, cwd, serviceId) {
|
|
132
|
+
const ts = deps.loadTypeScript(cwd);
|
|
133
|
+
if (!ts) {
|
|
134
|
+
return {
|
|
135
|
+
kind: "manual",
|
|
136
|
+
reason: "the project's TypeScript, which the code is edited with, could not be loaded",
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
const entries = findEntryFiles(cwd, ts);
|
|
140
|
+
if (entries.length === 0) {
|
|
141
|
+
return {
|
|
142
|
+
kind: "manual",
|
|
143
|
+
reason: "could not find the application's main.ts",
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
if (entries.length > 1) {
|
|
147
|
+
// One key is one application: wiring them all would report every app
|
|
148
|
+
// in the workspace as this one.
|
|
149
|
+
return {
|
|
150
|
+
kind: "manual",
|
|
151
|
+
reason: `this workspace has ${entries.length} applications (${entries.join(", ")}), and the key is for one of them`,
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
return wireApplication(ts, cwd, entries[0], serviceId);
|
|
155
|
+
}
|
|
62
156
|
/**
|
|
63
157
|
* Polls until the link is approved, denied or expires. A string is the
|
|
64
158
|
* message to end on; transient network failures are retried until the code's
|
package/dist/cli/observe-cli.js
CHANGED
|
@@ -1,13 +1,17 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { spawn } from "node:child_process";
|
|
3
|
+
import { createRequire } from "node:module";
|
|
3
4
|
import { hostname } from "node:os";
|
|
4
5
|
import { resolve } from "node:path";
|
|
5
6
|
import { link } from "./link.js";
|
|
7
|
+
import { loadTypeScript } from "./project-setup.js";
|
|
8
|
+
const { version } = createRequire(import.meta.url)("../../package.json");
|
|
6
9
|
const HOSTED_COLLECTOR_ENDPOINT = "https://observe-api.nestjs.com";
|
|
7
10
|
const USAGE = `Usage: npx @nestjs/observe link [--no-browser] [--cwd <dir>]
|
|
8
11
|
|
|
9
12
|
link Link this project to NestJS Observe: approve a code in the
|
|
10
|
-
dashboard, and the API key pair is written into .env.
|
|
13
|
+
dashboard, and the API key pair is written into .env. In an app
|
|
14
|
+
that does not use the SDK yet, it is installed and wired in too.
|
|
11
15
|
|
|
12
16
|
Options:
|
|
13
17
|
--no-browser Print the link page instead of opening it.
|
|
@@ -46,6 +50,7 @@ async function main(argv) {
|
|
|
46
50
|
cwd,
|
|
47
51
|
endpoint: (process.env.OBSERVE_ENDPOINT ?? HOSTED_COLLECTOR_ENDPOINT).replace(/\/+$/, ""),
|
|
48
52
|
openBrowser: interactive && !rest.includes("--no-browser"),
|
|
53
|
+
version,
|
|
49
54
|
}, {
|
|
50
55
|
fetch,
|
|
51
56
|
sleep: (ms) => new Promise((done) => setTimeout(done, ms)),
|
|
@@ -53,6 +58,21 @@ async function main(argv) {
|
|
|
53
58
|
log: (line) => console.log(line),
|
|
54
59
|
hostname,
|
|
55
60
|
now: Date.now,
|
|
61
|
+
run,
|
|
62
|
+
loadTypeScript,
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Runs the package manager with the terminal attached. On Windows through the
|
|
67
|
+
* shell, which is what finds `npm.cmd`; there `^` is cmd.exe's escape
|
|
68
|
+
* character, so each argument is quoted.
|
|
69
|
+
*/
|
|
70
|
+
function run(command, args, cwd) {
|
|
71
|
+
const windows = process.platform === "win32";
|
|
72
|
+
return new Promise((done) => {
|
|
73
|
+
const child = spawn(command, windows ? args.map((arg) => `"${arg}"`) : args, { cwd, stdio: "inherit", shell: windows });
|
|
74
|
+
child.on("error", () => done(-1));
|
|
75
|
+
child.on("close", (code) => done(code ?? -1));
|
|
56
76
|
});
|
|
57
77
|
}
|
|
58
78
|
main(process.argv.slice(2)).then((code) => process.exit(code), (err) => {
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export type PackageManager = "npm" | "pnpm" | "yarn" | "bun";
|
|
2
|
+
/**
|
|
3
|
+
* The package manager the project is installed with.
|
|
4
|
+
*
|
|
5
|
+
* The nearest lockfile decides, looked for from `cwd` up to the repository's
|
|
6
|
+
* root - a package inside a workspace has its lockfile at the root. Without
|
|
7
|
+
* one, Corepack's `packageManager` field in package.json does, and npm is
|
|
8
|
+
* the answer when neither says anything. Running `npx` says nothing either
|
|
9
|
+
* way: it is how the command was started, not how the project installs.
|
|
10
|
+
*/
|
|
11
|
+
export declare function detectPackageManager(cwd: string): PackageManager;
|
|
12
|
+
/** The command that adds `spec` to the project's dependencies. */
|
|
13
|
+
export declare function addDependencyCommand(manager: PackageManager, spec: string): [command: string, args: string[]];
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
/** Lockfiles, in the order they are looked for in each directory. */
|
|
4
|
+
const LOCKFILES = [
|
|
5
|
+
["pnpm-lock.yaml", "pnpm"],
|
|
6
|
+
["yarn.lock", "yarn"],
|
|
7
|
+
["bun.lock", "bun"],
|
|
8
|
+
["bun.lockb", "bun"],
|
|
9
|
+
["package-lock.json", "npm"],
|
|
10
|
+
["npm-shrinkwrap.json", "npm"],
|
|
11
|
+
];
|
|
12
|
+
const MANAGERS = new Set(["npm", "pnpm", "yarn", "bun"]);
|
|
13
|
+
/**
|
|
14
|
+
* The package manager the project is installed with.
|
|
15
|
+
*
|
|
16
|
+
* The nearest lockfile decides, looked for from `cwd` up to the repository's
|
|
17
|
+
* root - a package inside a workspace has its lockfile at the root. Without
|
|
18
|
+
* one, Corepack's `packageManager` field in package.json does, and npm is
|
|
19
|
+
* the answer when neither says anything. Running `npx` says nothing either
|
|
20
|
+
* way: it is how the command was started, not how the project installs.
|
|
21
|
+
*/
|
|
22
|
+
export function detectPackageManager(cwd) {
|
|
23
|
+
for (let dir = cwd;; dir = dirname(dir)) {
|
|
24
|
+
const found = LOCKFILES.find(([file]) => existsSync(join(dir, file)));
|
|
25
|
+
if (found) {
|
|
26
|
+
return found[1];
|
|
27
|
+
}
|
|
28
|
+
// The repository's root is as far as the project goes: a lockfile
|
|
29
|
+
// above it belongs to something else.
|
|
30
|
+
if (existsSync(join(dir, ".git")) || dirname(dir) === dir) {
|
|
31
|
+
break;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return declaredPackageManager(cwd) ?? "npm";
|
|
35
|
+
}
|
|
36
|
+
/** `"pnpm@9.12.0"` in package.json's `packageManager` field, as `"pnpm"`. */
|
|
37
|
+
function declaredPackageManager(cwd) {
|
|
38
|
+
try {
|
|
39
|
+
const { packageManager } = JSON.parse(readFileSync(join(cwd, "package.json"), "utf8"));
|
|
40
|
+
const name = typeof packageManager === "string"
|
|
41
|
+
? packageManager.split("@")[0]
|
|
42
|
+
: undefined;
|
|
43
|
+
return name && MANAGERS.has(name) ? name : undefined;
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
return undefined;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
/** The command that adds `spec` to the project's dependencies. */
|
|
50
|
+
export function addDependencyCommand(manager, spec) {
|
|
51
|
+
return manager === "npm"
|
|
52
|
+
? ["npm", ["install", spec]]
|
|
53
|
+
: [manager, ["add", spec]];
|
|
54
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type * as TS from "typescript";
|
|
2
|
+
export type TypeScript = typeof TS;
|
|
3
|
+
export declare const SDK_PACKAGE = "@nestjs/observe";
|
|
4
|
+
/** Where the setup by hand is written down, for whatever link cannot do. */
|
|
5
|
+
export declare const QUICK_START_URL = "https://observe.nestjs.com/documentation/sdk#quick-start";
|
|
6
|
+
/** What link has to do to the project, besides writing the key pair. */
|
|
7
|
+
export interface ProjectSetup {
|
|
8
|
+
/**
|
|
9
|
+
* `@nestjs/observe` is not a dependency yet - or the app still has to be
|
|
10
|
+
* wired and the installed SDK is older than this one, whose types the
|
|
11
|
+
* wiring is written against.
|
|
12
|
+
*/
|
|
13
|
+
install: boolean;
|
|
14
|
+
/** No source file uses `@nestjs/observe` yet. */
|
|
15
|
+
wire: boolean;
|
|
16
|
+
/** Why the project cannot take the SDK, when it cannot. */
|
|
17
|
+
unsupported?: string;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Looks at the project before anything is asked of the API, so a project the
|
|
21
|
+
* SDK cannot run in is turned away before a key is issued for it, and the
|
|
22
|
+
* person approving knows what else the command is about to change.
|
|
23
|
+
*/
|
|
24
|
+
export declare function inspectProject(cwd: string, version: string, ts: TypeScript | undefined): ProjectSetup;
|
|
25
|
+
/**
|
|
26
|
+
* The project's own TypeScript, which the code is edited with - parsed by the
|
|
27
|
+
* compiler that will build it, so whatever syntax the project uses, it reads.
|
|
28
|
+
* Undefined without one; the CLI does not bring a compiler of its own.
|
|
29
|
+
*/
|
|
30
|
+
export declare function loadTypeScript(cwd: string): TypeScript | undefined;
|
|
31
|
+
/**
|
|
32
|
+
* The entry files of the project's applications, relative to it: the root
|
|
33
|
+
* application's, and every application project's in a monorepo. A monorepo's
|
|
34
|
+
* root usually names one of its own projects, so duplicates collapse.
|
|
35
|
+
*/
|
|
36
|
+
export declare function findEntryFiles(cwd: string, ts: TypeScript | undefined): string[];
|
|
37
|
+
/**
|
|
38
|
+
* The application's name the way the dashboard turns it into a `serviceId`
|
|
39
|
+
* for the setup it shows, so the two agree: lower-case, dashes for spaces,
|
|
40
|
+
* nothing else but letters and digits. The package name stands in when the
|
|
41
|
+
* application's name leaves nothing.
|
|
42
|
+
*/
|
|
43
|
+
export declare function serviceIdFor(...names: Array<string | undefined>): string;
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import { dirname, join, posix } from "node:path";
|
|
4
|
+
export const SDK_PACKAGE = "@nestjs/observe";
|
|
5
|
+
/** The oldest NestJS major the SDK's peer range takes. */
|
|
6
|
+
const MIN_NEST_MAJOR = 11;
|
|
7
|
+
/** Where the setup by hand is written down, for whatever link cannot do. */
|
|
8
|
+
export const QUICK_START_URL = "https://observe.nestjs.com/documentation/sdk#quick-start";
|
|
9
|
+
/** Directories never searched for the SDK's imports. */
|
|
10
|
+
const SKIPPED_DIRECTORIES = new Set([
|
|
11
|
+
"node_modules",
|
|
12
|
+
"dist",
|
|
13
|
+
"build",
|
|
14
|
+
"coverage",
|
|
15
|
+
".git",
|
|
16
|
+
]);
|
|
17
|
+
/** Enough to cover any real source tree, and a bound on a pathological one. */
|
|
18
|
+
const MAX_SCANNED_FILES = 20_000;
|
|
19
|
+
/**
|
|
20
|
+
* Looks at the project before anything is asked of the API, so a project the
|
|
21
|
+
* SDK cannot run in is turned away before a key is issued for it, and the
|
|
22
|
+
* person approving knows what else the command is about to change.
|
|
23
|
+
*/
|
|
24
|
+
export function inspectProject(cwd, version, ts) {
|
|
25
|
+
const pkg = readPackageJson(cwd);
|
|
26
|
+
const declared = declaredRange(pkg, SDK_PACKAGE);
|
|
27
|
+
const wire = !usesSdk(cwd, readNestCliConfig(cwd, ts));
|
|
28
|
+
const installed = installedVersion(cwd, SDK_PACKAGE);
|
|
29
|
+
const install = declared === undefined ||
|
|
30
|
+
(wire && (installed === undefined || isOlder(installed, version)));
|
|
31
|
+
if (!install) {
|
|
32
|
+
return { install, wire };
|
|
33
|
+
}
|
|
34
|
+
const nest = installedVersion(cwd, "@nestjs/core") ?? declaredRange(pkg, "@nestjs/core");
|
|
35
|
+
if (nest === undefined) {
|
|
36
|
+
return {
|
|
37
|
+
install,
|
|
38
|
+
wire,
|
|
39
|
+
unsupported: "This does not look like a NestJS project: package.json has no @nestjs/core",
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
const major = Number(/\d+/.exec(nest)?.[0]);
|
|
43
|
+
if (major < MIN_NEST_MAJOR) {
|
|
44
|
+
return {
|
|
45
|
+
install,
|
|
46
|
+
wire,
|
|
47
|
+
unsupported: `NestJS Observe needs NestJS ${MIN_NEST_MAJOR} or later, and this project has @nestjs/core ${nest}. Upgrade NestJS first`,
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
return { install, wire };
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* The project's own TypeScript, which the code is edited with - parsed by the
|
|
54
|
+
* compiler that will build it, so whatever syntax the project uses, it reads.
|
|
55
|
+
* Undefined without one; the CLI does not bring a compiler of its own.
|
|
56
|
+
*/
|
|
57
|
+
export function loadTypeScript(cwd) {
|
|
58
|
+
try {
|
|
59
|
+
const ts = createRequire(join(cwd, "package.json"))("typescript");
|
|
60
|
+
return typeof ts.createSourceFile === "function" ? ts : undefined;
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
return undefined;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* `nest-cli.json`, the file the Nest CLI loads. It may carry comments, which
|
|
68
|
+
* only the project's TypeScript can read past; without it such a file counts
|
|
69
|
+
* as absent, and the defaults - `src/main.ts` - apply.
|
|
70
|
+
*/
|
|
71
|
+
function readNestCliConfig(cwd, ts) {
|
|
72
|
+
for (const name of ["nest-cli.json", ".nest-cli.json"]) {
|
|
73
|
+
const path = join(cwd, name);
|
|
74
|
+
if (!existsSync(path)) {
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
const text = readFileSync(path, "utf8");
|
|
78
|
+
try {
|
|
79
|
+
return JSON.parse(text);
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
const parsed = ts?.parseConfigFileTextToJson(path, text);
|
|
83
|
+
return parsed?.config ?? {};
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return {};
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* The entry files of the project's applications, relative to it: the root
|
|
90
|
+
* application's, and every application project's in a monorepo. A monorepo's
|
|
91
|
+
* root usually names one of its own projects, so duplicates collapse.
|
|
92
|
+
*/
|
|
93
|
+
export function findEntryFiles(cwd, ts) {
|
|
94
|
+
const config = readNestCliConfig(cwd, ts);
|
|
95
|
+
const found = new Set();
|
|
96
|
+
const add = (sourceRoot, entryFile) => {
|
|
97
|
+
if (!sourceRoot) {
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
const path = posix.normalize(`${sourceRoot.replace(/\\/g, "/")}/${entryFile ?? "main"}.ts`);
|
|
101
|
+
if (existsSync(join(cwd, path))) {
|
|
102
|
+
found.add(path);
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
for (const project of Object.values(config.projects ?? {})) {
|
|
106
|
+
if (project?.type === "library") {
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
add(project?.sourceRoot ??
|
|
110
|
+
(project?.root ? `${project.root}/src` : undefined), project?.entryFile);
|
|
111
|
+
}
|
|
112
|
+
add(config.sourceRoot ?? "src", config.entryFile);
|
|
113
|
+
return [...found];
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Whether any source file already imports the SDK: a `nest new` project
|
|
117
|
+
* generated with Observe, or one wired by hand. Either way the code is left
|
|
118
|
+
* alone.
|
|
119
|
+
*/
|
|
120
|
+
function usesSdk(cwd, config) {
|
|
121
|
+
const roots = new Set([config.sourceRoot ?? "src", "apps", "libs"]);
|
|
122
|
+
for (const project of Object.values(config.projects ?? {})) {
|
|
123
|
+
const root = project?.sourceRoot ?? project?.root;
|
|
124
|
+
if (root) {
|
|
125
|
+
roots.add(root);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
let budget = MAX_SCANNED_FILES;
|
|
129
|
+
const search = (dir) => {
|
|
130
|
+
let entries;
|
|
131
|
+
try {
|
|
132
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
133
|
+
}
|
|
134
|
+
catch {
|
|
135
|
+
return false;
|
|
136
|
+
}
|
|
137
|
+
for (const entry of entries) {
|
|
138
|
+
if (budget <= 0) {
|
|
139
|
+
return false;
|
|
140
|
+
}
|
|
141
|
+
const path = join(dir, entry.name);
|
|
142
|
+
if (entry.isDirectory()) {
|
|
143
|
+
if (!SKIPPED_DIRECTORIES.has(entry.name) && search(path)) {
|
|
144
|
+
return true;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
else if (/\.[cm]?[jt]s$/.test(entry.name)) {
|
|
148
|
+
budget -= 1;
|
|
149
|
+
if (readFileSync(path, "utf8").includes(SDK_PACKAGE)) {
|
|
150
|
+
return true;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return false;
|
|
155
|
+
};
|
|
156
|
+
return [...roots].some((root) => search(join(cwd, root)));
|
|
157
|
+
}
|
|
158
|
+
function readPackageJson(cwd) {
|
|
159
|
+
try {
|
|
160
|
+
return JSON.parse(readFileSync(join(cwd, "package.json"), "utf8"));
|
|
161
|
+
}
|
|
162
|
+
catch {
|
|
163
|
+
return {};
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
/** The range package.json asks for `name` in, from any dependency section. */
|
|
167
|
+
function declaredRange(pkg, name) {
|
|
168
|
+
for (const section of [
|
|
169
|
+
"dependencies",
|
|
170
|
+
"devDependencies",
|
|
171
|
+
"peerDependencies",
|
|
172
|
+
]) {
|
|
173
|
+
const range = pkg[section]?.[name];
|
|
174
|
+
if (typeof range === "string") {
|
|
175
|
+
return range;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
return undefined;
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* The version of `name` the project resolves, hoisted or not. Read off the
|
|
182
|
+
* package's own package.json, found from its entry point when the package
|
|
183
|
+
* does not export that file.
|
|
184
|
+
*/
|
|
185
|
+
function installedVersion(cwd, name) {
|
|
186
|
+
const require = createRequire(join(cwd, "package.json"));
|
|
187
|
+
const readVersion = (path) => {
|
|
188
|
+
const pkg = JSON.parse(readFileSync(path, "utf8"));
|
|
189
|
+
return pkg.name === name ? pkg.version : undefined;
|
|
190
|
+
};
|
|
191
|
+
try {
|
|
192
|
+
return readVersion(require.resolve(`${name}/package.json`));
|
|
193
|
+
}
|
|
194
|
+
catch {
|
|
195
|
+
// Not exported, or not installed: try the entry point.
|
|
196
|
+
}
|
|
197
|
+
try {
|
|
198
|
+
for (let dir = dirname(require.resolve(name));; dir = dirname(dir)) {
|
|
199
|
+
const path = join(dir, "package.json");
|
|
200
|
+
if (existsSync(path)) {
|
|
201
|
+
const version = readVersion(path);
|
|
202
|
+
if (version) {
|
|
203
|
+
return version;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
if (dirname(dir) === dir) {
|
|
207
|
+
return undefined;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
catch {
|
|
212
|
+
return undefined;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
/** `"0.3.16"`, or `"0.3.16-beta.1"`, as `[0, 3, 16]`. */
|
|
216
|
+
function releaseOf(version) {
|
|
217
|
+
return (/(\d+)\.(\d+)\.(\d+)/.exec(version) ?? []).slice(1, 4).map(Number);
|
|
218
|
+
}
|
|
219
|
+
/** Whether `a` is an older release than `b`, by major, minor and patch. */
|
|
220
|
+
function isOlder(a, b) {
|
|
221
|
+
const [x, y] = [releaseOf(a), releaseOf(b)];
|
|
222
|
+
for (let i = 0; i < 3; i++) {
|
|
223
|
+
if ((x[i] ?? 0) !== (y[i] ?? 0)) {
|
|
224
|
+
return (x[i] ?? 0) < (y[i] ?? 0);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
return false;
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* The application's name the way the dashboard turns it into a `serviceId`
|
|
231
|
+
* for the setup it shows, so the two agree: lower-case, dashes for spaces,
|
|
232
|
+
* nothing else but letters and digits. The package name stands in when the
|
|
233
|
+
* application's name leaves nothing.
|
|
234
|
+
*/
|
|
235
|
+
export function serviceIdFor(...names) {
|
|
236
|
+
for (const name of names) {
|
|
237
|
+
const id = (name ?? "")
|
|
238
|
+
.replace(/^@[^/]+\//, "")
|
|
239
|
+
.toLowerCase()
|
|
240
|
+
.trim()
|
|
241
|
+
.replace(/\s+/g, "-")
|
|
242
|
+
.replace(/-{2,}/g, "-")
|
|
243
|
+
.replace(/[^a-z0-9-]/g, "");
|
|
244
|
+
if (id) {
|
|
245
|
+
return id;
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
return "app";
|
|
249
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { TypeScript } from "./project-setup.js";
|
|
2
|
+
/** One file the wiring changed, and what it changed there. */
|
|
3
|
+
export interface WiredFile {
|
|
4
|
+
/** Relative to the project, with forward slashes. */
|
|
5
|
+
path: string;
|
|
6
|
+
change: string;
|
|
7
|
+
}
|
|
8
|
+
export type WireResult = {
|
|
9
|
+
kind: "wired";
|
|
10
|
+
files: WiredFile[];
|
|
11
|
+
} | {
|
|
12
|
+
kind: "manual";
|
|
13
|
+
reason: string;
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* Wires `@nestjs/observe` into one application the way `nest new` generates
|
|
17
|
+
* it: `createObserveModule()` and `ObserveModule.forRoot()` in the root
|
|
18
|
+
* module, `ObserveInstrument` passed to `NestFactory.create()`.
|
|
19
|
+
*
|
|
20
|
+
* The root module is the one `main.ts` hands to `NestFactory.create()`, found
|
|
21
|
+
* by following its import - not assumed to be `app.module.ts`. The key pair is
|
|
22
|
+
* read from `OBSERVE_APP_KEY` and `OBSERVE_APP_SECRET`, which link has just
|
|
23
|
+
* written into `.env`.
|
|
24
|
+
*
|
|
25
|
+
* Both files change or neither does: every edit is worked out first, and
|
|
26
|
+
* each edited file has to parse before anything is written. Whatever cannot
|
|
27
|
+
* be done safely comes back as a reason, for the person to finish by hand.
|
|
28
|
+
*/
|
|
29
|
+
export declare function wireApplication(ts: TypeScript, cwd: string, mainPath: string, serviceId: string): WireResult;
|
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join, posix } from "node:path";
|
|
3
|
+
import { SDK_PACKAGE } from "./project-setup.js";
|
|
4
|
+
/** What a step could not do, as the reason the CLI prints. */
|
|
5
|
+
class ManualStep {
|
|
6
|
+
reason;
|
|
7
|
+
constructor(reason) {
|
|
8
|
+
this.reason = reason;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Wires `@nestjs/observe` into one application the way `nest new` generates
|
|
13
|
+
* it: `createObserveModule()` and `ObserveModule.forRoot()` in the root
|
|
14
|
+
* module, `ObserveInstrument` passed to `NestFactory.create()`.
|
|
15
|
+
*
|
|
16
|
+
* The root module is the one `main.ts` hands to `NestFactory.create()`, found
|
|
17
|
+
* by following its import - not assumed to be `app.module.ts`. The key pair is
|
|
18
|
+
* read from `OBSERVE_APP_KEY` and `OBSERVE_APP_SECRET`, which link has just
|
|
19
|
+
* written into `.env`.
|
|
20
|
+
*
|
|
21
|
+
* Both files change or neither does: every edit is worked out first, and
|
|
22
|
+
* each edited file has to parse before anything is written. Whatever cannot
|
|
23
|
+
* be done safely comes back as a reason, for the person to finish by hand.
|
|
24
|
+
*/
|
|
25
|
+
export function wireApplication(ts, cwd, mainPath, serviceId) {
|
|
26
|
+
try {
|
|
27
|
+
const files = planWiring(ts, cwd, mainPath, serviceId);
|
|
28
|
+
for (const file of files) {
|
|
29
|
+
if (syntaxErrors(ts, file.path, file.text) >
|
|
30
|
+
syntaxErrors(ts, file.path, file.original)) {
|
|
31
|
+
return manual(`editing ${file.path} would not have left it valid TypeScript`);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
for (const file of files) {
|
|
35
|
+
writeFileSync(join(cwd, file.path), file.text);
|
|
36
|
+
}
|
|
37
|
+
return {
|
|
38
|
+
kind: "wired",
|
|
39
|
+
files: files.map(({ path, change }) => ({ path, change })),
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
catch (err) {
|
|
43
|
+
if (err instanceof ManualStep) {
|
|
44
|
+
return manual(err.reason);
|
|
45
|
+
}
|
|
46
|
+
throw err;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
function manual(reason) {
|
|
50
|
+
return { kind: "manual", reason };
|
|
51
|
+
}
|
|
52
|
+
function planWiring(ts, cwd, mainPath, serviceId) {
|
|
53
|
+
const mainText = readFileSync(join(cwd, mainPath), "utf8");
|
|
54
|
+
const main = parse(ts, mainPath, mainText);
|
|
55
|
+
const create = findNestFactoryCreate(ts, main);
|
|
56
|
+
if (!create) {
|
|
57
|
+
throw new ManualStep(`${mainPath} has no NestFactory.create() call`);
|
|
58
|
+
}
|
|
59
|
+
const [rootArgument] = create.arguments;
|
|
60
|
+
if (!rootArgument || !ts.isIdentifier(rootArgument)) {
|
|
61
|
+
throw new ManualStep(`the module NestFactory.create() starts in ${mainPath} is not a plain class name`);
|
|
62
|
+
}
|
|
63
|
+
const rootModule = rootArgument.text;
|
|
64
|
+
const moduleImport = findImportOf(ts, main, rootModule);
|
|
65
|
+
const specifier = moduleImport && ts.isStringLiteral(moduleImport.moduleSpecifier)
|
|
66
|
+
? moduleImport.moduleSpecifier.text
|
|
67
|
+
: undefined;
|
|
68
|
+
if (!moduleImport || !specifier?.startsWith(".")) {
|
|
69
|
+
throw new ManualStep(`${mainPath} does not import ${rootModule} from a file of this project`);
|
|
70
|
+
}
|
|
71
|
+
const modulePath = resolveImport(cwd, mainPath, specifier);
|
|
72
|
+
if (!modulePath) {
|
|
73
|
+
throw new ManualStep(`could not find ${specifier}, which ${mainPath} imports ${rootModule} from`);
|
|
74
|
+
}
|
|
75
|
+
const moduleText = readFileSync(join(cwd, modulePath), "utf8");
|
|
76
|
+
if (moduleText.includes("createObserveModule")) {
|
|
77
|
+
throw new ManualStep(`${modulePath} already calls createObserveModule(), so it was left alone`);
|
|
78
|
+
}
|
|
79
|
+
return [
|
|
80
|
+
{
|
|
81
|
+
path: modulePath,
|
|
82
|
+
original: moduleText,
|
|
83
|
+
text: wireRootModule(ts, modulePath, moduleText, rootModule, serviceId),
|
|
84
|
+
change: `registers ObserveModule first in ${rootModule}'s imports, serviceId "${serviceId}"`,
|
|
85
|
+
},
|
|
86
|
+
{
|
|
87
|
+
path: mainPath,
|
|
88
|
+
original: mainText,
|
|
89
|
+
text: wireMain(ts, mainPath, mainText, main, create, moduleImport),
|
|
90
|
+
change: "passes ObserveInstrument to NestFactory.create()",
|
|
91
|
+
},
|
|
92
|
+
];
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* The root module: the import and the `createObserveModule()` call after the
|
|
96
|
+
* last import, and `ObserveModule.forRoot()` as the first of `@Module()`'s
|
|
97
|
+
* imports - ahead of `BullModule` and anything else that registers a queue,
|
|
98
|
+
* so the jobs still running when the app stops are reported.
|
|
99
|
+
*/
|
|
100
|
+
function wireRootModule(ts, path, text, className, serviceId) {
|
|
101
|
+
const source = parse(ts, path, text);
|
|
102
|
+
const declaration = source.statements.find((statement) => ts.isClassDeclaration(statement) && statement.name?.text === className);
|
|
103
|
+
const decorator = declaration
|
|
104
|
+
? decoratorsOf(ts, declaration).find((candidate) => ts.isCallExpression(candidate.expression) &&
|
|
105
|
+
ts.isIdentifier(candidate.expression.expression) &&
|
|
106
|
+
candidate.expression.expression.text === "Module")
|
|
107
|
+
: undefined;
|
|
108
|
+
const metadata = decorator
|
|
109
|
+
? decorator.expression.arguments[0]
|
|
110
|
+
: undefined;
|
|
111
|
+
if (!decorator || !metadata || !ts.isObjectLiteralExpression(metadata)) {
|
|
112
|
+
throw new ManualStep(`could not find @Module({ ... }) on ${className} in ${path}`);
|
|
113
|
+
}
|
|
114
|
+
const style = styleOf(ts, source, text);
|
|
115
|
+
const edits = [];
|
|
116
|
+
const imports = metadata.properties.find((property) => propertyName(ts, property) === "imports");
|
|
117
|
+
if (imports) {
|
|
118
|
+
if (!ts.isPropertyAssignment(imports) ||
|
|
119
|
+
!ts.isArrayLiteralExpression(imports.initializer)) {
|
|
120
|
+
throw new ManualStep(`the imports of ${className} in ${path} are not a plain array`);
|
|
121
|
+
}
|
|
122
|
+
edits.push(prependElement(text, source, imports.initializer, lineIndent(text, imports.getStart(source)), style, serviceId));
|
|
123
|
+
}
|
|
124
|
+
else {
|
|
125
|
+
edits.push(prependImportsProperty(text, source, metadata, lineIndent(text, decorator.getStart(source)), style, serviceId));
|
|
126
|
+
}
|
|
127
|
+
const { quote, semicolon, eol } = style;
|
|
128
|
+
const declarations = `import { createObserveModule } from ${quote}${SDK_PACKAGE}${quote}${semicolon}${eol}${eol}` +
|
|
129
|
+
`export const { ObserveModule, ObserveInstrument } = createObserveModule()${semicolon}`;
|
|
130
|
+
const lastImport = source.statements.findLast(ts.isImportDeclaration);
|
|
131
|
+
edits.push(lastImport
|
|
132
|
+
? {
|
|
133
|
+
start: lastImport.getEnd(),
|
|
134
|
+
end: lastImport.getEnd(),
|
|
135
|
+
text: `${eol}${declarations}`,
|
|
136
|
+
}
|
|
137
|
+
: { start: 0, end: 0, text: `${declarations}${eol}${eol}` });
|
|
138
|
+
return applyEdits(text, edits);
|
|
139
|
+
}
|
|
140
|
+
/** `ObserveModule.forRoot({ ... })`, its first line at `indent`. */
|
|
141
|
+
function forRootCall(serviceId, indent, style) {
|
|
142
|
+
const { quote, unit, eol } = style;
|
|
143
|
+
const inner = indent + unit;
|
|
144
|
+
return [
|
|
145
|
+
"ObserveModule.forRoot({",
|
|
146
|
+
`${inner}appKey: process.env.OBSERVE_APP_KEY,`,
|
|
147
|
+
`${inner}appSecret: process.env.OBSERVE_APP_SECRET,`,
|
|
148
|
+
`${inner}serviceId: ${quote}${serviceId}${quote},`,
|
|
149
|
+
`${indent}})`,
|
|
150
|
+
].join(eol);
|
|
151
|
+
}
|
|
152
|
+
/** `ObserveModule.forRoot()` as the first element of an `imports` array. */
|
|
153
|
+
function prependElement(text, source, array, propertyIndent, style, serviceId) {
|
|
154
|
+
const { eol } = style;
|
|
155
|
+
const open = array.getStart(source);
|
|
156
|
+
const inner = text.slice(open + 1, array.getEnd() - 1);
|
|
157
|
+
// One element a line already: in at the top, at the elements' own
|
|
158
|
+
// indentation, the rest as it was.
|
|
159
|
+
if (array.elements.length > 0 && startsLine(text, open + 1)) {
|
|
160
|
+
const indent = lineIndent(text, array.elements[0].getStart(source));
|
|
161
|
+
const call = forRootCall(serviceId, indent, style);
|
|
162
|
+
return { start: open + 1, end: open + 1, text: `${eol}${indent}${call},` };
|
|
163
|
+
}
|
|
164
|
+
const indent = propertyIndent + style.unit;
|
|
165
|
+
const call = forRootCall(serviceId, indent, style);
|
|
166
|
+
// Empty, or all on one line: laid out a line each, keeping what was there
|
|
167
|
+
// - comments included - on the line after.
|
|
168
|
+
const rest = inner.trim();
|
|
169
|
+
const comma = array.elements.length > 0 && !array.elements.hasTrailingComma ? "," : "";
|
|
170
|
+
return {
|
|
171
|
+
start: open,
|
|
172
|
+
end: array.getEnd(),
|
|
173
|
+
text: `[${eol}${indent}${call},` +
|
|
174
|
+
(rest ? `${eol}${indent}${rest}${comma}` : "") +
|
|
175
|
+
`${eol}${propertyIndent}]`,
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
/** `imports: [ObserveModule.forRoot()]` as the first property of `@Module()`. */
|
|
179
|
+
function prependImportsProperty(text, source, metadata, decoratorIndent, style, serviceId) {
|
|
180
|
+
const { eol, unit } = style;
|
|
181
|
+
const open = metadata.getStart(source);
|
|
182
|
+
const multiline = metadata.properties.length > 0 && startsLine(text, open + 1);
|
|
183
|
+
const propertyIndent = multiline
|
|
184
|
+
? lineIndent(text, metadata.properties[0].getStart(source))
|
|
185
|
+
: decoratorIndent + unit;
|
|
186
|
+
const indent = propertyIndent + unit;
|
|
187
|
+
const property = `imports: [${eol}${indent}${forRootCall(serviceId, indent, style)},` +
|
|
188
|
+
`${eol}${propertyIndent}],`;
|
|
189
|
+
if (multiline) {
|
|
190
|
+
return {
|
|
191
|
+
start: open + 1,
|
|
192
|
+
end: open + 1,
|
|
193
|
+
text: `${eol}${propertyIndent}${property}`,
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
const rest = text.slice(open + 1, metadata.getEnd() - 1).trim();
|
|
197
|
+
const comma = metadata.properties.length > 0 && !metadata.properties.hasTrailingComma
|
|
198
|
+
? ","
|
|
199
|
+
: "";
|
|
200
|
+
return {
|
|
201
|
+
start: open,
|
|
202
|
+
end: metadata.getEnd(),
|
|
203
|
+
text: `{${eol}${propertyIndent}${property}` +
|
|
204
|
+
(rest ? `${eol}${propertyIndent}${rest}${comma}` : "") +
|
|
205
|
+
`${eol}${decoratorIndent}}`,
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* `main.ts`: `ObserveInstrument` imported alongside the root module, and
|
|
210
|
+
* passed as `instrument` in `NestFactory.create()`'s options - added to the
|
|
211
|
+
* options object when there is one, as a new argument when there is not.
|
|
212
|
+
*/
|
|
213
|
+
function wireMain(ts, path, text, source, create, moduleImport) {
|
|
214
|
+
const style = styleOf(ts, source, text);
|
|
215
|
+
const { eol, unit } = style;
|
|
216
|
+
const edits = [];
|
|
217
|
+
const args = create.arguments;
|
|
218
|
+
const last = args[args.length - 1];
|
|
219
|
+
if (args.length >= 2 && ts.isObjectLiteralExpression(last)) {
|
|
220
|
+
if (last.properties.some((property) => propertyName(ts, property) === "instrument")) {
|
|
221
|
+
throw new ManualStep(`NestFactory.create() in ${path} already has an instrument option`);
|
|
222
|
+
}
|
|
223
|
+
if (last.properties.length === 0) {
|
|
224
|
+
edits.push({
|
|
225
|
+
start: last.getStart(source),
|
|
226
|
+
end: last.getEnd(),
|
|
227
|
+
text: "{ instrument: ObserveInstrument }",
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
else {
|
|
231
|
+
const lastProperty = last.properties[last.properties.length - 1];
|
|
232
|
+
const separator = startsLine(text, last.getStart(source) + 1)
|
|
233
|
+
? `${eol}${lineIndent(text, lastProperty.getStart(source))}`
|
|
234
|
+
: " ";
|
|
235
|
+
edits.push({
|
|
236
|
+
start: lastProperty.getEnd(),
|
|
237
|
+
end: lastProperty.getEnd(),
|
|
238
|
+
text: `,${separator}instrument: ObserveInstrument`,
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
else if (startsLine(text, args.pos)) {
|
|
243
|
+
// Arguments a line each: the options as one more line.
|
|
244
|
+
edits.push({
|
|
245
|
+
start: last.getEnd(),
|
|
246
|
+
end: last.getEnd(),
|
|
247
|
+
text: `,${eol}${lineIndent(text, last.getStart(source))}{ instrument: ObserveInstrument }`,
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
else {
|
|
251
|
+
const indent = lineIndent(text, create.getStart(source));
|
|
252
|
+
edits.push({
|
|
253
|
+
start: last.getEnd(),
|
|
254
|
+
end: last.getEnd(),
|
|
255
|
+
text: `, {${eol}${indent}${unit}instrument: ObserveInstrument,${eol}${indent}}`,
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
const bindings = moduleImport.importClause?.namedBindings;
|
|
259
|
+
if (bindings && ts.isNamedImports(bindings) && bindings.elements.length > 0) {
|
|
260
|
+
const lastBinding = bindings.elements[bindings.elements.length - 1];
|
|
261
|
+
edits.push({
|
|
262
|
+
start: lastBinding.getEnd(),
|
|
263
|
+
end: lastBinding.getEnd(),
|
|
264
|
+
text: ", ObserveInstrument",
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
else {
|
|
268
|
+
const specifier = moduleImport.moduleSpecifier.getText(source);
|
|
269
|
+
edits.push({
|
|
270
|
+
start: moduleImport.getEnd(),
|
|
271
|
+
end: moduleImport.getEnd(),
|
|
272
|
+
text: `${eol}import { ObserveInstrument } from ${specifier}${style.semicolon}`,
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
return applyEdits(text, edits);
|
|
276
|
+
}
|
|
277
|
+
function styleOf(ts, source, text) {
|
|
278
|
+
const firstImport = source.statements.find(ts.isImportDeclaration);
|
|
279
|
+
return {
|
|
280
|
+
quote: firstImport
|
|
281
|
+
? text[firstImport.moduleSpecifier.getStart(source)]
|
|
282
|
+
: "'",
|
|
283
|
+
semicolon: firstImport && !firstImport.getText(source).endsWith(";") ? "" : ";",
|
|
284
|
+
unit: indentUnit(text),
|
|
285
|
+
eol: text.includes("\r\n") ? "\r\n" : "\n",
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* One level of indentation: a tab if lines are indented with tabs, otherwise
|
|
290
|
+
* the shallowest indentation in the file. Doc comments' ` * ` lines do not
|
|
291
|
+
* count; they are indented by one space whatever the file uses.
|
|
292
|
+
*/
|
|
293
|
+
function indentUnit(text) {
|
|
294
|
+
let unit;
|
|
295
|
+
for (const line of text.split(/\r?\n/)) {
|
|
296
|
+
const match = /^([ \t]+)[^\s*]/.exec(line);
|
|
297
|
+
if (!match) {
|
|
298
|
+
continue;
|
|
299
|
+
}
|
|
300
|
+
if (match[1].startsWith("\t")) {
|
|
301
|
+
return "\t";
|
|
302
|
+
}
|
|
303
|
+
if (unit === undefined || match[1].length < unit.length) {
|
|
304
|
+
unit = match[1];
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
return unit ?? " ";
|
|
308
|
+
}
|
|
309
|
+
/** The whitespace the line holding `position` starts with. */
|
|
310
|
+
function lineIndent(text, position) {
|
|
311
|
+
const start = text.lastIndexOf("\n", position - 1) + 1;
|
|
312
|
+
return /^[ \t]*/.exec(text.slice(start))?.[0] ?? "";
|
|
313
|
+
}
|
|
314
|
+
/** Whether nothing but a line break follows `position` on its line. */
|
|
315
|
+
function startsLine(text, position) {
|
|
316
|
+
return /^[ \t]*(\/\/[^\n]*)?\r?\n/.test(text.slice(position));
|
|
317
|
+
}
|
|
318
|
+
function parse(ts, path, text) {
|
|
319
|
+
return ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true);
|
|
320
|
+
}
|
|
321
|
+
/**
|
|
322
|
+
* Syntax errors only - a file can be valid TypeScript and still not type-check
|
|
323
|
+
* against packages that are not installed yet. Compared with the file as it
|
|
324
|
+
* was, so a project that already trips the parser somewhere is not refused.
|
|
325
|
+
*/
|
|
326
|
+
function syntaxErrors(ts, path, text) {
|
|
327
|
+
const { diagnostics } = ts.transpileModule(text, {
|
|
328
|
+
fileName: path,
|
|
329
|
+
reportDiagnostics: true,
|
|
330
|
+
compilerOptions: { experimentalDecorators: true },
|
|
331
|
+
});
|
|
332
|
+
return (diagnostics ?? []).filter((diagnostic) => diagnostic.category === ts.DiagnosticCategory.Error).length;
|
|
333
|
+
}
|
|
334
|
+
function findNestFactoryCreate(ts, source) {
|
|
335
|
+
let found;
|
|
336
|
+
const visit = (node) => {
|
|
337
|
+
if (found) {
|
|
338
|
+
return;
|
|
339
|
+
}
|
|
340
|
+
if (ts.isCallExpression(node) &&
|
|
341
|
+
ts.isPropertyAccessExpression(node.expression) &&
|
|
342
|
+
ts.isIdentifier(node.expression.expression) &&
|
|
343
|
+
node.expression.expression.text === "NestFactory" &&
|
|
344
|
+
node.expression.name.text === "create") {
|
|
345
|
+
found = node;
|
|
346
|
+
return;
|
|
347
|
+
}
|
|
348
|
+
ts.forEachChild(node, visit);
|
|
349
|
+
};
|
|
350
|
+
visit(source);
|
|
351
|
+
return found;
|
|
352
|
+
}
|
|
353
|
+
function findImportOf(ts, source, identifier) {
|
|
354
|
+
return source.statements.find((statement) => {
|
|
355
|
+
if (!ts.isImportDeclaration(statement) || !statement.importClause) {
|
|
356
|
+
return false;
|
|
357
|
+
}
|
|
358
|
+
const { name, namedBindings } = statement.importClause;
|
|
359
|
+
return (name?.text === identifier ||
|
|
360
|
+
(!!namedBindings &&
|
|
361
|
+
ts.isNamedImports(namedBindings) &&
|
|
362
|
+
namedBindings.elements.some((element) => element.name.text === identifier)));
|
|
363
|
+
});
|
|
364
|
+
}
|
|
365
|
+
/** `./app.module` or `./app.module.js` from `src/main.ts`, as `src/app.module.ts`. */
|
|
366
|
+
function resolveImport(cwd, fromPath, specifier) {
|
|
367
|
+
const base = posix.join(posix.dirname(fromPath), specifier.replace(/\.(js|mjs|cjs|ts|mts|cts)$/, ""));
|
|
368
|
+
return [`${base}.ts`, `${base}.mts`, `${base}/index.ts`].find((candidate) => existsSync(join(cwd, candidate)));
|
|
369
|
+
}
|
|
370
|
+
/**
|
|
371
|
+
* A class's decorators - through `getDecorators()` from TypeScript 4.8, which
|
|
372
|
+
* moved them off the node, and off the node before that.
|
|
373
|
+
*/
|
|
374
|
+
function decoratorsOf(ts, node) {
|
|
375
|
+
if (typeof ts.getDecorators === "function") {
|
|
376
|
+
return ts.getDecorators(node) ?? [];
|
|
377
|
+
}
|
|
378
|
+
return node.decorators ?? [];
|
|
379
|
+
}
|
|
380
|
+
function propertyName(ts, property) {
|
|
381
|
+
const name = property.name;
|
|
382
|
+
return name && (ts.isIdentifier(name) || ts.isStringLiteral(name))
|
|
383
|
+
? name.text
|
|
384
|
+
: undefined;
|
|
385
|
+
}
|
|
386
|
+
function applyEdits(text, edits) {
|
|
387
|
+
return [...edits]
|
|
388
|
+
.sort((a, b) => b.start - a.start)
|
|
389
|
+
.reduce((result, edit) => result.slice(0, edit.start) + edit.text + result.slice(edit.end), text);
|
|
390
|
+
}
|
|
@@ -149,26 +149,31 @@ export interface ObserveOptions {
|
|
|
149
149
|
/**
|
|
150
150
|
* Application key identifying this service to the collector.
|
|
151
151
|
*
|
|
152
|
-
*
|
|
153
|
-
*
|
|
152
|
+
* `npx @nestjs/observe link` issues the key and secret together and writes
|
|
153
|
+
* them into `.env`; so does the dashboard at https://observe.nestjs.com.
|
|
154
|
+
* Left out - or still holding the `nest new` placeholder - it is read from
|
|
155
|
+
* `OBSERVE_APP_KEY` when the options resolve.
|
|
154
156
|
*
|
|
155
157
|
* Sent as `x-api-key` on every ingest request, alongside `appSecret`.
|
|
156
158
|
* Without valid credentials the collector answers 401 and the batch is
|
|
157
159
|
* dropped; the agent then backs off, to one attempt an hour, until a
|
|
158
|
-
* restart picks up fixed credentials. With this or `appSecret` unset,
|
|
159
|
-
* nothing
|
|
160
|
-
* says so - while a collector of
|
|
160
|
+
* restart picks up fixed credentials. With this or `appSecret` unset, and
|
|
161
|
+
* nothing in the environment either, nothing is sent to the hosted
|
|
162
|
+
* collector at all - a warning at startup says so - while a collector of
|
|
163
|
+
* your own still receives the batches.
|
|
161
164
|
*/
|
|
162
|
-
appKey
|
|
165
|
+
appKey?: string;
|
|
163
166
|
/**
|
|
164
|
-
* Secret paired with `appKey`, issued with it
|
|
167
|
+
* Secret paired with `appKey`, issued with it. Left out - or still holding
|
|
168
|
+
* the `nest new` placeholder - it is read from `OBSERVE_APP_SECRET` when the
|
|
169
|
+
* options resolve.
|
|
165
170
|
*
|
|
166
171
|
* Sent as `x-api-secret`. Shown once when the key is issued and not
|
|
167
172
|
* retrievable afterwards, so treat it as you would a password: supply it from
|
|
168
173
|
* the environment rather than committing it alongside the rest of this config.
|
|
169
174
|
* If it is lost, issue a new pair from the dashboard.
|
|
170
175
|
*/
|
|
171
|
-
appSecret
|
|
176
|
+
appSecret?: string;
|
|
172
177
|
/**
|
|
173
178
|
* Base URL of the collector, without a trailing path.
|
|
174
179
|
*
|
|
@@ -53,10 +53,9 @@ export declare class HttpObserveAgentService<Store extends Record<string, unknow
|
|
|
53
53
|
* either plucked the trace or is about to.
|
|
54
54
|
*
|
|
55
55
|
* Eviction is deferred, not immediate: Express does not cancel the handler
|
|
56
|
-
* on abort, so its spans are usually still closing when `close` fires
|
|
57
|
-
*
|
|
58
|
-
*
|
|
59
|
-
* a shutting-down process open.
|
|
56
|
+
* on abort, so its spans are usually still closing when `close` fires. The
|
|
57
|
+
* grace period lets the handler drain first; `unref` keeps the timer from
|
|
58
|
+
* holding a shutting-down process open.
|
|
60
59
|
*/
|
|
61
60
|
private evictTraceOnClientAbort;
|
|
62
61
|
/**
|
|
@@ -94,8 +94,11 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
|
|
|
94
94
|
httpAdapter.setOnRequestHook((req, res, done) => {
|
|
95
95
|
this.startHttpRequestTracing(req, res, done);
|
|
96
96
|
});
|
|
97
|
-
|
|
97
|
+
// Fastify waits for `done` before it runs the next onResponse hook.
|
|
98
|
+
// Express does not pass one.
|
|
99
|
+
httpAdapter.setOnResponseHook((req, res, done) => {
|
|
98
100
|
this.endHttpRequestTracing(req, res);
|
|
101
|
+
done?.();
|
|
99
102
|
});
|
|
100
103
|
}
|
|
101
104
|
startHttpRequestTracing(req, res, done) {
|
|
@@ -207,10 +210,9 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
|
|
|
207
210
|
* either plucked the trace or is about to.
|
|
208
211
|
*
|
|
209
212
|
* Eviction is deferred, not immediate: Express does not cancel the handler
|
|
210
|
-
* on abort, so its spans are usually still closing when `close` fires
|
|
211
|
-
*
|
|
212
|
-
*
|
|
213
|
-
* a shutting-down process open.
|
|
213
|
+
* on abort, so its spans are usually still closing when `close` fires. The
|
|
214
|
+
* grace period lets the handler drain first; `unref` keeps the timer from
|
|
215
|
+
* holding a shutting-down process open.
|
|
214
216
|
*/
|
|
215
217
|
evictTraceOnClientAbort(res, traceId) {
|
|
216
218
|
const response = res;
|
|
@@ -195,6 +195,12 @@ export declare class OperationTraceRegistry {
|
|
|
195
195
|
private awaitingCompletion;
|
|
196
196
|
hasSnapshotsAwaitingCompletion(): boolean;
|
|
197
197
|
pluckSnapshot(traceId: string): Promise<RequestSnapshot | JobSnapshot | undefined>;
|
|
198
|
+
/**
|
|
199
|
+
* One line per trace `pluckSnapshot` gives up on, naming the spans that kept
|
|
200
|
+
* it open. Their late ends are silent: one un-awaited call usually holds a
|
|
201
|
+
* whole chain of spans open, and a line per span said the same thing N times.
|
|
202
|
+
*/
|
|
203
|
+
private reportDroppedTrace;
|
|
198
204
|
/**
|
|
199
205
|
* Whether `skipSpans` claims a finished operation. Only request snapshots
|
|
200
206
|
* are asked: a job has no status to be judged by.
|
|
@@ -370,7 +370,9 @@ export class OperationTraceRegistry {
|
|
|
370
370
|
callerId, error) {
|
|
371
371
|
const snapshot = this.traceSnapshots.get(traceId);
|
|
372
372
|
if (!snapshot) {
|
|
373
|
-
|
|
373
|
+
// The trace was dropped while this span was still open - `pluckSnapshot`
|
|
374
|
+
// gave up on it (and said so, once for the whole trace), or the client
|
|
375
|
+
// aborted. Nothing is left to record it in.
|
|
374
376
|
return;
|
|
375
377
|
}
|
|
376
378
|
snapshot.refsMarkedAsComplete += 1;
|
|
@@ -561,6 +563,7 @@ export class OperationTraceRegistry {
|
|
|
561
563
|
this.awaitingCompletion -= 1;
|
|
562
564
|
}
|
|
563
565
|
if (snapshot.refsCounter > snapshot.refsMarkedAsComplete) {
|
|
566
|
+
this.reportDroppedTrace(traceId, snapshot);
|
|
564
567
|
cleanup();
|
|
565
568
|
return undefined;
|
|
566
569
|
}
|
|
@@ -597,6 +600,23 @@ export class OperationTraceRegistry {
|
|
|
597
600
|
}
|
|
598
601
|
return undefined;
|
|
599
602
|
}
|
|
603
|
+
/**
|
|
604
|
+
* One line per trace `pluckSnapshot` gives up on, naming the spans that kept
|
|
605
|
+
* it open. Their late ends are silent: one un-awaited call usually holds a
|
|
606
|
+
* whole chain of spans open, and a line per span said the same thing N times.
|
|
607
|
+
*/
|
|
608
|
+
reportDroppedTrace(traceId, snapshot) {
|
|
609
|
+
const open = [];
|
|
610
|
+
for (const node of this.callerIdsByTraceId.get(traceId)?.values() ?? []) {
|
|
611
|
+
if (node.type === "start") {
|
|
612
|
+
open.push(`"${node.className}#${node.methodKey}"`);
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
const operation = ("operationId" in snapshot && snapshot.operationId) ||
|
|
616
|
+
("name" in snapshot && snapshot.name) ||
|
|
617
|
+
traceId;
|
|
618
|
+
this.logger.warn(`Trace "${traceId}" (${operation}) was not reported: ${open.join(", ") || "a span"} had not ended ${SNAPSHOT_COMPLETION_TIMEOUT_MS}ms after the operation did. Some of your async operations were not awaited and outlived the operation that started them. Ignore if this is the desired behavior.`);
|
|
619
|
+
}
|
|
600
620
|
/**
|
|
601
621
|
* Whether `skipSpans` claims a finished operation. Only request snapshots
|
|
602
622
|
* are asked: a job has no status to be judged by.
|
package/package.json
CHANGED