@starko-one/sdk 0.0.0-stage → 0.1.0-beta.0

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 (108) hide show
  1. package/CHANGELOG.md +124 -0
  2. package/LICENSE +17 -0
  3. package/NOTICE +58 -0
  4. package/README.md +81 -2
  5. package/dist/api-B5IHeINe.d.ts +558 -0
  6. package/dist/api-DR4HazCu.d.cts +558 -0
  7. package/dist/browser/index.cjs +168 -0
  8. package/dist/browser/index.d.cts +131 -0
  9. package/dist/browser/index.d.ts +131 -0
  10. package/dist/browser/index.js +7 -0
  11. package/dist/build/rollup.cjs +22 -0
  12. package/dist/build/rollup.d.cts +34 -0
  13. package/dist/build/rollup.d.ts +34 -0
  14. package/dist/build/rollup.js +3 -0
  15. package/dist/build/vite.cjs +51 -0
  16. package/dist/build/vite.d.cts +23 -0
  17. package/dist/build/vite.d.ts +23 -0
  18. package/dist/build/vite.js +46 -0
  19. package/dist/build/webpack.cjs +18 -0
  20. package/dist/build/webpack.d.cts +39 -0
  21. package/dist/build/webpack.d.ts +39 -0
  22. package/dist/build/webpack.js +3 -0
  23. package/dist/chunk-7HYGODU6.cjs +583 -0
  24. package/dist/chunk-A5M4NOVT.js +413 -0
  25. package/dist/chunk-A7MYYWMP.cjs +15 -0
  26. package/dist/chunk-BAQA47FM.js +1113 -0
  27. package/dist/chunk-CM7HM6CC.js +563 -0
  28. package/dist/chunk-DFYNIWUN.js +608 -0
  29. package/dist/chunk-DMVVCGKO.cjs +96 -0
  30. package/dist/chunk-FARGXYJ4.cjs +56 -0
  31. package/dist/chunk-G3MYIAX2.js +1226 -0
  32. package/dist/chunk-G4NAVZQ4.js +249 -0
  33. package/dist/chunk-GH7RYPKS.js +96 -0
  34. package/dist/chunk-HADYYQNL.cjs +134 -0
  35. package/dist/chunk-HOQPAB4X.js +178 -0
  36. package/dist/chunk-J5RU73SW.js +214 -0
  37. package/dist/chunk-JNAJ3YZB.cjs +223 -0
  38. package/dist/chunk-KN7H22EQ.cjs +659 -0
  39. package/dist/chunk-LDQ4I7FZ.cjs +1151 -0
  40. package/dist/chunk-NPGESRVQ.js +1212 -0
  41. package/dist/chunk-OPWM5V7A.cjs +258 -0
  42. package/dist/chunk-PYYWPIFL.cjs +1230 -0
  43. package/dist/chunk-R7JLZ4WO.cjs +115 -0
  44. package/dist/chunk-SC6VQSES.js +213 -0
  45. package/dist/chunk-TPSJGLR3.cjs +220 -0
  46. package/dist/chunk-UKBY6HPC.js +131 -0
  47. package/dist/chunk-VRSEHRBX.cjs +185 -0
  48. package/dist/chunk-X74AONZA.js +90 -0
  49. package/dist/chunk-XW3I5CJN.js +12 -0
  50. package/dist/chunk-XW56FKKJ.js +53 -0
  51. package/dist/chunk-Z3G5SW7R.cjs +1251 -0
  52. package/dist/chunk-ZVMAN7OO.cjs +431 -0
  53. package/dist/cli/index.cjs +1487 -0
  54. package/dist/common-ARWXbeS3.d.ts +36 -0
  55. package/dist/common-CwIFh2hK.d.cts +36 -0
  56. package/dist/dedupe-eHBIfUUD.d.cts +13 -0
  57. package/dist/dedupe-fw8aNtt4.d.ts +13 -0
  58. package/dist/handler-DTZ4Rzcf.d.ts +82 -0
  59. package/dist/handler-_00lctTI.d.cts +82 -0
  60. package/dist/index.cjs +277 -0
  61. package/dist/index.d.cts +187 -0
  62. package/dist/index.d.ts +187 -0
  63. package/dist/index.js +4 -0
  64. package/dist/next/client.cjs +113 -0
  65. package/dist/next/client.d.cts +26 -0
  66. package/dist/next/client.d.ts +26 -0
  67. package/dist/next/client.js +41 -0
  68. package/dist/next/config.cjs +275 -0
  69. package/dist/next/config.d.cts +193 -0
  70. package/dist/next/config.d.ts +193 -0
  71. package/dist/next/config.js +261 -0
  72. package/dist/next/index.cjs +148 -0
  73. package/dist/next/index.d.cts +32 -0
  74. package/dist/next/index.d.ts +32 -0
  75. package/dist/next/index.js +59 -0
  76. package/dist/node/index.cjs +257 -0
  77. package/dist/node/index.d.cts +145 -0
  78. package/dist/node/index.d.ts +145 -0
  79. package/dist/node/index.js +83 -0
  80. package/dist/options-0BhybO54.d.cts +47 -0
  81. package/dist/options-0BhybO54.d.ts +47 -0
  82. package/dist/react/index.cjs +107 -0
  83. package/dist/react/index.d.cts +84 -0
  84. package/dist/react/index.d.ts +84 -0
  85. package/dist/react/index.js +103 -0
  86. package/dist/scope-Bvh45bOf.d.cts +404 -0
  87. package/dist/scope-Bvh45bOf.d.ts +404 -0
  88. package/dist/server-edge-BPOGA3GH.cjs +51 -0
  89. package/dist/server-edge-GYKAJREU.js +48 -0
  90. package/dist/server-node-HYK2OB2J.js +24 -0
  91. package/dist/server-node-J2DBAHDV.cjs +27 -0
  92. package/dist/session-C_WzbEN2.d.cts +4 -0
  93. package/dist/session-C_WzbEN2.d.ts +4 -0
  94. package/dist/session-propagation-B7REA7uy.d.cts +30 -0
  95. package/dist/session-propagation-BnJjKJbR.d.ts +30 -0
  96. package/dist/starko.min.js +6 -0
  97. package/docs/browser.md +381 -0
  98. package/docs/configuration.md +269 -0
  99. package/docs/nextjs.md +312 -0
  100. package/docs/node.md +376 -0
  101. package/docs/other-backends.md +232 -0
  102. package/docs/privacy.md +112 -0
  103. package/docs/react.md +187 -0
  104. package/docs/source-maps.md +332 -0
  105. package/docs/troubleshooting.md +171 -0
  106. package/docs/widget.md +84 -0
  107. package/docs/wire-format.md +367 -0
  108. package/package.json +98 -4
package/docs/node.md ADDED
@@ -0,0 +1,376 @@
1
+ # Node.js
2
+
3
+ `@starko-one/sdk/node` reports errors from servers, workers, scripts and
4
+ serverless functions on Node.js 18 and later. It uses Node's built-ins only.
5
+ For Next.js use [nextjs.md](./nextjs.md), which starts this SDK for you.
6
+
7
+ ## Shortest setup
8
+
9
+ ```sh
10
+ npm install @starko-one/sdk
11
+ ```
12
+
13
+ ```ts
14
+ import * as Starko from "@starko-one/sdk/node";
15
+
16
+ Starko.init({
17
+ workspaceKey: "<STARKO_WORKSPACE_KEY>",
18
+ apiKey: process.env.STARKO_API_KEY,
19
+ release: "api@2.3.0",
20
+ environment: "production",
21
+ });
22
+ ```
23
+
24
+ Call `init` once, at start-up, before the rest of your app runs, so errors
25
+ thrown while it starts are captured. From then on the SDK captures uncaught
26
+ exceptions and unhandled promise rejections, and isolates every incoming HTTP
27
+ request (below). `init` never throws.
28
+
29
+ `release` defaults to the `STARKO_RELEASE` environment variable, then to the
30
+ release a build plugin wrote into your server bundle. The bundle's release
31
+ is read for each event, so `init` may run before the bundle loads
32
+ (`node --require ./instrument.js dist/server.js`). If you upload source
33
+ maps (only needed when your server code is bundled or compiled), use the
34
+ release they were uploaded for.
35
+
36
+ ## The secret key (`apiKey`)
37
+
38
+ `apiKey` is optional. It is a secret key (`sk_starko_…`) with the
39
+ `errors:write` scope, created in Starko under Settings. With it:
40
+
41
+ - the `user.id` your server sets is linked to the customer without a user
42
+ hash (a browser cannot be trusted with that; a server holding the key can);
43
+ - the per-IP limits of the ingest API do not apply to your server.
44
+
45
+ It is sent as `Authorization: Bearer …` on the requests that send events,
46
+ only to the configured `host`, and never logged. Redirects are never
47
+ followed, so it cannot be forwarded to another host. Keep it in an
48
+ environment variable on the server. **Never ship it to a browser**: anyone
49
+ holding it can send events that Starko trusts. Without it, the server's
50
+ events are accepted like a browser's, and a user needs a hash to be linked
51
+ (see [browser.md](./browser.md#identify-the-user)).
52
+
53
+ ## Every request in its own scope
54
+
55
+ From `init` on, each request an HTTP, HTTPS or HTTP/2 server receives
56
+ runs in its own scope, with no middleware: the user, tags, breadcrumbs and
57
+ console lines of one request never appear on another request's errors, and
58
+ every event carries the request's method, URL and route and the browser's
59
+ session id (from the `x-starko-session-id` header, see
60
+ [nextjs.md](./nextjs.md#how-a-server-error-links-to-the-browser-session)).
61
+ The SDK finds each server through Node's diagnostics channels, at its
62
+ first connection or request, and wraps the server's `emit`, so servers
63
+ created before or after `init` are covered. If the SDK's own code fails,
64
+ your handler runs unscoped; what your handler throws is never changed.
65
+
66
+ A request scope starts from the **base**: the `user` passed to `init`, and
67
+ the tags, extra and contexts set before the process began serving (below).
68
+ It never starts with a user set with `setUser` and never with earlier
69
+ breadcrumbs.
70
+
71
+ Covered: any framework that serves through a `node:http`, `node:https` or
72
+ `node:http2` server (Express is tested). Each `request`, `checkContinue`,
73
+ `checkExpectation`, `upgrade` (WebSockets) and `connect` event gets its own
74
+ scope, and on HTTP/2 servers both the compatibility API
75
+ (`http2.createServer(handler)`, `createSecureServer`) and the raw `stream`
76
+ event do. Tested on Node 20, 22, 24 and 26.
77
+
78
+ Not covered, so use `wrapHandler` or `runWithRequestScope` (below):
79
+
80
+ - servers that do not go through `node:http` (uWebSockets.js, for one);
81
+ - the Edge runtime (see [nextjs.md](./nextjs.md#edge-runtime)).
82
+
83
+ So in a request handler:
84
+
85
+ ```ts
86
+ import { createServer } from "node:http";
87
+ import * as Starko from "@starko-one/sdk/node";
88
+
89
+ Starko.init({ workspaceKey: "<STARKO_WORKSPACE_KEY>", apiKey: process.env.STARKO_API_KEY });
90
+
91
+ createServer((req, res) => {
92
+ const userId = req.headers["x-user-id"];
93
+ if (typeof userId === "string") Starko.setUser({ id: userId }); // this request only
94
+ Starko.setTag("tenant", "acme"); // this request only
95
+ res.end("ok");
96
+ }).listen(3000);
97
+ ```
98
+
99
+ ### Code outside a request
100
+
101
+ A process **begins serving** at the first connection or request one of its
102
+ servers receives after `init`, at Next.js's `register()`, at the first
103
+ request scope (`runWithRequestScope`, `wrapHandler`, Express), or when you
104
+ call `markServing()`, whichever comes first.
105
+
106
+ - **Before that** (start-up, a CLI, a script), what you set outside a
107
+ request (`setUser`, `setTag`, breadcrumbs) applies to every later event.
108
+ - **When it begins**, the base is fixed: `init({ user })` and the tags,
109
+ extra and contexts set so far. `setUser` users and breadcrumbs are not
110
+ part of it.
111
+ - **After that**, code outside any request (a job, a queue consumer, a
112
+ timer, a database pool's callback, top-level code) gets a scope of its
113
+ own on its first write. What it sets is seen by the rest of that
114
+ synchronous code and by everything it starts afterwards (its `await`s,
115
+ timers, promises), never by a request or another job. `setUser` with a
116
+ different user starts a fresh scope from the base, so the next job of a
117
+ loop carries none of the previous job's tags or breadcrumbs. A later
118
+ callback of the same timer or socket (the next tick of an interval, the
119
+ next reply on a pooled connection) does not see what an earlier one set.
120
+ An error captured outside a request where nothing was set carries the
121
+ base.
122
+
123
+ A worker or queue consumer with no HTTP server begins serving only at its
124
+ first request scope: call `markServing()` after `init` to get this per-job
125
+ behaviour from the start. For exact boundaries, run each job in `runWithRequestScope`:
126
+
127
+ ```ts
128
+ import * as Starko from "@starko-one/sdk/node";
129
+
130
+ Starko.init({ workspaceKey: "<STARKO_WORKSPACE_KEY>", apiKey: process.env.STARKO_API_KEY });
131
+ Starko.markServing();
132
+
133
+ export function handleJob(job: { id: string; userId: string; run: () => Promise<void> }) {
134
+ return Starko.runWithRequestScope(async () => {
135
+ Starko.setUser({ id: job.userId }); // this job only
136
+ Starko.setTag("job", job.id);
137
+ try {
138
+ await job.run();
139
+ } catch (error) {
140
+ Starko.captureException(error);
141
+ }
142
+ });
143
+ }
144
+ ```
145
+
146
+ Limits of the automatic per-job scopes:
147
+
148
+ - Two jobs started in the same synchronous run, before their first
149
+ `await`, share one scope unless they set different users. Wrap each in
150
+ `runWithRequestScope`.
151
+ - A user and breadcrumbs set before serving began stay with the global
152
+ scope: a job started at start-up that captures an error after serving
153
+ began does not carry them. Set the user again in the job, or pass a
154
+ process-wide user to `init({ user })`.
155
+ - Writing to `getGlobalScope()` after serving began reaches no event.
156
+
157
+ ## Express
158
+
159
+ ```ts
160
+ import express from "express";
161
+ import * as Starko from "@starko-one/sdk/node";
162
+
163
+ Starko.init({ workspaceKey: "<STARKO_WORKSPACE_KEY>", apiKey: process.env.STARKO_API_KEY });
164
+
165
+ const app = express();
166
+ app.use(Starko.expressRequestHandler()); // first
167
+
168
+ app.get("/orders/:id", (req, res) => {
169
+ throw new Error(`Order ${req.params.id} not found in the warehouse`);
170
+ });
171
+
172
+ app.use(Starko.expressErrorHandler()); // after the routes, before your own error handlers
173
+ app.use((err: Error, req: express.Request, res: express.Response, next: express.NextFunction) => {
174
+ res.status(500).send("Something went wrong");
175
+ });
176
+
177
+ app.listen(3000);
178
+ ```
179
+
180
+ - `expressErrorHandler()` captures errors passed to `next(err)` (and, on
181
+ Express 5, thrown or rejected by handlers), then calls `next(err)`, so
182
+ your error handling runs exactly as before. By default it captures only
183
+ errors that become a 5xx: a `status`, `statusCode`, `status_code` or
184
+ `output.statusCode` of 500 or more, or none. Change that with
185
+ `expressErrorHandler({ shouldHandleError: (error) => true })`. A captured
186
+ error with a status below 500 is recorded as handled.
187
+ - `expressRequestHandler()` is optional (every request already has its own
188
+ scope). It records the route as Express matched it (`/orders/:id`,
189
+ including the mount path of nested routers) and opens the request scope
190
+ itself where the automatic isolation is not active.
191
+ - Express 4 and 5.
192
+
193
+ ## Other frameworks and serverless: `wrapHandler`
194
+
195
+ ```ts
196
+ import * as Starko from "@starko-one/sdk/node";
197
+
198
+ Starko.init({ workspaceKey: "<STARKO_WORKSPACE_KEY>", apiKey: process.env.STARKO_API_KEY });
199
+
200
+ export const handler = Starko.wrapHandler(
201
+ async (event: { rawPath: string; requestContext: { http: { method: string } } }) => {
202
+ if (!event.rawPath.startsWith("/api/")) throw new Error(`No route for ${event.rawPath}`);
203
+ return { statusCode: 200, body: "ok" };
204
+ },
205
+ { getRequestData: (event) => ({ method: event.requestContext.http.method, url: event.rawPath }) },
206
+ );
207
+ ```
208
+
209
+ Each call of the wrapped function:
210
+
211
+ - runs in its own request scope. When the first argument is a request
212
+ (Node's `IncomingMessage`, Express's `req`, a Fetch `Request`), its method,
213
+ URL and session header are read; otherwise pass `getRequestData`;
214
+ - captures what the function throws or rejects with (as unhandled), then
215
+ rethrows it unchanged;
216
+ - flushes queued events before the returned promise settles, for at most
217
+ `flushTimeout` (default 2000 ms), because a serverless platform may freeze
218
+ the process as soon as the handler returns. When the platform offers a
219
+ `waitUntil` for the request (Vercel, Cloudflare via OpenNext), the flush is
220
+ handed to it instead and the call settles at once. Nothing is flushed when
221
+ nothing is queued. A synchronous function stays synchronous: its flush is
222
+ started, not awaited.
223
+
224
+ For code that is not a handler, `runWithRequestScope(fn, requestData?)`
225
+ runs `fn` in a new request scope, a fork of the base (not of the scope it
226
+ is called from), and begins serving. `withScope(fn)` forks the current
227
+ scope for one callback.
228
+
229
+ ## Flush before the process ends
230
+
231
+ The SDK never keeps a process alive: its timers and sockets do not hold the
232
+ event loop. What happens to queued events:
233
+
234
+ | How the process ends | Queued events |
235
+ | --- | --- |
236
+ | The event loop empties (a script finishes) | Sent first: the SDK holds the process for at most `shutdownTimeout` (default 2000 ms). A process with nothing queued exits at once. |
237
+ | `SIGTERM` / `SIGINT`, and your app has **no** handler for that signal | Sent first (at most `shutdownTimeout`), then the signal is raised again, so the process ends the way the signal ends it (exit status 128 + signal number). |
238
+ | `SIGTERM` / `SIGINT`, and your app **has** a handler | The SDK does nothing; your handler decides. Flush in it (below). |
239
+ | `process.exit()` | **Lost.** `process.exit` ends the process synchronously and no network request can run after it. Flush first. |
240
+ | A crash (see below) | Sent for at most `fatalFlushTimeout` (default 1000 ms). |
241
+
242
+ None of these flushes waits for the workspace's remote config: the events
243
+ go out at once.
244
+
245
+ So before any `process.exit`:
246
+
247
+ ```ts
248
+ import * as Starko from "@starko-one/sdk/node";
249
+
250
+ Starko.init({ workspaceKey: "<STARKO_WORKSPACE_KEY>" });
251
+
252
+ process.on("SIGTERM", async () => {
253
+ await Starko.flush(2000); // resolves true when everything went out within 2 s
254
+ process.exit(143);
255
+ });
256
+ ```
257
+
258
+ `close(timeout)` flushes and then removes every hook; nothing is sent after it.
259
+
260
+ ### Shutdown and signals
261
+
262
+ The `SIGTERM` / `SIGINT` flush is the `FlushOnExit` integration. Turn the
263
+ signal part off with `flushOnExitIntegration({ signals: false })` (see
264
+ [configuration.md](./configuration.md#adding-and-removing-integrations)).
265
+ The `beforeExit` flush stays.
266
+
267
+ ## When the process crashes
268
+
269
+ An uncaught exception, or a promise rejection Node turns into one:
270
+
271
+ - **Your app has its own `uncaughtException` listener:** the SDK only
272
+ captures the error (level `error`). Your listener decides what happens, as
273
+ before.
274
+ - **It has none** (another error SDK's listener does not count): Node would
275
+ print the error and exit with code 1. The SDK captures it (level `fatal`),
276
+ prints it to stderr the way Node does, sends it for at most
277
+ `fatalFlushTimeout` (default 1000 ms), then calls `process.exit(1)`
278
+ (`process.abort()` under `--abort-on-uncaught-exception`). While it sends,
279
+ new HTTP connections are refused, as a dead process would refuse them, and
280
+ a second uncaught error is captured and printed without extending the
281
+ wait. Your timers and I/O keep running during the wait, and
282
+ `process.on("exit")` listeners run after it. For a thrown value that is
283
+ not an `Error`, the printed text has no source excerpt.
284
+ - **In a worker thread** (`worker_threads`) with no listener of its own:
285
+ the SDK captures the error (level `fatal`), sends it for at most
286
+ `fatalFlushTimeout`, then hands it back to Node, so the worker ends and
287
+ the parent's `Worker` emits `'error'` with the same value and the same
288
+ exit code as without the SDK. `uncaughtExceptionMonitor` listeners in the
289
+ worker run twice. With a listener of its own, the worker's error is only
290
+ captured (level `error`).
291
+
292
+ What the SDK never changes: whether the process exits, its exit code, and
293
+ what Node does with an unhandled rejection under your
294
+ `--unhandled-rejections` mode:
295
+
296
+ | Mode | Captured | What Node does (unchanged) |
297
+ | --- | --- | --- |
298
+ | `throw` (default) | Yes | Raises it as an uncaught exception (above), unless your app listens for `unhandledRejection`. |
299
+ | `strict` | Yes, as an uncaught exception | Raises it as an uncaught exception. |
300
+ | `warn-with-error-code` | Yes | Prints a warning and sets exit code 1. |
301
+ | `warn`, `none` | Yes | Prints a warning, or nothing. |
302
+
303
+ ## Limits on a server
304
+
305
+ A server runs for weeks, so there is no lifetime cap. Instead:
306
+
307
+ - per error: 10 at once, then 1 every 10 seconds. An error here is its
308
+ type and the first 120 characters of its message, with numbers, UUIDs
309
+ and long hex ids masked
310
+ (`Order 1234 not found` and `Order 98 not found` count as one); without
311
+ a message, its type and the file and line it was thrown from;
312
+ - 300 events a minute across all errors (`maxEventsPerMinute`), so a crash
313
+ loop throwing ever new errors still sends at most 300 a minute;
314
+ - 500 events waiting in memory (`maxQueueSize`); the oldest are dropped first.
315
+
316
+ Drops by the first two limits are printed even without `debug`, at most
317
+ once a minute per limit, with the number dropped since the previous line
318
+ (for the per-error limit, also the latest dropped error's key); a full
319
+ queue is printed once. The workspace's
320
+ remote config (on/off, sample rate, rules) is read just before the first
321
+ event is sent, so an idle process makes no request at all.
322
+
323
+ ## Proxies
324
+
325
+ The SDK sends with `node:http` / `node:https`. On Node 24.5 and later, run
326
+ with `NODE_USE_ENV_PROXY=1` and it honours `HTTPS_PROXY` and `NO_PROXY`. On
327
+ any version, you can pass the `fetch` to send with instead, for example
328
+ undici's with a proxy agent:
329
+
330
+ ```ts
331
+ import { fetch as undiciFetch, ProxyAgent } from "undici";
332
+ import * as Starko from "@starko-one/sdk/node";
333
+
334
+ const dispatcher = new ProxyAgent("http://proxy.internal:3128");
335
+
336
+ Starko.init({
337
+ workspaceKey: "<STARKO_WORKSPACE_KEY>",
338
+ fetch: ((input: string, init: RequestInit) => undiciFetch(input, { ...init, dispatcher })) as unknown as typeof fetch,
339
+ });
340
+ ```
341
+
342
+ With your own `fetch`, a request in flight keeps the process alive until it
343
+ ends (at most 10 seconds), because the SDK cannot release its socket.
344
+
345
+ ## Source lines
346
+
347
+ Each in-app frame of an event gets up to 7 lines of source before and after
348
+ it, read from disk after sampling and the rate limits (so only for events
349
+ that are sent). A file is read only when all of these hold:
350
+
351
+ - the frame names an absolute path or a `file://` URL;
352
+ - the file ends in `.js`, `.mjs`, `.cjs`, `.jsx`, `.ts`, `.tsx`, `.mts` or
353
+ `.cts` (before and after resolving symbolic links) and its name does not
354
+ start with a dot;
355
+ - its real path is inside the application root or a directory you add
356
+ with `contextLinesIntegration({ roots })`. The application root is the
357
+ working directory at `init` (`process.cwd()`). When that is a filesystem
358
+ root (`/`, the default working directory of a systemd service), it is
359
+ the main module's directory instead (`require.main`, else the script in
360
+ `process.argv[1]`); when that is a filesystem root too, or unknown, no
361
+ file is read. A filesystem root given in `roots` is ignored;
362
+ - it is not under `node_modules` (unless `includeNodeModules: true`), not
363
+ larger than 1 MiB, not minified (no line over 1000 characters, no `.min.`
364
+ in the name).
365
+
366
+ Never read: `.env` files and any other dotfile, files outside those
367
+ directories (a stack can name any path), files reached through a link that
368
+ points outside them, and anything that is not a source file. At most 10
369
+ files per event, each line cut to 300 characters. Turn source lines off by
370
+ removing the `ContextLines` integration.
371
+
372
+ ## See also
373
+
374
+ - [configuration.md](./configuration.md#nodejs): every option and its default.
375
+ - [privacy.md](./privacy.md): what a server event contains.
376
+ - [troubleshooting.md](./troubleshooting.md).
@@ -0,0 +1,232 @@
1
+ # Servers without a Starko SDK
2
+
3
+ There is a Starko SDK for browsers and Node.js only. A server written in
4
+ another language can report errors in two ways:
5
+
6
+ - **(a) the HTTP API** that the SDKs use: any language, full control,
7
+ customers linked when you send a secret key;
8
+ - **(b) PostHog's server SDKs pointed at Starko**: less code, but only for
9
+ the languages listed below, and errors are never linked to a customer.
10
+
11
+ ## (a) The HTTP API
12
+
13
+ One `POST` with a JSON body. A complete example, a Python `KeyError` sent as
14
+ a `custom` frame:
15
+
16
+ ```sh
17
+ curl -sS https://v2.starko.one/api/v1/ingest/errors \
18
+ -H "Content-Type: application/json" \
19
+ -H "Authorization: Bearer <STARKO_API_KEY>" \
20
+ --data-binary @- <<'JSON'
21
+ {
22
+ "v": 1,
23
+ "workspace": "<STARKO_WORKSPACE_KEY>",
24
+ "sdk": { "name": "acme.billing-worker", "version": "1.0.0" },
25
+ "sent_at": 1795000000500,
26
+ "events": [
27
+ {
28
+ "event_id": "0b0e7a52-5c1f-4c58-9a57-6f1d2f0c9a11",
29
+ "timestamp": 1795000000000,
30
+ "platform": "python",
31
+ "level": "error",
32
+ "exception_list": [
33
+ {
34
+ "type": "KeyError",
35
+ "value": "'invoice_id'",
36
+ "mechanism": { "type": "generic", "handled": false },
37
+ "stacktrace": {
38
+ "type": "raw",
39
+ "frames": [
40
+ { "platform": "custom", "lang": "python", "filename": "billing/jobs.py", "function": "charge", "module": "billing.jobs", "lineno": 42, "in_app": true, "resolved": true },
41
+ { "platform": "custom", "lang": "python", "filename": "billing/worker.py", "function": "run", "module": "billing.worker", "lineno": 17, "in_app": true, "resolved": true }
42
+ ]
43
+ }
44
+ }
45
+ ],
46
+ "release": "billing@3.1.0",
47
+ "environment": "production",
48
+ "server_name": "worker-1",
49
+ "user": { "id": "user_123" }
50
+ }
51
+ ]
52
+ }
53
+ JSON
54
+ ```
55
+
56
+ Required fields:
57
+
58
+ | Where | Fields |
59
+ | --- | --- |
60
+ | Body | `v` (always `1`), `workspace` (the workspace key), `sdk` (`name`, `version` of your sender), `sent_at` (your clock, epoch milliseconds, set again on every retry), `events` (1 to 20). |
61
+ | Each event | `event_id` (a new UUID per event; Starko counts an id once, so a retry never double-counts), `timestamp` (epoch milliseconds), `platform` (`dotnet`, `php`, `python`, `ruby`, `go`, `java`, `other`, …), `level` (`fatal`, `error`, `warning`, `info`, `debug`; only `error` and `fatal` can file a ticket), `exception_list` (at least one). |
62
+ | Each exception | `type`, `value` (the message). |
63
+ | Each `custom` frame | `platform: "custom"` and `lang` (lowercase language name). |
64
+
65
+ Frames are ordered **most recent call first**: `frames[0]` is where the
66
+ error was thrown. `custom` frames are stored as you send them; send
67
+ `"resolved": true` when they already show your source (languages that run
68
+ their source, or carry debug info). Everything else (`release`, `user`,
69
+ `tags`, `extra`, `breadcrumbs`, `request`, …) is optional and described in
70
+ [wire-format.md](./wire-format.md), with the limits on each field.
71
+
72
+ `Authorization: Bearer <STARKO_API_KEY>` is optional: a secret key with the
73
+ `errors:write` scope. With it, the `user.id` you send is linked to the
74
+ customer in Starko and the per-IP limits do not apply. Without it, a user is
75
+ kept as text unless you send a user hash (see
76
+ [browser.md](./browser.md#identify-the-user)).
77
+
78
+ ### Responses
79
+
80
+ Every response is JSON, `{ "ok": …, "message": …, "data": … }`; when a
81
+ request is refused, `data.reason` says why.
82
+
83
+ | Status | `data.reason` | What to do |
84
+ | --- | --- | --- |
85
+ | 200 | | Done. `data.accepted` and `data.rejected` count the events; rejected ones failed validation. |
86
+ | 3xx | | Do not follow the redirect (the POST would become a GET and your key would go to another host). Drop the batch and fix the URL. |
87
+ | 400 | `invalid`, `unsupported_version` | Drop the batch: the body is malformed. |
88
+ | 401 | `invalid` | Your secret key is not valid. A configuration error: do not retry; fix or remove the key. |
89
+ | 401 | `unknown_workspace` | Unknown workspace key. Stop sending until it is fixed. |
90
+ | 403 | `disabled` | Error tracking is off for the workspace. Stop sending. |
91
+ | 413 | `too_large` | Body too large (512 KiB as sent, 2 MiB decompressed). Halve the batch and retry once. |
92
+ | 429 | `rate_limit` | Wait `Retry-After` seconds, then retry. |
93
+ | 429 | `quota` | The workspace's allowance is used up. Drop the batch; send nothing until `Retry-After` has passed. |
94
+ | 503 | `busy` | Wait `Retry-After` seconds, then retry. |
95
+
96
+ Retry network failures and 5xx with back-off, at most three attempts per
97
+ batch, and never sooner than `Retry-After` when the answer has one.
98
+ A 401 or 403 **without** one of the reasons above comes from something in
99
+ between (a proxy, a firewall) and is temporary. The full rules are in
100
+ [wire-format.md](./wire-format.md#responses).
101
+
102
+ ### PHP
103
+
104
+ ```php
105
+ <?php
106
+ function starko_report(Throwable $e, bool $handled = true): void
107
+ {
108
+ $trace = $e->getTrace();
109
+ // Frame 0 is where the exception was thrown; each trace entry adds its caller.
110
+ $frames = [['platform' => 'custom', 'lang' => 'php', 'filename' => $e->getFile(), 'lineno' => $e->getLine(),
111
+ 'function' => $trace[0]['function'] ?? '{main}', 'resolved' => true]];
112
+ foreach ($trace as $i => $call) {
113
+ if (!isset($call['file'], $call['line'])) continue;
114
+ $frames[] = ['platform' => 'custom', 'lang' => 'php', 'filename' => $call['file'], 'lineno' => $call['line'],
115
+ 'function' => $trace[$i + 1]['function'] ?? '{main}', 'resolved' => true];
116
+ }
117
+
118
+ $id = random_bytes(16);
119
+ $id[6] = chr((ord($id[6]) & 0x0f) | 0x40);
120
+ $id[8] = chr((ord($id[8]) & 0x3f) | 0x80);
121
+ $now = (int) round(microtime(true) * 1000);
122
+
123
+ $body = json_encode([
124
+ 'v' => 1,
125
+ 'workspace' => '<STARKO_WORKSPACE_KEY>',
126
+ 'sdk' => ['name' => 'acme.php', 'version' => '1.0.0'],
127
+ 'sent_at' => $now,
128
+ 'events' => [[
129
+ 'event_id' => vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($id), 4)),
130
+ 'timestamp' => $now,
131
+ 'platform' => 'php',
132
+ 'level' => 'error',
133
+ 'exception_list' => [[
134
+ 'type' => get_class($e),
135
+ 'value' => $e->getMessage(),
136
+ 'mechanism' => ['type' => 'generic', 'handled' => $handled],
137
+ 'stacktrace' => ['type' => 'raw', 'frames' => array_slice($frames, 0, 50)],
138
+ ]],
139
+ ]],
140
+ ], JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE);
141
+
142
+ $context = stream_context_create(['http' => [
143
+ 'method' => 'POST',
144
+ 'header' => "Content-Type: application/json\r\n",
145
+ 'content' => $body,
146
+ 'timeout' => 5,
147
+ 'follow_location' => 0,
148
+ 'ignore_errors' => true,
149
+ ]]);
150
+ @file_get_contents('https://v2.starko.one/api/v1/ingest/errors', false, $context);
151
+ }
152
+
153
+ set_exception_handler(function (Throwable $e): void {
154
+ starko_report($e, false);
155
+ error_log((string) $e);
156
+ http_response_code(500);
157
+ });
158
+ ```
159
+
160
+ Call `starko_report($e)` from your own `catch` blocks too. This sends one
161
+ exception; chain `$e->getPrevious()` as further items of `exception_list`
162
+ if you need causes. A web request waits for the call (at most the 5-second
163
+ timeout); for high volumes, queue the reports and send them in batches of up
164
+ to 20 from a worker.
165
+
166
+ ## (b) PostHog server SDKs pointed at Starko
167
+
168
+ Starko accepts PostHog's capture format at `{your Starko host}/api/ingest/ph`.
169
+ Point a PostHog **server** SDK at it, with the Starko workspace key as the
170
+ project token:
171
+
172
+ - Only `$exception` events are kept. Every other event (page views,
173
+ identify, custom events, …) is discarded when the request arrives: never
174
+ queued, stored or logged.
175
+ - These errors are **never linked to a customer**. The `distinct_id` is kept
176
+ on the error as text.
177
+ - Use a PostHog client that sends **only exceptions** to Starko. If you also
178
+ use PostHog for analytics, keep that in a separate client pointed at
179
+ PostHog.
180
+ - In browsers, use `@starko-one/sdk` instead.
181
+
182
+ ### Python (`posthog` 8 and later)
183
+
184
+ ```python
185
+ from posthog import Posthog
186
+
187
+ posthog = Posthog(project_api_key="<STARKO_WORKSPACE_KEY>", host="https://v2.starko.one/api/ingest/ph", enable_exception_autocapture=True)
188
+ ```
189
+
190
+ Do not set `personal_api_key`: it starts feature-flag polling. For Django,
191
+ Flask and ASGI apps, use the integrations as PostHog's documentation shows,
192
+ with this client.
193
+
194
+ ### .NET (PostHog 2.x)
195
+
196
+ ```csharp
197
+ var posthog = new PostHogClient(new PostHogOptions { ProjectToken = "<STARKO_WORKSPACE_KEY>", HostUrl = new Uri("https://v2.starko.one/api/ingest/ph/"), CaptureUnhandledExceptions = true });
198
+ ```
199
+
200
+ In ASP.NET Core, also capture the exceptions of requests:
201
+
202
+ ```csharp
203
+ app.UsePostHogRequestContext(o => o.CaptureExceptions = true);
204
+ ```
205
+
206
+ **The trailing slash on `HostUrl` is required.** Without it the SDK posts to
207
+ the wrong path and the events are lost. If you configure the client in
208
+ `appsettings.json`, the same applies there:
209
+ `"HostUrl": "https://v2.starko.one/api/ingest/ph/"`. Do not set
210
+ `PersonalApiKey`.
211
+
212
+ ### Node (`posthog-node` 6)
213
+
214
+ ```js
215
+ import { PostHog } from 'posthog-node'
216
+
217
+ const posthog = new PostHog('<STARKO_WORKSPACE_KEY>', { host: 'https://v2.starko.one/api/ingest/ph', enableExceptionAutocapture: true })
218
+ ```
219
+
220
+ Prefer `@starko-one/sdk/node` ([node.md](./node.md)): it links users to
221
+ customers, isolates requests and adds source lines.
222
+
223
+ ### PHP and Ruby: not supported through this route yet
224
+
225
+ Their SDKs post to a path that ends in a slash, which the Starko host
226
+ currently answers with a redirect they do not follow; Ruby's SDK also drops
227
+ the path from the host. Use the [HTTP API](#a-the-http-api) for now (the PHP
228
+ example above).
229
+
230
+ ### Go
231
+
232
+ Not verified. Use the HTTP API.