@honeybadger-io/nextjs 5.11.6 → 6.0.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 (62) hide show
  1. package/README.md +5 -42
  2. package/dist/capture-request-error.d.ts +35 -0
  3. package/dist/capture-request-error.test.d.ts +2 -0
  4. package/dist/capture-router-transition-start.d.ts +21 -0
  5. package/dist/client.d.ts +2 -0
  6. package/dist/copy-config-files.js +106 -34
  7. package/dist/copy-config-files.js.map +1 -1
  8. package/dist/edge.d.ts +2 -1
  9. package/dist/flush.d.ts +24 -0
  10. package/dist/honeybadger-nextjs-client.cjs.js +35 -0
  11. package/dist/honeybadger-nextjs-client.cjs.js.map +1 -0
  12. package/dist/honeybadger-nextjs-client.esm.js +27 -0
  13. package/dist/honeybadger-nextjs-client.esm.js.map +1 -0
  14. package/dist/honeybadger-nextjs-edge.cjs.js +320 -240
  15. package/dist/honeybadger-nextjs-edge.cjs.js.map +1 -1
  16. package/dist/honeybadger-nextjs-edge.esm.js +317 -240
  17. package/dist/honeybadger-nextjs-edge.esm.js.map +1 -1
  18. package/dist/honeybadger-nextjs.cjs.js +835 -387
  19. package/dist/honeybadger-nextjs.cjs.js.map +1 -1
  20. package/dist/honeybadger-nextjs.esm.js +829 -386
  21. package/dist/honeybadger-nextjs.esm.js.map +1 -1
  22. package/dist/index.d.ts +5 -2
  23. package/dist/insights-instrumentation.d.ts +30 -2
  24. package/dist/insights.d.ts +72 -0
  25. package/dist/insights.test.d.ts +2 -0
  26. package/dist/setup.d.ts +11 -0
  27. package/dist/setup.test.d.ts +2 -0
  28. package/dist/source-maps.d.ts +55 -0
  29. package/dist/source-maps.test.d.ts +2 -0
  30. package/dist/types.d.ts +20 -8
  31. package/package.json +33 -11
  32. package/src/capture-request-error.test.ts +245 -0
  33. package/src/capture-request-error.ts +92 -0
  34. package/src/capture-router-transition-start.ts +33 -0
  35. package/src/client.ts +4 -0
  36. package/src/copy-config-files.test.ts +250 -16
  37. package/src/copy-config-files.ts +117 -34
  38. package/src/edge.ts +12 -1
  39. package/src/flush.ts +58 -0
  40. package/src/index.ts +7 -2
  41. package/src/insights-instrumentation.ts +104 -11
  42. package/src/insights.test.ts +192 -0
  43. package/src/insights.ts +225 -0
  44. package/src/setup.test.ts +214 -0
  45. package/src/setup.ts +172 -0
  46. package/src/source-maps.test.ts +803 -0
  47. package/src/source-maps.ts +515 -0
  48. package/src/types.ts +38 -21
  49. package/templates/_error.js +14 -10
  50. package/templates/_error_app_router.js +1 -1
  51. package/templates/_error_app_router.tsx +1 -1
  52. package/templates/honeybadger.server.config.js +5 -16
  53. package/templates/instrumentation-client.js +21 -0
  54. package/templates/instrumentation.js +29 -0
  55. package/dist/webpack.d.ts +0 -3
  56. package/dist/with-honeybadger.d.ts +0 -32
  57. package/dist/with-honeybadger.test.d.ts +0 -2
  58. package/src/webpack.ts +0 -228
  59. package/src/with-honeybadger.test.ts +0 -527
  60. package/src/with-honeybadger.ts +0 -286
  61. package/templates/honeybadger.browser.config.js +0 -13
  62. package/templates/honeybadger.edge.config.js +0 -13
@@ -0,0 +1,515 @@
1
+ import fs from 'fs'
2
+ import os from 'os'
3
+ import path from 'path'
4
+ import picomatch from 'picomatch'
5
+ // Type-only, so nothing from plugin-core is pulled into the module graph at import time.
6
+ import type { Types } from '@honeybadger-io/plugin-core'
7
+ import { HoneybadgerNextJsConfig } from './types'
8
+
9
+ /**
10
+ * Loads plugin-core on demand, never at module scope.
11
+ *
12
+ * Its module body runs `fetchRetry(require('node-fetch'))` as a side effect, which throws
13
+ * `ArgumentError: fetch must be a function` inside the Next.js server runtime. This module
14
+ * shares a barrel with the runtime instrumentation exports, so a top-level import here
15
+ * would break `instrumentation.ts` for every app. plugin-core is a rollup external, so this
16
+ * stays a real deferred require in both the CJS and ESM bundles.
17
+ */
18
+ function loadPluginCore() {
19
+ return import('@honeybadger-io/plugin-core')
20
+ }
21
+
22
+ /**
23
+ * The build output directory Next.js serves over HTTP, relative to `distDir`. `.next/static`
24
+ * is published at `/_next/static`; everything else in `distDir` is not served.
25
+ */
26
+ const BROWSER_OUTPUT_DIR = 'static'
27
+
28
+ /**
29
+ * The directories inside `distDir` whose JavaScript is actually shipped, and so the only
30
+ * ones worth collecting maps from. `distDir` also holds build tooling — `build/chunks`,
31
+ * `cache`, `required-server-files.js` — and a `standalone` copy of the server when that
32
+ * output mode is on. Walking all of it uploads maps under a `minified_url` no request can
33
+ * ever produce.
34
+ */
35
+ const OUTPUT_DIRS = [BROWSER_OUTPUT_DIR, 'server']
36
+
37
+ /**
38
+ * Metadata Next.js passes to `compiler.runAfterProductionCompile`.
39
+ */
40
+ export type AfterProductionCompileMetadata = {
41
+ distDir: string
42
+ projectDir: string
43
+ }
44
+
45
+ function log(type: 'error' | 'warn' | 'debug', silent: boolean, msg: string): void {
46
+ if (['error', 'warn'].includes(type) || !silent) {
47
+ console[type]('[HoneybadgerNextJs]', msg)
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Whether the project has configured source map upload.
53
+ *
54
+ * Separate from `resolveUploadOptions` because `withHoneybadgerConfig` needs the answer
55
+ * while building the config, and must not emit the "not configured" warning there — the
56
+ * hook will do that once, at build time.
57
+ */
58
+ export function isSourceMapUploadConfigured(
59
+ honeybadgerNextJsConfig: HoneybadgerNextJsConfig = {}
60
+ ): boolean {
61
+ if (honeybadgerNextJsConfig.disableSourceMapUpload) {
62
+ return false
63
+ }
64
+
65
+ const apiKey = honeybadgerNextJsConfig.apiKey || process.env.NEXT_PUBLIC_HONEYBADGER_API_KEY
66
+ const assetsUrl = honeybadgerNextJsConfig.assetsUrl || process.env.NEXT_PUBLIC_HONEYBADGER_ASSETS_URL
67
+
68
+ return Boolean(apiKey && assetsUrl)
69
+ }
70
+
71
+ /**
72
+ * Resolves the upload options, falling back to the same environment variables the
73
+ * configuration templates use.
74
+ *
75
+ * Returns `null` rather than throwing when the project has not configured source map
76
+ * upload. `cleanOptions` throws on a missing `apiKey`/`assetsUrl`, and Next.js re-throws
77
+ * whatever this hook throws — so validating eagerly would fail the build of every app
78
+ * that simply does not use this feature.
79
+ */
80
+ export async function resolveUploadOptions(
81
+ honeybadgerNextJsConfig: HoneybadgerNextJsConfig = {}
82
+ ): Promise<Types.HbPluginOptions | null> {
83
+ const silent = honeybadgerNextJsConfig.silent ?? true
84
+
85
+ if (honeybadgerNextJsConfig.disableSourceMapUpload) {
86
+ log('debug', silent, 'source map upload disabled')
87
+ return null
88
+ }
89
+
90
+ // `disableSourceMapUpload` is this package's own switch, handled above; everything else
91
+ // on the config is a plugin-core option and passes straight through.
92
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
93
+ const { disableSourceMapUpload, ...provided } = honeybadgerNextJsConfig
94
+ const apiKey = provided.apiKey || process.env.NEXT_PUBLIC_HONEYBADGER_API_KEY
95
+ const assetsUrl = provided.assetsUrl || process.env.NEXT_PUBLIC_HONEYBADGER_ASSETS_URL
96
+
97
+ if (!apiKey || !assetsUrl) {
98
+ log('warn', silent, 'skipping source map upload; set apiKey and assetsUrl to enable it')
99
+ return null
100
+ }
101
+
102
+ // `cleanOptions` merges as `{ ...defaults, ...options }`, so a key present with an
103
+ // `undefined` value overwrites the default rather than falling back to it. An unset
104
+ // revision would upload as `undefined` instead of `main`, and a fault whose revision
105
+ // does not match its source map is never symbolicated — so drop empty values instead
106
+ // of passing them through.
107
+ const { cleanOptions } = await loadPluginCore()
108
+
109
+ return cleanOptions(withoutUndefined({
110
+ ...provided,
111
+ apiKey,
112
+ assetsUrl,
113
+ revision: provided.revision || process.env.NEXT_PUBLIC_HONEYBADGER_REVISION,
114
+ silent,
115
+ }))
116
+ }
117
+
118
+ function withoutUndefined<T extends Record<string, unknown>>(options: T): T {
119
+ return Object.fromEntries(
120
+ Object.entries(options).filter(([, value]) => value !== undefined)
121
+ ) as T
122
+ }
123
+
124
+ // Mirrors plugin-core's DEFAULT_DEVELOPMENT_ENVIRONMENTS. Duplicated so a development
125
+ // build can be recognised before plugin-core is loaded — see uploadSourceMapsAfterBuild.
126
+ const DEFAULT_DEVELOPMENT_ENVIRONMENTS = ['dev', 'development', 'test']
127
+
128
+ function isDevEnv(developmentEnvironments: string[]): boolean {
129
+ if (!process.env.NODE_ENV) {
130
+ return false
131
+ }
132
+
133
+ return developmentEnvironments.includes(process.env.NODE_ENV)
134
+ }
135
+
136
+ async function walk(dir: string, onFile: (filePath: string) => void): Promise<void> {
137
+ let entries: fs.Dirent[]
138
+ try {
139
+ entries = await fs.promises.readdir(dir, { withFileTypes: true })
140
+ }
141
+ catch (error) {
142
+ // A build output directory that isn't there is not an error worth failing on — the
143
+ // server tree does not exist unless `experimental.serverSourceMaps` is on. Anything
144
+ // else (permissions, I/O) would silently shrink the upload to whatever happened to be
145
+ // readable, so let it propagate and be governed by `ignoreErrors`.
146
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
147
+ return
148
+ }
149
+
150
+ throw error
151
+ }
152
+
153
+ for (const entry of entries) {
154
+ const entryPath = path.join(dir, entry.name)
155
+ if (entry.isDirectory()) {
156
+ await walk(entryPath, onFile)
157
+ } else if (entry.isFile()) {
158
+ onFile(entryPath)
159
+ }
160
+ }
161
+ }
162
+
163
+ /**
164
+ * A source map is only worth uploading when it carries the original sources. Next.js
165
+ * emits maps without `sourcesContent` for some outputs, and those symbolicate to
166
+ * nothing. Same check the rollup and esbuild plugins apply.
167
+ */
168
+ async function hasSourcesContent(sourcemapFilePath: string): Promise<boolean> {
169
+ try {
170
+ const contents = await fs.promises.readFile(sourcemapFilePath, 'utf8')
171
+ const parsed = JSON.parse(contents)
172
+ return Array.isArray(parsed.sourcesContent) && parsed.sourcesContent.length > 0
173
+ }
174
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
175
+ catch (error) {
176
+ return false
177
+ }
178
+ }
179
+
180
+ // Enough to reach the `sourceMappingURL` comment, which is the last line of a built file.
181
+ const SOURCE_MAPPING_URL_TAIL_BYTES = 2048
182
+
183
+ /**
184
+ * The source map a built JavaScript file points at, or `null` when it has none.
185
+ *
186
+ * Resolved from the file's own `sourceMappingURL` comment rather than by assuming the map
187
+ * sits beside it as `<name>.js.map`. That sibling convention is webpack's; Turbopack gives
188
+ * the map an independent hash — `1mfl5gjk9763d.js` points at `33ri1p-shrphb.js.map`.
189
+ *
190
+ * Only the tail of the file is read, since the comment is always its last line.
191
+ */
192
+ async function locateSourcemap(jsFilePath: string): Promise<string | null> {
193
+ let tail: string
194
+ try {
195
+ const handle = await fs.promises.open(jsFilePath, 'r')
196
+ try {
197
+ const { size } = await handle.stat()
198
+ const length = Math.min(size, SOURCE_MAPPING_URL_TAIL_BYTES)
199
+ const buffer = Buffer.alloc(length)
200
+ await handle.read(buffer, 0, length, size - length)
201
+ tail = buffer.toString('utf8')
202
+ } finally {
203
+ await handle.close()
204
+ }
205
+ }
206
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
207
+ catch (error) {
208
+ return null
209
+ }
210
+
211
+ // The last comment wins, per the source map spec. No Next.js chunk currently carries
212
+ // two, but a bundled library that mentions `sourceMappingURL` in its tail would
213
+ // otherwise mispair the map.
214
+ const matches = [...tail.matchAll(/[#@]\s*sourceMappingURL=(\S+)/g)]
215
+ const url = matches.at(-1)?.[1]
216
+
217
+ // No map, or an inline `data:` map, which there is nothing to upload for.
218
+ if (!url || url.startsWith('data:')) {
219
+ return null
220
+ }
221
+
222
+ // `decodeURIComponent` throws on malformed escapes such as `bad%.map`. Scoped to just
223
+ // the decode, because letting it escape would abandon the whole build's upload over one
224
+ // unreadable footer rather than skipping that single file.
225
+ let decodedUrl: string
226
+ try {
227
+ decodedUrl = decodeURIComponent(url)
228
+ }
229
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
230
+ catch (error) {
231
+ return null
232
+ }
233
+
234
+ const sourcemapFilePath = path.resolve(path.dirname(jsFilePath), decodedUrl)
235
+
236
+ return fs.existsSync(sourcemapFilePath) ? sourcemapFilePath : null
237
+ }
238
+
239
+ /**
240
+ * Pairs each built `.js` file with the source map it declares.
241
+ *
242
+ * `jsFilename` is the path relative to `distDir`, because that is what `assetsUrl`
243
+ * addresses: the configuration templates point it at `<origin>/_next`, and `.next/x`
244
+ * is served at `/_next/x`. `uploadSourcemap` builds `minified_url` by joining the two.
245
+ *
246
+ * Only `static/` and `server/` are walked — see `OUTPUT_DIRS`. Server maps exist only when
247
+ * `experimental.serverSourceMaps` is on, which `withHoneybadgerConfig` enables alongside
248
+ * upload. Server chunks are not served over HTTP, so whether their frames match the
249
+ * uploaded `minified_url` depends on the runtime path rewriting tracked in #1602 — but
250
+ * not uploading them at all guarantees server frames stay minified, which is the defect
251
+ * that issue reports.
252
+ */
253
+ export async function collectSourcemaps(
254
+ distDir: string,
255
+ ignorePaths: string[] = []
256
+ ): Promise<Types.SourcemapInfo[]> {
257
+ const jsFilePaths: string[] = []
258
+ for (const outputDir of OUTPUT_DIRS) {
259
+ await walk(path.join(distDir, outputDir), (filePath) => {
260
+ if (filePath.endsWith('.js')) {
261
+ jsFilePaths.push(filePath)
262
+ }
263
+ })
264
+ }
265
+
266
+ const collected: Types.SourcemapInfo[] = []
267
+
268
+ for (const jsFilePath of jsFilePaths) {
269
+ if (picomatch.isMatch(jsFilePath, ignorePaths, { basename: true })) {
270
+ continue
271
+ }
272
+
273
+ const sourcemapFilePath = await locateSourcemap(jsFilePath)
274
+ if (!sourcemapFilePath) {
275
+ continue
276
+ }
277
+
278
+ if (!await hasSourcesContent(sourcemapFilePath)) {
279
+ continue
280
+ }
281
+
282
+ // Posix separators: these become URL paths.
283
+ const jsFilename = path.relative(distDir, jsFilePath).split(path.sep).join('/')
284
+
285
+ collected.push({
286
+ sourcemapFilename: path.relative(distDir, sourcemapFilePath).split(path.sep).join('/'),
287
+ sourcemapFilePath,
288
+ jsFilename,
289
+ jsFilePath,
290
+ })
291
+ }
292
+
293
+ return collected
294
+ }
295
+
296
+ /**
297
+ * Bundler URL schemes that appear in a map's `sources`.
298
+ *
299
+ * Turbopack writes `turbopack:///[project]/app/page.tsx`; webpack writes
300
+ * `webpack://_N_E/./app/page.tsx` or `webpack:///./app/page.tsx`.
301
+ */
302
+ const SOURCE_SCHEME_PREFIXES = [
303
+ /^turbopack:\/\/\/\[[^\]]+\]\//,
304
+ /^webpack:\/\/[^/]*\/(\.\/)?/,
305
+ ]
306
+
307
+ function normalizeSource(source: string): string {
308
+ for (const prefix of SOURCE_SCHEME_PREFIXES) {
309
+ const normalized = source.replace(prefix, '')
310
+ if (normalized !== source) {
311
+ return normalized
312
+ }
313
+ }
314
+
315
+ return source
316
+ }
317
+
318
+ /**
319
+ * Rewrites each map's `sources` to project-relative paths, in a throwaway copy.
320
+ *
321
+ * Honeybadger decides whether a mapped frame is *your* code by testing the resolved source
322
+ * against the notice's `projectRoot`, which the browser client defaults to the page origin.
323
+ * A source still carrying its bundler scheme never matches, so the frame is treated as
324
+ * library code and the fault surfaces the next frame instead — for a React app, an unmapped
325
+ * framework chunk. Stripping the scheme leaves a relative path, which Honeybadger resolves
326
+ * against the minified URL and therefore under the origin.
327
+ *
328
+ * Done here rather than by asking users to set `projectRoot` to a bundler-specific prefix,
329
+ * because that value differs between Turbopack and webpack and cannot be chosen correctly
330
+ * from client config.
331
+ *
332
+ * The originals on disk are untouched: Next.js reads the server maps itself.
333
+ */
334
+ async function withNormalizedSources(
335
+ sourcemaps: Types.SourcemapInfo[]
336
+ ): Promise<{ sourcemaps: Types.SourcemapInfo[]; cleanup: () => Promise<void> }> {
337
+ const unchanged = { sourcemaps, cleanup: async () => undefined }
338
+ if (sourcemaps.length === 0) {
339
+ return unchanged
340
+ }
341
+
342
+ let tempDir: string
343
+ try {
344
+ tempDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'honeybadger-sourcemaps-'))
345
+ }
346
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
347
+ catch (error) {
348
+ // Uploading unnormalized maps beats not uploading at all.
349
+ return unchanged
350
+ }
351
+
352
+ const cleanup = () => fs.promises.rm(tempDir, { recursive: true, force: true })
353
+ const normalized: Types.SourcemapInfo[] = []
354
+
355
+ for (const [index, sourcemap] of sourcemaps.entries()) {
356
+ try {
357
+ const parsed = JSON.parse(await fs.promises.readFile(sourcemap.sourcemapFilePath, 'utf8'))
358
+ const sources: unknown = parsed.sources
359
+
360
+ if (!Array.isArray(sources) || !sources.some((source) => normalizeSource(String(source)) !== source)) {
361
+ normalized.push(sourcemap)
362
+ continue
363
+ }
364
+
365
+ parsed.sources = sources.map((source) => normalizeSource(String(source)))
366
+ // Named by position, so two maps can never collide in the temp directory.
367
+ const copyPath = path.join(tempDir, `${index}.js.map`)
368
+ await fs.promises.writeFile(copyPath, JSON.stringify(parsed))
369
+ normalized.push({ ...sourcemap, sourcemapFilePath: copyPath })
370
+ }
371
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
372
+ catch (error) {
373
+ // A map we cannot rewrite is still worth uploading as it is.
374
+ normalized.push(sourcemap)
375
+ }
376
+ }
377
+
378
+ return { sourcemaps: normalized, cleanup }
379
+ }
380
+
381
+ /**
382
+ * Removes the *browser* source map files after they have been uploaded.
383
+ *
384
+ * Only for maps this package caused to be generated. `productionBrowserSourceMaps`
385
+ * publishes what it generates and Next.js has no hidden-source-map equivalent, so deleting
386
+ * after upload is what keeps them out of visitors' hands.
387
+ *
388
+ * Server maps are deliberately left alone. `.next/server` is not served, so there is no
389
+ * exposure to undo, and Next.js reads those maps itself when it formats server-side stack
390
+ * traces — deleting them would degrade the project's own logs for no benefit.
391
+ *
392
+ * The `sourceMappingURL` comments in the emitted JavaScript are left behind, so a browser
393
+ * that goes looking will get a 404 rather than the source.
394
+ */
395
+ async function deleteBrowserSourcemapFiles(distDir: string, silent: boolean): Promise<void> {
396
+ // Deliberately every `.js.map` under `static`, not just the ones that were uploaded.
397
+ // `collectSourcemaps` drops maps that are ignored, malformed, unpaired, or missing
398
+ // `sourcesContent` — all of which Next.js still serves. Deleting only what we uploaded
399
+ // would leave exactly those behind, publicly readable, because of an option we turned on.
400
+ const mapFilePaths: string[] = []
401
+ await walk(path.join(distDir, BROWSER_OUTPUT_DIR), (filePath) => {
402
+ if (filePath.endsWith('.js.map')) {
403
+ mapFilePaths.push(filePath)
404
+ }
405
+ })
406
+
407
+ let deleted = 0
408
+ for (const mapFilePath of mapFilePaths) {
409
+ try {
410
+ await fs.promises.unlink(mapFilePath)
411
+ deleted++
412
+ } catch (error) {
413
+ // Loud, and not gated behind `silent`: a map we failed to remove is one this package
414
+ // caused to be served. That is exposure, not cleanup noise.
415
+ log(
416
+ 'warn',
417
+ silent,
418
+ `could not delete ${path.relative(distDir, mapFilePath)}, so it will be served ` +
419
+ `publicly: ${(error as Error).message}`
420
+ )
421
+ }
422
+ }
423
+
424
+ log('debug', silent, `deleted ${deleted} browser source map file(s) from the build output`)
425
+ }
426
+
427
+ /**
428
+ * Uploads the build's source maps to Honeybadger.
429
+ *
430
+ * Registered by `withHoneybadgerConfig` on Next.js's `compiler.runAfterProductionCompile`
431
+ * hook, which runs for both Turbopack and webpack builds.
432
+ *
433
+ * Next.js re-throws whatever this hook throws, which would fail the user's build, so a
434
+ * failed upload is only allowed to propagate when `ignoreErrors` is off.
435
+ */
436
+ export async function uploadSourceMapsAfterBuild(
437
+ honeybadgerNextJsConfig: HoneybadgerNextJsConfig | undefined,
438
+ metadata: AfterProductionCompileMetadata,
439
+ options: { deleteBrowserSourcemaps?: boolean } = {}
440
+ ): Promise<void> {
441
+ // Read from the raw config rather than the resolved options, because the error handling
442
+ // below has to cover resolving them at all: `cleanOptions` can throw, and loading
443
+ // plugin-core can fail outright. Doing that outside the try meant a failure there ignored
444
+ // `ignoreErrors` and skipped the cleanup that keeps browser maps off the wire.
445
+ const silent = honeybadgerNextJsConfig?.silent ?? true
446
+ const ignoreErrors = honeybadgerNextJsConfig?.ignoreErrors ?? false
447
+
448
+ // Outside the try/finally below: a build that never intended to upload also never enabled
449
+ // the browser maps, so there is nothing of ours to clean up. Decided from the raw config
450
+ // so it needs no plugin-core.
451
+ const developmentEnvironments =
452
+ honeybadgerNextJsConfig?.developmentEnvironments ?? DEFAULT_DEVELOPMENT_ENVIRONMENTS
453
+ if (isDevEnv(developmentEnvironments)) {
454
+ log('debug', silent, `skipping source map upload in ${process.env.NODE_ENV}`)
455
+ return
456
+ }
457
+
458
+ try {
459
+ const uploadOptions = await resolveUploadOptions(honeybadgerNextJsConfig)
460
+ if (!uploadOptions) {
461
+ return
462
+ }
463
+
464
+ const { uploadSourcemaps, sendDeployNotification } = await loadPluginCore()
465
+
466
+ const sourcemaps = await collectSourcemaps(metadata.distDir, uploadOptions.ignorePaths)
467
+
468
+ if (sourcemaps.length === 0) {
469
+ // Upload is configured, so finding nothing means something is wrong — a `distDir`
470
+ // that moved, or an `ignorePaths` that matches everything. Silence here would look
471
+ // exactly like success.
472
+ log('warn', silent, `found no source maps to upload in ${metadata.distDir}`)
473
+ return
474
+ }
475
+
476
+ const normalized = await withNormalizedSources(sourcemaps)
477
+ try {
478
+ await uploadSourcemaps(normalized.sourcemaps, uploadOptions)
479
+ } finally {
480
+ await normalized.cleanup()
481
+ }
482
+
483
+ // Only after maps actually went up. A failed upload already skips this by throwing, so
484
+ // announcing a deploy for a build that uploaded nothing was the one inconsistent case —
485
+ // and it reads as "the maps for this revision are in place" when they are not.
486
+ if (uploadOptions.deploy) {
487
+ await sendDeployNotification(uploadOptions)
488
+ }
489
+ } catch (error) {
490
+ if (!ignoreErrors) {
491
+ throw error
492
+ }
493
+
494
+ log('error', silent, `source map upload failed: ${(error as Error).message}`)
495
+ } finally {
496
+ // Unconditionally, including after a failed upload. We enabled
497
+ // `productionBrowserSourceMaps`, so these maps ship publicly unless something removes
498
+ // them — and `ignoreErrors: true`, which the docs recommend so an outage cannot block a
499
+ // deploy, would otherwise turn every failed upload into published source. Keeping them
500
+ // to preserve "the only copy" is not worth that: a rebuild regenerates them, whereas a
501
+ // deploy that served them cannot be recalled.
502
+ if (options.deleteBrowserSourcemaps) {
503
+ try {
504
+ await deleteBrowserSourcemapFiles(metadata.distDir, silent)
505
+ } catch (error) {
506
+ // Never let cleanup mask the upload failure that is already propagating.
507
+ log(
508
+ 'warn',
509
+ silent,
510
+ `could not clean up browser source maps: ${(error as Error).message}`
511
+ )
512
+ }
513
+ }
514
+ }
515
+ }
package/src/types.ts CHANGED
@@ -1,23 +1,40 @@
1
- export type NextJsRuntime = 'server' | 'browser' | 'edge'
1
+ /**
2
+ * Options for `withHoneybadgerConfig`.
3
+ *
4
+ * `apiKey` and `assetsUrl` are what enable source map upload; both fall back to
5
+ * `NEXT_PUBLIC_HONEYBADGER_API_KEY` and `NEXT_PUBLIC_HONEYBADGER_ASSETS_URL`. Everything
6
+ * else is optional and defaulted by `@honeybadger-io/plugin-core`.
7
+ */
2
8
  export type HoneybadgerNextJsConfig = {
3
- disableSourceMapUpload?: boolean
4
- silent?: boolean
5
- webpackPluginOptions?: Omit<HoneybadgerWebpackPluginOptions, 'silent'>
6
- }
7
-
8
- // this should be in @honeybadger-io/webpack
9
- export type HoneybadgerWebpackPluginOptions = {
10
- apiKey: string
11
- assetsUrl: string
12
- revision?: string
13
- endpoint?: string
14
- silent?: boolean
15
- ignoreErrors?: boolean
16
- retries?: number
17
- workerCount?: number
18
- deploy?: false | {
19
- repository?: string,
20
- environment?: string,
21
- localUsername?: string,
22
- }
9
+ /** Honeybadger project API key. */
10
+ apiKey?: string
11
+ /** Public URL of the build output, normally `https://your-site.com/_next`. */
12
+ assetsUrl?: string
13
+ /** Ties uploaded maps to the errors that reference them; they must match to symbolicate. */
14
+ revision?: string
15
+ endpoint?: string
16
+ /** Suppresses this package's informational logging. Warnings and errors always print. */
17
+ silent?: boolean
18
+ /** Log a failed upload instead of failing the build. */
19
+ ignoreErrors?: boolean
20
+ // Globs whose matching maps are not uploaded. Matched against each built JavaScript
21
+ // file's *name*, not its path: `main.js` and `**/main.js` work, while a path pattern such
22
+ // as `static/chunks/*.js` never matches. This mirrors the rollup, esbuild and webpack
23
+ // plugins, which all match with picomatch's `basename` option.
24
+ //
25
+ // Line comments rather than JSDoc because the glob contains `*/`, which would close a
26
+ // block comment.
27
+ ignorePaths?: Array<string>
28
+ /** `NODE_ENV` values for which upload is skipped entirely. */
29
+ developmentEnvironments?: Array<string>
30
+ retries?: number
31
+ workerCount?: number
32
+ /** Send a deploy notification once the maps are uploaded. */
33
+ deploy?: false | {
34
+ repository?: string,
35
+ environment?: string,
36
+ localUsername?: string,
37
+ }
38
+ /** Turn off source map upload without removing the rest of the configuration. */
39
+ disableSourceMapUpload?: boolean
23
40
  }
@@ -1,5 +1,5 @@
1
1
  import NextErrorComponent from 'next/error'
2
- import { Honeybadger } from '@honeybadger-io/react'
2
+ import Honeybadger from '@honeybadger-io/js'
3
3
  /**
4
4
  * This component is called when:
5
5
  * - on the server, when data fetching methods throw or reject
@@ -14,20 +14,24 @@ const CustomErrorComponent = props => {
14
14
  CustomErrorComponent.getInitialProps = async contextData => {
15
15
  const { req, res, err } = contextData
16
16
 
17
+ // Server-side errors are already reported by `onRequestError` in instrumentation, which
18
+ // also covers API routes and middleware that this component never sees. Reporting them
19
+ // here too would duplicate every one, so this only handles the client, where that hook
20
+ // does not run and nothing else catches a failing `getInitialProps`.
21
+ const onServer = Boolean(req)
22
+
17
23
  // exclude 40x except when this component is rendered from a routing error or a custom server
18
24
  // https://nextjs.org/docs/advanced-features/custom-error-page#caveats
19
- const statusCode = (res && res.statusCode) || contextData.statusCode;
20
- if (statusCode && statusCode < 500) {
21
- Honeybadger.config.logger.debug(`_error.js skipping because statusCode is ${statusCode}: ${req && req.url}`)
25
+ const statusCode = (res && res.statusCode) || contextData.statusCode
26
+
27
+ if (onServer || (statusCode && statusCode < 500)) {
28
+ Honeybadger.config.logger.debug(
29
+ `_error.js skipping: onServer=${onServer} statusCode=${statusCode}`
30
+ )
22
31
  }
23
32
  else {
24
33
  await Honeybadger.notifyAsync(err || `_error.js called with falsy error (${err})`, {
25
- context:
26
- {
27
- url: req.url,
28
- method: req.method,
29
- statusCode: res.statusCode,
30
- }
34
+ context: { statusCode }
31
35
  })
32
36
  }
33
37
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  // eslint-disable-next-line import/no-unresolved
4
4
  import { useEffect } from 'react'
5
- import { Honeybadger } from '@honeybadger-io/react'
5
+ import Honeybadger from '@honeybadger-io/js'
6
6
 
7
7
  /**
8
8
  * error.[js|tsx]: https://nextjs.org/docs/app/building-your-application/routing/error-handling
@@ -2,7 +2,7 @@
2
2
 
3
3
  // eslint-disable-next-line import/no-unresolved
4
4
  import { useEffect } from 'react'
5
- import { Honeybadger } from '@honeybadger-io/react'
5
+ import Honeybadger from '@honeybadger-io/js'
6
6
 
7
7
  /**
8
8
  * error.[js|tsx]: https://nextjs.org/docs/app/building-your-application/routing/error-handling
@@ -1,27 +1,16 @@
1
1
  import Honeybadger from '@honeybadger-io/js'
2
2
 
3
- const projectRoot = process.cwd()
4
-
5
3
  export const config = {
6
4
  apiKey: process.env.NEXT_PUBLIC_HONEYBADGER_API_KEY,
7
5
  environment: process.env.NEXT_PUBLIC_VERCEL_ENV || process.env.VERCEL_ENV || process.env.NODE_ENV,
8
6
  revision: process.env.NEXT_PUBLIC_HONEYBADGER_REVISION,
9
- projectRoot: 'webpack:///./',
10
7
  // debug: true,
11
8
  // reportData: true,
9
+ insights: { enabled: true, http: true },
12
10
  }
13
11
 
14
- Honeybadger
15
- .configure(config)
16
- .beforeNotify((notice) => {
17
- if (!notice) {
18
- return
19
- }
20
- notice.backtrace.forEach((line) => {
21
- if (line.file) {
22
- line.file = line.file.replace(`${projectRoot}/.next/server`, `${process.env.NEXT_PUBLIC_HONEYBADGER_ASSETS_URL}/..`)
23
- }
24
- return line
25
- })
26
- })
12
+ // Server-side frames are not symbolicated yet: the paths reported at runtime do not match
13
+ // the source maps uploaded for `.next/server`. Tracked in
14
+ // https://github.com/honeybadger-io/honeybadger-js/issues/1602
15
+ Honeybadger.configure(config)
27
16
  Honeybadger.logger.debug('Honeybadger configured for server')