@nestjs/observe 0.3.14 → 0.3.16

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.
@@ -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
- * Sign up at https://observe.nestjs.com and create a service; the dashboard
153
- * issues the key and secret together.
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 is sent to the hosted collector at all - a warning at startup
160
- * says so - while a collector of your own still receives the batches.
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: string;
165
+ appKey?: string;
163
166
  /**
164
- * Secret paired with `appKey`, issued with it at https://observe.nestjs.com.
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: string;
176
+ appSecret?: string;
172
177
  /**
173
178
  * Base URL of the collector, without a trailing path.
174
179
  *
@@ -64,6 +64,34 @@ function withServiceId(options) {
64
64
  new Logger("ObserveModule").warn(`serviceId "${named}" is sent as "${sent}": the collector takes at most ${MAX_SERVICE_ID_LENGTH} characters.`);
65
65
  return { ...options, serviceId: sent };
66
66
  }
67
+ /** The credentials `nest new` writes before an account exists. */
68
+ const SCAFFOLD_CREDENTIALS = {
69
+ appKey: "YOUR_APP_KEY",
70
+ appSecret: "YOUR_APP_SECRET",
71
+ };
72
+ /**
73
+ * `appKey` and `appSecret` from `OBSERVE_APP_KEY` and `OBSERVE_APP_SECRET`
74
+ * when the options leave them out - or still hold the `nest new`
75
+ * placeholders, which is what a project linked with
76
+ * `npx @nestjs/observe link` keeps in its AppModule while the real pair sits
77
+ * in its `.env`. A value the application passes explicitly always wins.
78
+ *
79
+ * Read when the options resolve, which for `forRoot()` is when AppModule is
80
+ * imported: early enough for `node --env-file` and `nest start --env-file`,
81
+ * which load the file before any module runs.
82
+ */
83
+ function credentialFromEnv(value, placeholder, variable) {
84
+ return (!value || value === placeholder) && process.env[variable]
85
+ ? process.env[variable]
86
+ : value;
87
+ }
88
+ function withCredentialsFromEnv(options) {
89
+ return {
90
+ ...options,
91
+ appKey: credentialFromEnv(options.appKey, SCAFFOLD_CREDENTIALS.appKey, "OBSERVE_APP_KEY"),
92
+ appSecret: credentialFromEnv(options.appSecret, SCAFFOLD_CREDENTIALS.appSecret, "OBSERVE_APP_SECRET"),
93
+ };
94
+ }
67
95
  /**
68
96
  * Names the release when the application did not, so Releases, regressions
69
97
  * and fix verification work without anyone threading a version through the
@@ -116,10 +144,10 @@ export function createObserveModule(options = {}) {
116
144
  providers: [
117
145
  {
118
146
  provide: OBSERVE_OPTIONS,
119
- useValue: withServiceVersion(withServiceId({
147
+ useValue: withServiceVersion(withServiceId(withCredentialsFromEnv({
120
148
  ...options,
121
149
  ...observeOpts,
122
- })),
150
+ }))),
123
151
  },
124
152
  ],
125
153
  };
@@ -158,10 +186,10 @@ export function createObserveModule(options = {}) {
158
186
  provide: OBSERVE_OPTIONS,
159
187
  useFactory: async (...args) => {
160
188
  const opts = await useFactory(...args);
161
- return withServiceVersion(withServiceId({
189
+ return withServiceVersion(withServiceId(withCredentialsFromEnv({
162
190
  ...options,
163
191
  ...opts,
164
- }));
192
+ })));
165
193
  },
166
194
  inject: asyncOptions.inject || [],
167
195
  };
@@ -172,10 +200,10 @@ export function createObserveModule(options = {}) {
172
200
  }
173
201
  return {
174
202
  provide: OBSERVE_OPTIONS,
175
- useFactory: async (optionsFactory) => withServiceVersion(withServiceId({
203
+ useFactory: async (optionsFactory) => withServiceVersion(withServiceId(withCredentialsFromEnv({
176
204
  ...options,
177
205
  ...(await optionsFactory.createObserveOptions()),
178
- })),
206
+ }))),
179
207
  inject: [optionsFactoryToken],
180
208
  };
181
209
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nestjs/observe",
3
- "version": "0.3.14",
3
+ "version": "0.3.16",
4
4
  "description": "Observability and APM agent for NestJS - traces, runtime metrics and custom metrics",
5
5
  "author": "Kamil Mysliwiec",
6
6
  "homepage": "https://observe.nestjs.com",
@@ -30,6 +30,9 @@
30
30
  ],
31
31
  "main": "./dist/index.js",
32
32
  "types": "./dist/index.d.ts",
33
+ "bin": {
34
+ "observe": "./dist/cli/observe-cli.js"
35
+ },
33
36
  "exports": {
34
37
  ".": {
35
38
  "types": "./dist/index.d.ts",