@honeybadger-io/nextjs 5.11.5 → 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 +34 -12
  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,214 @@
1
+ import type { NextConfig } from 'next'
2
+ import { withHoneybadgerConfig } from './setup'
3
+
4
+ const uploadSourceMapsAfterBuild = jest.fn()
5
+ let uploadConfigured = false
6
+ jest.mock('./source-maps', () => ({
7
+ uploadSourceMapsAfterBuild: (...args: unknown[]) => uploadSourceMapsAfterBuild(...args),
8
+ isSourceMapUploadConfigured: () => uploadConfigured,
9
+ }))
10
+
11
+ type Config = NextConfig & {
12
+ compiler?: { runAfterProductionCompile?: (metadata: { distDir: string; projectDir: string }) => unknown }
13
+ }
14
+
15
+ const metadata = { distDir: '.next', projectDir: '/app' }
16
+
17
+ describe('withHoneybadgerConfig', () => {
18
+ beforeEach(() => {
19
+ uploadConfigured = false
20
+ uploadSourceMapsAfterBuild.mockReset().mockResolvedValue(undefined)
21
+ })
22
+
23
+ describe('serverExternalPackages', () => {
24
+ it('adds the package when the option is absent', () => {
25
+ const result = withHoneybadgerConfig({}) as Config
26
+
27
+ expect(result.serverExternalPackages).toEqual(['@honeybadger-io/js'])
28
+ })
29
+
30
+ it('appends to an existing list rather than replacing it', () => {
31
+ const result = withHoneybadgerConfig({ serverExternalPackages: ['other-package'] }) as Config
32
+
33
+ expect(result.serverExternalPackages).toEqual(['other-package', '@honeybadger-io/js'])
34
+ })
35
+
36
+ it('does not add the package twice', () => {
37
+ const result = withHoneybadgerConfig({
38
+ serverExternalPackages: ['@honeybadger-io/js'],
39
+ }) as Config
40
+
41
+ expect(result.serverExternalPackages).toEqual(['@honeybadger-io/js'])
42
+ })
43
+
44
+ it('leaves the rest of the config untouched', () => {
45
+ const result = withHoneybadgerConfig({ reactStrictMode: true, basePath: '/app' }) as Config
46
+
47
+ expect(result).toMatchObject({ reactStrictMode: true, basePath: '/app' })
48
+ })
49
+
50
+ it('does not mutate the config it was given', () => {
51
+ const original: Config = { serverExternalPackages: ['other-package'] }
52
+
53
+ withHoneybadgerConfig(original)
54
+
55
+ expect(original.serverExternalPackages).toEqual(['other-package'])
56
+ expect(original.compiler).toBeUndefined()
57
+ })
58
+ })
59
+
60
+ describe('source map upload', () => {
61
+ it('registers the post-compile hook', async () => {
62
+ const result = withHoneybadgerConfig({}) as Config
63
+
64
+ await result.compiler?.runAfterProductionCompile?.(metadata)
65
+
66
+ expect(uploadSourceMapsAfterBuild).toHaveBeenCalledWith(undefined, metadata, expect.anything())
67
+ })
68
+
69
+ it('passes the Honeybadger config through to the upload', async () => {
70
+ const hbConfig = { apiKey: 'k', assetsUrl: 'https://example.com/_next' }
71
+ const result = withHoneybadgerConfig({}, hbConfig) as Config
72
+
73
+ await result.compiler?.runAfterProductionCompile?.(metadata)
74
+
75
+ expect(uploadSourceMapsAfterBuild).toHaveBeenCalledWith(hbConfig, metadata, expect.anything())
76
+ })
77
+
78
+ // The hook is a single function, so replacing it outright would silently disable
79
+ // whatever the project already registered there.
80
+ it('runs an existing hook as well, and first', async () => {
81
+ const order: string[] = []
82
+ uploadSourceMapsAfterBuild.mockImplementation(async () => { order.push('honeybadger') })
83
+ const existing = jest.fn(async () => { order.push('existing') })
84
+
85
+ const result = withHoneybadgerConfig({
86
+ compiler: { runAfterProductionCompile: existing },
87
+ }) as Config
88
+ await result.compiler?.runAfterProductionCompile?.(metadata)
89
+
90
+ expect(existing).toHaveBeenCalledWith(metadata)
91
+ expect(order).toEqual(['existing', 'honeybadger'])
92
+ })
93
+
94
+ it('lets an existing hook failure fail the build, without uploading', async () => {
95
+ const existing = jest.fn(async () => { throw new Error('their hook broke') })
96
+
97
+ const result = withHoneybadgerConfig({
98
+ compiler: { runAfterProductionCompile: existing },
99
+ }) as Config
100
+
101
+ await expect(result.compiler?.runAfterProductionCompile?.(metadata))
102
+ .rejects.toThrow('their hook broke')
103
+ expect(uploadSourceMapsAfterBuild).not.toHaveBeenCalled()
104
+ })
105
+
106
+ it('preserves other compiler options', () => {
107
+ const result = withHoneybadgerConfig({
108
+ compiler: { removeConsole: true } as Record<string, unknown>,
109
+ }) as Config
110
+
111
+ expect(result.compiler).toMatchObject({ removeConsole: true })
112
+ expect(typeof result.compiler?.runAfterProductionCompile).toBe('function')
113
+ })
114
+ })
115
+
116
+ describe('productionBrowserSourceMaps', () => {
117
+ // Next.js emits no production browser source maps by default, so upload would find
118
+ // nothing. The webpack plugin this replaces got them via `devtool: hidden-source-map`,
119
+ // which has no Turbopack equivalent.
120
+ it('turns it on when upload is configured, and deletes the maps afterwards', async () => {
121
+ uploadConfigured = true
122
+
123
+ const result = withHoneybadgerConfig({}) as Config
124
+ await result.compiler?.runAfterProductionCompile?.(metadata)
125
+
126
+ expect(result.productionBrowserSourceMaps).toBe(true)
127
+ expect(uploadSourceMapsAfterBuild).toHaveBeenCalledWith(
128
+ undefined, metadata, { deleteBrowserSourcemaps: true }
129
+ )
130
+ })
131
+
132
+ it('leaves it alone when upload is not configured', () => {
133
+ uploadConfigured = false
134
+
135
+ const result = withHoneybadgerConfig({}) as Config
136
+
137
+ expect(result.productionBrowserSourceMaps).toBeUndefined()
138
+ })
139
+
140
+ // Somebody who asked for served source maps meant it, so we neither re-enable nor
141
+ // delete behind them.
142
+ it('respects an explicit true, and does not delete their maps', async () => {
143
+ uploadConfigured = true
144
+
145
+ const result = withHoneybadgerConfig({ productionBrowserSourceMaps: true }) as Config
146
+ await result.compiler?.runAfterProductionCompile?.(metadata)
147
+
148
+ expect(result.productionBrowserSourceMaps).toBe(true)
149
+ expect(uploadSourceMapsAfterBuild).toHaveBeenCalledWith(
150
+ undefined, metadata, { deleteBrowserSourcemaps: false }
151
+ )
152
+ })
153
+
154
+ it('respects an explicit false', () => {
155
+ uploadConfigured = true
156
+
157
+ const result = withHoneybadgerConfig({ productionBrowserSourceMaps: false }) as Config
158
+
159
+ expect(result.productionBrowserSourceMaps).toBe(false)
160
+ })
161
+ })
162
+
163
+ // `productionBrowserSourceMaps` covers only the browser build. The webpack plugin this
164
+ // replaces set `devtool: 'hidden-source-map'` with no `isServer` guard, so server maps
165
+ // were written too — see honeybadger-js#1602. Without this option the hook has strictly
166
+ // less to collect than the old plugin generated.
167
+ describe('experimental.serverSourceMaps', () => {
168
+ it('turns it on when upload is configured', () => {
169
+ uploadConfigured = true
170
+
171
+ const result = withHoneybadgerConfig({}) as Config
172
+
173
+ expect(result.experimental?.serverSourceMaps).toBe(true)
174
+ })
175
+
176
+ it('does not introduce the key when upload is not configured', () => {
177
+ uploadConfigured = false
178
+
179
+ const result = withHoneybadgerConfig({}) as Config
180
+
181
+ expect('experimental' in result).toBe(false)
182
+ })
183
+
184
+ it('preserves other experimental options', () => {
185
+ uploadConfigured = true
186
+
187
+ const result = withHoneybadgerConfig({
188
+ experimental: { cssChunking: true } as Record<string, unknown>,
189
+ }) as Config
190
+
191
+ expect(result.experimental).toMatchObject({ cssChunking: true, serverSourceMaps: true })
192
+ })
193
+
194
+ it.each([true, false])('respects an explicit %s', (explicit) => {
195
+ uploadConfigured = true
196
+
197
+ const result = withHoneybadgerConfig({
198
+ experimental: { serverSourceMaps: explicit },
199
+ }) as Config
200
+
201
+ expect(result.experimental?.serverSourceMaps).toBe(explicit)
202
+ })
203
+
204
+ // The browser switch is independent: somebody who set productionBrowserSourceMaps
205
+ // themselves should still get server maps.
206
+ it('turns it on even when the browser maps were set explicitly', () => {
207
+ uploadConfigured = true
208
+
209
+ const result = withHoneybadgerConfig({ productionBrowserSourceMaps: true }) as Config
210
+
211
+ expect(result.experimental?.serverSourceMaps).toBe(true)
212
+ })
213
+ })
214
+ })
package/src/setup.ts ADDED
@@ -0,0 +1,172 @@
1
+ import { HoneybadgerNextJsConfig } from './types'
2
+ import { isSourceMapUploadConfigured, uploadSourceMapsAfterBuild } from './source-maps'
3
+ import type { AfterProductionCompileMetadata } from './source-maps'
4
+
5
+ const HONEYBADGER_JS_PACKAGE = '@honeybadger-io/js'
6
+
7
+ let _silent = true
8
+
9
+ function log(type: 'error' | 'warn' | 'debug', msg: string): void {
10
+ if (['error', 'warn'].includes(type) || !_silent) {
11
+ console[type]('[HoneybadgerNextJs]', msg)
12
+ }
13
+ }
14
+
15
+ /**
16
+ * Next.js warns when a package that requires files dynamically is bundled into the
17
+ * server build. @honeybadger-io/js does exactly that, so it has to be listed as an
18
+ * external package.
19
+ *
20
+ * First reported in https://github.com/honeybadger-io/honeybadger-js/issues/1351,
21
+ * caused by https://github.com/honeybadger-io/honeybadger-js/pull/1268.
22
+ *
23
+ * `serverExternalPackages` is unconditionally available from Next 15 onwards, which is
24
+ * this package's minimum supported version, so the older
25
+ * `experimental.serverComponentsExternalPackages` fallback is gone.
26
+ */
27
+ function withHoneybadgerExternalized(serverExternalPackages: unknown): string[] {
28
+ if (!Array.isArray(serverExternalPackages)) {
29
+ log('debug', `adding serverExternalPackages option with value ["${HONEYBADGER_JS_PACKAGE}"]`)
30
+ return [HONEYBADGER_JS_PACKAGE]
31
+ }
32
+
33
+ if (serverExternalPackages.includes(HONEYBADGER_JS_PACKAGE)) {
34
+ return serverExternalPackages as string[]
35
+ }
36
+
37
+ log('debug', `adding ${HONEYBADGER_JS_PACKAGE} to serverExternalPackages`)
38
+ return [...serverExternalPackages as string[], HONEYBADGER_JS_PACKAGE]
39
+ }
40
+
41
+ type CompilerConfig = {
42
+ runAfterProductionCompile?: (metadata: AfterProductionCompileMetadata) => unknown
43
+ }
44
+
45
+ type ExperimentalConfig = {
46
+ serverSourceMaps?: boolean
47
+ }
48
+
49
+ /**
50
+ * The parts of a Next.js config this function reads.
51
+ *
52
+ * Structural on purpose, rather than `import type { NextConfig } from 'next'`. Importing it
53
+ * would bake whichever Next.js version this package was built against into the published
54
+ * declaration files, and `NextConfig` is not compatible across the supported range — Next 16
55
+ * widened `headers()` to return `Header[] | Promise<Header[]>`, so a Next 16 user passing
56
+ * their own `NextConfig` got a type error against our Next 15 copy of it.
57
+ *
58
+ * This is the type the config is *read* through, not the generic constraint. Constraining
59
+ * to it directly is not possible: the two things callers do are mutually exclusive under
60
+ * excess-property checking. `NextConfig` is an interface with no index signature, so a
61
+ * constraint carrying `[key: string]: unknown` rejects it — while a constraint without one
62
+ * rejects an inline literal that sets any other Next.js option, such as `reactStrictMode`.
63
+ * So the generic stays `object` and the strictness lives at the call site, where the caller
64
+ * annotates their own config as `NextConfig`.
65
+ */
66
+ type NextConfigLike = {
67
+ serverExternalPackages?: string[]
68
+ productionBrowserSourceMaps?: boolean
69
+ experimental?: ExperimentalConfig
70
+ compiler?: CompilerConfig
71
+ }
72
+
73
+ /**
74
+ * Registers the source map upload on Next.js's post-compile hook, composing with any hook
75
+ * the project already declares rather than replacing it.
76
+ *
77
+ * The hook is invoked from Next.js's generic build pipeline, so it runs for both Turbopack
78
+ * and webpack builds. Next.js documents it as being "useful for third-party tools to
79
+ * collect build outputs like sourcemaps".
80
+ */
81
+ function withSourceMapUpload(
82
+ compiler: CompilerConfig | undefined,
83
+ honeybadgerNextJsConfig: HoneybadgerNextJsConfig | undefined,
84
+ deleteBrowserSourcemaps: boolean
85
+ ): CompilerConfig {
86
+ const existingHook = compiler?.runAfterProductionCompile
87
+
88
+ return {
89
+ ...compiler,
90
+ runAfterProductionCompile: async (metadata: AfterProductionCompileMetadata) => {
91
+ // The project's own hook runs first, and is not swallowed: if it throws, that is
92
+ // its build failing, not ours.
93
+ if (typeof existingHook === 'function') {
94
+ await existingHook(metadata)
95
+ }
96
+
97
+ await uploadSourceMapsAfterBuild(honeybadgerNextJsConfig, metadata, { deleteBrowserSourcemaps })
98
+ },
99
+ }
100
+ }
101
+
102
+ /**
103
+ * Opts into server source maps, so frames from `.next/server` can be symbolicated too.
104
+ *
105
+ * `productionBrowserSourceMaps` covers only the browser build, so without this option
106
+ * there are no server maps to collect at all. Whether the uploaded server maps actually
107
+ * match the frames reported at runtime is tracked in
108
+ * https://github.com/honeybadger-io/honeybadger-js/issues/1602.
109
+ *
110
+ * Unlike the browser maps, these are never published: `.next/server` is not served, so
111
+ * they are left in place after upload rather than deleted.
112
+ */
113
+ function withServerSourceMaps(
114
+ experimental: ExperimentalConfig | undefined,
115
+ enable: boolean
116
+ ): ExperimentalConfig | undefined {
117
+ // An explicit setting is the project's call, either way.
118
+ if (!enable || experimental?.serverSourceMaps !== undefined) {
119
+ return experimental
120
+ }
121
+
122
+ log('debug', 'enabling experimental.serverSourceMaps so server frames can be symbolicated')
123
+ return { ...experimental, serverSourceMaps: true }
124
+ }
125
+
126
+ /**
127
+ * Wraps a Next.js config so Honeybadger's build-time requirements are applied: the
128
+ * `@honeybadger-io/js` externalization, and source map upload after a production build.
129
+ *
130
+ * Instrumentation itself is not set up here — that moved to the bundler-agnostic
131
+ * `instrumentation.ts` / `instrumentation-client.ts` conventions, so it works under both
132
+ * Turbopack and webpack. See https://github.com/honeybadger-io/honeybadger-js/issues/1434.
133
+ */
134
+ export function withHoneybadgerConfig<T extends object>(
135
+ config: T = {} as T,
136
+ honeybadgerNextJsConfig?: HoneybadgerNextJsConfig
137
+ ): T {
138
+ _silent = honeybadgerNextJsConfig?.silent ?? true
139
+
140
+ const given = config as NextConfigLike
141
+
142
+ const uploadConfigured = isSourceMapUploadConfigured(honeybadgerNextJsConfig)
143
+
144
+ // Next.js does not emit production browser source maps unless asked, so upload would
145
+ // find nothing to send. `productionBrowserSourceMaps` is the only switch, and it also
146
+ // serves the maps it generates.
147
+ //
148
+ // So turn it on when upload is configured, and have the post-build step delete the maps
149
+ // once they are uploaded. An explicit setting is always respected: a project that asked
150
+ // for served source maps keeps them, and keeps them served.
151
+ const enableBrowserSourceMaps =
152
+ given.productionBrowserSourceMaps === undefined && uploadConfigured
153
+
154
+ const experimental = withServerSourceMaps(
155
+ given.experimental,
156
+ uploadConfigured
157
+ )
158
+
159
+ return {
160
+ ...config,
161
+ serverExternalPackages: withHoneybadgerExternalized(given.serverExternalPackages),
162
+ productionBrowserSourceMaps: enableBrowserSourceMaps ? true : given.productionBrowserSourceMaps,
163
+ // Only introduce the key when there is something to put in it, so a config that never
164
+ // mentioned `experimental` does not suddenly grow the field.
165
+ ...(experimental ? { experimental } : {}),
166
+ compiler: withSourceMapUpload(
167
+ given.compiler,
168
+ honeybadgerNextJsConfig,
169
+ enableBrowserSourceMaps
170
+ ),
171
+ } as T
172
+ }