-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathapplyPatches.ts
More file actions
56 lines (45 loc) · 2.13 KB
/
applyPatches.ts
File metadata and controls
56 lines (45 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import { debug } from '@sentry/core';
import type { Env, Hono } from 'hono';
import { DEBUG_BUILD } from '../debug-build';
import { patchAppRequest } from './patchAppRequest';
import { patchAppUse, patchHttpMethodHandlers } from './patchAppUse';
import { type HonoRoute, type RouteHookHandle, installRouteHookOnPrototype, wrapSubAppMiddleware } from './patchRoute';
// Lazily set by the first call to earlyPatchHono or applyPatches.
let _routeHook: RouteHookHandle | undefined;
/**
* Hooks `HonoBase.prototype.route` at import time, before `sentry()` runs.
*
* Collecting sub-app references early ensures nothing is missed if sub-apps are mounted synchronously before the `sentry()` middleware is registered.
*/
export function earlyPatchHono(): void {
_routeHook ??= installRouteHookOnPrototype();
}
/**
* Instruments a Hono app instance for Sentry tracing in middleware and route handlers.
*
* - `use` and `request` are per-instance class fields → must be patched on the instance.
* - `route` is a prototype method → hooked once globally, covers all instances.
* - Retroactively instruments sub-apps mounted before `sentry()` was called.
*/
export function applyPatches<E extends Env>(app: Hono<E>): void {
// Always call — installRouteHookOnPrototype is idempotent and returns existing handle when prototype already patched
_routeHook = installRouteHookOnPrototype();
// `app.use` (instance own property) — wraps middleware at registration time on this instance.
patchAppUse(app);
// `app.get`, `app.post`, … (instance own properties) — wraps inline middleware (all-but-last handler).
patchHttpMethodHandlers(app);
patchAppRequest(app);
_routeHook.activate();
const pendingSubApps = _routeHook.getPendingSubApps();
if (pendingSubApps.size > 0) {
DEBUG_BUILD &&
debug.log(
`[hono] ${pendingSubApps.size} sub-app(s) were mounted before sentry(). Tracing is applied retroactively. Consider registering sentry() before calling app.route().`,
);
}
for (const subApp of pendingSubApps) {
wrapSubAppMiddleware(subApp.routes as HonoRoute[]);
patchAppRequest(subApp);
}
pendingSubApps.clear();
}