spanport 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,169 @@
1
- # Temporary Holding Version
1
+ # spanport (Node.js SDK)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Send your Node.js app's logs to Spanport. Keep logging the way you already do.
4
+
5
+ ```bash
6
+ npm install spanport
7
+ ```
8
+
9
+ ```js
10
+ import * as spanport from "spanport";
11
+
12
+ spanport.init({
13
+ // From Setup → API keys → Data keys in Spanport (shown once)
14
+ dataKey: "sp_ingest_...",
15
+ service: "orders-api",
16
+ // Defaults: http://localhost:4318 and http://localhost:8000
17
+ collectorUrl: "https://spanport-collector.example.com",
18
+ serverUrl: "https://spanport.example.com",
19
+ });
20
+
21
+ console.error("Payment failed for order 1042"); // sent automatically
22
+ ```
23
+
24
+ **pino and winston** write JSON lines to `spanport.logStream()`:
25
+
26
+ ```js
27
+ import pino from "pino";
28
+ const logger = pino(pino.multistream([{ stream: process.stdout }, { stream: spanport.logStream() }]));
29
+
30
+ import winston from "winston";
31
+ const logger = winston.createLogger({
32
+ format: winston.format.combine(winston.format.timestamp(), winston.format.json()),
33
+ transports: [
34
+ new winston.transports.Console(),
35
+ new winston.transports.Stream({ stream: spanport.logStream() }),
36
+ ],
37
+ });
38
+ ```
39
+
40
+ - **`console.debug/log/info/warn/error` are sent automatically**; what your app prints doesn't change. Turn this off with `captureConsole: false`.
41
+ - **Logs are sent in the background**, in batches. A normal exit sends what is left; on `SIGTERM`, send it yourself: `process.on("SIGTERM", async () => { await spanport.shutdown(); process.exit(0); })`.
42
+ - **Logs inside an OpenTelemetry span** carry its `trace_id` and `span_id`; so do pino lines that include them.
43
+ - **Wrong key?** At start-up the SDK asks the server once whether the key is valid and prints a clear error on stderr if not. Pass `checkKey: false` if the app cannot reach the server.
44
+ - **Use `https://` for anything beyond your own machine or Docker network.** The data key is sent with every batch.
45
+ - **It never breaks your app.** `init()` never throws; setup and key problems are printed on stderr as `spanport: ...` and the app carries on. An unreachable collector is not reported yet (see [Troubleshooting](#nothing-arrives-and-there-is-no-error)).
46
+
47
+ Node.js 22.15 or newer. ES module; CommonJS apps can `require("spanport")`.
48
+
49
+ At start-up the SDK prints, on stderr:
50
+
51
+ ```
52
+ INFO spanport: sending logs for service orders-api to http://localhost:4318
53
+ INFO spanport: data key ...a1b2 accepted
54
+ ```
55
+
56
+ If the second line is missing or says something else, see [Troubleshooting](#troubleshooting).
57
+
58
+ ## What Spanport receives
59
+
60
+ | You write | Message | Level | Fields you can filter on |
61
+ | --- | --- | --- | --- |
62
+ | `console.log("Paid", { orderId: 7 })` | `Paid { orderId: 7 }` (as the terminal shows it) | `debug` DEBUG, `log`/`info` INFO, `warn` WARN, `error` ERROR | none: objects become part of the text |
63
+ | pino `logger.info({ "user.id": "u42" }, "Paid")` | `Paid` | pino's level (`fatal` is FATAL, `trace` is TRACE) | every other key, e.g. `user.id` |
64
+ | winston `logger.info("Paid", { "user.id": "u42" })` | `Paid` | winston's level (`http` is INFO, `verbose` is DEBUG) | every other key |
65
+
66
+ - **Use flat, dotted names for fields**: `{ "user.id": "u42" }`, not `{ user: { id: "u42" } }`. A nested object arrives as one field (`user`) holding JSON text, so the User ID filter can't see it.
67
+ - Spanport's **Client IP** and **User ID** filters read the fields `client.ip` and `user.id`. Every line also has `log.source` (`console` or `stream`) and the `service` you passed to `init()`.
68
+ - Errors: `console.error(err)` and pino's `logger.error(err)` both keep the stack trace in the message.
69
+
70
+ ## Finding logs in Spanport
71
+
72
+ Pick the project and time range first; a search only looks inside that range.
73
+
74
+ - **Message contains** finds any part of the text, ignoring case. `nitish` finds `GET /api/files 200 12ms user=nitish@acme.com`; `nitishbharadwaj` doesn't, because those letters never appear together in that line.
75
+ - **User ID is u42** and **Client IP is ...** work only for lines that carry the `user.id` / `client.ip` fields (pino or winston, see above). A user written inside the message text is found with Message contains instead.
76
+ - **Any other field** you send: choose "Type a query instead" and write `field:value`, e.g. `order.id:1042` or `tenant:acme*` (`*` is a wildcard). In a query, a plain word matches a whole word: `timeout` finds "request timeout" but not "timeouts"; use `timeout*` for that.
77
+ - Expand a line to see all its fields, with Filter and Exclude next to each.
78
+
79
+ ## Troubleshooting
80
+
81
+ ### Nothing arrives and there is no error
82
+
83
+ The SDK checks the data key, not the collector. If `collectorUrl` is wrong or the collector is down, batches are dropped **without a message**. Check that the collector answers from where the app runs:
84
+
85
+ ```bash
86
+ curl -i -X POST http://localhost:4318/v1/logs -H "Content-Type: application/json" -d "{}"
87
+ ```
88
+
89
+ Any HTTP answer (e.g. `200`) means it is reachable; "connection refused" means it isn't. An app running in Docker can't reach the host's `localhost`: use `http://host.docker.internal:4318`, or `http://collector:4318` on the Spanport Compose network. Also check the Logs page shows the right project and a time range that includes now.
90
+
91
+ ### Searching for a name or id finds nothing
92
+
93
+ Search finds only text that is in the line. Expand a line you expect to match and look at its message and fields: if the user appears as `user=nitish@acme.com` inside the message, search **Message contains** `nitish@acme.com`; to use the **User ID** filter, send `user.id` as a field (see [What Spanport receives](#what-spanport-receives)).
94
+
95
+ ### NestJS errors show in the terminal but not in Spanport
96
+
97
+ Nest's built-in logger writes straight to `process.stdout`/`process.stderr`, not through `console`, so the SDK never sees its lines. That includes `ERROR [ExceptionsHandler] ...` for every unhandled exception. Route Nest's logger through `console` and they arrive with the right level (and stack trace), while the terminal output stays the same:
98
+
99
+ ```ts
100
+ // src/common/logger/console-routed.logger.ts
101
+ import { LoggerService } from "@nestjs/common";
102
+
103
+ function asText(value: unknown): string {
104
+ if (value instanceof Error) return value.stack ?? value.message;
105
+ return typeof value === "string" ? value : JSON.stringify(value);
106
+ }
107
+
108
+ // Nest passes the context last; a value with line breaks is a stack trace, not a context.
109
+ function formatLine(message: unknown, optionalParams: unknown[]): string {
110
+ const lastParam = optionalParams.at(-1);
111
+ const context = typeof lastParam === "string" && !lastParam.includes("\n") ? lastParam : undefined;
112
+ const extraValues = context === undefined ? optionalParams : optionalParams.slice(0, -1);
113
+ const firstLine = context ? `[${context}] ${asText(message)}` : asText(message);
114
+ return [firstLine, ...extraValues.map(asText)].join("\n");
115
+ }
116
+
117
+ export class ConsoleRoutedLogger implements LoggerService {
118
+ log(message: unknown, ...params: unknown[]) { console.log(formatLine(message, params)); }
119
+ warn(message: unknown, ...params: unknown[]) { console.warn(formatLine(message, params)); }
120
+ error(message: unknown, ...params: unknown[]) { console.error(formatLine(message, params)); }
121
+ fatal(message: unknown, ...params: unknown[]) { console.error(formatLine(message, params)); }
122
+ debug(message: unknown, ...params: unknown[]) { console.debug(formatLine(message, params)); }
123
+ verbose(message: unknown, ...params: unknown[]) { console.debug(formatLine(message, params)); }
124
+ }
125
+ ```
126
+
127
+ ```ts
128
+ // main.ts
129
+ const app = await NestFactory.create(AppModule, { logger: new ConsoleRoutedLogger() });
130
+ ```
131
+
132
+ The same applies to any library that writes to `process.stdout` directly: give it a logger that uses `console`, pino or winston.
133
+
134
+ ### Failed requests show as INFO
135
+
136
+ Every `console.log` line is INFO, whatever its text says. A request logger should pick the method by status, so the ERROR and WARN cards on the Logs page count failed calls:
137
+
138
+ ```ts
139
+ const writeLine = status >= 500 ? console.error : status >= 400 ? console.warn : console.log;
140
+ writeLine(`${method} ${url} ${status} ${durationMs}ms`);
141
+ ```
142
+
143
+ ### "data key ...xxxx was rejected"
144
+
145
+ The server doesn't know the key: it was mistyped, revoked, deleted, belongs to an archived project, or is an admin key (`sp_admin_...`) instead of a data key (`sp_ingest_...`). Check it with:
146
+
147
+ ```bash
148
+ curl -i http://localhost:8000/api/v1/api-keys/current -H "Authorization: Bearer sp_ingest_..."
149
+ ```
150
+
151
+ `200` means the key is fine; `401` means create a new data key on the API keys page (it is shown once) and restart the app with it.
152
+
153
+ ### Client IP and user are empty
154
+
155
+ The SDK sends only what a log line carries. Add them as fields named `client.ip` and `user.id`, e.g. with pino: `logger.error({ "client.ip": req.ip, "user.id": userId }, "Payment failed")`. Behind a proxy, read the client address from `X-Forwarded-For` (`app.set("trust proxy", true)` in Express).
156
+
157
+ ### "could not reach ... to check data key"
158
+
159
+ The key check couldn't reach `serverUrl` (default `http://localhost:8000`). Logs are still sent to the collector, but nobody has confirmed the key. Point `serverUrl` at the Spanport server, or pass `checkKey: false` if the app has no route to it.
160
+
161
+ ## Development
162
+
163
+ ```bash
164
+ npm install
165
+ npm test
166
+ npm run lint
167
+ npm run typecheck
168
+ npm run build
169
+ ```
@@ -0,0 +1,14 @@
1
+ /** Copies console.debug/log/info/warn/error calls to Spanport. The app's console output is unchanged. */
2
+ import { type ConsoleMethod } from "./severity.js";
3
+ /**
4
+ * Wrap the console methods so each call is also passed to `onLog`.
5
+ *
6
+ * The original method always runs first. A failure in `onLog` is ignored on purpose: the app's
7
+ * console must keep working whatever happens to Spanport. A call made while `onLog` is running
8
+ * (e.g. by an exporter that logs) is not passed on again, so it can't loop.
9
+ *
10
+ * @param onLog - Receives the method and the formatted message, as console would print it.
11
+ * @returns A function that puts the original console methods back.
12
+ */
13
+ export declare function captureConsole(onLog: (method: ConsoleMethod, message: string) => void): () => void;
14
+ //# sourceMappingURL=consoleCapture.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"consoleCapture.d.ts","sourceRoot":"","sources":["../src/consoleCapture.ts"],"names":[],"mappings":"AAAA,yGAAyG;AAKzG,OAAO,EAAE,KAAK,aAAa,EAAE,MAAM,eAAe,CAAC;AAInD;;;;;;;;;GASG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,CAAC,MAAM,EAAE,aAAa,EAAE,OAAO,EAAE,MAAM,KAAK,IAAI,GAAG,MAAM,IAAI,CAwBlG"}
@@ -0,0 +1,44 @@
1
+ /** Copies console.debug/log/info/warn/error calls to Spanport. The app's console output is unchanged. */
2
+ import { format } from "node:util";
3
+ import { CAPTURED_CONSOLE_METHODS } from "./constants.js";
4
+ import {} from "./severity.js";
5
+ /**
6
+ * Wrap the console methods so each call is also passed to `onLog`.
7
+ *
8
+ * The original method always runs first. A failure in `onLog` is ignored on purpose: the app's
9
+ * console must keep working whatever happens to Spanport. A call made while `onLog` is running
10
+ * (e.g. by an exporter that logs) is not passed on again, so it can't loop.
11
+ *
12
+ * @param onLog - Receives the method and the formatted message, as console would print it.
13
+ * @returns A function that puts the original console methods back.
14
+ */
15
+ export function captureConsole(onLog) {
16
+ const originals = new Map();
17
+ let passingOn = false;
18
+ for (const method of CAPTURED_CONSOLE_METHODS) {
19
+ // Kept as-is so restore puts back the exact original; always called with console as `this`.
20
+ // eslint-disable-next-line @typescript-eslint/unbound-method
21
+ const original = console[method];
22
+ originals.set(method, original);
23
+ console[method] = (...args) => {
24
+ original.apply(console, args);
25
+ if (passingOn)
26
+ return;
27
+ passingOn = true;
28
+ try {
29
+ onLog(method, format(...args));
30
+ }
31
+ catch {
32
+ // Never let Spanport break the app's console.
33
+ }
34
+ finally {
35
+ passingOn = false;
36
+ }
37
+ };
38
+ }
39
+ return () => {
40
+ for (const [method, original] of originals)
41
+ console[method] = original;
42
+ };
43
+ }
44
+ //# sourceMappingURL=consoleCapture.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"consoleCapture.js","sourceRoot":"","sources":["../src/consoleCapture.ts"],"names":[],"mappings":"AAAA,yGAAyG;AAEzG,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAEnC,OAAO,EAAE,wBAAwB,EAAE,MAAM,gBAAgB,CAAC;AAC1D,OAAO,EAAsB,MAAM,eAAe,CAAC;AAInD;;;;;;;;;GASG;AACH,MAAM,UAAU,cAAc,CAAC,KAAuD;IACpF,MAAM,SAAS,GAAG,IAAI,GAAG,EAAkC,CAAC;IAC5D,IAAI,SAAS,GAAG,KAAK,CAAC;IACtB,KAAK,MAAM,MAAM,IAAI,wBAAwB,EAAE,CAAC;QAC9C,4FAA4F;QAC5F,6DAA6D;QAC7D,MAAM,QAAQ,GAAoB,OAAO,CAAC,MAAM,CAAC,CAAC;QAClD,SAAS,CAAC,GAAG,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;QAChC,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,IAAe,EAAQ,EAAE;YAC7C,QAAQ,CAAC,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;YAC9B,IAAI,SAAS;gBAAE,OAAO;YACtB,SAAS,GAAG,IAAI,CAAC;YACjB,IAAI,CAAC;gBACH,KAAK,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC;YACjC,CAAC;YAAC,MAAM,CAAC;gBACP,8CAA8C;YAChD,CAAC;oBAAS,CAAC;gBACT,SAAS,GAAG,KAAK,CAAC;YACpB,CAAC;QACH,CAAC,CAAC;IACJ,CAAC;IACD,OAAO,GAAG,EAAE;QACV,KAAK,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,IAAI,SAAS;YAAE,OAAO,CAAC,MAAM,CAAC,GAAG,QAAQ,CAAC;IACzE,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,38 @@
1
+ /** SDK constants. Code refers to these by name, never by inline value. */
2
+ export declare const DATA_KEY_PREFIX = "sp_ingest_";
3
+ export declare const DEFAULT_COLLECTOR_URL = "http://localhost:4318";
4
+ export declare const DEFAULT_SERVER_URL = "http://localhost:8000";
5
+ export declare const OTLP_LOGS_PATH = "/v1/logs";
6
+ export declare const CURRENT_API_KEY_PATH = "/api/v1/api-keys/current";
7
+ export declare const AUTHORIZATION_HEADER = "Authorization";
8
+ export declare const BEARER_PREFIX = "Bearer ";
9
+ export declare const ALLOWED_URL_PROTOCOLS: readonly string[];
10
+ export declare const KEY_CHECK_TIMEOUT_MS = 5000;
11
+ export declare const VISIBLE_KEY_SUFFIX_LENGTH = 4;
12
+ export declare const HTTP_UNAUTHORIZED = 401;
13
+ /** console methods the SDK copies to Spanport; the original output is unchanged. */
14
+ export declare const CAPTURED_CONSOLE_METHODS: readonly ["debug", "log", "info", "warn", "error"];
15
+ /** pino's numeric levels (pino's own defaults). */
16
+ export declare const PINO_TRACE = 10;
17
+ export declare const PINO_DEBUG = 20;
18
+ export declare const PINO_INFO = 30;
19
+ export declare const PINO_WARN = 40;
20
+ export declare const PINO_ERROR = 50;
21
+ export declare const PINO_FATAL = 60;
22
+ export declare const SERVICE_NAME_ATTRIBUTE = "service.name";
23
+ /** Instrumentation scope name on every log record the SDK emits. */
24
+ export declare const SDK_SCOPE_NAME = "spanport";
25
+ /** Prefix on the SDK's own stderr messages, which are never exported. */
26
+ export declare const SDK_MESSAGE_PREFIX = "spanport:";
27
+ /** Where a log came from, recorded as the `log.source` attribute. */
28
+ export declare const LOG_SOURCE_ATTRIBUTE = "log.source";
29
+ export declare const CONSOLE_SOURCE = "console";
30
+ export declare const LOG_STREAM_SOURCE = "stream";
31
+ /** Fields of a pino or winston JSON line that become part of the record rather than attributes. */
32
+ export declare const MESSAGE_FIELDS: readonly string[];
33
+ export declare const LEVEL_FIELD = "level";
34
+ export declare const TIME_FIELDS: readonly string[];
35
+ export declare const TRACE_ID_FIELD = "trace_id";
36
+ export declare const SPAN_ID_FIELD = "span_id";
37
+ export declare const LINE_SEPARATOR = "\n";
38
+ //# sourceMappingURL=constants.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAE1E,eAAO,MAAM,eAAe,eAAe,CAAC;AAC5C,eAAO,MAAM,qBAAqB,0BAA0B,CAAC;AAC7D,eAAO,MAAM,kBAAkB,0BAA0B,CAAC;AAC1D,eAAO,MAAM,cAAc,aAAa,CAAC;AACzC,eAAO,MAAM,oBAAoB,6BAA6B,CAAC;AAC/D,eAAO,MAAM,oBAAoB,kBAAkB,CAAC;AACpD,eAAO,MAAM,aAAa,YAAY,CAAC;AACvC,eAAO,MAAM,qBAAqB,EAAE,SAAS,MAAM,EAAwB,CAAC;AAC5E,eAAO,MAAM,oBAAoB,OAAO,CAAC;AACzC,eAAO,MAAM,yBAAyB,IAAI,CAAC;AAC3C,eAAO,MAAM,iBAAiB,MAAM,CAAC;AAErC,oFAAoF;AACpF,eAAO,MAAM,wBAAwB,oDAAqD,CAAC;AAE3F,mDAAmD;AACnD,eAAO,MAAM,UAAU,KAAK,CAAC;AAC7B,eAAO,MAAM,UAAU,KAAK,CAAC;AAC7B,eAAO,MAAM,SAAS,KAAK,CAAC;AAC5B,eAAO,MAAM,SAAS,KAAK,CAAC;AAC5B,eAAO,MAAM,UAAU,KAAK,CAAC;AAC7B,eAAO,MAAM,UAAU,KAAK,CAAC;AAE7B,eAAO,MAAM,sBAAsB,iBAAiB,CAAC;AACrD,oEAAoE;AACpE,eAAO,MAAM,cAAc,aAAa,CAAC;AACzC,yEAAyE;AACzE,eAAO,MAAM,kBAAkB,cAAc,CAAC;AAE9C,qEAAqE;AACrE,eAAO,MAAM,oBAAoB,eAAe,CAAC;AACjD,eAAO,MAAM,cAAc,YAAY,CAAC;AACxC,eAAO,MAAM,iBAAiB,WAAW,CAAC;AAE1C,mGAAmG;AACnG,eAAO,MAAM,cAAc,EAAE,SAAS,MAAM,EAAuB,CAAC;AACpE,eAAO,MAAM,WAAW,UAAU,CAAC;AACnC,eAAO,MAAM,WAAW,EAAE,SAAS,MAAM,EAA0B,CAAC;AACpE,eAAO,MAAM,cAAc,aAAa,CAAC;AACzC,eAAO,MAAM,aAAa,YAAY,CAAC;AACvC,eAAO,MAAM,cAAc,OAAO,CAAC"}
@@ -0,0 +1,38 @@
1
+ /** SDK constants. Code refers to these by name, never by inline value. */
2
+ export const DATA_KEY_PREFIX = "sp_ingest_";
3
+ export const DEFAULT_COLLECTOR_URL = "http://localhost:4318";
4
+ export const DEFAULT_SERVER_URL = "http://localhost:8000";
5
+ export const OTLP_LOGS_PATH = "/v1/logs";
6
+ export const CURRENT_API_KEY_PATH = "/api/v1/api-keys/current";
7
+ export const AUTHORIZATION_HEADER = "Authorization";
8
+ export const BEARER_PREFIX = "Bearer ";
9
+ export const ALLOWED_URL_PROTOCOLS = ["http:", "https:"];
10
+ export const KEY_CHECK_TIMEOUT_MS = 5000;
11
+ export const VISIBLE_KEY_SUFFIX_LENGTH = 4;
12
+ export const HTTP_UNAUTHORIZED = 401;
13
+ /** console methods the SDK copies to Spanport; the original output is unchanged. */
14
+ export const CAPTURED_CONSOLE_METHODS = ["debug", "log", "info", "warn", "error"];
15
+ /** pino's numeric levels (pino's own defaults). */
16
+ export const PINO_TRACE = 10;
17
+ export const PINO_DEBUG = 20;
18
+ export const PINO_INFO = 30;
19
+ export const PINO_WARN = 40;
20
+ export const PINO_ERROR = 50;
21
+ export const PINO_FATAL = 60;
22
+ export const SERVICE_NAME_ATTRIBUTE = "service.name";
23
+ /** Instrumentation scope name on every log record the SDK emits. */
24
+ export const SDK_SCOPE_NAME = "spanport";
25
+ /** Prefix on the SDK's own stderr messages, which are never exported. */
26
+ export const SDK_MESSAGE_PREFIX = "spanport:";
27
+ /** Where a log came from, recorded as the `log.source` attribute. */
28
+ export const LOG_SOURCE_ATTRIBUTE = "log.source";
29
+ export const CONSOLE_SOURCE = "console";
30
+ export const LOG_STREAM_SOURCE = "stream";
31
+ /** Fields of a pino or winston JSON line that become part of the record rather than attributes. */
32
+ export const MESSAGE_FIELDS = ["msg", "message"];
33
+ export const LEVEL_FIELD = "level";
34
+ export const TIME_FIELDS = ["time", "timestamp"];
35
+ export const TRACE_ID_FIELD = "trace_id";
36
+ export const SPAN_ID_FIELD = "span_id";
37
+ export const LINE_SEPARATOR = "\n";
38
+ //# sourceMappingURL=constants.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"constants.js","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAE1E,MAAM,CAAC,MAAM,eAAe,GAAG,YAAY,CAAC;AAC5C,MAAM,CAAC,MAAM,qBAAqB,GAAG,uBAAuB,CAAC;AAC7D,MAAM,CAAC,MAAM,kBAAkB,GAAG,uBAAuB,CAAC;AAC1D,MAAM,CAAC,MAAM,cAAc,GAAG,UAAU,CAAC;AACzC,MAAM,CAAC,MAAM,oBAAoB,GAAG,0BAA0B,CAAC;AAC/D,MAAM,CAAC,MAAM,oBAAoB,GAAG,eAAe,CAAC;AACpD,MAAM,CAAC,MAAM,aAAa,GAAG,SAAS,CAAC;AACvC,MAAM,CAAC,MAAM,qBAAqB,GAAsB,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;AAC5E,MAAM,CAAC,MAAM,oBAAoB,GAAG,IAAI,CAAC;AACzC,MAAM,CAAC,MAAM,yBAAyB,GAAG,CAAC,CAAC;AAC3C,MAAM,CAAC,MAAM,iBAAiB,GAAG,GAAG,CAAC;AAErC,oFAAoF;AACpF,MAAM,CAAC,MAAM,wBAAwB,GAAG,CAAC,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,CAAU,CAAC;AAE3F,mDAAmD;AACnD,MAAM,CAAC,MAAM,UAAU,GAAG,EAAE,CAAC;AAC7B,MAAM,CAAC,MAAM,UAAU,GAAG,EAAE,CAAC;AAC7B,MAAM,CAAC,MAAM,SAAS,GAAG,EAAE,CAAC;AAC5B,MAAM,CAAC,MAAM,SAAS,GAAG,EAAE,CAAC;AAC5B,MAAM,CAAC,MAAM,UAAU,GAAG,EAAE,CAAC;AAC7B,MAAM,CAAC,MAAM,UAAU,GAAG,EAAE,CAAC;AAE7B,MAAM,CAAC,MAAM,sBAAsB,GAAG,cAAc,CAAC;AACrD,oEAAoE;AACpE,MAAM,CAAC,MAAM,cAAc,GAAG,UAAU,CAAC;AACzC,yEAAyE;AACzE,MAAM,CAAC,MAAM,kBAAkB,GAAG,WAAW,CAAC;AAE9C,qEAAqE;AACrE,MAAM,CAAC,MAAM,oBAAoB,GAAG,YAAY,CAAC;AACjD,MAAM,CAAC,MAAM,cAAc,GAAG,SAAS,CAAC;AACxC,MAAM,CAAC,MAAM,iBAAiB,GAAG,QAAQ,CAAC;AAE1C,mGAAmG;AACnG,MAAM,CAAC,MAAM,cAAc,GAAsB,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC;AACpE,MAAM,CAAC,MAAM,WAAW,GAAG,OAAO,CAAC;AACnC,MAAM,CAAC,MAAM,WAAW,GAAsB,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;AACpE,MAAM,CAAC,MAAM,cAAc,GAAG,UAAU,CAAC;AACzC,MAAM,CAAC,MAAM,aAAa,GAAG,SAAS,CAAC;AACvC,MAAM,CAAC,MAAM,cAAc,GAAG,IAAI,CAAC"}
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Spanport SDK: send your Node.js app's logs to Spanport.
3
+ *
4
+ * import * as spanport from "spanport";
5
+ * spanport.init({ dataKey: "sp_ingest_...", service: "orders-api" });
6
+ *
7
+ * It never breaks the host app: init() never throws, logs are sent in the background, and if
8
+ * anything is wrong it says so on stderr and the app carries on.
9
+ */
10
+ import { type Writable } from "node:stream";
11
+ export interface SpanportOptions {
12
+ /** The project's data key (sp_ingest_...). */
13
+ dataKey: string;
14
+ /** Name of this app as shown in Spanport, e.g. "orders-api". */
15
+ service: string;
16
+ /** The Spanport OTel Collector (OTLP/HTTP). Default http://localhost:4318. */
17
+ collectorUrl?: string;
18
+ /** The Spanport server, asked once whether the data key is valid. Default http://localhost:8000. */
19
+ serverUrl?: string;
20
+ /** Set false to skip the start-up key check (e.g. no route to the server). Default true. */
21
+ checkKey?: boolean;
22
+ /** Set false to stop copying console.* calls to Spanport. Default true. */
23
+ captureConsole?: boolean;
24
+ }
25
+ /**
26
+ * Start sending this app's logs to Spanport. Call once at start-up. Never throws.
27
+ *
28
+ * @param options - Data key, service name and where Spanport runs.
29
+ */
30
+ export declare function init(options: SpanportOptions): void;
31
+ /**
32
+ * Send any logs still queued, stop capturing console and stop. Safe to call more than once.
33
+ * Call it on SIGTERM; a normal exit calls it for you. Never rejects.
34
+ */
35
+ export declare function shutdown(): Promise<void>;
36
+ /**
37
+ * A stream for pino or winston (JSON lines). Lines written before init() or after shutdown()
38
+ * are dropped.
39
+ *
40
+ * pino(spanport.logStream())
41
+ * new winston.transports.Stream({ stream: spanport.logStream() })
42
+ *
43
+ * @returns A new writable stream.
44
+ */
45
+ export declare function logStream(): Writable;
46
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EAAE,KAAK,QAAQ,EAAE,MAAM,aAAa,CAAC;AAqB5C,MAAM,WAAW,eAAe;IAC9B,8CAA8C;IAC9C,OAAO,EAAE,MAAM,CAAC;IAChB,gEAAgE;IAChE,OAAO,EAAE,MAAM,CAAC;IAChB,8EAA8E;IAC9E,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,oGAAoG;IACpG,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,4FAA4F;IAC5F,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,2EAA2E;IAC3E,cAAc,CAAC,EAAE,OAAO,CAAC;CAC1B;AAWD;;;;GAIG;AACH,wBAAgB,IAAI,CAAC,OAAO,EAAE,eAAe,GAAG,IAAI,CAMnD;AAED;;;GAGG;AACH,wBAAsB,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC,CAU9C;AAED;;;;;;;;GAQG;AACH,wBAAgB,SAAS,IAAI,QAAQ,CAIpC"}