@reliantlabs/forge-web-runtime 0.3.0 → 0.3.2
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 +25 -25
- package/dist/devlog.d.ts +50 -0
- package/dist/devlog.js +449 -0
- package/dist/devlog.js.map +1 -0
- package/dist/error-boundary.js +2 -1
- package/dist/error-boundary.js.map +1 -1
- package/dist/errors.js.map +1 -1
- package/dist/index.d.ts +8 -0
- package/dist/index.js +8 -0
- package/dist/index.js.map +1 -1
- package/dist/interceptors.js.map +1 -1
- package/dist/mock-transport.js +1 -1
- package/dist/mock-transport.js.map +1 -1
- package/dist/resource.js +2 -2
- package/dist/resource.js.map +1 -1
- package/dist/route-guard.js.map +1 -1
- package/dist/service-hooks.js +9 -0
- package/dist/service-hooks.js.map +1 -1
- package/dist/telemetry.js.map +1 -1
- package/package.json +53 -25
package/README.md
CHANGED
|
@@ -7,12 +7,12 @@ App Router and Vite SPA alike).
|
|
|
7
7
|
```ts
|
|
8
8
|
import {
|
|
9
9
|
buildRuntimeInterceptors, // Connect transport stack
|
|
10
|
-
ConnectClientError,
|
|
11
|
-
RuntimeShell,
|
|
12
|
-
useSession,
|
|
13
|
-
RouteGuard,
|
|
14
|
-
Resource,
|
|
15
|
-
initClientTelemetry,
|
|
10
|
+
ConnectClientError, // typed client errors
|
|
11
|
+
RuntimeShell, // session + error boundary + toast host
|
|
12
|
+
useSession, // the signed-in user
|
|
13
|
+
RouteGuard, // signed-in render gate
|
|
14
|
+
Resource, // the list tristate + cursor pagination
|
|
15
|
+
initClientTelemetry, // opt-in client RUM
|
|
16
16
|
} from "@reliantlabs/forge-web-runtime";
|
|
17
17
|
```
|
|
18
18
|
|
|
@@ -94,8 +94,8 @@ an opaque external."
|
|
|
94
94
|
```ts
|
|
95
95
|
import {
|
|
96
96
|
buildRuntimeInterceptors, // the Connect transport stack
|
|
97
|
-
ConnectClientError,
|
|
98
|
-
setTraceSampled,
|
|
97
|
+
ConnectClientError, // what the stack throws
|
|
98
|
+
setTraceSampled, // traceInterceptor's knob
|
|
99
99
|
} from "@reliantlabs/forge-web-runtime/interceptors";
|
|
100
100
|
```
|
|
101
101
|
|
|
@@ -112,7 +112,7 @@ entirely. `src/interceptors.ts` is guarded by
|
|
|
112
112
|
`src/interceptors-entry.test.ts`, which walks the entry point's real import
|
|
113
113
|
graph and fails if React ever appears in it.
|
|
114
114
|
|
|
115
|
-
(This subpath was
|
|
115
|
+
(This subpath was _also_ the workaround for React 18 vs 19 type skew, back
|
|
116
116
|
when the package published its sources. That is no longer why it exists — see
|
|
117
117
|
"One `.d.ts` for React 18 and 19" above; the barrel typechecks fine from Expo
|
|
118
118
|
now. It stays because dead components in a mobile bundle is a separate and
|
|
@@ -145,21 +145,21 @@ the built CSS and the components render unstyled.
|
|
|
145
145
|
|
|
146
146
|
Required tokens:
|
|
147
147
|
|
|
148
|
-
| Token
|
|
149
|
-
|
|
|
150
|
-
| `--color-surface`
|
|
151
|
-
| `--color-surface-muted`
|
|
152
|
-
| `--color-border`
|
|
153
|
-
| `--color-ink`
|
|
154
|
-
| `--color-ink-muted`
|
|
155
|
-
| `--color-ink-subtle`
|
|
156
|
-
| `--color-accent`
|
|
157
|
-
| `--color-danger`
|
|
158
|
-
| `--color-danger-hover`
|
|
159
|
-
| `--color-danger-surface` | error panel background
|
|
160
|
-
| `--color-danger-border`
|
|
161
|
-
| `--color-danger-ink`
|
|
162
|
-
| `--color-on-danger`
|
|
148
|
+
| Token | Used for |
|
|
149
|
+
| ------------------------ | -------------------------------- |
|
|
150
|
+
| `--color-surface` | table / panel background |
|
|
151
|
+
| `--color-surface-muted` | table head, row hover |
|
|
152
|
+
| `--color-border` | table and panel rules |
|
|
153
|
+
| `--color-ink` | primary text |
|
|
154
|
+
| `--color-ink-muted` | secondary text, empty states |
|
|
155
|
+
| `--color-ink-subtle` | placeholders, disabled controls |
|
|
156
|
+
| `--color-accent` | focus ring, active filter border |
|
|
157
|
+
| `--color-danger` | error text, destructive fill |
|
|
158
|
+
| `--color-danger-hover` | destructive fill hover |
|
|
159
|
+
| `--color-danger-surface` | error panel background |
|
|
160
|
+
| `--color-danger-border` | error panel border |
|
|
161
|
+
| `--color-danger-ink` | error text on a danger surface |
|
|
162
|
+
| `--color-on-danger` | text on a danger fill |
|
|
163
163
|
|
|
164
164
|
## Local development
|
|
165
165
|
|
|
@@ -180,7 +180,7 @@ app's bundler is already watching this directory (Metro via `watchFolders`,
|
|
|
180
180
|
Next via `transpilePackages`, Vite because a linked dep is treated as source),
|
|
181
181
|
so a save still lands in the running app; it just arrives one compile later.
|
|
182
182
|
|
|
183
|
-
You do not have to remember to build before the
|
|
183
|
+
You do not have to remember to build before the _first_ install. `prepare`
|
|
184
184
|
(`scripts/build.mjs`) runs when npm materialises the `file:` link and again
|
|
185
185
|
before `npm publish` — the two moments a consumable `dist/` has to exist. On a
|
|
186
186
|
checkout that has never been developed it installs this package's own
|
package/dist/devlog.d.ts
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/** Console methods this module mirrors. */
|
|
2
|
+
declare const LEVELS: readonly ["log", "info", "warn", "error", "debug"];
|
|
3
|
+
type Level = (typeof LEVELS)[number];
|
|
4
|
+
/**
|
|
5
|
+
* One log line on the wire.
|
|
6
|
+
*
|
|
7
|
+
* Also the whole v1 body: a legacy endpoint receives exactly this object, which
|
|
8
|
+
* is why the shape is unchanged and still exported.
|
|
9
|
+
*/
|
|
10
|
+
export interface DevLogPayload {
|
|
11
|
+
level: Level | "error";
|
|
12
|
+
msg: string;
|
|
13
|
+
}
|
|
14
|
+
/** The v2 body: many lines, one request. */
|
|
15
|
+
export interface DevLogBatch {
|
|
16
|
+
entries: DevLogPayload[];
|
|
17
|
+
}
|
|
18
|
+
export interface DevLoggingOptions {
|
|
19
|
+
/**
|
|
20
|
+
* Whether to install at all. Pass `import.meta.env.DEV` (Vite) or
|
|
21
|
+
* `process.env.NODE_ENV !== "production"` (Next.js). When false this is a
|
|
22
|
+
* no-op, so the call site needs no conditional of its own.
|
|
23
|
+
*/
|
|
24
|
+
dev: boolean;
|
|
25
|
+
/** Endpoint the dev server serves. Defaults to the forge convention. */
|
|
26
|
+
endpoint?: string;
|
|
27
|
+
/**
|
|
28
|
+
* Also keep writing to the real console. Default true — the browser devtools
|
|
29
|
+
* experience should be unchanged; this feature ADDS a sink, it does not move
|
|
30
|
+
* one.
|
|
31
|
+
*/
|
|
32
|
+
mirrorToConsole?: boolean;
|
|
33
|
+
}
|
|
34
|
+
export declare const DEV_LOG_ENDPOINT = "/__forge/log";
|
|
35
|
+
/**
|
|
36
|
+
* Mirror console output and uncaught errors to the dev server, which prints
|
|
37
|
+
* them into .forge/logs/<env>/frontend_<name>.log.
|
|
38
|
+
*
|
|
39
|
+
* The window listeners are the point of the feature as much as the console
|
|
40
|
+
* override is: an uncaught TypeError or a rejected promise produces no console
|
|
41
|
+
* call of its own, and those are exactly the failures worth seeing.
|
|
42
|
+
*
|
|
43
|
+
* Safe to call more than once; the second call is a no-op.
|
|
44
|
+
*/
|
|
45
|
+
export declare function installDevLogging(options: DevLoggingOptions): void;
|
|
46
|
+
/** Restore the original console methods and remove the window listeners. */
|
|
47
|
+
export declare function uninstallDevLogging(): void;
|
|
48
|
+
/** Whether the console override is currently installed. Exposed for tests. */
|
|
49
|
+
export declare function devLoggingInstalled(): boolean;
|
|
50
|
+
export {};
|
package/dist/devlog.js
ADDED
|
@@ -0,0 +1,449 @@
|
|
|
1
|
+
// Dev-only browser log forwarding.
|
|
2
|
+
//
|
|
3
|
+
// A browser's console is a dead end: an agent debugging a scaffolded frontend
|
|
4
|
+
// cannot open devtools, so every console line and — worse — every uncaught
|
|
5
|
+
// error is invisible to it. The backend has no such gap (structured slog, the
|
|
6
|
+
// observe ComponentChain, and forge's dev loop already tees each process's
|
|
7
|
+
// stdout to .forge/logs/<env>/). This closes the frontend half by POSTing
|
|
8
|
+
// browser console output to a dev-server endpoint that prints it, so it lands
|
|
9
|
+
// in .forge/logs/<env>/frontend_<name>.log next to the server logs.
|
|
10
|
+
//
|
|
11
|
+
// ── Why this batches (protocol v2) ───────────────────────────────────────
|
|
12
|
+
//
|
|
13
|
+
// The first version sent one fetch POST per console call. Measured in a real
|
|
14
|
+
// app that logs freely, that is ~80 requests/s at light load and 200+/s in a
|
|
15
|
+
// burst, and those requests are not free bystanders: they share the browser's
|
|
16
|
+
// six-connections-per-origin pool and the dev server's single event loop with
|
|
17
|
+
// the app's own RPCs. In the same session, RPC latency averaged 37ms in quiet
|
|
18
|
+
// seconds and 127ms in seconds carrying 200+ log lines. Worse, `keepalive`
|
|
19
|
+
// requests draw on a 64 KiB in-flight browser quota shared across the page, so
|
|
20
|
+
// a burst does not just slow things down — some of it gets rejected, and the
|
|
21
|
+
// original `.catch(() => {})` made that indistinguishable from silence.
|
|
22
|
+
//
|
|
23
|
+
// So entries are buffered and flushed as a batch:
|
|
24
|
+
//
|
|
25
|
+
// - every FLUSH_INTERVAL_MS, timer armed when an entry lands in an empty
|
|
26
|
+
// buffer (the common case: a few lines coalesce into one request),
|
|
27
|
+
// - immediately once buffered output reaches MAX_BATCH_BYTES,
|
|
28
|
+
// - on a microtask for anything error-level, so a crash never waits 250ms
|
|
29
|
+
// while a same-tick burst still coalesces,
|
|
30
|
+
// - synchronously via sendBeacon on pagehide / visibilitychange→hidden,
|
|
31
|
+
// which is the only way output survives a navigation or a crash-reload.
|
|
32
|
+
//
|
|
33
|
+
// At most ONE request is in flight. Entries logged during it keep buffering and
|
|
34
|
+
// go out when it settles, which is what makes the printed order the log order —
|
|
35
|
+
// six parallel POSTs would interleave on the server.
|
|
36
|
+
//
|
|
37
|
+
// Nothing is ever dropped silently. A full buffer, a rejected request and an
|
|
38
|
+
// over-quota request all increment a counter, and the next batch to leave
|
|
39
|
+
// carries a synthetic warn line saying how many lines were lost and why. The
|
|
40
|
+
// failure this replaces was a dead sink that looked exactly like working code.
|
|
41
|
+
//
|
|
42
|
+
// ── Legacy endpoints ─────────────────────────────────────────────────────
|
|
43
|
+
//
|
|
44
|
+
// The receiving endpoint is a scaffold-once file the PROJECT owns (a Vite
|
|
45
|
+
// plugin / a Next.js route handler), so upgrading this package through npm will
|
|
46
|
+
// routinely meet an endpoint that predates batching. Such an endpoint answers
|
|
47
|
+
// 204 and prints one empty line for the whole batch — total, silent loss. A v2
|
|
48
|
+
// endpoint therefore returns `X-Forge-Devlog: 2`, and a 2xx without it makes
|
|
49
|
+
// this client fall back permanently to one v1 POST per line (plus one warn
|
|
50
|
+
// line telling the developer to update the endpoint).
|
|
51
|
+
//
|
|
52
|
+
// DEV ONLY, and structurally so. The receiving endpoint is a Vite plugin
|
|
53
|
+
// gated `apply: "serve"` / a Next.js route behind a NODE_ENV check, so it does
|
|
54
|
+
// not exist in a production build; installDevLogging() additionally no-ops
|
|
55
|
+
// unless it is handed dev: true. A production bundle therefore has no
|
|
56
|
+
// endpoint to post to AND no code that would post.
|
|
57
|
+
//
|
|
58
|
+
// It is also reversible: uninstallDevLogging() restores the original console
|
|
59
|
+
// methods, and the scaffolded call site is an ordinary line in main.tsx /
|
|
60
|
+
// providers.tsx that a project can delete outright.
|
|
61
|
+
/** Console methods this module mirrors. */
|
|
62
|
+
const LEVELS = ["log", "info", "warn", "error", "debug"];
|
|
63
|
+
export const DEV_LOG_ENDPOINT = "/__forge/log";
|
|
64
|
+
/** Response header a batching endpoint sets. Its ABSENCE selects v1 fallback. */
|
|
65
|
+
const PROTOCOL_HEADER = "X-Forge-Devlog";
|
|
66
|
+
/** Cap a single line so a runaway loop cannot fill the disk. Matches the endpoints. */
|
|
67
|
+
const MAX_LINE = 8_000;
|
|
68
|
+
/** How long a line may wait for company before it is sent. */
|
|
69
|
+
const FLUSH_INTERVAL_MS = 250;
|
|
70
|
+
/**
|
|
71
|
+
* Per-request ceiling. Deliberately half of the browser's 64 KiB shared
|
|
72
|
+
* `keepalive` in-flight quota: with one request in flight, a batch cannot be
|
|
73
|
+
* the thing that pushes the page over it.
|
|
74
|
+
*/
|
|
75
|
+
const MAX_BATCH_BYTES = 32 * 1024;
|
|
76
|
+
/** Buffer ceiling. Past it entries are dropped and counted, never queued forever. */
|
|
77
|
+
const MAX_BUFFER_ENTRIES = 5_000;
|
|
78
|
+
const original = {};
|
|
79
|
+
let installed = false;
|
|
80
|
+
// Guards against infinite recursion. The forwarder calls fetch(), and anything
|
|
81
|
+
// that logs inside fetch (an interceptor, a polyfill, a devtools extension)
|
|
82
|
+
// would otherwise re-enter the override forever. Such a line is still mirrored
|
|
83
|
+
// to the real console — it is only forwarding that is suppressed.
|
|
84
|
+
let forwarding = false;
|
|
85
|
+
let endpointUrl = DEV_LOG_ENDPOINT;
|
|
86
|
+
let buffer = [];
|
|
87
|
+
let bufferedBytes = 0;
|
|
88
|
+
let flushTimer;
|
|
89
|
+
let requestInFlight = false;
|
|
90
|
+
let errorFlushQueued = false;
|
|
91
|
+
let droppedCount = 0;
|
|
92
|
+
let droppedReason = "";
|
|
93
|
+
/** Set for good once an endpoint is known not to understand batches. */
|
|
94
|
+
let legacyEndpoint = false;
|
|
95
|
+
/**
|
|
96
|
+
* Render one console argument as a string.
|
|
97
|
+
*
|
|
98
|
+
* Circular structures and BigInt are the two cases a plain JSON.stringify
|
|
99
|
+
* throws on, and the old fallback to String(value) turned both into
|
|
100
|
+
* "[object Object]" — deleting exactly the shape you were trying to read. The
|
|
101
|
+
* replacer keeps the object and names the cycle instead.
|
|
102
|
+
*/
|
|
103
|
+
function render(value) {
|
|
104
|
+
if (typeof value === "string")
|
|
105
|
+
return value;
|
|
106
|
+
if (value instanceof Error) {
|
|
107
|
+
return `${value.name}: ${value.message}${value.stack ? `\n${value.stack}` : ""}`;
|
|
108
|
+
}
|
|
109
|
+
try {
|
|
110
|
+
const seen = new WeakSet();
|
|
111
|
+
return (JSON.stringify(value, (_key, val) => {
|
|
112
|
+
if (typeof val === "bigint")
|
|
113
|
+
return `${val}n`;
|
|
114
|
+
if (typeof val === "object" && val !== null) {
|
|
115
|
+
if (seen.has(val))
|
|
116
|
+
return "[Circular]";
|
|
117
|
+
seen.add(val);
|
|
118
|
+
}
|
|
119
|
+
return val;
|
|
120
|
+
}) ?? String(value));
|
|
121
|
+
}
|
|
122
|
+
catch {
|
|
123
|
+
// DOM nodes, getters that throw — never let logging throw.
|
|
124
|
+
return String(value);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
function truncate(msg) {
|
|
128
|
+
return msg.length > MAX_LINE ? `${msg.slice(0, MAX_LINE)}… (truncated)` : msg;
|
|
129
|
+
}
|
|
130
|
+
function entryBytes(entry) {
|
|
131
|
+
return JSON.stringify(entry).length;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Buffer one line and decide whether it can wait.
|
|
135
|
+
*
|
|
136
|
+
* Arguments are rendered HERE rather than at flush time: a console argument is
|
|
137
|
+
* a live object, and by the time a batch leaves 250ms later the array it logged
|
|
138
|
+
* may have been mutated or emptied. The snapshot is the value at the call.
|
|
139
|
+
*/
|
|
140
|
+
function capture(level, args) {
|
|
141
|
+
if (forwarding)
|
|
142
|
+
return;
|
|
143
|
+
if (buffer.length >= MAX_BUFFER_ENTRIES) {
|
|
144
|
+
droppedCount += 1;
|
|
145
|
+
droppedReason = "buffer full";
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
const entry = { level, msg: truncate(args.map(render).join(" ")) };
|
|
149
|
+
const wasEmpty = buffer.length === 0;
|
|
150
|
+
buffer.push(entry);
|
|
151
|
+
bufferedBytes += entryBytes(entry);
|
|
152
|
+
if (bufferedBytes >= MAX_BATCH_BYTES) {
|
|
153
|
+
flush();
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
if (level === "error") {
|
|
157
|
+
// An error is what someone is waiting for; it must not sit in a timer. The
|
|
158
|
+
// microtask (rather than a direct flush) lets a same-tick burst — a failing
|
|
159
|
+
// render logging three times — still leave as one request.
|
|
160
|
+
if (!errorFlushQueued) {
|
|
161
|
+
errorFlushQueued = true;
|
|
162
|
+
queueMicrotask(() => {
|
|
163
|
+
errorFlushQueued = false;
|
|
164
|
+
flush();
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
if (wasEmpty)
|
|
170
|
+
armTimer();
|
|
171
|
+
}
|
|
172
|
+
function armTimer() {
|
|
173
|
+
if (flushTimer !== undefined)
|
|
174
|
+
return;
|
|
175
|
+
flushTimer = setTimeout(() => {
|
|
176
|
+
flushTimer = undefined;
|
|
177
|
+
flush();
|
|
178
|
+
}, FLUSH_INTERVAL_MS);
|
|
179
|
+
}
|
|
180
|
+
function clearFlushTimer() {
|
|
181
|
+
if (flushTimer === undefined)
|
|
182
|
+
return;
|
|
183
|
+
clearTimeout(flushTimer);
|
|
184
|
+
flushTimer = undefined;
|
|
185
|
+
}
|
|
186
|
+
/** Pull entries off the front of the buffer without exceeding MAX_BATCH_BYTES. */
|
|
187
|
+
function takeBatch(limit = MAX_BATCH_BYTES) {
|
|
188
|
+
const batch = [];
|
|
189
|
+
let size = '{"entries":[]}'.length;
|
|
190
|
+
while (buffer.length > 0) {
|
|
191
|
+
const entry = buffer[0];
|
|
192
|
+
const cost = entryBytes(entry) + (batch.length > 0 ? 1 : 0);
|
|
193
|
+
// Always take at least one entry: a single line that somehow exceeds the
|
|
194
|
+
// limit must still leave, or it stalls every line behind it forever.
|
|
195
|
+
if (batch.length > 0 && size + cost > limit)
|
|
196
|
+
break;
|
|
197
|
+
buffer.shift();
|
|
198
|
+
bufferedBytes -= entryBytes(entry);
|
|
199
|
+
batch.push(entry);
|
|
200
|
+
size += cost;
|
|
201
|
+
}
|
|
202
|
+
if (buffer.length === 0)
|
|
203
|
+
bufferedBytes = 0;
|
|
204
|
+
return batch;
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Prepend the "we lost lines" notice, if any, so it travels with the next batch
|
|
208
|
+
* rather than needing a request of its own.
|
|
209
|
+
*/
|
|
210
|
+
function drainDroppedNotice() {
|
|
211
|
+
if (droppedCount === 0)
|
|
212
|
+
return;
|
|
213
|
+
const notice = {
|
|
214
|
+
level: "warn",
|
|
215
|
+
msg: `[forge-devlog] dropped ${droppedCount} lines (${droppedReason})`,
|
|
216
|
+
};
|
|
217
|
+
buffer.unshift(notice);
|
|
218
|
+
bufferedBytes += entryBytes(notice);
|
|
219
|
+
droppedCount = 0;
|
|
220
|
+
droppedReason = "";
|
|
221
|
+
}
|
|
222
|
+
function post(body) {
|
|
223
|
+
// The recursion guard must wrap the CALL, not the promise: a fetch polyfill
|
|
224
|
+
// that logs does so synchronously from inside fetch().
|
|
225
|
+
forwarding = true;
|
|
226
|
+
try {
|
|
227
|
+
return fetch(endpointUrl, {
|
|
228
|
+
method: "POST",
|
|
229
|
+
headers: { "Content-Type": "application/json" },
|
|
230
|
+
body,
|
|
231
|
+
// A log emitted during unload (the interesting case for a crash on
|
|
232
|
+
// navigation) is cancelled without this.
|
|
233
|
+
keepalive: true,
|
|
234
|
+
// Never let log forwarding trip a credentials or CORS policy.
|
|
235
|
+
credentials: "omit",
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
finally {
|
|
239
|
+
forwarding = false;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* Send one request's worth of buffered output, if nothing is in flight.
|
|
244
|
+
*
|
|
245
|
+
* The single-flight rule is what guarantees the dev server prints lines in the
|
|
246
|
+
* order they were logged, and it doubles as backpressure: a slow endpoint makes
|
|
247
|
+
* batches bigger rather than making requests pile up.
|
|
248
|
+
*/
|
|
249
|
+
function flush() {
|
|
250
|
+
if (requestInFlight)
|
|
251
|
+
return;
|
|
252
|
+
drainDroppedNotice();
|
|
253
|
+
if (buffer.length === 0)
|
|
254
|
+
return;
|
|
255
|
+
clearFlushTimer();
|
|
256
|
+
const batch = legacyEndpoint ? takeBatch(0) : takeBatch();
|
|
257
|
+
if (batch.length === 0)
|
|
258
|
+
return;
|
|
259
|
+
const body = legacyEndpoint
|
|
260
|
+
? JSON.stringify(batch[0])
|
|
261
|
+
: JSON.stringify({ entries: batch });
|
|
262
|
+
requestInFlight = true;
|
|
263
|
+
post(body).then((response) => {
|
|
264
|
+
requestInFlight = false;
|
|
265
|
+
if (!response.ok) {
|
|
266
|
+
countDropped(batch.length, `endpoint returned ${response.status}`);
|
|
267
|
+
}
|
|
268
|
+
else if (!legacyEndpoint && !response.headers.get(PROTOCOL_HEADER)) {
|
|
269
|
+
adoptLegacyMode(batch);
|
|
270
|
+
}
|
|
271
|
+
if (buffer.length > 0 || droppedCount > 0)
|
|
272
|
+
flush();
|
|
273
|
+
}, () => {
|
|
274
|
+
requestInFlight = false;
|
|
275
|
+
countDropped(batch.length, "request failed");
|
|
276
|
+
if (buffer.length > 0)
|
|
277
|
+
flush();
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
function countDropped(count, reason) {
|
|
281
|
+
droppedCount += count;
|
|
282
|
+
droppedReason = reason;
|
|
283
|
+
}
|
|
284
|
+
/**
|
|
285
|
+
* A 2xx with no protocol header came from an endpoint written before batching.
|
|
286
|
+
* It parsed `{entries:[...]}` as a v1 body, found no `msg`, and printed one
|
|
287
|
+
* empty line — so this batch is lost unless it is re-sent one line at a time,
|
|
288
|
+
* and so is everything after it.
|
|
289
|
+
*/
|
|
290
|
+
function adoptLegacyMode(lost) {
|
|
291
|
+
legacyEndpoint = true;
|
|
292
|
+
const notice = {
|
|
293
|
+
level: "warn",
|
|
294
|
+
msg: "[forge-devlog] this dev server's /__forge/log endpoint predates batched " +
|
|
295
|
+
"posts; update it (forge skill: debug) — falling back to one request per line",
|
|
296
|
+
};
|
|
297
|
+
buffer.unshift(notice, ...lost);
|
|
298
|
+
bufferedBytes += [notice, ...lost].reduce((n, e) => n + entryBytes(e), 0);
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* Last-chance flush on page teardown.
|
|
302
|
+
*
|
|
303
|
+
* fetch — even with keepalive — is not reliable here, and an async flush is
|
|
304
|
+
* hopeless: the event loop may not run again. sendBeacon hands the bytes to the
|
|
305
|
+
* browser to deliver after the document is gone, which is precisely the case
|
|
306
|
+
* where the last few log lines explain what happened.
|
|
307
|
+
*/
|
|
308
|
+
function flushOnUnload() {
|
|
309
|
+
drainDroppedNotice();
|
|
310
|
+
if (buffer.length === 0)
|
|
311
|
+
return;
|
|
312
|
+
const canBeacon = typeof navigator !== "undefined" && typeof navigator.sendBeacon === "function";
|
|
313
|
+
if (!canBeacon) {
|
|
314
|
+
// No beacon: keepalive fetch is the only remaining option, and one request
|
|
315
|
+
// has a better chance of leaving than a queue of them.
|
|
316
|
+
flush();
|
|
317
|
+
return;
|
|
318
|
+
}
|
|
319
|
+
forwarding = true;
|
|
320
|
+
try {
|
|
321
|
+
while (buffer.length > 0) {
|
|
322
|
+
const batch = legacyEndpoint ? takeBatch(0) : takeBatch();
|
|
323
|
+
const body = legacyEndpoint
|
|
324
|
+
? JSON.stringify(batch[0])
|
|
325
|
+
: JSON.stringify({ entries: batch });
|
|
326
|
+
// text/plain is not a decoration: sendBeacon with application/json is a
|
|
327
|
+
// non-simple request and would need a CORS preflight it cannot make. The
|
|
328
|
+
// endpoints parse the body regardless of Content-Type for this reason.
|
|
329
|
+
const blob = new Blob([body], { type: "text/plain;charset=UTF-8" });
|
|
330
|
+
if (!navigator.sendBeacon(endpointUrl, blob)) {
|
|
331
|
+
// The beacon queue is full (64 KiB per origin). Nothing later will fit
|
|
332
|
+
// either, so stop and account for what is left.
|
|
333
|
+
countDropped(batch.length + buffer.length, "beacon queue full");
|
|
334
|
+
buffer = [];
|
|
335
|
+
bufferedBytes = 0;
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
finally {
|
|
341
|
+
forwarding = false;
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
function onWindowError(event) {
|
|
345
|
+
capture("error", [
|
|
346
|
+
event.error ??
|
|
347
|
+
`${event.message} @ ${event.filename}:${event.lineno}:${event.colno}`,
|
|
348
|
+
]);
|
|
349
|
+
}
|
|
350
|
+
function onRejection(event) {
|
|
351
|
+
capture("error", ["unhandled rejection:", event.reason]);
|
|
352
|
+
}
|
|
353
|
+
let errorHandler;
|
|
354
|
+
let rejectionHandler;
|
|
355
|
+
let pageHideHandler;
|
|
356
|
+
let visibilityHandler;
|
|
357
|
+
/**
|
|
358
|
+
* Mirror console output and uncaught errors to the dev server, which prints
|
|
359
|
+
* them into .forge/logs/<env>/frontend_<name>.log.
|
|
360
|
+
*
|
|
361
|
+
* The window listeners are the point of the feature as much as the console
|
|
362
|
+
* override is: an uncaught TypeError or a rejected promise produces no console
|
|
363
|
+
* call of its own, and those are exactly the failures worth seeing.
|
|
364
|
+
*
|
|
365
|
+
* Safe to call more than once; the second call is a no-op.
|
|
366
|
+
*/
|
|
367
|
+
export function installDevLogging(options) {
|
|
368
|
+
// `dev` is read off `options` rather than destructured with a default, and
|
|
369
|
+
// checked FIRST. A bundler constant-folds `import.meta.env.DEV` to false at
|
|
370
|
+
// the CALL SITE and can then drop the argument entirely, leaving a bare
|
|
371
|
+
// `installDevLogging({})` — with a defaulted `dev` that call would install
|
|
372
|
+
// the override in a production bundle. `options?.dev !== true` is therefore
|
|
373
|
+
// fail-closed: absent, undefined, or anything non-true means do nothing.
|
|
374
|
+
if (options?.dev !== true)
|
|
375
|
+
return;
|
|
376
|
+
if (installed)
|
|
377
|
+
return;
|
|
378
|
+
if (typeof window === "undefined")
|
|
379
|
+
return; // SSR / prerender pass
|
|
380
|
+
const { endpoint = DEV_LOG_ENDPOINT, mirrorToConsole = true } = options;
|
|
381
|
+
installed = true;
|
|
382
|
+
endpointUrl = endpoint;
|
|
383
|
+
buffer = [];
|
|
384
|
+
bufferedBytes = 0;
|
|
385
|
+
droppedCount = 0;
|
|
386
|
+
droppedReason = "";
|
|
387
|
+
legacyEndpoint = false;
|
|
388
|
+
requestInFlight = false;
|
|
389
|
+
for (const level of LEVELS) {
|
|
390
|
+
// Keep the ORIGINAL reference, not a bound copy: uninstall must restore
|
|
391
|
+
// console.log to the identical function it replaced, so a second consumer
|
|
392
|
+
// holding that reference (or a test asserting on it) sees no difference.
|
|
393
|
+
const previous = console[level];
|
|
394
|
+
original[level] = previous;
|
|
395
|
+
console[level] = (...args) => {
|
|
396
|
+
if (mirrorToConsole)
|
|
397
|
+
previous.apply(console, args);
|
|
398
|
+
capture(level, args);
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
errorHandler = (e) => onWindowError(e);
|
|
402
|
+
rejectionHandler = (e) => onRejection(e);
|
|
403
|
+
pageHideHandler = () => flushOnUnload();
|
|
404
|
+
window.addEventListener("error", errorHandler);
|
|
405
|
+
window.addEventListener("unhandledrejection", rejectionHandler);
|
|
406
|
+
window.addEventListener("pagehide", pageHideHandler);
|
|
407
|
+
if (typeof document !== "undefined") {
|
|
408
|
+
// visibilitychange→hidden is the only teardown signal mobile Safari
|
|
409
|
+
// reliably fires; pagehide alone loses the whole buffer there.
|
|
410
|
+
visibilityHandler = () => {
|
|
411
|
+
if (document.visibilityState === "hidden")
|
|
412
|
+
flushOnUnload();
|
|
413
|
+
};
|
|
414
|
+
document.addEventListener("visibilitychange", visibilityHandler);
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
/** Restore the original console methods and remove the window listeners. */
|
|
418
|
+
export function uninstallDevLogging() {
|
|
419
|
+
if (!installed)
|
|
420
|
+
return;
|
|
421
|
+
// Flush before restoring: whatever is buffered was logged while this was
|
|
422
|
+
// installed, and a teardown is no reason to lose it.
|
|
423
|
+
clearFlushTimer();
|
|
424
|
+
flush();
|
|
425
|
+
for (const level of LEVELS) {
|
|
426
|
+
const previous = original[level];
|
|
427
|
+
if (previous)
|
|
428
|
+
console[level] = previous;
|
|
429
|
+
delete original[level];
|
|
430
|
+
}
|
|
431
|
+
if (errorHandler)
|
|
432
|
+
window.removeEventListener("error", errorHandler);
|
|
433
|
+
if (rejectionHandler)
|
|
434
|
+
window.removeEventListener("unhandledrejection", rejectionHandler);
|
|
435
|
+
if (pageHideHandler)
|
|
436
|
+
window.removeEventListener("pagehide", pageHideHandler);
|
|
437
|
+
if (visibilityHandler && typeof document !== "undefined")
|
|
438
|
+
document.removeEventListener("visibilitychange", visibilityHandler);
|
|
439
|
+
errorHandler = undefined;
|
|
440
|
+
rejectionHandler = undefined;
|
|
441
|
+
pageHideHandler = undefined;
|
|
442
|
+
visibilityHandler = undefined;
|
|
443
|
+
installed = false;
|
|
444
|
+
}
|
|
445
|
+
/** Whether the console override is currently installed. Exposed for tests. */
|
|
446
|
+
export function devLoggingInstalled() {
|
|
447
|
+
return installed;
|
|
448
|
+
}
|
|
449
|
+
//# sourceMappingURL=devlog.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"devlog.js","sourceRoot":"","sources":["../src/devlog.ts"],"names":[],"mappings":"AAAA,mCAAmC;AACnC,EAAE;AACF,8EAA8E;AAC9E,2EAA2E;AAC3E,8EAA8E;AAC9E,2EAA2E;AAC3E,0EAA0E;AAC1E,8EAA8E;AAC9E,oEAAoE;AACpE,EAAE;AACF,4EAA4E;AAC5E,EAAE;AACF,6EAA6E;AAC7E,6EAA6E;AAC7E,8EAA8E;AAC9E,8EAA8E;AAC9E,8EAA8E;AAC9E,2EAA2E;AAC3E,+EAA+E;AAC/E,6EAA6E;AAC7E,wEAAwE;AACxE,EAAE;AACF,kDAAkD;AAClD,EAAE;AACF,2EAA2E;AAC3E,uEAAuE;AACvE,gEAAgE;AAChE,4EAA4E;AAC5E,+CAA+C;AAC/C,0EAA0E;AAC1E,4EAA4E;AAC5E,EAAE;AACF,gFAAgF;AAChF,gFAAgF;AAChF,qDAAqD;AACrD,EAAE;AACF,6EAA6E;AAC7E,0EAA0E;AAC1E,6EAA6E;AAC7E,+EAA+E;AAC/E,EAAE;AACF,4EAA4E;AAC5E,EAAE;AACF,0EAA0E;AAC1E,gFAAgF;AAChF,8EAA8E;AAC9E,+EAA+E;AAC/E,6EAA6E;AAC7E,2EAA2E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gBAAgB,CAAC,CAAC;IACrE,IAAI,eAAe;QAAE,MAAM,CAAC,mBAAmB,CAAC,UAAU,EAAE,eAAe,CAAC,CAAC;IAC7E,IAAI,iBAAiB,IAAI,OAAO,QAAQ,KAAK,WAAW;QACtD,QAAQ,CAAC,mBAAmB,CAAC,kBAAkB,EAAE,iBAAiB,CAAC,CAAC;IACtE,YAAY,GAAG,SAAS,CAAC;IACzB,gBAAgB,GAAG,SAAS,CAAC;IAC7B,eAAe,GAAG,SAAS,CAAC;IAC5B,iBAAiB,GAAG,SAAS,CAAC;IAC9B,SAAS,GAAG,KAAK,CAAC;AACpB,CAAC;AAED,8EAA8E;AAC9E,MAAM,UAAU,mBAAmB;IACjC,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["// Dev-only browser log forwarding.\n//\n// A browser's console is a dead end: an agent debugging a scaffolded frontend\n// cannot open devtools, so every console line and — worse — every uncaught\n// error is invisible to it. The backend has no such gap (structured slog, the\n// observe ComponentChain, and forge's dev loop already tees each process's\n// stdout to .forge/logs/<env>/). This closes the frontend half by POSTing\n// browser console output to a dev-server endpoint that prints it, so it lands\n// in .forge/logs/<env>/frontend_<name>.log next to the server logs.\n//\n// ── Why this batches (protocol v2) ───────────────────────────────────────\n//\n// The first version sent one fetch POST per console call. Measured in a real\n// app that logs freely, that is ~80 requests/s at light load and 200+/s in a\n// burst, and those requests are not free bystanders: they share the browser's\n// six-connections-per-origin pool and the dev server's single event loop with\n// the app's own RPCs. In the same session, RPC latency averaged 37ms in quiet\n// seconds and 127ms in seconds carrying 200+ log lines. Worse, `keepalive`\n// requests draw on a 64 KiB in-flight browser quota shared across the page, so\n// a burst does not just slow things down — some of it gets rejected, and the\n// original `.catch(() => {})` made that indistinguishable from silence.\n//\n// So entries are buffered and flushed as a batch:\n//\n// - every FLUSH_INTERVAL_MS, timer armed when an entry lands in an empty\n// buffer (the common case: a few lines coalesce into one request),\n// - immediately once buffered output reaches MAX_BATCH_BYTES,\n// - on a microtask for anything error-level, so a crash never waits 250ms\n// while a same-tick burst still coalesces,\n// - synchronously via sendBeacon on pagehide / visibilitychange→hidden,\n// which is the only way output survives a navigation or a crash-reload.\n//\n// At most ONE request is in flight. Entries logged during it keep buffering and\n// go out when it settles, which is what makes the printed order the log order —\n// six parallel POSTs would interleave on the server.\n//\n// Nothing is ever dropped silently. A full buffer, a rejected request and an\n// over-quota request all increment a counter, and the next batch to leave\n// carries a synthetic warn line saying how many lines were lost and why. The\n// failure this replaces was a dead sink that looked exactly like working code.\n//\n// ── Legacy endpoints ─────────────────────────────────────────────────────\n//\n// The receiving endpoint is a scaffold-once file the PROJECT owns (a Vite\n// plugin / a Next.js route handler), so upgrading this package through npm will\n// routinely meet an endpoint that predates batching. Such an endpoint answers\n// 204 and prints one empty line for the whole batch — total, silent loss. A v2\n// endpoint therefore returns `X-Forge-Devlog: 2`, and a 2xx without it makes\n// this client fall back permanently to one v1 POST per line (plus one warn\n// line telling the developer to update the endpoint).\n//\n// DEV ONLY, and structurally so. The receiving endpoint is a Vite plugin\n// gated `apply: \"serve\"` / a Next.js route behind a NODE_ENV check, so it does\n// not exist in a production build; installDevLogging() additionally no-ops\n// unless it is handed dev: true. A production bundle therefore has no\n// endpoint to post to AND no code that would post.\n//\n// It is also reversible: uninstallDevLogging() restores the original console\n// methods, and the scaffolded call site is an ordinary line in main.tsx /\n// providers.tsx that a project can delete outright.\n\n/** Console methods this module mirrors. */\nconst LEVELS = [\"log\", \"info\", \"warn\", \"error\", \"debug\"] as const;\n\ntype Level = (typeof LEVELS)[number];\n\n/**\n * One log line on the wire.\n *\n * Also the whole v1 body: a legacy endpoint receives exactly this object, which\n * is why the shape is unchanged and still exported.\n */\nexport interface DevLogPayload {\n level: Level | \"error\";\n msg: string;\n}\n\n/** The v2 body: many lines, one request. */\nexport interface DevLogBatch {\n entries: DevLogPayload[];\n}\n\nexport interface DevLoggingOptions {\n /**\n * Whether to install at all. Pass `import.meta.env.DEV` (Vite) or\n * `process.env.NODE_ENV !== \"production\"` (Next.js). When false this is a\n * no-op, so the call site needs no conditional of its own.\n */\n dev: boolean;\n /** Endpoint the dev server serves. Defaults to the forge convention. */\n endpoint?: string;\n /**\n * Also keep writing to the real console. Default true — the browser devtools\n * experience should be unchanged; this feature ADDS a sink, it does not move\n * one.\n */\n mirrorToConsole?: boolean;\n}\n\nexport const DEV_LOG_ENDPOINT = \"/__forge/log\";\n\n/** Response header a batching endpoint sets. Its ABSENCE selects v1 fallback. */\nconst PROTOCOL_HEADER = \"X-Forge-Devlog\";\n\n/** Cap a single line so a runaway loop cannot fill the disk. Matches the endpoints. */\nconst MAX_LINE = 8_000;\n\n/** How long a line may wait for company before it is sent. */\nconst FLUSH_INTERVAL_MS = 250;\n\n/**\n * Per-request ceiling. Deliberately half of the browser's 64 KiB shared\n * `keepalive` in-flight quota: with one request in flight, a batch cannot be\n * the thing that pushes the page over it.\n */\nconst MAX_BATCH_BYTES = 32 * 1024;\n\n/** Buffer ceiling. Past it entries are dropped and counted, never queued forever. */\nconst MAX_BUFFER_ENTRIES = 5_000;\n\nconst original: Partial<Record<Level, (...args: unknown[]) => void>> = {};\nlet installed = false;\n\n// Guards against infinite recursion. The forwarder calls fetch(), and anything\n// that logs inside fetch (an interceptor, a polyfill, a devtools extension)\n// would otherwise re-enter the override forever. Such a line is still mirrored\n// to the real console — it is only forwarding that is suppressed.\nlet forwarding = false;\n\nlet endpointUrl = DEV_LOG_ENDPOINT;\nlet buffer: DevLogPayload[] = [];\nlet bufferedBytes = 0;\nlet flushTimer: ReturnType<typeof setTimeout> | undefined;\nlet requestInFlight = false;\nlet errorFlushQueued = false;\nlet droppedCount = 0;\nlet droppedReason = \"\";\n/** Set for good once an endpoint is known not to understand batches. */\nlet legacyEndpoint = false;\n\n/**\n * Render one console argument as a string.\n *\n * Circular structures and BigInt are the two cases a plain JSON.stringify\n * throws on, and the old fallback to String(value) turned both into\n * \"[object Object]\" — deleting exactly the shape you were trying to read. The\n * replacer keeps the object and names the cycle instead.\n */\nfunction render(value: unknown): string {\n if (typeof value === \"string\") return value;\n if (value instanceof Error) {\n return `${value.name}: ${value.message}${value.stack ? `\\n${value.stack}` : \"\"}`;\n }\n try {\n const seen = new WeakSet<object>();\n return (\n JSON.stringify(value, (_key, val: unknown) => {\n if (typeof val === \"bigint\") return `${val}n`;\n if (typeof val === \"object\" && val !== null) {\n if (seen.has(val)) return \"[Circular]\";\n seen.add(val);\n }\n return val;\n }) ?? String(value)\n );\n } catch {\n // DOM nodes, getters that throw — never let logging throw.\n return String(value);\n }\n}\n\nfunction truncate(msg: string): string {\n return msg.length > MAX_LINE ? `${msg.slice(0, MAX_LINE)}… (truncated)` : msg;\n}\n\nfunction entryBytes(entry: DevLogPayload): number {\n return JSON.stringify(entry).length;\n}\n\n/**\n * Buffer one line and decide whether it can wait.\n *\n * Arguments are rendered HERE rather than at flush time: a console argument is\n * a live object, and by the time a batch leaves 250ms later the array it logged\n * may have been mutated or emptied. The snapshot is the value at the call.\n */\nfunction capture(level: DevLogPayload[\"level\"], args: unknown[]): void {\n if (forwarding) return;\n\n if (buffer.length >= MAX_BUFFER_ENTRIES) {\n droppedCount += 1;\n droppedReason = \"buffer full\";\n return;\n }\n\n const entry: DevLogPayload = { level, msg: truncate(args.map(render).join(\" \")) };\n const wasEmpty = buffer.length === 0;\n buffer.push(entry);\n bufferedBytes += entryBytes(entry);\n\n if (bufferedBytes >= MAX_BATCH_BYTES) {\n flush();\n return;\n }\n\n if (level === \"error\") {\n // An error is what someone is waiting for; it must not sit in a timer. The\n // microtask (rather than a direct flush) lets a same-tick burst — a failing\n // render logging three times — still leave as one request.\n if (!errorFlushQueued) {\n errorFlushQueued = true;\n queueMicrotask(() => {\n errorFlushQueued = false;\n flush();\n });\n }\n return;\n }\n\n if (wasEmpty) armTimer();\n}\n\nfunction armTimer(): void {\n if (flushTimer !== undefined) return;\n flushTimer = setTimeout(() => {\n flushTimer = undefined;\n flush();\n }, FLUSH_INTERVAL_MS);\n}\n\nfunction clearFlushTimer(): void {\n if (flushTimer === undefined) return;\n clearTimeout(flushTimer);\n flushTimer = undefined;\n}\n\n/** Pull entries off the front of the buffer without exceeding MAX_BATCH_BYTES. */\nfunction takeBatch(limit = MAX_BATCH_BYTES): DevLogPayload[] {\n const batch: DevLogPayload[] = [];\n let size = '{\"entries\":[]}'.length;\n while (buffer.length > 0) {\n const entry = buffer[0] as DevLogPayload;\n const cost = entryBytes(entry) + (batch.length > 0 ? 1 : 0);\n // Always take at least one entry: a single line that somehow exceeds the\n // limit must still leave, or it stalls every line behind it forever.\n if (batch.length > 0 && size + cost > limit) break;\n buffer.shift();\n bufferedBytes -= entryBytes(entry);\n batch.push(entry);\n size += cost;\n }\n if (buffer.length === 0) bufferedBytes = 0;\n return batch;\n}\n\n/**\n * Prepend the \"we lost lines\" notice, if any, so it travels with the next batch\n * rather than needing a request of its own.\n */\nfunction drainDroppedNotice(): void {\n if (droppedCount === 0) return;\n const notice: DevLogPayload = {\n level: \"warn\",\n msg: `[forge-devlog] dropped ${droppedCount} lines (${droppedReason})`,\n };\n buffer.unshift(notice);\n bufferedBytes += entryBytes(notice);\n droppedCount = 0;\n droppedReason = \"\";\n}\n\nfunction post(body: string): Promise<Response> {\n // The recursion guard must wrap the CALL, not the promise: a fetch polyfill\n // that logs does so synchronously from inside fetch().\n forwarding = true;\n try {\n return fetch(endpointUrl, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body,\n // A log emitted during unload (the interesting case for a crash on\n // navigation) is cancelled without this.\n keepalive: true,\n // Never let log forwarding trip a credentials or CORS policy.\n credentials: \"omit\",\n });\n } finally {\n forwarding = false;\n }\n}\n\n/**\n * Send one request's worth of buffered output, if nothing is in flight.\n *\n * The single-flight rule is what guarantees the dev server prints lines in the\n * order they were logged, and it doubles as backpressure: a slow endpoint makes\n * batches bigger rather than making requests pile up.\n */\nfunction flush(): void {\n if (requestInFlight) return;\n drainDroppedNotice();\n if (buffer.length === 0) return;\n clearFlushTimer();\n\n const batch = legacyEndpoint ? takeBatch(0) : takeBatch();\n if (batch.length === 0) return;\n\n const body = legacyEndpoint\n ? JSON.stringify(batch[0])\n : JSON.stringify({ entries: batch } satisfies DevLogBatch);\n\n requestInFlight = true;\n post(body).then(\n (response) => {\n requestInFlight = false;\n if (!response.ok) {\n countDropped(batch.length, `endpoint returned ${response.status}`);\n } else if (!legacyEndpoint && !response.headers.get(PROTOCOL_HEADER)) {\n adoptLegacyMode(batch);\n }\n if (buffer.length > 0 || droppedCount > 0) flush();\n },\n () => {\n requestInFlight = false;\n countDropped(batch.length, \"request failed\");\n if (buffer.length > 0) flush();\n },\n );\n}\n\nfunction countDropped(count: number, reason: string): void {\n droppedCount += count;\n droppedReason = reason;\n}\n\n/**\n * A 2xx with no protocol header came from an endpoint written before batching.\n * It parsed `{entries:[...]}` as a v1 body, found no `msg`, and printed one\n * empty line — so this batch is lost unless it is re-sent one line at a time,\n * and so is everything after it.\n */\nfunction adoptLegacyMode(lost: DevLogPayload[]): void {\n legacyEndpoint = true;\n const notice: DevLogPayload = {\n level: \"warn\",\n msg:\n \"[forge-devlog] this dev server's /__forge/log endpoint predates batched \" +\n \"posts; update it (forge skill: debug) — falling back to one request per line\",\n };\n buffer.unshift(notice, ...lost);\n bufferedBytes += [notice, ...lost].reduce((n, e) => n + entryBytes(e), 0);\n}\n\n/**\n * Last-chance flush on page teardown.\n *\n * fetch — even with keepalive — is not reliable here, and an async flush is\n * hopeless: the event loop may not run again. sendBeacon hands the bytes to the\n * browser to deliver after the document is gone, which is precisely the case\n * where the last few log lines explain what happened.\n */\nfunction flushOnUnload(): void {\n drainDroppedNotice();\n if (buffer.length === 0) return;\n\n const canBeacon =\n typeof navigator !== \"undefined\" && typeof navigator.sendBeacon === \"function\";\n if (!canBeacon) {\n // No beacon: keepalive fetch is the only remaining option, and one request\n // has a better chance of leaving than a queue of them.\n flush();\n return;\n }\n\n forwarding = true;\n try {\n while (buffer.length > 0) {\n const batch = legacyEndpoint ? takeBatch(0) : takeBatch();\n const body = legacyEndpoint\n ? JSON.stringify(batch[0])\n : JSON.stringify({ entries: batch } satisfies DevLogBatch);\n // text/plain is not a decoration: sendBeacon with application/json is a\n // non-simple request and would need a CORS preflight it cannot make. The\n // endpoints parse the body regardless of Content-Type for this reason.\n const blob = new Blob([body], { type: \"text/plain;charset=UTF-8\" });\n if (!navigator.sendBeacon(endpointUrl, blob)) {\n // The beacon queue is full (64 KiB per origin). Nothing later will fit\n // either, so stop and account for what is left.\n countDropped(batch.length + buffer.length, \"beacon queue full\");\n buffer = [];\n bufferedBytes = 0;\n return;\n }\n }\n } finally {\n forwarding = false;\n }\n}\n\nfunction onWindowError(event: ErrorEvent): void {\n capture(\"error\", [\n event.error ??\n `${event.message} @ ${event.filename}:${event.lineno}:${event.colno}`,\n ]);\n}\n\nfunction onRejection(event: PromiseRejectionEvent): void {\n capture(\"error\", [\"unhandled rejection:\", event.reason]);\n}\n\nlet errorHandler: ((e: ErrorEvent) => void) | undefined;\nlet rejectionHandler: ((e: PromiseRejectionEvent) => void) | undefined;\nlet pageHideHandler: (() => void) | undefined;\nlet visibilityHandler: (() => void) | undefined;\n\n/**\n * Mirror console output and uncaught errors to the dev server, which prints\n * them into .forge/logs/<env>/frontend_<name>.log.\n *\n * The window listeners are the point of the feature as much as the console\n * override is: an uncaught TypeError or a rejected promise produces no console\n * call of its own, and those are exactly the failures worth seeing.\n *\n * Safe to call more than once; the second call is a no-op.\n */\nexport function installDevLogging(options: DevLoggingOptions): void {\n // `dev` is read off `options` rather than destructured with a default, and\n // checked FIRST. A bundler constant-folds `import.meta.env.DEV` to false at\n // the CALL SITE and can then drop the argument entirely, leaving a bare\n // `installDevLogging({})` — with a defaulted `dev` that call would install\n // the override in a production bundle. `options?.dev !== true` is therefore\n // fail-closed: absent, undefined, or anything non-true means do nothing.\n if (options?.dev !== true) return;\n if (installed) return;\n if (typeof window === \"undefined\") return; // SSR / prerender pass\n\n const { endpoint = DEV_LOG_ENDPOINT, mirrorToConsole = true } = options;\n installed = true;\n endpointUrl = endpoint;\n buffer = [];\n bufferedBytes = 0;\n droppedCount = 0;\n droppedReason = \"\";\n legacyEndpoint = false;\n requestInFlight = false;\n\n for (const level of LEVELS) {\n // Keep the ORIGINAL reference, not a bound copy: uninstall must restore\n // console.log to the identical function it replaced, so a second consumer\n // holding that reference (or a test asserting on it) sees no difference.\n const previous = console[level] as (...args: unknown[]) => void;\n original[level] = previous;\n console[level] = (...args: unknown[]) => {\n if (mirrorToConsole) previous.apply(console, args);\n capture(level, args);\n };\n }\n\n errorHandler = (e) => onWindowError(e);\n rejectionHandler = (e) => onRejection(e);\n pageHideHandler = () => flushOnUnload();\n window.addEventListener(\"error\", errorHandler);\n window.addEventListener(\"unhandledrejection\", rejectionHandler);\n window.addEventListener(\"pagehide\", pageHideHandler);\n\n if (typeof document !== \"undefined\") {\n // visibilitychange→hidden is the only teardown signal mobile Safari\n // reliably fires; pagehide alone loses the whole buffer there.\n visibilityHandler = () => {\n if (document.visibilityState === \"hidden\") flushOnUnload();\n };\n document.addEventListener(\"visibilitychange\", visibilityHandler);\n }\n}\n\n/** Restore the original console methods and remove the window listeners. */\nexport function uninstallDevLogging(): void {\n if (!installed) return;\n\n // Flush before restoring: whatever is buffered was logged while this was\n // installed, and a teardown is no reason to lose it.\n clearFlushTimer();\n flush();\n\n for (const level of LEVELS) {\n const previous = original[level];\n if (previous) console[level] = previous;\n delete original[level];\n }\n if (errorHandler) window.removeEventListener(\"error\", errorHandler);\n if (rejectionHandler)\n window.removeEventListener(\"unhandledrejection\", rejectionHandler);\n if (pageHideHandler) window.removeEventListener(\"pagehide\", pageHideHandler);\n if (visibilityHandler && typeof document !== \"undefined\")\n document.removeEventListener(\"visibilitychange\", visibilityHandler);\n errorHandler = undefined;\n rejectionHandler = undefined;\n pageHideHandler = undefined;\n visibilityHandler = undefined;\n installed = false;\n}\n\n/** Whether the console override is currently installed. Exposed for tests. */\nexport function devLoggingInstalled(): boolean {\n return installed;\n}\n"]}
|
package/dist/error-boundary.js
CHANGED
|
@@ -22,7 +22,8 @@ export class RuntimeErrorBoundary extends Component {
|
|
|
22
22
|
this.props.onError?.(error, info);
|
|
23
23
|
}
|
|
24
24
|
componentDidUpdate(prev) {
|
|
25
|
-
if (this.state.error &&
|
|
25
|
+
if (this.state.error &&
|
|
26
|
+
!shallowEqual(prev.resetKeys, this.props.resetKeys)) {
|
|
26
27
|
this.reset();
|
|
27
28
|
}
|
|
28
29
|
}
|