@deploze/next 0.0.0-stage → 0.1.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.
@@ -0,0 +1,134 @@
1
+ import { C as Collector } from './collector-BHP98_1d.js';
2
+ export { a as CollectorOptions, R as RecordInput, c as createCollector } from './collector-BHP98_1d.js';
3
+
4
+ /**
5
+ * OpenTelemetry span processor — automatic per-route capture.
6
+ *
7
+ * Next.js emits a span for every request when an OTel tracer provider is
8
+ * registered (via @vercel/otel or a raw OTel SDK). The root request span
9
+ * carries the normalized route, HTTP status, method, and duration — so a
10
+ * span processor can record request counts, latency, AND error samples for
11
+ * every route with ZERO per-route code. This is the recommended automatic
12
+ * path; `withDeploze`/`trackRequest` remain manual escape hatches.
13
+ *
14
+ * Zero runtime dependencies: the OTel `SpanProcessor` interface is
15
+ * duck-typed by the tracer provider, and `ReadableSpan` is plain data — so
16
+ * we model only the fields we read as local structural types.
17
+ */
18
+
19
+ /** OTel HrTime: [seconds, nanoseconds]. */
20
+ type HrTime = [number, number];
21
+ /** The subset of OTel's ReadableSpan we consume. */
22
+ interface ReadableSpanLike {
23
+ name: string;
24
+ attributes: Record<string, unknown>;
25
+ startTime: HrTime;
26
+ endTime: HrTime;
27
+ events?: Array<{
28
+ name: string;
29
+ attributes?: Record<string, unknown>;
30
+ }>;
31
+ }
32
+ /** Structural match for OTel's SpanProcessor (methods are duck-typed). */
33
+ interface SpanProcessorLike {
34
+ onStart(span: unknown, parentContext?: unknown): void;
35
+ onEnd(span: ReadableSpanLike): void;
36
+ shutdown(): Promise<void>;
37
+ forceFlush(): Promise<void>;
38
+ }
39
+ /**
40
+ * Convert Next's dynamic route template to the SDK's `:param` form so
41
+ * buckets merge with value-based normalization:
42
+ * /users/[id] -> /users/:id
43
+ * /blog/[...slug] -> /blog/:slug
44
+ * /shop/[[...path]] -> /shop/:path
45
+ */
46
+ declare function bracketRouteToPattern(route: string): string;
47
+ interface DeplozeSpanProcessorOptions {
48
+ /** Injectable for tests; defaults to the shared singleton. */
49
+ collector?: Collector;
50
+ }
51
+ declare class DeplozeSpanProcessor implements SpanProcessorLike {
52
+ private readonly collector;
53
+ constructor(options?: DeplozeSpanProcessorOptions);
54
+ onStart(): void;
55
+ onEnd(span: ReadableSpanLike): void;
56
+ forceFlush(): Promise<void>;
57
+ shutdown(): Promise<void>;
58
+ }
59
+ /**
60
+ * One-line convenience: register OpenTelemetry (via @vercel/otel, which
61
+ * ships as a dependency of this package) with the Deploze span processor.
62
+ * Call from `instrumentation.ts`'s `register()`.
63
+ *
64
+ * Prefer the explicit form when you already configure OTel yourself:
65
+ * registerOTel({ serviceName, spanProcessors: [new DeplozeSpanProcessor()] })
66
+ *
67
+ * Falls back to error-only mode (a helpful warning) if @vercel/otel can't be
68
+ * resolved at runtime (e.g. an unusual bundler/edge setup), so it never
69
+ * throws during app startup.
70
+ */
71
+ declare function registerDeploze(options?: {
72
+ serviceName?: string;
73
+ }): Promise<void>;
74
+
75
+ /**
76
+ * @deploze/next — Deploze ingestion SDK for Next.js
77
+ *
78
+ * Recommended (automatic per-route capture — requests, latency, errors):
79
+ * npm i @deploze/next
80
+ * # set DEPLOZE_INGEST_KEY in your environment (dpi_... from repo settings)
81
+ *
82
+ * @vercel/otel ships as a dependency of this package — no separate install.
83
+ *
84
+ * // instrumentation.ts (project root or src/):
85
+ * import { registerOTel } from '@vercel/otel';
86
+ * import { DeplozeSpanProcessor } from '@deploze/next';
87
+ * export function register() {
88
+ * registerOTel({ serviceName: 'my-app', spanProcessors: [new DeplozeSpanProcessor()] });
89
+ * }
90
+ *
91
+ * No per-route edits: Next.js emits a span for every request and the
92
+ * processor records it. When using the span processor you do NOT also
93
+ * export `onRequestError` (it would double-count errors).
94
+ *
95
+ * Fallbacks when you can't run OTel:
96
+ * - error-only: `export { register, onRequestError } from '@deploze/next'`
97
+ * - manual success capture: wrap handlers with `withDeploze`, or call
98
+ * `trackRequest` from middleware / a custom server.
99
+ */
100
+ /**
101
+ * Next.js instrumentation hook. Called once per server instance start.
102
+ * Boots the collector; use this together with `onRequestError` for the
103
+ * error-only fallback path (the OTel span processor supersedes it).
104
+ */
105
+ declare function register(): void;
106
+ /**
107
+ * Next.js instrumentation error hook — captures uncaught request errors
108
+ * (server components, route handlers, middleware).
109
+ */
110
+ declare function onRequestError(error: unknown, request: {
111
+ path: string;
112
+ method: string;
113
+ }): void;
114
+ /**
115
+ * Record a completed request explicitly (for middleware or custom servers).
116
+ */
117
+ declare function trackRequest(input: {
118
+ path: string;
119
+ method?: string;
120
+ status: number;
121
+ durationMs?: number;
122
+ errorMessage?: string;
123
+ }): void;
124
+ type RouteHandler<Ctx> = (request: Request, context: Ctx) => Response | Promise<Response>;
125
+ /**
126
+ * Wrap a route handler to record status + latency for every invocation.
127
+ *
128
+ * export const GET = withDeploze(async (req) => { ... });
129
+ */
130
+ declare function withDeploze<Ctx = unknown>(handler: RouteHandler<Ctx>): RouteHandler<Ctx>;
131
+ /** Force a flush — useful in tests and short-lived scripts. */
132
+ declare function flush(): Promise<void>;
133
+
134
+ export { Collector, DeplozeSpanProcessor, type DeplozeSpanProcessorOptions, type SpanProcessorLike, bracketRouteToPattern, flush, onRequestError, register, registerDeploze, trackRequest, withDeploze };
package/dist/index.js ADDED
@@ -0,0 +1,182 @@
1
+ import {
2
+ createCollector
3
+ } from "./chunk-2ZXSSRDV.js";
4
+
5
+ // src/core/singleton.ts
6
+ var collector = null;
7
+ function getCollector() {
8
+ if (!collector) {
9
+ collector = createCollector();
10
+ }
11
+ return collector;
12
+ }
13
+ function scheduleFlush() {
14
+ const specifier = "next/server";
15
+ void import(
16
+ /* @vite-ignore */
17
+ specifier
18
+ ).then((mod) => {
19
+ if (typeof mod.after === "function") {
20
+ mod.after(() => getCollector().flush());
21
+ }
22
+ }).catch(() => {
23
+ });
24
+ }
25
+
26
+ // src/core/otel.ts
27
+ var NEXT_SPAN_TYPE = "next.span_type";
28
+ var NEXT_ROUTE = "next.route";
29
+ var HTTP_ROUTE = "http.route";
30
+ var HTTP_TARGET = "http.target";
31
+ var HTTP_STATUS = "http.status_code";
32
+ var HTTP_METHOD = "http.method";
33
+ var HTTP_USER_AGENT = "http.user_agent";
34
+ var USER_AGENT_ORIGINAL = "user_agent.original";
35
+ var REQUEST_SPAN_TYPE = "BaseServer.handleRequest";
36
+ var SYNTHETIC_USER_AGENT_MARKER = "Deploze-SyntheticMonitor";
37
+ function isSyntheticUserAgent(ua) {
38
+ return typeof ua === "string" && ua.includes(SYNTHETIC_USER_AGENT_MARKER);
39
+ }
40
+ function hrToMs(start, end) {
41
+ return (end[0] - start[0]) * 1e3 + (end[1] - start[1]) / 1e6;
42
+ }
43
+ function bracketRouteToPattern(route) {
44
+ return route.replace(/\[(?:\[?\.\.\.)?([^\]]+?)\]\]?/g, (_m, name) => `:${name}`);
45
+ }
46
+ var DeplozeSpanProcessor = class {
47
+ collector;
48
+ constructor(options = {}) {
49
+ this.collector = options.collector ?? getCollector();
50
+ }
51
+ onStart() {
52
+ }
53
+ onEnd(span) {
54
+ try {
55
+ const attrs = span.attributes || {};
56
+ if (attrs[NEXT_SPAN_TYPE] !== REQUEST_SPAN_TYPE) return;
57
+ const ua = attrs[USER_AGENT_ORIGINAL] ?? attrs[HTTP_USER_AGENT];
58
+ if (isSyntheticUserAgent(typeof ua === "string" ? ua : void 0)) return;
59
+ const status = Number(attrs[HTTP_STATUS]);
60
+ if (!Number.isFinite(status)) return;
61
+ const rawRoute = attrs[NEXT_ROUTE] ?? attrs[HTTP_ROUTE] ?? attrs[HTTP_TARGET];
62
+ if (!rawRoute) return;
63
+ const path = bracketRouteToPattern(String(rawRoute));
64
+ const method = attrs[HTTP_METHOD] != null ? String(attrs[HTTP_METHOD]) : void 0;
65
+ const durationMs = hrToMs(span.startTime, span.endTime);
66
+ let errorMessage;
67
+ if (status >= 500 && Array.isArray(span.events)) {
68
+ const ex = span.events.find((e) => e.name === "exception");
69
+ const message = ex?.attributes?.["exception.message"] ?? ex?.attributes?.["exception.type"];
70
+ if (message) errorMessage = String(message);
71
+ }
72
+ this.collector.record({
73
+ path,
74
+ method,
75
+ status,
76
+ durationMs: Number.isFinite(durationMs) && durationMs >= 0 ? durationMs : void 0,
77
+ errorMessage
78
+ });
79
+ scheduleFlush();
80
+ } catch {
81
+ }
82
+ }
83
+ async forceFlush() {
84
+ await this.collector.flush();
85
+ }
86
+ async shutdown() {
87
+ await this.collector.flush();
88
+ }
89
+ };
90
+ async function registerDeploze(options = {}) {
91
+ getCollector();
92
+ try {
93
+ const mod = await import("@vercel/otel");
94
+ if (typeof mod.registerOTel !== "function") {
95
+ throw new Error("registerOTel export not found");
96
+ }
97
+ mod.registerOTel({
98
+ serviceName: options.serviceName ?? "deploze-app",
99
+ spanProcessors: [new DeplozeSpanProcessor()]
100
+ });
101
+ } catch {
102
+ console.warn(
103
+ "[deploze] Could not load @vercel/otel for automatic per-route capture. Wrap handlers with withDeploze() or call trackRequest() manually instead. Continuing in error-only mode."
104
+ );
105
+ }
106
+ }
107
+
108
+ // src/index.ts
109
+ function register() {
110
+ getCollector();
111
+ const proc = globalThis.process;
112
+ if (proc?.on) {
113
+ proc.on("beforeExit", () => {
114
+ void getCollector().flush();
115
+ });
116
+ }
117
+ }
118
+ function onRequestError(error, request) {
119
+ const message = error instanceof Error ? error.message : typeof error === "string" ? error : "Unknown error";
120
+ getCollector().record({
121
+ path: request.path,
122
+ method: request.method,
123
+ status: 500,
124
+ errorMessage: message
125
+ });
126
+ scheduleFlush();
127
+ }
128
+ function trackRequest(input) {
129
+ getCollector().record(input);
130
+ scheduleFlush();
131
+ }
132
+ function withDeploze(handler) {
133
+ return async (request, context) => {
134
+ if (isSyntheticUserAgent(request.headers.get("user-agent"))) {
135
+ return handler(request, context);
136
+ }
137
+ const start = Date.now();
138
+ const path = safePathname(request.url);
139
+ try {
140
+ const response = await handler(request, context);
141
+ getCollector().record({
142
+ path,
143
+ method: request.method,
144
+ status: response.status,
145
+ durationMs: Date.now() - start
146
+ });
147
+ scheduleFlush();
148
+ return response;
149
+ } catch (error) {
150
+ getCollector().record({
151
+ path,
152
+ method: request.method,
153
+ status: 500,
154
+ durationMs: Date.now() - start,
155
+ errorMessage: error instanceof Error ? error.message : "Unknown error"
156
+ });
157
+ scheduleFlush();
158
+ throw error;
159
+ }
160
+ };
161
+ }
162
+ function safePathname(url) {
163
+ try {
164
+ return new URL(url).pathname;
165
+ } catch {
166
+ return url || "/unknown";
167
+ }
168
+ }
169
+ async function flush() {
170
+ await getCollector().flush();
171
+ }
172
+ export {
173
+ DeplozeSpanProcessor,
174
+ bracketRouteToPattern,
175
+ createCollector,
176
+ flush,
177
+ onRequestError,
178
+ register,
179
+ registerDeploze,
180
+ trackRequest,
181
+ withDeploze
182
+ };
package/package.json CHANGED
@@ -1,6 +1,74 @@
1
1
  {
2
2
  "name": "@deploze/next",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Deploze ingestion SDK — per-route request stats for deploy health verdicts. Aggregates in-memory, flushes tiny payloads, never blocks a request.",
5
+ "license": "MIT",
6
+ "author": "Deploze",
7
+ "homepage": "https://deploze.com",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/deploze/next.git"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/deploze/next/issues"
14
+ },
15
+ "type": "module",
16
+ "main": "./dist/index.cjs",
17
+ "module": "./dist/index.js",
18
+ "types": "./dist/index.d.ts",
19
+ "exports": {
20
+ ".": {
21
+ "types": "./dist/index.d.ts",
22
+ "import": "./dist/index.js",
23
+ "require": "./dist/index.cjs"
24
+ },
25
+ "./core": {
26
+ "types": "./dist/core/index.d.ts",
27
+ "import": "./dist/core/index.js",
28
+ "require": "./dist/core/index.cjs"
29
+ }
30
+ },
31
+ "files": [
32
+ "dist",
33
+ "postinstall.cjs",
34
+ "LICENSE"
35
+ ],
36
+ "engines": {
37
+ "node": ">=18.18"
38
+ },
39
+ "publishConfig": {
40
+ "access": "public"
41
+ },
42
+ "scripts": {
43
+ "build": "tsup src/index.ts src/core/index.ts --format esm,cjs --dts --clean",
44
+ "postinstall": "node ./postinstall.cjs",
45
+ "test": "vitest",
46
+ "test:run": "vitest run",
47
+ "typecheck": "tsc --noEmit",
48
+ "prepublishOnly": "npm run typecheck && npm run test:run && npm run build"
49
+ },
50
+ "dependencies": {
51
+ "@vercel/otel": ">=1.10.0 <3.0.0"
52
+ },
53
+ "peerDependencies": {
54
+ "next": ">=14"
55
+ },
56
+ "peerDependenciesMeta": {
57
+ "next": {
58
+ "optional": true
59
+ }
60
+ },
61
+ "devDependencies": {
62
+ "@types/node": "^20.19.43",
63
+ "tsup": "^8.0.0",
64
+ "typescript": "^5",
65
+ "vitest": "^4.0.18"
66
+ },
67
+ "keywords": [
68
+ "deploy",
69
+ "monitoring",
70
+ "observability",
71
+ "nextjs",
72
+ "deploze"
73
+ ]
74
+ }
@@ -0,0 +1,68 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Best-effort build-identity capture, run by npm at install time.
4
+ *
5
+ * Walks up from this package's install location to find the host project's
6
+ * `.git` dir and records HEAD's commit SHA into `.build-id.json` next to
7
+ * this script, which `src/core/build-id.ts` reads at runtime as a fallback
8
+ * identity signal for deploy attribution.
9
+ *
10
+ * Known limitations (by design — this is a fallback, not the primary
11
+ * signal; DEPLOZE_GIT_SHA/VERCEL_GIT_COMMIT_SHA take priority):
12
+ * - If CI restores a cached `node_modules` and skips reinstall (lockfile
13
+ * unchanged), this script never reruns and the SHA can go stale.
14
+ * - `.git` is commonly excluded from Docker build contexts via
15
+ * .dockerignore, in which case no SHA is captured at all.
16
+ * - Must never throw / block `npm install` — failures are swallowed.
17
+ */
18
+ 'use strict';
19
+
20
+ const fs = require('fs');
21
+ const path = require('path');
22
+
23
+ function findGitDir(startDir) {
24
+ let dir = startDir;
25
+ for (let i = 0; i < 12; i++) {
26
+ const candidate = path.join(dir, '.git');
27
+ if (fs.existsSync(candidate)) return candidate;
28
+ const parent = path.dirname(dir);
29
+ if (parent === dir) return null;
30
+ dir = parent;
31
+ }
32
+ return null;
33
+ }
34
+
35
+ function readHeadSha(gitDir) {
36
+ const head = fs.readFileSync(path.join(gitDir, 'HEAD'), 'utf8').trim();
37
+
38
+ if (/^[0-9a-f]{40}$/i.test(head)) return head; // detached HEAD
39
+
40
+ const match = head.match(/^ref:\s*(.+)$/);
41
+ if (!match) return null;
42
+ const ref = match[1].trim();
43
+
44
+ const refPath = path.join(gitDir, ref);
45
+ if (fs.existsSync(refPath)) return fs.readFileSync(refPath, 'utf8').trim();
46
+
47
+ const packedRefsPath = path.join(gitDir, 'packed-refs');
48
+ if (fs.existsSync(packedRefsPath)) {
49
+ const line = fs
50
+ .readFileSync(packedRefsPath, 'utf8')
51
+ .split('\n')
52
+ .find((l) => l.endsWith(' ' + ref));
53
+ if (line) return line.split(' ')[0];
54
+ }
55
+
56
+ return null;
57
+ }
58
+
59
+ try {
60
+ const gitDir = findGitDir(__dirname);
61
+ const sha = gitDir ? readHeadSha(gitDir) : null;
62
+ fs.writeFileSync(
63
+ path.join(__dirname, '.build-id.json'),
64
+ JSON.stringify({ sha: sha ?? null, generatedAt: new Date().toISOString() }),
65
+ );
66
+ } catch {
67
+ // Best effort only — never fail the install over this.
68
+ }