@djangocfg/devtools 2.1.638 → 2.1.639

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.
package/README.md CHANGED
@@ -39,3 +39,13 @@ await serverDevtools.captureError(err, { url: req.url })
39
39
  ```
40
40
 
41
41
  In the browser console: `window.devtools.status()`, `window.devtools.error('test')`.
42
+
43
+ ## Is it reaching the backend?
44
+
45
+ Ingest needs the API origin: `<Devtools baseUrl>`, or in `BaseApp` `auth.apiUrl` /
46
+ `apiUrl` (for `auth={false}`), or `NEXT_PUBLIC_API_URL` baked in at build time.
47
+ With none, devtools warns once in the console and drops events.
48
+
49
+ - `devtools.status()` returns `{ ingest, baseUrl, queued, sent, failed, lastError, lastSentAt, circuitOpen }`.
50
+ - `await devtools.ping()` sends one info event (`devtools ping`) and resolves with `status()`.
51
+ - Server: `python manage.py monitor_tail --frontend`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@djangocfg/devtools",
3
- "version": "2.1.638",
3
+ "version": "2.1.639",
4
4
  "description": "Frontend devtools for django-cfg apps: error/console capture with backend ingest, plus a floating debug panel. One package, one event stream.",
5
5
  "keywords": [
6
6
  "django",
@@ -51,18 +51,18 @@
51
51
  "test:watch": "vitest"
52
52
  },
53
53
  "peerDependencies": {
54
- "@djangocfg/api": "^2.1.638",
55
- "@djangocfg/ui-core": "^2.1.638",
54
+ "@djangocfg/api": "^2.1.639",
55
+ "@djangocfg/ui-core": "^2.1.639",
56
56
  "lucide-react": ">=0.400.0",
57
57
  "react": "^19.0.0",
58
58
  "react-dom": "^19.0.0",
59
59
  "zustand": "^5.0.0"
60
60
  },
61
61
  "devDependencies": {
62
- "@djangocfg/api": "^2.1.638",
63
- "@djangocfg/eslint-config": "^2.1.638",
64
- "@djangocfg/typescript-config": "^2.1.638",
65
- "@djangocfg/ui-core": "^2.1.638",
62
+ "@djangocfg/api": "^2.1.639",
63
+ "@djangocfg/eslint-config": "^2.1.639",
64
+ "@djangocfg/typescript-config": "^2.1.639",
65
+ "@djangocfg/ui-core": "^2.1.639",
66
66
  "@storybook/react-vite": "^10.6.5",
67
67
  "@types/node": "^25.9.5",
68
68
  "@types/react": "19.3.0",
@@ -0,0 +1,61 @@
1
+ // @vitest-environment jsdom
2
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
3
+
4
+ import { sendBatch } from '../ingest';
5
+ import type { DevtoolsEvent } from '../types';
6
+
7
+ const EVENT = { event_type: 'JS_ERROR', message: 'boom' } as unknown as DevtoolsEvent;
8
+ const KEY = 'cfg.auth.access_token';
9
+
10
+ function stubFetch() {
11
+ const fetchMock = vi.fn().mockResolvedValue({ ok: true, status: 202 });
12
+ vi.stubGlobal('fetch', fetchMock);
13
+ return fetchMock;
14
+ }
15
+
16
+ function headersOf(fetchMock: ReturnType<typeof vi.fn>): Record<string, string> {
17
+ return fetchMock.mock.calls[0]![1].headers as Record<string, string>;
18
+ }
19
+
20
+ function clearTokens() {
21
+ document.cookie = `${KEY}=; Max-Age=0; path=/`;
22
+ localStorage.removeItem(KEY);
23
+ sessionStorage.removeItem(KEY);
24
+ }
25
+
26
+ describe('ingest sends the signed-in user', () => {
27
+ beforeEach(clearTokens);
28
+ afterEach(() => {
29
+ clearTokens();
30
+ vi.unstubAllGlobals();
31
+ });
32
+
33
+ it('sends no Authorization header without a token, body unchanged', async () => {
34
+ const f = stubFetch();
35
+ await sendBatch('https://api.example.com', [EVENT]);
36
+ expect(headersOf(f).Authorization).toBeUndefined();
37
+ expect(headersOf(f)['Content-Type']).toBe('application/json');
38
+ expect(JSON.parse(f.mock.calls[0]![1].body)).toEqual({ events: [EVENT] });
39
+ });
40
+
41
+ it.each([
42
+ ['cookie', () => { document.cookie = `${KEY}=tok-cookie; path=/`; }, 'tok-cookie'],
43
+ ['localStorage', () => localStorage.setItem(KEY, 'tok-local'), 'tok-local'],
44
+ ['sessionStorage', () => sessionStorage.setItem(KEY, 'tok-session'), 'tok-session'],
45
+ ])('reads the token the api client stored in %s', async (_name, put, token) => {
46
+ put();
47
+ const f = stubFetch();
48
+ await sendBatch('https://api.example.com', [EVENT]);
49
+ expect(headersOf(f).Authorization).toBe(`Bearer ${token}`);
50
+ expect(JSON.parse(f.mock.calls[0]![1].body)).toEqual({ events: [EVENT] });
51
+ });
52
+
53
+ it('keeps the unload flush CORS-simple: text/plain and no Authorization', async () => {
54
+ localStorage.setItem(KEY, 'tok-local');
55
+ const f = stubFetch();
56
+ await sendBatch('https://api.example.com', [EVENT], true);
57
+ expect(headersOf(f)['Content-Type']).toBe('text/plain');
58
+ expect(headersOf(f).Authorization).toBeUndefined();
59
+ expect(f.mock.calls[0]![1].keepalive).toBe(true);
60
+ });
61
+ });
@@ -0,0 +1,96 @@
1
+ // @vitest-environment jsdom
2
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
3
+
4
+ /**
5
+ * `devtools.status()`, the no-baseUrl warning and `devtools.ping()`.
6
+ * Modules are re-imported per test: the warning is once per page load and the
7
+ * store is a singleton.
8
+ */
9
+ async function load() {
10
+ vi.resetModules();
11
+ return (await import('../instance')).devtools;
12
+ }
13
+
14
+ describe('devtools ingest diagnostics', () => {
15
+ let warn: ReturnType<typeof vi.spyOn>;
16
+
17
+ beforeEach(() => {
18
+ vi.stubEnv('NEXT_PUBLIC_API_URL', '');
19
+ // rawConsole binds console.warn at import time, so spy before importing.
20
+ warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
21
+ });
22
+
23
+ afterEach(() => {
24
+ vi.unstubAllEnvs();
25
+ vi.unstubAllGlobals();
26
+ vi.restoreAllMocks();
27
+ });
28
+
29
+ it('warns once, loudly, when ingest is on and no base URL resolves', async () => {
30
+ const devtools = await load();
31
+ devtools.init({ captureConsole: false });
32
+ devtools.destroy();
33
+ devtools.init({ captureConsole: false });
34
+ devtools.destroy();
35
+
36
+ const calls = warn.mock.calls.filter((c: unknown[]) => String(c[0]).includes('[devtools]'));
37
+ expect(calls).toHaveLength(1);
38
+ expect(String(calls[0]?.[0])).toContain('baseUrl');
39
+ expect(String(calls[0]?.[0])).toContain('NEXT_PUBLIC_API_URL');
40
+ });
41
+
42
+ it('does not warn when ingest is off or a baseUrl is given', async () => {
43
+ const devtools = await load();
44
+ devtools.init({ ingest: false, captureConsole: false });
45
+ devtools.destroy();
46
+ devtools.init({ baseUrl: 'https://api.example.com', captureConsole: false });
47
+ devtools.destroy();
48
+ expect(warn.mock.calls.filter((c: unknown[]) => String(c[0]).includes('[devtools]'))).toHaveLength(0);
49
+ });
50
+
51
+ it('status() reports a dropped event when there is no base URL', async () => {
52
+ const devtools = await load();
53
+ devtools.init({ captureConsole: false });
54
+ devtools.error('boom');
55
+ await devtools.ping();
56
+ const s = devtools.status();
57
+ devtools.destroy();
58
+ expect(s.ingest).toBe(true);
59
+ expect(s.baseUrl).toBe('');
60
+ expect(s.sent).toBe(0);
61
+ expect(s.failed).toBeGreaterThan(0);
62
+ expect(s.lastError).toContain('no baseUrl');
63
+ });
64
+
65
+ it('ping() posts one info event to the ingest endpoint and status() counts it', async () => {
66
+ const fetchMock = vi.fn().mockResolvedValue({ ok: true, status: 202 });
67
+ vi.stubGlobal('fetch', fetchMock);
68
+ const devtools = await load();
69
+ devtools.init({ baseUrl: 'https://api.example.com', captureConsole: false });
70
+
71
+ const s = await devtools.ping();
72
+ devtools.destroy();
73
+
74
+ expect(fetchMock).toHaveBeenCalledTimes(1);
75
+ const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
76
+ expect(url).toBe('https://api.example.com/cfg/monitor/ingest/');
77
+ const { events } = JSON.parse(String(init.body));
78
+ expect(events).toHaveLength(1);
79
+ expect(events[0].message).toBe('devtools ping');
80
+ expect(events[0].level).toBe('info');
81
+ expect(s).toMatchObject({ ingest: true, baseUrl: 'https://api.example.com', queued: 0, sent: 1, failed: 0, lastError: null, circuitOpen: false });
82
+ expect(s.lastSentAt).toBeTypeOf('number');
83
+ });
84
+
85
+ it('status() records a failed send and keeps the events queued', async () => {
86
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false, status: 502 }));
87
+ const devtools = await load();
88
+ devtools.init({ baseUrl: 'https://api.example.com', captureConsole: false });
89
+ const s = await devtools.ping();
90
+ devtools.destroy();
91
+ expect(s.sent).toBe(0);
92
+ expect(s.failed).toBe(1);
93
+ expect(s.queued).toBe(1);
94
+ expect(s.lastError).toBe('ingest 502');
95
+ });
96
+ });
package/src/index.ts CHANGED
@@ -27,6 +27,7 @@ export type {
27
27
  CustomDebugTab,
28
28
  DevtoolsConfig,
29
29
  DevtoolsEvent,
30
+ DevtoolsStatus,
30
31
  LogEntry,
31
32
  Logger,
32
33
  LogLevel,
package/src/ingest.ts CHANGED
@@ -2,7 +2,10 @@
2
2
  * Ingest transport — one plain fetch to `POST /cfg/monitor/ingest/`.
3
3
  *
4
4
  * The endpoint is AllowAny + rate-limited on the backend and always answers
5
- * 202; nothing here needs auth headers or a generated client.
5
+ * 202; nothing here needs a generated client. When the visitor is signed in, the
6
+ * regular send adds `Authorization: Bearer <access token>` (see `readAccessToken`)
7
+ * so the server can log the user's id next to the error; with no token the
8
+ * request is exactly what it was, and an invalid token is ignored server-side.
6
9
  *
7
10
  * ─────────────────────────────────────────────────────────────────────────────
8
11
  * WHY THIS DOES NOT USE @djangocfg/analytics' BeaconTransport
@@ -32,9 +35,32 @@
32
35
  * Same trap, same fix, as @djangocfg/analytics. Verified in Chrome 149.
33
36
  */
34
37
 
38
+ import { CFG_KEYS, cfgStorage } from '@djangocfg/api/storage'
39
+
35
40
  import { INGEST_PATH } from './internal'
36
41
  import type { DevtoolsEvent } from './types'
37
42
 
43
+ /**
44
+ * The access token the `@djangocfg/api` client sends, or null.
45
+ *
46
+ * Read from the same registry key (`cfg.auth.access_token`) in the order the client
47
+ * can have stored it: the shared cookie (default), then localStorage, then
48
+ * sessionStorage (hosts that called `setStorageMode`). Browser only; the Node
49
+ * `server` entry has no token and sends none.
50
+ */
51
+ export function readAccessToken(): string | null {
52
+ if (typeof window === 'undefined') return null
53
+ for (const store of ['cookie', 'local', 'session'] as const) {
54
+ try {
55
+ const value = cfgStorage.read(CFG_KEYS.accessToken.key, store)
56
+ if (value) return value
57
+ } catch {
58
+ /* storage blocked: try the next one */
59
+ }
60
+ }
61
+ return null
62
+ }
63
+
38
64
  export async function sendBatch(
39
65
  baseUrl: string,
40
66
  events: DevtoolsEvent[],
@@ -50,12 +76,21 @@ export async function sendBatch(
50
76
  // Returning cleanly keeps the breaker closed and the app silent.
51
77
  if (!baseUrl) return
52
78
 
79
+ const headers: Record<string, string> = {
80
+ // Unload flushes must stay CORS-simple or they never leave the browser.
81
+ 'Content-Type': useBeacon ? 'text/plain' : 'application/json',
82
+ }
83
+ // `Authorization` is not CORS-safelisted either: on the unload flush it would bring
84
+ // the preflight back and lose the very event that mattered. So the unload flush is
85
+ // sent anonymous; every regular flush (5 s timer, buffer full, ping) carries the user.
86
+ if (!useBeacon) {
87
+ const token = readAccessToken()
88
+ if (token) headers.Authorization = `Bearer ${token}`
89
+ }
90
+
53
91
  const res = await fetch(`${baseUrl}${INGEST_PATH}`, {
54
92
  method: 'POST',
55
- headers: {
56
- // Unload flushes must stay CORS-simple or they never leave the browser.
57
- 'Content-Type': useBeacon ? 'text/plain' : 'application/json',
58
- },
93
+ headers,
59
94
  body: JSON.stringify({ events }),
60
95
  credentials: 'include',
61
96
  ...(useBeacon ? { keepalive: true } : {}),
package/src/instance.ts CHANGED
@@ -16,8 +16,9 @@ import {
16
16
  import { DEFAULT_FLUSH_INTERVAL, getSessionId, isDevelopment, rawConsole } from './internal'
17
17
  import { devtoolsStore } from './store'
18
18
  import { EventLevel, EventType } from './types'
19
- import type { DevtoolsConfig, DevtoolsEvent, Logger } from './types'
19
+ import type { DevtoolsConfig, DevtoolsEvent, DevtoolsStatus, Logger } from './types'
20
20
 
21
+ let warnedNoBaseUrl = false
21
22
  let flushTimer: ReturnType<typeof setInterval> | null = null
22
23
  const cleanups: Array<() => void> = []
23
24
 
@@ -68,6 +69,15 @@ export const devtools = {
68
69
  baseUrl: config.baseUrl ?? process.env.NEXT_PUBLIC_API_URL ?? '',
69
70
  }
70
71
  devtoolsStore.getState().setConfig(resolved)
72
+ if (resolved.ingest !== false && !resolved.baseUrl && !warnedNoBaseUrl) {
73
+ warnedNoBaseUrl = true
74
+ // rawConsole: the wrapped console.warn would feed this line into capture.
75
+ rawConsole.warn(
76
+ '[devtools] ingest is on but no base URL resolved, so browser errors are NOT sent to the backend. ' +
77
+ "Fix: pass devtools={{ baseUrl: 'https://api.example.com' }} (or BaseApp apiUrl / auth.apiUrl), " +
78
+ 'or declare NEXT_PUBLIC_API_URL at build time (turbo env is an allow-list). Check with window.devtools.status().',
79
+ )
80
+ }
71
81
  getSessionId() // ensure the session cookie exists
72
82
 
73
83
  if (resolved.captureJsErrors !== false) cleanups.push(installJsErrorCapture())
@@ -164,18 +174,46 @@ export const devtools = {
164
174
 
165
175
  /** Force-flush the ingest outbox. */
166
176
  flush(): void {
167
- devtoolsStore.getState().flush()
177
+ void devtoolsStore.getState().flush()
168
178
  },
169
179
 
170
- /** Print current state to the console (for `window.devtools.status()`). */
171
- status(): void {
180
+ /**
181
+ * State of the ingest pipe, also printed to the console. Returns
182
+ * {ingest, baseUrl, queued, sent, failed, lastError, lastSentAt, circuitOpen}.
183
+ */
184
+ status(): DevtoolsStatus {
172
185
  const s = devtoolsStore.getState()
186
+ const result: DevtoolsStatus = {
187
+ ingest: s.config.ingest !== false,
188
+ baseUrl: s.config.baseUrl ?? '',
189
+ queued: s.outbox.length,
190
+ sent: s._sent,
191
+ failed: s._failed,
192
+ lastError: s._lastError,
193
+ lastSentAt: s._lastSentAt,
194
+ circuitOpen: Date.now() < s._pausedUntil,
195
+ }
173
196
  console.group('[devtools] status')
197
+ console.log('ingest:', result)
174
198
  console.log('config:', s.config)
175
199
  console.log('panel entries:', s.entries.length)
176
- console.log('ingest outbox:', s.outbox.length)
177
200
  console.log('session_id:', getSessionId())
178
201
  console.groupEnd()
202
+ return result
203
+ },
204
+
205
+ /**
206
+ * End-to-end check: sends one info-level `devtools ping` event to the backend
207
+ * now (django_monitor logs it, never alerts) and resolves with `status()`.
208
+ * Then `manage.py monitor_tail --frontend` shows it on the server.
209
+ */
210
+ async ping(): Promise<DevtoolsStatus> {
211
+ const s = devtoolsStore.getState()
212
+ const event = makeEvent(EventType.WARNING, EventLevel.INFO, 'devtools ping', { ping: true })
213
+ // A unique fingerprint: the dedupe would drop a second ping within 30 s.
214
+ s.capture({ ...event, fingerprint: `devtools-ping-${Date.now()}` })
215
+ await devtoolsStore.getState().flush()
216
+ return devtools.status()
179
217
  },
180
218
  }
181
219
 
package/src/store.ts CHANGED
@@ -56,13 +56,19 @@ export interface DevtoolsState {
56
56
  // Circuit breaker
57
57
  _failures: number
58
58
  _pausedUntil: number
59
+ // Ingest counters, read by `devtools.status()`
60
+ _sent: number
61
+ _failed: number
62
+ _lastError: string | null
63
+ _lastSentAt: number | null
59
64
 
60
65
  setConfig: (config: DevtoolsConfig) => void
61
66
  /** Add a local panel entry (loggers, custom instrumentation). Never ingested. */
62
67
  addEntry: (entry: Omit<LogEntry, 'id' | 'timestamp'>) => void
63
68
  /** Capture an event: panel entry + (if enabled) ingest outbox. */
64
69
  capture: (event: DevtoolsEvent) => void
65
- flush: (useBeacon?: boolean) => void
70
+ /** Send the outbox now. Resolves when the batch was delivered or failed. */
71
+ flush: (useBeacon?: boolean) => Promise<void>
66
72
  clearEntries: () => void
67
73
  // Panel UI
68
74
  openPanel: () => void
@@ -79,6 +85,10 @@ export const devtoolsStore = createStore<DevtoolsState>((set, get) => ({
79
85
  tab: 'logs',
80
86
  _failures: 0,
81
87
  _pausedUntil: 0,
88
+ _sent: 0,
89
+ _failed: 0,
90
+ _lastError: null,
91
+ _lastSentAt: null,
82
92
 
83
93
  setConfig(config) {
84
94
  set({ config })
@@ -140,20 +150,31 @@ export const devtoolsStore = createStore<DevtoolsState>((set, get) => ({
140
150
  set({ outbox })
141
151
 
142
152
  if (outbox.length >= (config.maxBufferSize ?? DEFAULT_MAX_BUFFER) || event.level === 'error') {
143
- get().flush()
153
+ void get().flush()
144
154
  }
145
155
  },
146
156
 
147
157
  flush(useBeacon = false) {
148
158
  const { outbox, config, _pausedUntil } = get()
149
- if (outbox.length === 0 || Date.now() < _pausedUntil) return
159
+ if (outbox.length === 0 || Date.now() < _pausedUntil) return Promise.resolve()
150
160
 
151
161
  const batch = outbox.slice(0, MAX_BATCH)
152
162
  set({ outbox: outbox.slice(MAX_BATCH) })
153
163
 
154
- sendBatch(config.baseUrl ?? '', batch, useBeacon).then(
155
- () => set({ _failures: 0, _pausedUntil: 0 }),
156
- () => {
164
+ // No API origin: sendBatch would drop the batch silently. Count it as
165
+ // failed and say why, so `devtools.status()` shows the misconfiguration.
166
+ // Not a transport failure, so the circuit breaker stays closed.
167
+ if (!config.baseUrl) {
168
+ set({
169
+ _failed: get()._failed + batch.length,
170
+ _lastError: 'no baseUrl: events dropped (pass devtools={{ baseUrl }} or set NEXT_PUBLIC_API_URL)',
171
+ })
172
+ return Promise.resolve()
173
+ }
174
+
175
+ return sendBatch(config.baseUrl, batch, useBeacon).then(
176
+ () => set({ _failures: 0, _pausedUntil: 0, _sent: get()._sent + batch.length, _lastSentAt: Date.now() }),
177
+ (err: unknown) => {
157
178
  const failures = get()._failures + 1
158
179
  // Put the batch back, ahead of whatever arrived meanwhile: a failed
159
180
  // send must not consume the events. Dropping them here would lose
@@ -164,6 +185,8 @@ export const devtoolsStore = createStore<DevtoolsState>((set, get) => ({
164
185
  set({
165
186
  outbox: requeued.length > MAX_OUTBOX ? requeued.slice(-MAX_OUTBOX) : requeued,
166
187
  _failures: failures,
188
+ _failed: get()._failed + batch.length,
189
+ _lastError: err instanceof Error ? err.message : String(err),
167
190
  _pausedUntil:
168
191
  failures >= BREAKER_THRESHOLD ? Date.now() + BREAKER_COOLDOWN_MS : get()._pausedUntil,
169
192
  })
package/src/types.ts CHANGED
@@ -49,7 +49,11 @@ export interface DevtoolsEvent {
49
49
  // ─── Config ──────────────────────────────────────────────────────────────────
50
50
 
51
51
  export interface DevtoolsConfig {
52
- /** Base URL for the django-cfg backend. Default: NEXT_PUBLIC_API_URL or same origin */
52
+ /**
53
+ * Base URL for the django-cfg backend. Default: NEXT_PUBLIC_API_URL. With no value
54
+ * at all ingest cannot send: devtools warns once in the console and
55
+ * `devtools.status()` shows `baseUrl: ''`. BaseApp fills it from `auth.apiUrl`.
56
+ */
53
57
  baseUrl?: string
54
58
  /** Project name sent with every event */
55
59
  project?: string
@@ -73,6 +77,25 @@ export interface DevtoolsConfig {
73
77
  debug?: boolean
74
78
  }
75
79
 
80
+ /** What `devtools.status()` returns: the state of the ingest pipe. */
81
+ export interface DevtoolsStatus {
82
+ /** Ingest is enabled (`ingest !== false`) */
83
+ ingest: boolean
84
+ /** Resolved API origin; empty means events are dropped */
85
+ baseUrl: string
86
+ /** Events waiting in the outbox */
87
+ queued: number
88
+ /** Events the backend accepted (2xx) */
89
+ sent: number
90
+ /** Events that failed to send or were dropped */
91
+ failed: number
92
+ lastError: string | null
93
+ /** ms epoch of the last successful send */
94
+ lastSentAt: number | null
95
+ /** Ingest paused by the circuit breaker after repeated failures */
96
+ circuitOpen: boolean
97
+ }
98
+
76
99
  export interface ServerDevtoolsConfig {
77
100
  /** Base URL for the django-cfg backend (absolute URL required on server) */
78
101
  baseUrl?: string