jskelet 0.2.3 → 0.2.5

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 (91) hide show
  1. package/AGENTS.md +132 -132
  2. package/CHANGELOG.md +15 -0
  3. package/LICENSE +21 -21
  4. package/bin/jskelet.mjs +103 -103
  5. package/docs/01-baslangic.md +285 -285
  6. package/docs/02-mimari.md +287 -287
  7. package/docs/03-routing.md +480 -480
  8. package/docs/04-render-ve-sablonlar.md +490 -490
  9. package/docs/05-islands.md +482 -482
  10. package/docs/06-cache.md +1209 -1202
  11. package/docs/08-build.md +366 -366
  12. package/docs/09-dev-araclari.md +335 -335
  13. package/docs/10-dagitim.md +329 -329
  14. package/docs/12-panel-ve-oturum.md +384 -384
  15. package/docs/README.md +105 -105
  16. package/docs/en/01-getting-started.md +292 -292
  17. package/docs/en/02-architecture.md +305 -305
  18. package/docs/en/03-routing.md +497 -497
  19. package/docs/en/04-rendering.md +504 -504
  20. package/docs/en/05-islands.md +492 -492
  21. package/docs/en/06-caching.md +1239 -1232
  22. package/docs/en/07-configuration.md +986 -986
  23. package/docs/en/08-build.md +383 -383
  24. package/docs/en/09-dev-tools.md +342 -342
  25. package/docs/en/10-deployment.md +332 -332
  26. package/docs/en/11-migration.md +359 -359
  27. package/docs/en/12-dashboards-and-sessions.md +392 -392
  28. package/docs/en/README.md +112 -112
  29. package/package.json +102 -102
  30. package/src/build/ensure-build.mjs +15 -15
  31. package/src/build/paths.mjs +143 -143
  32. package/src/build/resolve-peer.mjs +36 -36
  33. package/src/build/tasks/client.mjs +268 -268
  34. package/src/build/tasks/css.mjs +124 -124
  35. package/src/build/tasks/fonts.mjs +146 -146
  36. package/src/build/tasks/icons.mjs +224 -224
  37. package/src/build/tasks/images.mjs +244 -244
  38. package/src/build/tasks/precompress.mjs +78 -78
  39. package/src/client/cache-panel/i18n.js +670 -0
  40. package/src/client/cache-panel/login.html +74 -71
  41. package/src/client/cache-panel/panel.css +756 -740
  42. package/src/client/cache-panel/panel.html +308 -307
  43. package/src/client/cache-panel/panel.js +915 -808
  44. package/src/client/devtools/report.html +185 -185
  45. package/src/client/devtools/report.js +725 -725
  46. package/src/client/dom.js +95 -95
  47. package/src/client/form.js +192 -192
  48. package/src/client/index.js +35 -35
  49. package/src/client/registry.js +297 -297
  50. package/src/client/safe-image.js +91 -91
  51. package/src/client/store.js +36 -36
  52. package/src/client/swap.js +188 -188
  53. package/src/config/pattern.js +107 -107
  54. package/src/http/control-flow.js +71 -71
  55. package/src/http/cookies.js +257 -257
  56. package/src/http/request-cache.js +46 -46
  57. package/src/http/request-context.js +162 -162
  58. package/src/index.js +83 -83
  59. package/src/init.mjs +221 -221
  60. package/src/runtime/alias-hooks.mjs +119 -119
  61. package/src/runtime/register.mjs +4 -4
  62. package/src/server/assets.js +147 -147
  63. package/src/server/cache-deps.js +42 -42
  64. package/src/server/cache-panel.js +759 -738
  65. package/src/server/cloudflare.js +607 -595
  66. package/src/server/create-app.js +291 -291
  67. package/src/server/data-cache.js +462 -462
  68. package/src/server/dev/report.js +369 -369
  69. package/src/server/dev/socket.js +170 -170
  70. package/src/server/dev/version-check.mjs +139 -139
  71. package/src/server/html-cache.js +817 -817
  72. package/src/server/metadata.js +102 -102
  73. package/src/server/middleware/compression.js +205 -205
  74. package/src/server/middleware/csrf.js +134 -134
  75. package/src/server/middleware/dev-gate.js +62 -62
  76. package/src/server/middleware/headers.js +37 -37
  77. package/src/server/middleware/redirects.js +32 -32
  78. package/src/server/middleware/static-precompressed.js +100 -100
  79. package/src/server/middleware/upstream-proxy.js +141 -141
  80. package/src/server/prewarm.js +601 -601
  81. package/src/server/redis.js +569 -569
  82. package/src/server/router.js +128 -128
  83. package/src/server/status-page.js +164 -164
  84. package/src/server/upstream-limiter.js +376 -376
  85. package/src/server/upstream-tracking.js +166 -166
  86. package/src/start.mjs +7 -7
  87. package/src/templates/layout.ejs +44 -44
  88. package/src/version.mjs +31 -31
  89. package/src/views/components/loader.js +85 -85
  90. package/src/views/helpers/html.js +102 -102
  91. package/src/views/helpers/tags.js +245 -245
@@ -1,369 +1,369 @@
1
- /**
2
- * "Detaylı İncele" raporunun veri katmanı.
3
- *
4
- * Overlay baloncuğu anlık durumu gösterir; bu modül ise sitenin tamamına
5
- * bakan bir görünüm üretir: gezilen her sayfanın Web Vitals ölçümleri, SSR
6
- * çıktısının boyutu, island (CSR) durumu, tarayıcı ve sunucu tarafındaki API
7
- * çağrıları, build çıktısındaki chunk/varlık kırılımı ve HTML önbelleği.
8
- *
9
- * Yalnızca development'ta yüklenir (devtools ile birlikte mount edilir),
10
- * üretim çıktısına girmez.
11
- */
12
- import fs from "node:fs";
13
- import path from "node:path";
14
- import zlib from "node:zlib";
15
- import { getHtmlCacheEntries, getHtmlCacheSize } from "../html-cache.js";
16
- import { getDataCacheSize, getDataCacheStats } from "../data-cache.js";
17
- import { getRedisStatus } from "../redis.js";
18
- import { getUpstreamLimiterStatus } from "../upstream-limiter.js";
19
- import { prewarmProgress } from "../prewarm.js";
20
- import { getConfig } from "../../config/index.js";
21
-
22
- /** Yollar config'ten: framework paket içine taşındığında `../..` sayan her hesap bozulur. */
23
- const ROOT = getConfig().root;
24
- const PUBLIC_DIR = getConfig().dirs.public;
25
- const GENERATED_DIR = getConfig().dirs.generated;
26
-
27
- /* ------------------------------------------------------------- sayfa ölçümleri */
28
-
29
- /**
30
- * @typedef {{
31
- * url: string,
32
- * title: string | null,
33
- * at: number,
34
- * visits: number,
35
- * metrics: Record<string, number | null>,
36
- * resources: { count: number, bytes: number, byType: Record<string, { count: number, bytes: number }> },
37
- * islands: { total: number, ready: number, names: string[] },
38
- * api: { url: string, ms: number, status: number, bytes: number, initiator: string }[],
39
- * html: { bytes: number | null, cache: string | null, ms: number | null },
40
- * }} PageReport
41
- */
42
-
43
- /** @type {Map<string, PageReport>} */
44
- const pages = new Map();
45
-
46
- /** Tarayıcıdan gelen ölçüm paketini saklar. En yeni paket öncekini ezer. */
47
- export function recordPageReport(payload) {
48
- if (!payload?.url) return;
49
-
50
- let url;
51
- try {
52
- url = new URL(payload.url).pathname + new URL(payload.url).search;
53
- } catch {
54
- url = String(payload.url);
55
- }
56
-
57
- const previous = pages.get(url);
58
-
59
- pages.set(url, {
60
- url,
61
- title: payload.title ?? previous?.title ?? null,
62
- at: Date.now(),
63
- visits: (previous?.visits ?? 0) + 1,
64
- metrics: payload.metrics ?? {},
65
- resources: payload.resources ?? { count: 0, bytes: 0, byType: {} },
66
- islands: payload.islands ?? { total: 0, ready: 0, names: [] },
67
- api: Array.isArray(payload.api) ? payload.api.slice(0, 100) : [],
68
- html: previous?.html ?? { bytes: null, cache: null, ms: null },
69
- });
70
- }
71
-
72
- /** Ölçümler tarayıcı sekmesinde değil sunucuda durur; sıfırlama da buradan. */
73
- export function clearPageReports() {
74
- pages.clear();
75
- serverApiCalls.length = 0;
76
- }
77
-
78
- /* --------------------------------------------------- sunucu tarafı API çağrıları */
79
-
80
- /**
81
- * @type {{ url: string, host: string, method: string, status: number, ms: number,
82
- * bytes: number, at: number, error: string | null }[]}
83
- */
84
- const serverApiCalls = [];
85
- const MAX_API_CALLS = 300;
86
-
87
- /**
88
- * SSR sırasında yapılan dış çağrıları ölçer. `globalThis.fetch` sarılır;
89
- * yalnızca dev'de çağrıldığı için üretim yolu dokunulmaz kalır.
90
- */
91
- export function trackServerFetch() {
92
- const original = globalThis.fetch;
93
- if (original.__jskeletWrapped) return;
94
-
95
- /** @type {typeof fetch} */
96
- const wrapped = async (input, init) => {
97
- const url = typeof input === "string" ? input : (input?.url ?? String(input));
98
- const started = Date.now();
99
-
100
- // Kendi sunucumuza yapılan istekler (ısıtma, sağlık kontrolü) API sayılmaz.
101
- const isSelf = /^https?:\/\/(127\.0\.0\.1|localhost)/i.test(url);
102
-
103
- try {
104
- const response = await original(input, init);
105
- if (!isSelf) {
106
- push({
107
- url,
108
- method: init?.method ?? "GET",
109
- status: response.status,
110
- ms: Date.now() - started,
111
- bytes: Number(response.headers.get("content-length") ?? 0),
112
- error: response.ok ? null : `HTTP ${response.status}`,
113
- });
114
- }
115
- return response;
116
- } catch (error) {
117
- if (!isSelf) {
118
- push({
119
- url,
120
- method: init?.method ?? "GET",
121
- status: 0,
122
- ms: Date.now() - started,
123
- bytes: 0,
124
- error: error instanceof Error ? error.message : String(error),
125
- });
126
- }
127
- throw error;
128
- }
129
- };
130
-
131
- wrapped.__jskeletWrapped = true;
132
- globalThis.fetch = wrapped;
133
- }
134
-
135
- /** @param {{ url: string, method: string, status: number, ms: number, bytes: number, error: string | null }} call */
136
- function push(call) {
137
- let host = "—";
138
- try {
139
- host = new URL(call.url).host;
140
- } catch {
141
- // Göreli adres: host bilinmiyor.
142
- }
143
-
144
- serverApiCalls.push({ ...call, host, at: Date.now() });
145
- while (serverApiCalls.length > MAX_API_CALLS) serverApiCalls.shift();
146
- }
147
-
148
- /* ------------------------------------------------------------ build çıktısı */
149
-
150
- /** Boyut hesapları dosya değişmedikçe tekrarlanmaz. */
151
- const sizeCache = new Map();
152
-
153
- /**
154
- * @param {string} file mutlak yol
155
- * @returns {{ bytes: number, gzip: number, brotli: number | null } | null}
156
- */
157
- function measure(file) {
158
- let stat;
159
- try {
160
- stat = fs.statSync(file);
161
- } catch {
162
- return null;
163
- }
164
-
165
- const key = `${file}:${stat.size}:${stat.mtimeMs}`;
166
- const hit = sizeCache.get(key);
167
- if (hit) return hit;
168
-
169
- let gzip = 0;
170
- let brotli = null;
171
-
172
- try {
173
- const buffer = fs.readFileSync(file);
174
- // Build önceden sıkıştırılmış eşlerini üretiyorsa onları kullan; yoksa
175
- // gzip'i burada hesapla (rapor tek seferlik, maliyeti kabul edilebilir).
176
- brotli = statSize(`${file}.br`);
177
- gzip = statSize(`${file}.gz`) ?? zlib.gzipSync(buffer, { level: 6 }).length;
178
- } catch {
179
- return null;
180
- }
181
-
182
- const value = { bytes: stat.size, gzip, brotli };
183
- sizeCache.set(key, value);
184
- return value;
185
- }
186
-
187
- /** @param {string} file @returns {number | null} */
188
- function statSize(file) {
189
- try {
190
- return fs.statSync(file).size;
191
- } catch {
192
- return null;
193
- }
194
- }
195
-
196
- /** @returns {Record<string, string>} */
197
- function readJson(file, fallback) {
198
- try {
199
- return JSON.parse(fs.readFileSync(file, "utf8"));
200
- } catch {
201
- return fallback;
202
- }
203
- }
204
-
205
- /**
206
- * Manifest girdileri + boyutları. Yol public/ altına göre çözülür.
207
- */
208
- function assets() {
209
- const manifest = readJson(path.join(GENERATED_DIR, "manifest.json"), {});
210
-
211
- return Object.entries(manifest).map(([name, url]) => {
212
- const size = measure(path.join(PUBLIC_DIR, url.replace(/^\//, "")));
213
- return {
214
- name,
215
- url,
216
- kind: path.extname(url).slice(1) || "other",
217
- bytes: size?.bytes ?? null,
218
- gzip: size?.gzip ?? null,
219
- brotli: size?.brotli ?? null,
220
- };
221
- });
222
- }
223
-
224
- /**
225
- * esbuild metafile'ından chunk analizi: her çıktı için boyut, hangi
226
- * kaynaklardan oluştuğu ve hangi chunk'ları import ettiği.
227
- */
228
- function chunks() {
229
- const metafile = readJson(path.join(GENERATED_DIR, "metafile.json"), null);
230
- if (!metafile?.outputs) return { outputs: [], groups: [], available: false };
231
-
232
- /** @type {Record<string, number>} */
233
- const groups = {};
234
-
235
- const outputs = Object.entries(metafile.outputs)
236
- .filter(([file]) => file.endsWith(".js") || file.endsWith(".css"))
237
- .map(([file, output]) => {
238
- const size = measure(path.join(ROOT, file));
239
-
240
- const inputs = Object.entries(output.inputs ?? {})
241
- .map(([source, info]) => ({ source, bytes: info.bytesInOutput ?? 0 }))
242
- .filter((input) => input.bytes > 0)
243
- .sort((a, b) => b.bytes - a.bytes);
244
-
245
- for (const input of inputs) {
246
- const group = groupOf(input.source);
247
- groups[group] = (groups[group] ?? 0) + input.bytes;
248
- }
249
-
250
- return {
251
- file: `/${file.split(path.sep).join("/").replace(/^public\//, "")}`,
252
- entry: output.entryPoint ?? null,
253
- isChunk: file.includes("chunks"),
254
- bytes: output.bytes,
255
- gzip: size?.gzip ?? null,
256
- brotli: size?.brotli ?? null,
257
- imports: (output.imports ?? [])
258
- .filter((item) => item.kind !== "file-loader")
259
- .map((item) => ({
260
- path: `/${item.path.split(path.sep).join("/").replace(/^public\//, "")}`,
261
- kind: item.kind,
262
- })),
263
- inputs: inputs.slice(0, 40),
264
- inputCount: inputs.length,
265
- };
266
- })
267
- .sort((a, b) => b.bytes - a.bytes);
268
-
269
- return {
270
- available: true,
271
- outputs,
272
- groups: Object.entries(groups)
273
- .map(([name, bytes]) => ({ name, bytes }))
274
- .sort((a, b) => b.bytes - a.bytes),
275
- };
276
- }
277
-
278
- /**
279
- * Kaynak dosyayı okunur bir gruba indirger: paket adı ya da üst klasör.
280
- * @param {string} source
281
- */
282
- function groupOf(source) {
283
- const normalized = source.split(path.sep).join("/");
284
- const modules = normalized.lastIndexOf("node_modules/");
285
-
286
- if (modules >= 0) {
287
- const rest = normalized.slice(modules + "node_modules/".length).split("/");
288
- return rest[0].startsWith("@") ? `${rest[0]}/${rest[1]}` : rest[0];
289
- }
290
-
291
- const parts = normalized.split("/").filter(Boolean);
292
- return parts.slice(0, 2).join("/") || normalized;
293
- }
294
-
295
- /* ------------------------------------------------------------------- rapor */
296
-
297
- /**
298
- * Rapor sayfasının tek veri kaynağı.
299
- * @param {{ requests: object[], errors: object[] }} devtools
300
- */
301
- export function buildReport(devtools) {
302
- const usage = process.memoryUsage();
303
-
304
- // SSR ölçümleri: ısıtma turu her sayfanın HTML boyutunu ve render süresini
305
- // biliyor; gezilen sayfalarla eşleştirilir.
306
- const warmByPath = new Map(
307
- (prewarmProgress.entries ?? []).map((entry) => [entry.path, entry]),
308
- );
309
-
310
- const pageList = [...pages.values()].map((page) => {
311
- const warm = warmByPath.get(page.url.split("?")[0]);
312
- return {
313
- ...page,
314
- html: warm
315
- ? { bytes: warm.bytes, cache: warm.cache, ms: warm.ms }
316
- : page.html,
317
- };
318
- });
319
-
320
- // Hiç gezilmemiş ama ısıtılmış sayfalar da listelenir: SSR tarafı bilinir,
321
- // istemci ölçümleri boş kalır.
322
- for (const entry of prewarmProgress.entries ?? []) {
323
- if (pages.has(entry.path)) continue;
324
- pageList.push({
325
- url: entry.path,
326
- title: null,
327
- at: prewarmProgress.finishedAt ?? prewarmProgress.startedAt,
328
- visits: 0,
329
- metrics: {},
330
- resources: { count: 0, bytes: 0, byType: {} },
331
- islands: { total: 0, ready: 0, names: [] },
332
- api: [],
333
- html: { bytes: entry.bytes, cache: entry.cache, ms: entry.ms },
334
- });
335
- }
336
-
337
- return {
338
- generatedAt: Date.now(),
339
- process: {
340
- pid: process.pid,
341
- node: process.version,
342
- uptime: process.uptime(),
343
- memory: { rss: usage.rss, heapUsed: usage.heapUsed },
344
- env: process.env.NODE_ENV ?? "development",
345
- },
346
- pages: pageList.sort((a, b) => (b.visits - a.visits) || b.at - a.at),
347
- serverApi: serverApiCalls.slice().reverse(),
348
- build: { assets: assets(), ...chunks() },
349
- cache: {
350
- size: getHtmlCacheSize(),
351
- entries: getHtmlCacheEntries(),
352
- // Veri önbelleğinden yalnızca sayaç: uzun kuyruklu bir sitede on
353
- // binlerce anahtar oluyor ve dökümü rapora koymak faydasız bir yük.
354
- data: getDataCacheSize(),
355
- // Sayaçlar dökümün yerine geçmiyor, onu tamamlıyor: "kaç girdi var"
356
- // sorusundan çok "kaç okuma upstream'e gitti" sorusu karar veriyor.
357
- dataStats: getDataCacheStats(),
358
- // Paylaşımlı kademe kapalıyken de basılır: "Redis'i açtım ama neden
359
- // çalışmıyor" sorusunun cevabı en çok burada aranıyor.
360
- redis: getRedisStatus(),
361
- },
362
- // Hız freninin o anki durumu. 429 fırtınasında "şu an saniyede kaça
363
- // indi" bilgisi olmadan ayar yapmak körlemesine oluyor.
364
- upstream: getUpstreamLimiterStatus(),
365
- prewarm: { ...prewarmProgress },
366
- requests: devtools.requests,
367
- errors: devtools.errors,
368
- };
369
- }
1
+ /**
2
+ * "Detaylı İncele" raporunun veri katmanı.
3
+ *
4
+ * Overlay baloncuğu anlık durumu gösterir; bu modül ise sitenin tamamına
5
+ * bakan bir görünüm üretir: gezilen her sayfanın Web Vitals ölçümleri, SSR
6
+ * çıktısının boyutu, island (CSR) durumu, tarayıcı ve sunucu tarafındaki API
7
+ * çağrıları, build çıktısındaki chunk/varlık kırılımı ve HTML önbelleği.
8
+ *
9
+ * Yalnızca development'ta yüklenir (devtools ile birlikte mount edilir),
10
+ * üretim çıktısına girmez.
11
+ */
12
+ import fs from "node:fs";
13
+ import path from "node:path";
14
+ import zlib from "node:zlib";
15
+ import { getHtmlCacheEntries, getHtmlCacheSize } from "../html-cache.js";
16
+ import { getDataCacheSize, getDataCacheStats } from "../data-cache.js";
17
+ import { getRedisStatus } from "../redis.js";
18
+ import { getUpstreamLimiterStatus } from "../upstream-limiter.js";
19
+ import { prewarmProgress } from "../prewarm.js";
20
+ import { getConfig } from "../../config/index.js";
21
+
22
+ /** Yollar config'ten: framework paket içine taşındığında `../..` sayan her hesap bozulur. */
23
+ const ROOT = getConfig().root;
24
+ const PUBLIC_DIR = getConfig().dirs.public;
25
+ const GENERATED_DIR = getConfig().dirs.generated;
26
+
27
+ /* ------------------------------------------------------------- sayfa ölçümleri */
28
+
29
+ /**
30
+ * @typedef {{
31
+ * url: string,
32
+ * title: string | null,
33
+ * at: number,
34
+ * visits: number,
35
+ * metrics: Record<string, number | null>,
36
+ * resources: { count: number, bytes: number, byType: Record<string, { count: number, bytes: number }> },
37
+ * islands: { total: number, ready: number, names: string[] },
38
+ * api: { url: string, ms: number, status: number, bytes: number, initiator: string }[],
39
+ * html: { bytes: number | null, cache: string | null, ms: number | null },
40
+ * }} PageReport
41
+ */
42
+
43
+ /** @type {Map<string, PageReport>} */
44
+ const pages = new Map();
45
+
46
+ /** Tarayıcıdan gelen ölçüm paketini saklar. En yeni paket öncekini ezer. */
47
+ export function recordPageReport(payload) {
48
+ if (!payload?.url) return;
49
+
50
+ let url;
51
+ try {
52
+ url = new URL(payload.url).pathname + new URL(payload.url).search;
53
+ } catch {
54
+ url = String(payload.url);
55
+ }
56
+
57
+ const previous = pages.get(url);
58
+
59
+ pages.set(url, {
60
+ url,
61
+ title: payload.title ?? previous?.title ?? null,
62
+ at: Date.now(),
63
+ visits: (previous?.visits ?? 0) + 1,
64
+ metrics: payload.metrics ?? {},
65
+ resources: payload.resources ?? { count: 0, bytes: 0, byType: {} },
66
+ islands: payload.islands ?? { total: 0, ready: 0, names: [] },
67
+ api: Array.isArray(payload.api) ? payload.api.slice(0, 100) : [],
68
+ html: previous?.html ?? { bytes: null, cache: null, ms: null },
69
+ });
70
+ }
71
+
72
+ /** Ölçümler tarayıcı sekmesinde değil sunucuda durur; sıfırlama da buradan. */
73
+ export function clearPageReports() {
74
+ pages.clear();
75
+ serverApiCalls.length = 0;
76
+ }
77
+
78
+ /* --------------------------------------------------- sunucu tarafı API çağrıları */
79
+
80
+ /**
81
+ * @type {{ url: string, host: string, method: string, status: number, ms: number,
82
+ * bytes: number, at: number, error: string | null }[]}
83
+ */
84
+ const serverApiCalls = [];
85
+ const MAX_API_CALLS = 300;
86
+
87
+ /**
88
+ * SSR sırasında yapılan dış çağrıları ölçer. `globalThis.fetch` sarılır;
89
+ * yalnızca dev'de çağrıldığı için üretim yolu dokunulmaz kalır.
90
+ */
91
+ export function trackServerFetch() {
92
+ const original = globalThis.fetch;
93
+ if (original.__jskeletWrapped) return;
94
+
95
+ /** @type {typeof fetch} */
96
+ const wrapped = async (input, init) => {
97
+ const url = typeof input === "string" ? input : (input?.url ?? String(input));
98
+ const started = Date.now();
99
+
100
+ // Kendi sunucumuza yapılan istekler (ısıtma, sağlık kontrolü) API sayılmaz.
101
+ const isSelf = /^https?:\/\/(127\.0\.0\.1|localhost)/i.test(url);
102
+
103
+ try {
104
+ const response = await original(input, init);
105
+ if (!isSelf) {
106
+ push({
107
+ url,
108
+ method: init?.method ?? "GET",
109
+ status: response.status,
110
+ ms: Date.now() - started,
111
+ bytes: Number(response.headers.get("content-length") ?? 0),
112
+ error: response.ok ? null : `HTTP ${response.status}`,
113
+ });
114
+ }
115
+ return response;
116
+ } catch (error) {
117
+ if (!isSelf) {
118
+ push({
119
+ url,
120
+ method: init?.method ?? "GET",
121
+ status: 0,
122
+ ms: Date.now() - started,
123
+ bytes: 0,
124
+ error: error instanceof Error ? error.message : String(error),
125
+ });
126
+ }
127
+ throw error;
128
+ }
129
+ };
130
+
131
+ wrapped.__jskeletWrapped = true;
132
+ globalThis.fetch = wrapped;
133
+ }
134
+
135
+ /** @param {{ url: string, method: string, status: number, ms: number, bytes: number, error: string | null }} call */
136
+ function push(call) {
137
+ let host = "—";
138
+ try {
139
+ host = new URL(call.url).host;
140
+ } catch {
141
+ // Göreli adres: host bilinmiyor.
142
+ }
143
+
144
+ serverApiCalls.push({ ...call, host, at: Date.now() });
145
+ while (serverApiCalls.length > MAX_API_CALLS) serverApiCalls.shift();
146
+ }
147
+
148
+ /* ------------------------------------------------------------ build çıktısı */
149
+
150
+ /** Boyut hesapları dosya değişmedikçe tekrarlanmaz. */
151
+ const sizeCache = new Map();
152
+
153
+ /**
154
+ * @param {string} file mutlak yol
155
+ * @returns {{ bytes: number, gzip: number, brotli: number | null } | null}
156
+ */
157
+ function measure(file) {
158
+ let stat;
159
+ try {
160
+ stat = fs.statSync(file);
161
+ } catch {
162
+ return null;
163
+ }
164
+
165
+ const key = `${file}:${stat.size}:${stat.mtimeMs}`;
166
+ const hit = sizeCache.get(key);
167
+ if (hit) return hit;
168
+
169
+ let gzip = 0;
170
+ let brotli = null;
171
+
172
+ try {
173
+ const buffer = fs.readFileSync(file);
174
+ // Build önceden sıkıştırılmış eşlerini üretiyorsa onları kullan; yoksa
175
+ // gzip'i burada hesapla (rapor tek seferlik, maliyeti kabul edilebilir).
176
+ brotli = statSize(`${file}.br`);
177
+ gzip = statSize(`${file}.gz`) ?? zlib.gzipSync(buffer, { level: 6 }).length;
178
+ } catch {
179
+ return null;
180
+ }
181
+
182
+ const value = { bytes: stat.size, gzip, brotli };
183
+ sizeCache.set(key, value);
184
+ return value;
185
+ }
186
+
187
+ /** @param {string} file @returns {number | null} */
188
+ function statSize(file) {
189
+ try {
190
+ return fs.statSync(file).size;
191
+ } catch {
192
+ return null;
193
+ }
194
+ }
195
+
196
+ /** @returns {Record<string, string>} */
197
+ function readJson(file, fallback) {
198
+ try {
199
+ return JSON.parse(fs.readFileSync(file, "utf8"));
200
+ } catch {
201
+ return fallback;
202
+ }
203
+ }
204
+
205
+ /**
206
+ * Manifest girdileri + boyutları. Yol public/ altına göre çözülür.
207
+ */
208
+ function assets() {
209
+ const manifest = readJson(path.join(GENERATED_DIR, "manifest.json"), {});
210
+
211
+ return Object.entries(manifest).map(([name, url]) => {
212
+ const size = measure(path.join(PUBLIC_DIR, url.replace(/^\//, "")));
213
+ return {
214
+ name,
215
+ url,
216
+ kind: path.extname(url).slice(1) || "other",
217
+ bytes: size?.bytes ?? null,
218
+ gzip: size?.gzip ?? null,
219
+ brotli: size?.brotli ?? null,
220
+ };
221
+ });
222
+ }
223
+
224
+ /**
225
+ * esbuild metafile'ından chunk analizi: her çıktı için boyut, hangi
226
+ * kaynaklardan oluştuğu ve hangi chunk'ları import ettiği.
227
+ */
228
+ function chunks() {
229
+ const metafile = readJson(path.join(GENERATED_DIR, "metafile.json"), null);
230
+ if (!metafile?.outputs) return { outputs: [], groups: [], available: false };
231
+
232
+ /** @type {Record<string, number>} */
233
+ const groups = {};
234
+
235
+ const outputs = Object.entries(metafile.outputs)
236
+ .filter(([file]) => file.endsWith(".js") || file.endsWith(".css"))
237
+ .map(([file, output]) => {
238
+ const size = measure(path.join(ROOT, file));
239
+
240
+ const inputs = Object.entries(output.inputs ?? {})
241
+ .map(([source, info]) => ({ source, bytes: info.bytesInOutput ?? 0 }))
242
+ .filter((input) => input.bytes > 0)
243
+ .sort((a, b) => b.bytes - a.bytes);
244
+
245
+ for (const input of inputs) {
246
+ const group = groupOf(input.source);
247
+ groups[group] = (groups[group] ?? 0) + input.bytes;
248
+ }
249
+
250
+ return {
251
+ file: `/${file.split(path.sep).join("/").replace(/^public\//, "")}`,
252
+ entry: output.entryPoint ?? null,
253
+ isChunk: file.includes("chunks"),
254
+ bytes: output.bytes,
255
+ gzip: size?.gzip ?? null,
256
+ brotli: size?.brotli ?? null,
257
+ imports: (output.imports ?? [])
258
+ .filter((item) => item.kind !== "file-loader")
259
+ .map((item) => ({
260
+ path: `/${item.path.split(path.sep).join("/").replace(/^public\//, "")}`,
261
+ kind: item.kind,
262
+ })),
263
+ inputs: inputs.slice(0, 40),
264
+ inputCount: inputs.length,
265
+ };
266
+ })
267
+ .sort((a, b) => b.bytes - a.bytes);
268
+
269
+ return {
270
+ available: true,
271
+ outputs,
272
+ groups: Object.entries(groups)
273
+ .map(([name, bytes]) => ({ name, bytes }))
274
+ .sort((a, b) => b.bytes - a.bytes),
275
+ };
276
+ }
277
+
278
+ /**
279
+ * Kaynak dosyayı okunur bir gruba indirger: paket adı ya da üst klasör.
280
+ * @param {string} source
281
+ */
282
+ function groupOf(source) {
283
+ const normalized = source.split(path.sep).join("/");
284
+ const modules = normalized.lastIndexOf("node_modules/");
285
+
286
+ if (modules >= 0) {
287
+ const rest = normalized.slice(modules + "node_modules/".length).split("/");
288
+ return rest[0].startsWith("@") ? `${rest[0]}/${rest[1]}` : rest[0];
289
+ }
290
+
291
+ const parts = normalized.split("/").filter(Boolean);
292
+ return parts.slice(0, 2).join("/") || normalized;
293
+ }
294
+
295
+ /* ------------------------------------------------------------------- rapor */
296
+
297
+ /**
298
+ * Rapor sayfasının tek veri kaynağı.
299
+ * @param {{ requests: object[], errors: object[] }} devtools
300
+ */
301
+ export function buildReport(devtools) {
302
+ const usage = process.memoryUsage();
303
+
304
+ // SSR ölçümleri: ısıtma turu her sayfanın HTML boyutunu ve render süresini
305
+ // biliyor; gezilen sayfalarla eşleştirilir.
306
+ const warmByPath = new Map(
307
+ (prewarmProgress.entries ?? []).map((entry) => [entry.path, entry]),
308
+ );
309
+
310
+ const pageList = [...pages.values()].map((page) => {
311
+ const warm = warmByPath.get(page.url.split("?")[0]);
312
+ return {
313
+ ...page,
314
+ html: warm
315
+ ? { bytes: warm.bytes, cache: warm.cache, ms: warm.ms }
316
+ : page.html,
317
+ };
318
+ });
319
+
320
+ // Hiç gezilmemiş ama ısıtılmış sayfalar da listelenir: SSR tarafı bilinir,
321
+ // istemci ölçümleri boş kalır.
322
+ for (const entry of prewarmProgress.entries ?? []) {
323
+ if (pages.has(entry.path)) continue;
324
+ pageList.push({
325
+ url: entry.path,
326
+ title: null,
327
+ at: prewarmProgress.finishedAt ?? prewarmProgress.startedAt,
328
+ visits: 0,
329
+ metrics: {},
330
+ resources: { count: 0, bytes: 0, byType: {} },
331
+ islands: { total: 0, ready: 0, names: [] },
332
+ api: [],
333
+ html: { bytes: entry.bytes, cache: entry.cache, ms: entry.ms },
334
+ });
335
+ }
336
+
337
+ return {
338
+ generatedAt: Date.now(),
339
+ process: {
340
+ pid: process.pid,
341
+ node: process.version,
342
+ uptime: process.uptime(),
343
+ memory: { rss: usage.rss, heapUsed: usage.heapUsed },
344
+ env: process.env.NODE_ENV ?? "development",
345
+ },
346
+ pages: pageList.sort((a, b) => (b.visits - a.visits) || b.at - a.at),
347
+ serverApi: serverApiCalls.slice().reverse(),
348
+ build: { assets: assets(), ...chunks() },
349
+ cache: {
350
+ size: getHtmlCacheSize(),
351
+ entries: getHtmlCacheEntries(),
352
+ // Veri önbelleğinden yalnızca sayaç: uzun kuyruklu bir sitede on
353
+ // binlerce anahtar oluyor ve dökümü rapora koymak faydasız bir yük.
354
+ data: getDataCacheSize(),
355
+ // Sayaçlar dökümün yerine geçmiyor, onu tamamlıyor: "kaç girdi var"
356
+ // sorusundan çok "kaç okuma upstream'e gitti" sorusu karar veriyor.
357
+ dataStats: getDataCacheStats(),
358
+ // Paylaşımlı kademe kapalıyken de basılır: "Redis'i açtım ama neden
359
+ // çalışmıyor" sorusunun cevabı en çok burada aranıyor.
360
+ redis: getRedisStatus(),
361
+ },
362
+ // Hız freninin o anki durumu. 429 fırtınasında "şu an saniyede kaça
363
+ // indi" bilgisi olmadan ayar yapmak körlemesine oluyor.
364
+ upstream: getUpstreamLimiterStatus(),
365
+ prewarm: { ...prewarmProgress },
366
+ requests: devtools.requests,
367
+ errors: devtools.errors,
368
+ };
369
+ }