@nestjs/observe 0.3.25 → 0.3.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/README.md +55 -2
  2. package/dist/agent/detached-observe-worker.js +50 -6
  3. package/dist/agent/observe-agent.shared-buffer.d.ts +44 -0
  4. package/dist/agent/observe-agent.shared-buffer.js +201 -19
  5. package/dist/agent/observe-agent.worker.d.ts +22 -2
  6. package/dist/agent/observe-agent.worker.js +43 -7
  7. package/dist/agent/telemetry-wire-contract.js +10 -4
  8. package/dist/cli/agent-notes.js +16 -4
  9. package/dist/cli/link.js +51 -4
  10. package/dist/cli/observe-cli.js +1 -19
  11. package/dist/cli/open-url.d.ts +27 -0
  12. package/dist/cli/open-url.js +63 -0
  13. package/dist/cli/package-manager.d.ts +6 -0
  14. package/dist/cli/package-manager.js +60 -3
  15. package/dist/cli/project-files.d.ts +62 -1
  16. package/dist/cli/project-files.js +229 -7
  17. package/dist/cli/project-setup.d.ts +6 -0
  18. package/dist/cli/project-setup.js +14 -1
  19. package/dist/cli/wire-application.js +6 -0
  20. package/dist/custom-metrics/counter.d.ts +13 -2
  21. package/dist/custom-metrics/counter.js +33 -16
  22. package/dist/custom-metrics/finite-value.util.d.ts +14 -0
  23. package/dist/custom-metrics/finite-value.util.js +33 -1
  24. package/dist/custom-metrics/gauge.d.ts +2 -0
  25. package/dist/custom-metrics/gauge.js +41 -17
  26. package/dist/custom-metrics/label-values.util.d.ts +37 -0
  27. package/dist/custom-metrics/label-values.util.js +51 -0
  28. package/dist/custom-metrics/summary.d.ts +23 -0
  29. package/dist/custom-metrics/summary.js +90 -12
  30. package/dist/instrument/create-instance-decorator.instrument.js +504 -116
  31. package/dist/instrument/raw-receiver.d.ts +6 -0
  32. package/dist/instrument/raw-receiver.js +32 -0
  33. package/dist/interfaces/observe-options.interface.d.ts +17 -6
  34. package/dist/objectives/objectives.registry.js +12 -0
  35. package/dist/observe.module.js +119 -3
  36. package/dist/otlp/otlp-encoders.js +22 -5
  37. package/dist/otlp/otlp-span.mapper.d.ts +2 -0
  38. package/dist/otlp/otlp-span.mapper.js +26 -4
  39. package/dist/otlp/otlp-trace-exporter.service.d.ts +63 -9
  40. package/dist/otlp/otlp-trace-exporter.service.js +295 -43
  41. package/dist/outgoing/http.integration.d.ts +8 -4
  42. package/dist/outgoing/http.integration.js +49 -17
  43. package/dist/outgoing/llm/llm-fetch.integration.js +62 -1
  44. package/dist/outgoing/llm/llm-providers.d.ts +16 -4
  45. package/dist/outgoing/llm/llm-providers.js +72 -22
  46. package/dist/outgoing/llm/llm-usage.d.ts +11 -6
  47. package/dist/outgoing/llm/llm-usage.js +72 -25
  48. package/dist/outgoing/mongodb.integration.d.ts +3 -1
  49. package/dist/outgoing/mongodb.integration.js +93 -18
  50. package/dist/outgoing/mssql.integration.js +25 -6
  51. package/dist/outgoing/mysql2.integration.js +17 -1
  52. package/dist/outgoing/outgoing-observe-agent.service.js +20 -4
  53. package/dist/outgoing/outgoing-span.recorder.js +17 -3
  54. package/dist/outgoing/pg.integration.d.ts +3 -2
  55. package/dist/outgoing/pg.integration.js +39 -11
  56. package/dist/outgoing/sql-statement.util.js +139 -21
  57. package/dist/outgoing/undici.integration.d.ts +13 -0
  58. package/dist/outgoing/undici.integration.js +68 -0
  59. package/dist/protocols/bull-observe-agent.service.js +23 -12
  60. package/dist/protocols/deferred-trace-completion.d.ts +17 -3
  61. package/dist/protocols/deferred-trace-completion.js +76 -9
  62. package/dist/protocols/graphql-observe-agent.service.d.ts +97 -6
  63. package/dist/protocols/graphql-observe-agent.service.js +354 -19
  64. package/dist/protocols/graphql-operation-parser.js +111 -26
  65. package/dist/protocols/http-observe-agent.service.d.ts +50 -9
  66. package/dist/protocols/http-observe-agent.service.js +220 -59
  67. package/dist/protocols/job-trace-runner.d.ts +42 -3
  68. package/dist/protocols/job-trace-runner.js +197 -36
  69. package/dist/protocols/queue-observe-agent.service.js +44 -20
  70. package/dist/protocols/rpc-observe-agent.service.d.ts +111 -8
  71. package/dist/protocols/rpc-observe-agent.service.js +332 -56
  72. package/dist/protocols/ws-observe-agent.service.d.ts +55 -5
  73. package/dist/protocols/ws-observe-agent.service.js +227 -21
  74. package/dist/services/index.d.ts +1 -1
  75. package/dist/services/index.js +1 -1
  76. package/dist/services/logger-patcher.service.js +16 -7
  77. package/dist/services/operation-trace.registry.d.ts +58 -1
  78. package/dist/services/operation-trace.registry.js +576 -63
  79. package/dist/services/stdout-forwarder.service.d.ts +69 -0
  80. package/dist/services/stdout-forwarder.service.js +308 -51
  81. package/dist/services/tracer.service.d.ts +39 -11
  82. package/dist/services/tracer.service.js +145 -36
  83. package/dist/utils/capture-request.util.d.ts +3 -1
  84. package/dist/utils/capture-request.util.js +128 -12
  85. package/dist/utils/context-accessor.util.d.ts +16 -0
  86. package/dist/utils/context-accessor.util.js +28 -0
  87. package/dist/utils/default-trace-id-generator.util.js +5 -7
  88. package/dist/utils/error-stack.util.d.ts +13 -0
  89. package/dist/utils/error-stack.util.js +166 -0
  90. package/dist/utils/fit-to-length.util.js +33 -10
  91. package/dist/utils/log-line.parser.d.ts +22 -0
  92. package/dist/utils/log-line.parser.js +20 -7
  93. package/dist/utils/log-redactor.d.ts +14 -0
  94. package/dist/utils/log-redactor.js +690 -65
  95. package/dist/utils/operation-state.util.d.ts +39 -0
  96. package/dist/utils/operation-state.util.js +50 -0
  97. package/dist/utils/redact-url-query.d.ts +37 -4
  98. package/dist/utils/redact-url-query.js +197 -32
  99. package/dist/utils/sensitive-keys.d.ts +4 -1
  100. package/dist/utils/sensitive-keys.js +48 -10
  101. package/dist/utils/shared-hook-slot.util.d.ts +48 -0
  102. package/dist/utils/shared-hook-slot.util.js +103 -0
  103. package/dist/utils/source-context.util.d.ts +14 -0
  104. package/dist/utils/source-context.util.js +142 -43
  105. package/dist/utils/source-map-resolver.util.js +33 -6
  106. package/dist/utils/store-copy.util.d.ts +10 -0
  107. package/dist/utils/store-copy.util.js +43 -0
  108. package/dist/utils/trace-context.util.js +21 -6
  109. package/package.json +2 -2
@@ -48,9 +48,9 @@ const TRACE_NODE = {
48
48
  t: { type: "object" },
49
49
  d: { type: "number" },
50
50
  // Boolean is the "an error occurred but was handled, details not captured"
51
- // form - every failed non-root span, and a root span failing on a thrown
52
- // primitive, reports `e: true` rather than an error object. See
53
- // `TraceSpan.error`.
51
+ // form - every failed non-root span, a root span failing on a thrown
52
+ // primitive, and a failed root span past the trace's 20 recorded errors,
53
+ // reports `e: true` rather than an error object. See `TraceSpan.error`.
54
54
  e: { type: "object", alsoAccepts: ["boolean"] },
55
55
  c: { type: "string", required: true, maxLength: 255 },
56
56
  m: { type: "string", required: true, maxLength: 255 },
@@ -462,7 +462,13 @@ export function createTelemetrySanitizer(shapes) {
462
462
  }
463
463
  else if (key in value) {
464
464
  // Explicit nulls fail the API's type checks even on optional
465
- // fields; absent keys do not.
465
+ // fields; absent keys do not. Reported like every other removal:
466
+ // a repair that is not is a batch dropped rather than re-sent -
467
+ // and a non-finite number reaches here as the `null` that
468
+ // `JSON.stringify` made of it. `undefined` never reached the wire.
469
+ if (value[key] === null) {
470
+ problems.push(`${fieldPath}: null, removed`);
471
+ }
466
472
  delete value[key];
467
473
  }
468
474
  continue;
@@ -1,5 +1,9 @@
1
1
  import { existsSync, readFileSync, writeFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
+ import { isProjectFile } from "./project-files.js";
4
+ /** What would take a path out of its backticks in the notes. */
5
+ // eslint-disable-next-line no-control-regex -- control characters are what it finds.
6
+ const UNQUOTABLE = /[`\u0000-\u001f\u007f\u0085\u2028\u2029]/;
3
7
  /** The file coding agents read for a repository's working notes. */
4
8
  export const AGENTS_FILE = "AGENTS.md";
5
9
  /**
@@ -52,14 +56,18 @@ export function pendingAgentNotes(cwd) {
52
56
  return existsSync(path) ? readFileSync(path, "utf8") : undefined;
53
57
  };
54
58
  const changes = [];
55
- const agents = read(AGENTS_FILE);
59
+ // A file that leads out of the project - a link to anywhere the person
60
+ // can write - is not the project's notes, and is left alone.
61
+ const agents = isProjectFile(cwd, AGENTS_FILE) ? read(AGENTS_FILE) : null;
56
62
  if (agents === undefined) {
57
63
  changes.push({ file: AGENTS_FILE, created: true });
58
64
  }
59
- else if (!agents.includes(AGENT_NOTES_HEADING)) {
65
+ else if (agents !== null && !agents.includes(AGENT_NOTES_HEADING)) {
60
66
  changes.push({ file: AGENTS_FILE, created: false });
61
67
  }
62
- const claude = read(CLAUDE_FILE);
68
+ const claude = isProjectFile(cwd, CLAUDE_FILE)
69
+ ? read(CLAUDE_FILE)
70
+ : undefined;
63
71
  if (claude !== undefined &&
64
72
  !claude.includes(AGENT_NOTES_HEADING) &&
65
73
  !claude.includes(`@${AGENTS_FILE}`)) {
@@ -74,7 +82,11 @@ export function pendingAgentNotes(cwd) {
74
82
  */
75
83
  export function writeAgentNotes(cwd, rootModule) {
76
84
  const changes = pendingAgentNotes(cwd);
77
- const notes = agentNotes(rootModule ? `\`${rootModule}\`` : undefined);
85
+ // Quoted only when the path cannot leave its quotes: a directory name is
86
+ // the project's to choose, and a backtick or a line break in it would
87
+ // put text of its own into the notes.
88
+ const quotable = rootModule !== undefined && !UNQUOTABLE.test(rootModule);
89
+ const notes = agentNotes(quotable ? `\`${rootModule}\`` : undefined);
78
90
  for (const change of changes) {
79
91
  const path = join(cwd, change.file);
80
92
  if (change.created) {
package/dist/cli/link.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { writeAgentNotes } from "./agent-notes.js";
2
+ import { webAddress } from "./open-url.js";
2
3
  import { addDependencyCommand, detectPackageManager, } from "./package-manager.js";
3
- import { addEnvFileToStartScripts, ensureEnvIgnored, readPackageName, writeEnvFile, } from "./project-files.js";
4
+ import { addEnvFileToStartScripts, ensureEnvIgnored, envFileIgnored, gitignoreProblem, isEnvFileValue, isProjectFile, LINK_FILES, readPackageName, trackedEnvFile, writeEnvFile, } from "./project-files.js";
4
5
  import { findEntryFiles, inspectProject, QUICK_START_URL, SDK_PACKAGE, serviceIdFor, } from "./project-setup.js";
5
6
  import { wireApplication } from "./wire-application.js";
6
7
  /** Extra seconds `slow_down` adds to the interval, as RFC 8628 says. */
@@ -30,6 +31,23 @@ export async function link(options, deps) {
30
31
  deps.log(`${setup.unsupported}. Nothing was written.`);
31
32
  return 1;
32
33
  }
34
+ // Before a code is asked for: no pair is issued for a project whose own
35
+ // files lead somewhere else, nor for one it cannot be kept out of git in.
36
+ const outside = LINK_FILES.find((file) => !isProjectFile(options.cwd, file));
37
+ if (outside) {
38
+ deps.log(`${outside} leads out of ${options.cwd} - a link, or one that leads nowhere - so link will not write to it. Nothing was written.`);
39
+ return 1;
40
+ }
41
+ const tracked = trackedEnvFile(options.cwd);
42
+ if (tracked) {
43
+ deps.log(`${tracked} is tracked by git, so the secret link writes into it would be in your next commit, whatever .gitignore says. Run git rm --cached ${tracked}, which keeps the file, and link again. Nothing was written.`);
44
+ return 1;
45
+ }
46
+ const gitignore = gitignoreProblem(options.cwd);
47
+ if (gitignore) {
48
+ deps.log(`${gitignore} Nothing was written.`);
49
+ return 1;
50
+ }
33
51
  const manager = detectPackageManager(options.cwd);
34
52
  let started;
35
53
  try {
@@ -42,8 +60,15 @@ export async function link(options, deps) {
42
60
  deps.log(`Could not reach NestJS Observe at ${options.endpoint}: ${describe(err)}`);
43
61
  return 1;
44
62
  }
63
+ // Printed and opened as parsed, and only as a web address: the page is
64
+ // whatever the service answered, and it is opened before any approval.
65
+ const page = webAddress(started.verificationUri);
66
+ if (!page) {
67
+ deps.log(`NestJS Observe at ${options.endpoint} answered with a link page that is not a web address. Nothing was written.`);
68
+ return 1;
69
+ }
45
70
  deps.log("");
46
- deps.log(` Open ${started.verificationUri}`);
71
+ deps.log(` Open ${page}`);
47
72
  deps.log(` and type ${started.userCode}`);
48
73
  deps.log("");
49
74
  deps.log(`Waiting for you to approve it in the dashboard. The code expires in ${Math.round(started.expiresIn / 60)} minutes.`);
@@ -54,15 +79,32 @@ export async function link(options, deps) {
54
79
  if (options.openBrowser) {
55
80
  // The page only, never the code: the code is typed, so a link that
56
81
  // carries it cannot approve anything on its own.
57
- deps.openUrl(started.verificationUri);
82
+ deps.openUrl(page);
58
83
  }
59
84
  const credentials = await waitForApproval(deps, options.endpoint, started);
60
85
  if (typeof credentials === "string") {
61
86
  deps.log(credentials);
62
87
  return 1;
63
88
  }
89
+ // `.env` is kept out of git before the secret is in it: written first, a
90
+ // .gitignore that then could not be updated left the secret in a file
91
+ // the next `git add .` takes.
92
+ let ignoredNow;
93
+ try {
94
+ ignoredNow = ensureEnvIgnored(options.cwd);
95
+ }
96
+ catch (err) {
97
+ deps.log(`Could not add .env to .gitignore (${describe(err)}), so the key pair was not written: it would not stay out of git. Fix .gitignore and link again.`);
98
+ return 1;
99
+ }
100
+ // Git has the last word on what it ignores: a rule elsewhere can take
101
+ // .env back, and a .env that links to another file is not what keeps
102
+ // that file out. Without a repository or git there is no one to ask.
103
+ if (envFileIgnored(options.cwd) === false) {
104
+ deps.log(`git does not ignore .env, or the file it leads to,${ignoredNow ? " even with the rule link added to .gitignore," : ""} so the key pair was not written: it would be in your next commit. git check-ignore -v .env shows the rule git goes by; link again once git ignores it.`);
105
+ return 1;
106
+ }
64
107
  writeEnvFile(options.cwd, credentials.appKey, credentials.appSecret);
65
- const ignoredNow = ensureEnvIgnored(options.cwd);
66
108
  const scripts = addEnvFileToStartScripts(options.cwd);
67
109
  deps.log("");
68
110
  deps.log(`✔ Linked to ${credentials.applicationName} in ${credentials.projectName}. The key pair is in .env.`);
@@ -188,6 +230,11 @@ async function waitForApproval(deps, endpoint, started) {
188
230
  }
189
231
  const body = (await response.json().catch(() => ({})));
190
232
  if (response.ok && body.appKey && body.appSecret) {
233
+ // Checked before anything is written: the pair goes into .env, which
234
+ // every start of the app loads.
235
+ if (!isEnvFileValue(body.appKey) || !isEnvFileValue(body.appSecret)) {
236
+ return `${endpoint} answered with something other than a key pair. Nothing was written.`;
237
+ }
191
238
  return body;
192
239
  }
193
240
  switch (body.error) {
@@ -4,6 +4,7 @@ import { createRequire } from "node:module";
4
4
  import { hostname } from "node:os";
5
5
  import { resolve } from "node:path";
6
6
  import { link } from "./link.js";
7
+ import { openUrl } from "./open-url.js";
7
8
  import { loadTypeScript } from "./project-setup.js";
8
9
  const { version } = createRequire(import.meta.url)("../../package.json");
9
10
  const HOSTED_COLLECTOR_ENDPOINT = "https://observe-api.nestjs.com";
@@ -16,25 +17,6 @@ const USAGE = `Usage: npx @nestjs/observe link [--no-browser] [--cwd <dir>]
16
17
  Options:
17
18
  --no-browser Print the link page instead of opening it.
18
19
  --cwd <dir> The project directory (default: the current one).`;
19
- /**
20
- * Opens the link page in the default browser, best effort: a headless box or
21
- * a missing opener just means the person opens the printed URL themselves.
22
- */
23
- function openUrl(url) {
24
- const [command, args] = process.platform === "darwin"
25
- ? ["open", [url]]
26
- : process.platform === "win32"
27
- ? ["cmd", ["/c", "start", "", url]]
28
- : ["xdg-open", [url]];
29
- try {
30
- const child = spawn(command, args, { stdio: "ignore", detached: true });
31
- child.on("error", () => undefined);
32
- child.unref();
33
- }
34
- catch {
35
- // Printed above; nothing else to do.
36
- }
37
- }
38
20
  async function main(argv) {
39
21
  const [command, ...rest] = argv;
40
22
  if (command !== "link") {
@@ -0,0 +1,27 @@
1
+ /**
2
+ * `value` as an http(s) URL, parsed and written back out - or undefined for
3
+ * anything else.
4
+ *
5
+ * The link page comes from whoever answers the link request, and is handed
6
+ * to the desktop's opener before anything has been approved: a local file, a
7
+ * script, or another scheme's handler is not that party's to open on the
8
+ * person's machine. Written back out, whitespace and control characters are
9
+ * percent-encoded, so what is printed and opened is one plain address.
10
+ */
11
+ export declare function webAddress(value: unknown): string | undefined;
12
+ /**
13
+ * The command that opens `url` in the default browser on `platform` - never
14
+ * through a shell.
15
+ *
16
+ * On Windows not `cmd /c start`: cmd.exe reads `&`, `|`, `^` and `%` in the
17
+ * URL as its own syntax, and a valid https URL can hold every one of them.
18
+ * `rundll32 url.dll,FileProtocolHandler` hands it to the same handler `start`
19
+ * does, as one plain argument.
20
+ */
21
+ export declare function browserCommand(url: string, platform: NodeJS.Platform): [string, string[]];
22
+ /**
23
+ * Opens the link page in the default browser, best effort: a headless box or
24
+ * a missing opener just means the person opens the printed URL themselves.
25
+ * Only a web address is opened.
26
+ */
27
+ export declare function openUrl(url: string): void;
@@ -0,0 +1,63 @@
1
+ import { spawn } from "node:child_process";
2
+ /**
3
+ * `value` as an http(s) URL, parsed and written back out - or undefined for
4
+ * anything else.
5
+ *
6
+ * The link page comes from whoever answers the link request, and is handed
7
+ * to the desktop's opener before anything has been approved: a local file, a
8
+ * script, or another scheme's handler is not that party's to open on the
9
+ * person's machine. Written back out, whitespace and control characters are
10
+ * percent-encoded, so what is printed and opened is one plain address.
11
+ */
12
+ export function webAddress(value) {
13
+ if (typeof value !== "string") {
14
+ return undefined;
15
+ }
16
+ try {
17
+ const url = new URL(value);
18
+ return url.protocol === "https:" || url.protocol === "http:"
19
+ ? url.href
20
+ : undefined;
21
+ }
22
+ catch {
23
+ return undefined;
24
+ }
25
+ }
26
+ /**
27
+ * The command that opens `url` in the default browser on `platform` - never
28
+ * through a shell.
29
+ *
30
+ * On Windows not `cmd /c start`: cmd.exe reads `&`, `|`, `^` and `%` in the
31
+ * URL as its own syntax, and a valid https URL can hold every one of them.
32
+ * `rundll32 url.dll,FileProtocolHandler` hands it to the same handler `start`
33
+ * does, as one plain argument.
34
+ */
35
+ export function browserCommand(url, platform) {
36
+ if (platform === "darwin") {
37
+ return ["open", [url]];
38
+ }
39
+ if (platform === "win32") {
40
+ return ["rundll32", ["url.dll,FileProtocolHandler", url]];
41
+ }
42
+ return ["xdg-open", [url]];
43
+ }
44
+ /**
45
+ * Opens the link page in the default browser, best effort: a headless box or
46
+ * a missing opener just means the person opens the printed URL themselves.
47
+ * Only a web address is opened.
48
+ */
49
+ export function openUrl(url) {
50
+ const address = webAddress(url);
51
+ if (!address) {
52
+ return;
53
+ }
54
+ const [command, args] = browserCommand(address, process.platform);
55
+ try {
56
+ const child = spawn(command, args, { stdio: "ignore", detached: true });
57
+ child.on("error", () => undefined);
58
+ child.unref();
59
+ }
60
+ catch {
61
+ // Printed already; nothing else to do.
62
+ }
63
+ }
@@ -7,6 +7,12 @@ export type PackageManager = "npm" | "pnpm" | "yarn" | "bun";
7
7
  * one, Corepack's `packageManager` field in package.json does, and npm is
8
8
  * the answer when neither says anything. Running `npx` says nothing either
9
9
  * way: it is how the command was started, not how the project installs.
10
+ *
11
+ * A project in no repository has no root to stop at, and a lockfile above
12
+ * it - a forgotten one in the home directory, say - belongs to something
13
+ * else: it made link install with a manager the project does not use, and
14
+ * outranked the project's own `packageManager` field. There, only `cwd` and
15
+ * the workspace it is a package of, if any, are looked in.
10
16
  */
11
17
  export declare function detectPackageManager(cwd: string): PackageManager;
12
18
  /** The command that adds `spec` to the project's dependencies. */
@@ -18,21 +18,78 @@ const MANAGERS = new Set(["npm", "pnpm", "yarn", "bun"]);
18
18
  * one, Corepack's `packageManager` field in package.json does, and npm is
19
19
  * the answer when neither says anything. Running `npx` says nothing either
20
20
  * way: it is how the command was started, not how the project installs.
21
+ *
22
+ * A project in no repository has no root to stop at, and a lockfile above
23
+ * it - a forgotten one in the home directory, say - belongs to something
24
+ * else: it made link install with a manager the project does not use, and
25
+ * outranked the project's own `packageManager` field. There, only `cwd` and
26
+ * the workspace it is a package of, if any, are looked in.
21
27
  */
22
28
  export function detectPackageManager(cwd) {
29
+ const root = repositoryRoot(cwd);
30
+ if (root === undefined) {
31
+ const workspace = workspaceRoot(cwd);
32
+ return (lockfileIn(cwd) ??
33
+ (workspace === undefined ? undefined : lockfileIn(workspace)) ??
34
+ declaredPackageManager(cwd) ??
35
+ (workspace === undefined
36
+ ? undefined
37
+ : declaredPackageManager(workspace)) ??
38
+ "npm");
39
+ }
23
40
  for (let dir = cwd;; dir = dirname(dir)) {
24
- const found = LOCKFILES.find(([file]) => existsSync(join(dir, file)));
41
+ const found = lockfileIn(dir);
25
42
  if (found) {
26
- return found[1];
43
+ return found;
27
44
  }
28
45
  // The repository's root is as far as the project goes: a lockfile
29
46
  // above it belongs to something else.
30
- if (existsSync(join(dir, ".git")) || dirname(dir) === dir) {
47
+ if (dir === root) {
31
48
  break;
32
49
  }
33
50
  }
34
51
  return declaredPackageManager(cwd) ?? "npm";
35
52
  }
53
+ function lockfileIn(dir) {
54
+ return LOCKFILES.find(([file]) => existsSync(join(dir, file)))?.[1];
55
+ }
56
+ /** The nearest directory from `cwd` up that holds a `.git`. */
57
+ function repositoryRoot(cwd) {
58
+ for (let dir = cwd;; dir = dirname(dir)) {
59
+ if (existsSync(join(dir, ".git"))) {
60
+ return dir;
61
+ }
62
+ if (dirname(dir) === dir) {
63
+ return undefined;
64
+ }
65
+ }
66
+ }
67
+ /**
68
+ * The nearest directory above `cwd` that is a workspace's root - one with a
69
+ * `pnpm-workspace.yaml`, or a package.json that lists `workspaces` - where
70
+ * the lockfile of a package inside it is.
71
+ */
72
+ function workspaceRoot(cwd) {
73
+ for (let dir = dirname(cwd);; dir = dirname(dir)) {
74
+ if (existsSync(join(dir, "pnpm-workspace.yaml")) || listsWorkspaces(dir)) {
75
+ return dir;
76
+ }
77
+ if (dirname(dir) === dir) {
78
+ return undefined;
79
+ }
80
+ }
81
+ }
82
+ /** Whether `<dir>/package.json` lists `workspaces`, as npm, Yarn and Bun read them. */
83
+ function listsWorkspaces(dir) {
84
+ try {
85
+ const { workspaces } = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
86
+ return (Array.isArray(workspaces) ||
87
+ Array.isArray(workspaces?.packages));
88
+ }
89
+ catch {
90
+ return false;
91
+ }
92
+ }
36
93
  /** `"pnpm@9.12.0"` in package.json's `packageManager` field, as `"pnpm"`. */
37
94
  function declaredPackageManager(cwd) {
38
95
  try {
@@ -1,6 +1,32 @@
1
+ /** The files `link` writes in every project, whatever else it does. */
2
+ export declare const LINK_FILES: string[];
3
+ /**
4
+ * Whether `path`, relative to `cwd`, is a file of the project's own once
5
+ * links are followed - where `link` may write.
6
+ *
7
+ * A checkout's files can be links to anywhere the person can write, and a
8
+ * project's own paths can climb out with `../`: written through, the key
9
+ * pair, the notes or the wiring would land in someone else's file, reported
10
+ * under an in-project name. A file still to be created is the project's when
11
+ * its directory is; a link that leads nowhere is not, because writing to it
12
+ * would create the file it points at.
13
+ */
14
+ export declare function isProjectFile(cwd: string, path: string): boolean;
1
15
  /** The variables `ObserveModule` falls back to for its key pair. */
2
16
  export declare const KEY_VARIABLE = "OBSERVE_APP_KEY";
3
17
  export declare const SECRET_VARIABLE = "OBSERVE_APP_SECRET";
18
+ /**
19
+ * Whether `value` can be written into `.env` as `writeEnvFile` writes it.
20
+ *
21
+ * The pair comes from the link service's reply, and `.env` is loaded into
22
+ * the app on every start: a quote and a line break would end the value and
23
+ * add a line of the reply's choosing - `NODE_OPTIONS=--import ...`, or a
24
+ * `DATABASE_URL` that wins over the project's own. Refused rather than
25
+ * escaped: no escape for a quote or a line break reads the same in Node's
26
+ * `--env-file`, `dotenv` and a shell, and `dotenv` reads `\'` as an escaped
27
+ * quote where Node ends the value.
28
+ */
29
+ export declare function isEnvFileValue(value: unknown): value is string;
4
30
  /**
5
31
  * Writes the key pair into `<cwd>/.env`, replacing an earlier pair and keeping
6
32
  * every other line as it was. Created owner-only when it does not exist.
@@ -10,9 +36,44 @@ export declare const SECRET_VARIABLE = "OBSERVE_APP_SECRET";
10
36
  * variables (`dotenv-expand`, `ConfigModule` with `expandVariables`) rewrites
11
37
  * everything after a `$`, and a shell sourcing the file stops at the `&`.
12
38
  * Node's own `--env-file` reads either form literally. Single quotes are
13
- * literal in all of them, and the alphabet has no quote in it to escape.
39
+ * literal in all of them, and a value with a quote - or anything else
40
+ * `isEnvFileValue` refuses - is not written at all.
14
41
  */
15
42
  export declare function writeEnvFile(cwd: string, appKey: string, appSecret: string): string;
43
+ /**
44
+ * `.env` as a path relative to `cwd` when git already tracks the file it is -
45
+ * itself, or what it links to - or undefined: not tracked, not in a
46
+ * repository, or no git to ask.
47
+ *
48
+ * An ignore rule does not apply to a file in the index, so the secret written
49
+ * into a tracked `.env` would be in the next `git commit -a` whatever
50
+ * `.gitignore` says. Git is asked as `askGit` asks it, with nothing of the
51
+ * project's that could run a program.
52
+ */
53
+ export declare function trackedEnvFile(cwd: string): string | undefined;
54
+ /**
55
+ * Whether git ignores the file the key pair is written into - `.env`, or
56
+ * what it links to: true or false as git answers, undefined when there is
57
+ * no repository or no git to ask.
58
+ *
59
+ * Asked of git itself, after `ensureEnvIgnored`, rather than read off
60
+ * `.gitignore`: git decides with every ignore file there is, and a rule
61
+ * `ensureEnvIgnored` saw does not ignore a file `.env` links to under
62
+ * another name. Asked the way `trackedEnvFile` asks.
63
+ */
64
+ export declare function envFileIgnored(cwd: string): boolean | undefined;
65
+ /**
66
+ * Why `ensureEnvIgnored` could not add `.env` to `<cwd>/.gitignore`, or
67
+ * undefined when it can: the file is there, a regular file that can be read
68
+ * and written, or it is not and the directory can take it. Asked before a
69
+ * code is, so no pair is issued for a project it could not be kept out of
70
+ * git in.
71
+ *
72
+ * A link is refused even when it stays in the project: git reads no
73
+ * `.gitignore` that is a symbolic link (2.32 and later), so a rule written
74
+ * through it would keep nothing out of git, however it read.
75
+ */
76
+ export declare function gitignoreProblem(cwd: string): string | undefined;
16
77
  /**
17
78
  * Makes sure `.env` is git-ignored, so the secret cannot be committed by
18
79
  * accident. `nest new` already ignores it; a project from elsewhere may not.