jskelet 0.6.3 → 0.6.4

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 (153) hide show
  1. package/AGENTS.md +136 -136
  2. package/CHANGELOG.md +628 -620
  3. package/LICENSE +21 -21
  4. package/README.md +2 -0
  5. package/bin/jskelet.mjs +130 -130
  6. package/docs/01-baslangic.md +291 -291
  7. package/docs/02-mimari.md +310 -310
  8. package/docs/03-routing.md +515 -515
  9. package/docs/04-render-ve-sablonlar.md +667 -661
  10. package/docs/05-islands.md +486 -486
  11. package/docs/06-cache.md +1467 -1443
  12. package/docs/07-yapilandirma.md +1208 -1197
  13. package/docs/08-build.md +429 -429
  14. package/docs/09-dev-araclari.md +364 -364
  15. package/docs/10-dagitim.md +348 -338
  16. package/docs/12-panel-ve-oturum.md +479 -478
  17. package/docs/README.md +83 -83
  18. package/docs/en/01-getting-started.md +298 -298
  19. package/docs/en/02-architecture.md +329 -329
  20. package/docs/en/03-routing.md +531 -531
  21. package/docs/en/04-rendering.md +675 -669
  22. package/docs/en/05-islands.md +497 -497
  23. package/docs/en/06-caching.md +1476 -1453
  24. package/docs/en/07-configuration.md +1229 -1219
  25. package/docs/en/08-build.md +447 -447
  26. package/docs/en/09-dev-tools.md +373 -373
  27. package/docs/en/10-deployment.md +351 -340
  28. package/docs/en/11-migration.md +398 -398
  29. package/docs/en/12-dashboards-and-sessions.md +489 -488
  30. package/docs/en/README.md +87 -87
  31. package/package.json +137 -137
  32. package/src/build/ensure-build.mjs +19 -19
  33. package/src/build/paths.mjs +153 -153
  34. package/src/build/resolve-peer.mjs +36 -36
  35. package/src/build/tasks/client.mjs +349 -349
  36. package/src/build/tasks/css.mjs +235 -235
  37. package/src/build/tasks/fonts.mjs +146 -146
  38. package/src/build/tasks/icons.mjs +357 -357
  39. package/src/build/tasks/images.mjs +244 -244
  40. package/src/build/tasks/precompress.mjs +78 -78
  41. package/src/build/tasks/templates.mjs +20 -20
  42. package/src/client/admin/i18n.js +764 -764
  43. package/src/client/admin/login.html +74 -74
  44. package/src/client/admin/panel.css +809 -809
  45. package/src/client/admin/panel.html +495 -495
  46. package/src/client/admin/panel.js +1251 -1251
  47. package/src/client/devtools/report.html +185 -185
  48. package/src/client/devtools/report.js +745 -745
  49. package/src/client/devtools/seo.js +628 -628
  50. package/src/client/dom.js +95 -95
  51. package/src/client/form.js +192 -192
  52. package/src/client/index.js +45 -45
  53. package/src/client/registry.js +305 -305
  54. package/src/client/safe-image.js +91 -91
  55. package/src/client/shared-cookie.js +225 -225
  56. package/src/client/store.js +36 -36
  57. package/src/client/swap.js +188 -188
  58. package/src/compile/codegen.js +336 -336
  59. package/src/compile/compile-all.js +149 -149
  60. package/src/compile/errors.js +66 -66
  61. package/src/compile/expr.js +409 -409
  62. package/src/compile/index.js +17 -17
  63. package/src/compile/parse.js +541 -541
  64. package/src/compile/resolve.js +211 -211
  65. package/src/compile/scan-exports.js +51 -51
  66. package/src/config/defaults.js +541 -534
  67. package/src/config/index.js +1500 -1469
  68. package/src/config/pattern.js +107 -107
  69. package/src/generate.mjs +163 -163
  70. package/src/http/control-flow.js +71 -71
  71. package/src/http/cookies-entry.js +21 -21
  72. package/src/http/cookies.js +277 -277
  73. package/src/http/request-cache.js +46 -46
  74. package/src/http/request-context.js +165 -165
  75. package/src/http/shared-cookie.js +178 -178
  76. package/src/index.js +101 -101
  77. package/src/init.mjs +232 -230
  78. package/src/migrate/apply.mjs +262 -262
  79. package/src/migrate/babel.mjs +79 -79
  80. package/src/migrate/classify.mjs +155 -155
  81. package/src/migrate/config.mjs +126 -126
  82. package/src/migrate/fs-walk.mjs +191 -191
  83. package/src/migrate/parse.mjs +26 -26
  84. package/src/migrate/scan.mjs +177 -177
  85. package/src/migrate/transform/expr-source.mjs +168 -168
  86. package/src/migrate/transform/island.mjs +67 -67
  87. package/src/migrate/transform/jsx-to-component.mjs +302 -302
  88. package/src/migrate/transform/jsx-to-jsk.mjs +330 -330
  89. package/src/migrate/transform/page-split.mjs +435 -435
  90. package/src/migrate/write.mjs +81 -81
  91. package/src/migrate.mjs +171 -171
  92. package/src/runtime/alias-hooks.mjs +119 -119
  93. package/src/runtime/register.mjs +4 -4
  94. package/src/server/admin/actions.js +229 -229
  95. package/src/server/admin/auth.js +125 -125
  96. package/src/server/admin/event-log.js +151 -151
  97. package/src/server/admin/gate.js +209 -209
  98. package/src/server/admin/inventory.js +188 -188
  99. package/src/server/admin/mount.js +56 -56
  100. package/src/server/admin/router.js +216 -216
  101. package/src/server/admin/snapshot.js +241 -241
  102. package/src/server/assets.js +147 -147
  103. package/src/server/auth/handoff.js +309 -309
  104. package/src/server/cache-blob.js +70 -70
  105. package/src/server/cache-control.js +45 -0
  106. package/src/server/cache-deps.js +42 -42
  107. package/src/server/cache-vary.js +113 -113
  108. package/src/server/cloudflare.js +607 -607
  109. package/src/server/create-app.js +366 -366
  110. package/src/server/data-cache.js +553 -553
  111. package/src/server/dev/report.js +485 -485
  112. package/src/server/dev/socket.js +170 -170
  113. package/src/server/dev/version-check.mjs +139 -139
  114. package/src/server/disk-cache.js +233 -233
  115. package/src/server/ejs-adapter.js +59 -59
  116. package/src/server/html-cache.js +1196 -1196
  117. package/src/server/image-optimizer.js +500 -500
  118. package/src/server/logs/access-middleware.js +66 -66
  119. package/src/server/logs/file-sink.js +193 -193
  120. package/src/server/logs/pipeline.js +165 -165
  121. package/src/server/logs/s3-put.js +214 -214
  122. package/src/server/logs/s3-sink.js +112 -112
  123. package/src/server/metadata.js +102 -102
  124. package/src/server/middleware/compression.js +205 -205
  125. package/src/server/middleware/csrf.js +134 -134
  126. package/src/server/middleware/dev-gate.js +75 -75
  127. package/src/server/middleware/headers.js +37 -37
  128. package/src/server/middleware/redirects.js +32 -32
  129. package/src/server/middleware/robots-txt.js +341 -341
  130. package/src/server/middleware/static-precompressed.js +121 -121
  131. package/src/server/middleware/trailing-slash.js +53 -53
  132. package/src/server/middleware/upstream-proxy.js +141 -141
  133. package/src/server/og-image.js +369 -356
  134. package/src/server/port-guard.js +255 -255
  135. package/src/server/prewarm.js +1082 -1082
  136. package/src/server/redis.js +588 -588
  137. package/src/server/render.js +910 -910
  138. package/src/server/router.js +157 -157
  139. package/src/server/status-page.js +265 -265
  140. package/src/server/upstream-limiter.js +376 -376
  141. package/src/server/upstream-tracking.js +166 -166
  142. package/src/shared/cookie-domain.js +66 -66
  143. package/src/start.mjs +22 -22
  144. package/src/templates/layout.ejs +30 -30
  145. package/src/templates/layout.jsk +30 -30
  146. package/src/version.mjs +31 -31
  147. package/src/views/components/loader.js +101 -101
  148. package/src/views/helpers/html.js +102 -102
  149. package/src/views/helpers/tags.js +375 -375
  150. package/types/config/defaults.d.ts +6 -0
  151. package/types/config/index.d.ts +6 -0
  152. package/types/server/cache-control.d.ts +28 -0
  153. package/types/server/og-image.d.ts +5 -0
@@ -1,485 +1,485 @@
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
- import { getRequestContext } from "../../http/request-context.js";
22
-
23
- /** Yollar config'ten: framework paket içine taşındığında `../..` sayan her hesap bozulur. */
24
- const ROOT = getConfig().root;
25
- const PUBLIC_DIR = getConfig().dirs.public;
26
- const GENERATED_DIR = getConfig().dirs.generated;
27
-
28
- /* ------------------------------------------------------------- sayfa ölçümleri */
29
-
30
- /**
31
- * @typedef {{
32
- * url: string,
33
- * title: string | null,
34
- * at: number,
35
- * visits: number,
36
- * metrics: Record<string, number | null>,
37
- * resources: { count: number, bytes: number, byType: Record<string, { count: number, bytes: number }> },
38
- * islands: { total: number, ready: number, names: string[] },
39
- * api: { url: string, ms: number, status: number, bytes: number, initiator: string }[],
40
- * html: { bytes: number | null, cache: string | null, ms: number | null },
41
- * }} PageReport
42
- */
43
-
44
- /** @type {Map<string, PageReport>} */
45
- const pages = new Map();
46
-
47
- /** Tarayıcıdan gelen ölçüm paketini saklar. En yeni paket öncekini ezer. */
48
- export function recordPageReport(payload) {
49
- if (!payload?.url) return;
50
-
51
- let url;
52
- try {
53
- url = new URL(payload.url).pathname + new URL(payload.url).search;
54
- } catch {
55
- url = String(payload.url);
56
- }
57
-
58
- const previous = pages.get(url);
59
-
60
- pages.set(url, {
61
- url,
62
- title: payload.title ?? previous?.title ?? null,
63
- at: Date.now(),
64
- visits: (previous?.visits ?? 0) + 1,
65
- metrics: payload.metrics ?? {},
66
- resources: payload.resources ?? { count: 0, bytes: 0, byType: {} },
67
- islands: payload.islands ?? { total: 0, ready: 0, names: [] },
68
- api: Array.isArray(payload.api) ? payload.api.slice(0, 100) : [],
69
- html: previous?.html ?? { bytes: null, cache: null, ms: null },
70
- });
71
- }
72
-
73
- /** Ölçümler tarayıcı sekmesinde değil sunucuda durur; sıfırlama da buradan. */
74
- export function clearPageReports() {
75
- pages.clear();
76
- serverApiCalls.length = 0;
77
- }
78
-
79
- /* --------------------------------------------------- sunucu tarafı API çağrıları */
80
-
81
- /**
82
- * @typedef {{
83
- * url: string,
84
- * host: string,
85
- * method: string,
86
- * status: number,
87
- * ms: number,
88
- * bytes: number,
89
- * at: number,
90
- * error: string | null,
91
- * page: string | null,
92
- * details: unknown,
93
- * }} ServerApiCall
94
- */
95
-
96
- /** @type {ServerApiCall[]} */
97
- const serverApiCalls = [];
98
- const MAX_API_CALLS = 300;
99
-
100
- /** Başarısız çağrı gövdesinin overlay'e taşınacak üst sınırı. */
101
- const DETAILS_MAX = 4_000;
102
-
103
- /**
104
- * @typedef {{
105
- * url: string,
106
- * method: string,
107
- * status: number,
108
- * ms: number,
109
- * bytes: number,
110
- * error: string | null,
111
- * page: string | null,
112
- * details: unknown,
113
- * }} ApiFailure
114
- */
115
-
116
- /**
117
- * SSR sırasında yapılan dış çağrıları ölçer. `globalThis.fetch` sarılır;
118
- * yalnızca dev'de çağrıldığı için üretim yolu dokunulmaz kalır.
119
- *
120
- * Başarısız cevaplar (4xx/5xx ya da ağ) isteğe bağlı `onFailure` ile
121
- * overlay hata günlüğüne de düşer — uygulama kendi logger'ıyla stderr'e
122
- * yazsa bile panel "hangi sayfa hangi API" bilgisini görsün.
123
- *
124
- * @param {{ onFailure?: (call: ApiFailure) => void }} [options]
125
- */
126
- export function trackServerFetch(options = {}) {
127
- const original = globalThis.fetch;
128
- if (/** @type {any} */ (original).__jskeletWrapped) return;
129
-
130
- const { onFailure } = options;
131
-
132
- /** @type {typeof fetch} */
133
- const wrapped = async (input, init) => {
134
- const url = typeof input === "string" ? input : (input?.url ?? String(input));
135
- const method = String(init?.method ?? "GET").toUpperCase();
136
- const started = Date.now();
137
- const page = currentPage();
138
-
139
- // Kendi sunucumuza yapılan istekler (ısıtma, sağlık kontrolü) API sayılmaz.
140
- const isSelf = /^https?:\/\/(127\.0\.0\.1|\[::1\]|localhost)(:|\/|$)/i.test(url);
141
-
142
- try {
143
- const response = await original(input, init);
144
- if (!isSelf) {
145
- const details = response.ok
146
- ? null
147
- : await readFailureDetails(response);
148
- const error = response.ok ? null : summarizeFailure(response.status, details);
149
- const call = {
150
- url,
151
- method,
152
- status: response.status,
153
- ms: Date.now() - started,
154
- bytes: Number(response.headers.get("content-length") ?? 0),
155
- error,
156
- page,
157
- details,
158
- };
159
- push(call);
160
- if (error) onFailure?.(call);
161
- }
162
- return response;
163
- } catch (error) {
164
- if (!isSelf) {
165
- const message = error instanceof Error ? error.message : String(error);
166
- const call = {
167
- url,
168
- method,
169
- status: 0,
170
- ms: Date.now() - started,
171
- bytes: 0,
172
- error: message,
173
- page,
174
- details: null,
175
- };
176
- push(call);
177
- onFailure?.(call);
178
- }
179
- throw error;
180
- }
181
- };
182
-
183
- /** @type {any} */ (wrapped).__jskeletWrapped = true;
184
- globalThis.fetch = wrapped;
185
- }
186
-
187
- /** @returns {string | null} */
188
- function currentPage() {
189
- return getRequestContext()?.pathname ?? null;
190
- }
191
-
192
- /**
193
- * @param {Response} response
194
- * @returns {Promise<unknown>}
195
- */
196
- async function readFailureDetails(response) {
197
- try {
198
- const text = (await response.clone().text()).slice(0, DETAILS_MAX);
199
- if (!text) return null;
200
- try {
201
- return JSON.parse(text);
202
- } catch {
203
- return text;
204
- }
205
- } catch {
206
- return null;
207
- }
208
- }
209
-
210
- /**
211
- * Overlay başlığı: durum + varsa API'nin kendi doğrulama mesajı.
212
- *
213
- * @param {number} status
214
- * @param {unknown} details
215
- * @returns {string}
216
- */
217
- function summarizeFailure(status, details) {
218
- const label = `HTTP ${status}`;
219
- const detail = failureMessage(details);
220
- return detail ? `${label}: ${detail}` : label;
221
- }
222
-
223
- /**
224
- * Upstream gövdesinden kısa, okunabilir bir cümle çıkarır. `[object Object]`
225
- * basmamak için nesneleri bilinçli dolaşır.
226
- *
227
- * @param {unknown} details
228
- * @returns {string | null}
229
- */
230
- function failureMessage(details) {
231
- if (details == null) return null;
232
- if (typeof details === "string") return details.slice(0, 280);
233
- if (typeof details !== "object") return String(details);
234
-
235
- const record = /** @type {Record<string, unknown>} */ (details);
236
- for (const key of ["details", "detail", "message", "error", "title"]) {
237
- const value = record[key];
238
- if (typeof value === "string" && value.trim()) return value.slice(0, 280);
239
- if (value && typeof value === "object") {
240
- const nested = failureMessage(value);
241
- if (nested) return nested;
242
- }
243
- }
244
- try {
245
- return JSON.stringify(details).slice(0, 280);
246
- } catch {
247
- return null;
248
- }
249
- }
250
-
251
- /** @param {Omit<ServerApiCall, "host" | "at">} call */
252
- function push(call) {
253
- let host = "—";
254
- try {
255
- host = new URL(call.url).host;
256
- } catch {
257
- // Göreli adres: host bilinmiyor.
258
- }
259
-
260
- serverApiCalls.push({ ...call, host, at: Date.now() });
261
- while (serverApiCalls.length > MAX_API_CALLS) serverApiCalls.shift();
262
- }
263
-
264
- /* ------------------------------------------------------------ build çıktısı */
265
-
266
- /** Boyut hesapları dosya değişmedikçe tekrarlanmaz. */
267
- const sizeCache = new Map();
268
-
269
- /**
270
- * @param {string} file mutlak yol
271
- * @returns {{ bytes: number, gzip: number, brotli: number | null } | null}
272
- */
273
- function measure(file) {
274
- let stat;
275
- try {
276
- stat = fs.statSync(file);
277
- } catch {
278
- return null;
279
- }
280
-
281
- const key = `${file}:${stat.size}:${stat.mtimeMs}`;
282
- const hit = sizeCache.get(key);
283
- if (hit) return hit;
284
-
285
- let gzip = 0;
286
- let brotli = null;
287
-
288
- try {
289
- const buffer = fs.readFileSync(file);
290
- // Build önceden sıkıştırılmış eşlerini üretiyorsa onları kullan; yoksa
291
- // gzip'i burada hesapla (rapor tek seferlik, maliyeti kabul edilebilir).
292
- brotli = statSize(`${file}.br`);
293
- gzip = statSize(`${file}.gz`) ?? zlib.gzipSync(buffer, { level: 6 }).length;
294
- } catch {
295
- return null;
296
- }
297
-
298
- const value = { bytes: stat.size, gzip, brotli };
299
- sizeCache.set(key, value);
300
- return value;
301
- }
302
-
303
- /** @param {string} file @returns {number | null} */
304
- function statSize(file) {
305
- try {
306
- return fs.statSync(file).size;
307
- } catch {
308
- return null;
309
- }
310
- }
311
-
312
- /** @returns {Record<string, string>} */
313
- function readJson(file, fallback) {
314
- try {
315
- return JSON.parse(fs.readFileSync(file, "utf8"));
316
- } catch {
317
- return fallback;
318
- }
319
- }
320
-
321
- /**
322
- * Manifest girdileri + boyutları. Yol public/ altına göre çözülür.
323
- */
324
- function assets() {
325
- const manifest = readJson(path.join(GENERATED_DIR, "manifest.json"), {});
326
-
327
- return Object.entries(manifest).map(([name, url]) => {
328
- const size = measure(path.join(PUBLIC_DIR, url.replace(/^\//, "")));
329
- return {
330
- name,
331
- url,
332
- kind: path.extname(url).slice(1) || "other",
333
- bytes: size?.bytes ?? null,
334
- gzip: size?.gzip ?? null,
335
- brotli: size?.brotli ?? null,
336
- };
337
- });
338
- }
339
-
340
- /**
341
- * esbuild metafile'ından chunk analizi: her çıktı için boyut, hangi
342
- * kaynaklardan oluştuğu ve hangi chunk'ları import ettiği.
343
- */
344
- function chunks() {
345
- const metafile = readJson(path.join(GENERATED_DIR, "metafile.json"), null);
346
- if (!metafile?.outputs) return { outputs: [], groups: [], available: false };
347
-
348
- /** @type {Record<string, number>} */
349
- const groups = {};
350
-
351
- const outputs = Object.entries(metafile.outputs)
352
- .filter(([file]) => file.endsWith(".js") || file.endsWith(".css"))
353
- .map(([file, output]) => {
354
- const size = measure(path.join(ROOT, file));
355
-
356
- const inputs = Object.entries(output.inputs ?? {})
357
- .map(([source, info]) => ({ source, bytes: info.bytesInOutput ?? 0 }))
358
- .filter((input) => input.bytes > 0)
359
- .sort((a, b) => b.bytes - a.bytes);
360
-
361
- for (const input of inputs) {
362
- const group = groupOf(input.source);
363
- groups[group] = (groups[group] ?? 0) + input.bytes;
364
- }
365
-
366
- return {
367
- file: `/${file.split(path.sep).join("/").replace(/^public\//, "")}`,
368
- entry: output.entryPoint ?? null,
369
- isChunk: file.includes("chunks"),
370
- bytes: output.bytes,
371
- gzip: size?.gzip ?? null,
372
- brotli: size?.brotli ?? null,
373
- imports: (output.imports ?? [])
374
- .filter((item) => item.kind !== "file-loader")
375
- .map((item) => ({
376
- path: `/${item.path.split(path.sep).join("/").replace(/^public\//, "")}`,
377
- kind: item.kind,
378
- })),
379
- inputs: inputs.slice(0, 40),
380
- inputCount: inputs.length,
381
- };
382
- })
383
- .sort((a, b) => b.bytes - a.bytes);
384
-
385
- return {
386
- available: true,
387
- outputs,
388
- groups: Object.entries(groups)
389
- .map(([name, bytes]) => ({ name, bytes }))
390
- .sort((a, b) => b.bytes - a.bytes),
391
- };
392
- }
393
-
394
- /**
395
- * Kaynak dosyayı okunur bir gruba indirger: paket adı ya da üst klasör.
396
- * @param {string} source
397
- */
398
- function groupOf(source) {
399
- const normalized = source.split(path.sep).join("/");
400
- const modules = normalized.lastIndexOf("node_modules/");
401
-
402
- if (modules >= 0) {
403
- const rest = normalized.slice(modules + "node_modules/".length).split("/");
404
- return rest[0].startsWith("@") ? `${rest[0]}/${rest[1]}` : rest[0];
405
- }
406
-
407
- const parts = normalized.split("/").filter(Boolean);
408
- return parts.slice(0, 2).join("/") || normalized;
409
- }
410
-
411
- /* ------------------------------------------------------------------- rapor */
412
-
413
- /**
414
- * Rapor sayfasının tek veri kaynağı.
415
- * @param {{ requests: object[], errors: object[] }} devtools
416
- */
417
- export function buildReport(devtools) {
418
- const usage = process.memoryUsage();
419
-
420
- // SSR ölçümleri: ısıtma turu her sayfanın HTML boyutunu ve render süresini
421
- // biliyor; gezilen sayfalarla eşleştirilir.
422
- const warmByPath = new Map(
423
- (prewarmProgress.entries ?? []).map((entry) => [entry.path, entry]),
424
- );
425
-
426
- const pageList = [...pages.values()].map((page) => {
427
- const warm = warmByPath.get(page.url.split("?")[0]);
428
- return {
429
- ...page,
430
- html: warm
431
- ? { bytes: warm.bytes, cache: warm.cache, ms: warm.ms }
432
- : page.html,
433
- };
434
- });
435
-
436
- // Hiç gezilmemiş ama ısıtılmış sayfalar da listelenir: SSR tarafı bilinir,
437
- // istemci ölçümleri boş kalır.
438
- for (const entry of prewarmProgress.entries ?? []) {
439
- if (pages.has(entry.path)) continue;
440
- pageList.push({
441
- url: entry.path,
442
- title: null,
443
- at: prewarmProgress.finishedAt ?? prewarmProgress.startedAt,
444
- visits: 0,
445
- metrics: {},
446
- resources: { count: 0, bytes: 0, byType: {} },
447
- islands: { total: 0, ready: 0, names: [] },
448
- api: [],
449
- html: { bytes: entry.bytes, cache: entry.cache, ms: entry.ms },
450
- });
451
- }
452
-
453
- return {
454
- generatedAt: Date.now(),
455
- process: {
456
- pid: process.pid,
457
- node: process.version,
458
- uptime: process.uptime(),
459
- memory: { rss: usage.rss, heapUsed: usage.heapUsed },
460
- env: process.env.NODE_ENV ?? "development",
461
- },
462
- pages: pageList.sort((a, b) => (b.visits - a.visits) || b.at - a.at),
463
- serverApi: serverApiCalls.slice().reverse(),
464
- build: { assets: assets(), ...chunks() },
465
- cache: {
466
- size: getHtmlCacheSize(),
467
- entries: getHtmlCacheEntries(),
468
- // Veri önbelleğinden yalnızca sayaç: uzun kuyruklu bir sitede on
469
- // binlerce anahtar oluyor ve dökümü rapora koymak faydasız bir yük.
470
- data: getDataCacheSize(),
471
- // Sayaçlar dökümün yerine geçmiyor, onu tamamlıyor: "kaç girdi var"
472
- // sorusundan çok "kaç okuma upstream'e gitti" sorusu karar veriyor.
473
- dataStats: getDataCacheStats(),
474
- // Paylaşımlı kademe kapalıyken de basılır: "Redis'i açtım ama neden
475
- // çalışmıyor" sorusunun cevabı en çok burada aranıyor.
476
- redis: getRedisStatus(),
477
- },
478
- // Hız freninin o anki durumu. 429 fırtınasında "şu an saniyede kaça
479
- // indi" bilgisi olmadan ayar yapmak körlemesine oluyor.
480
- upstream: getUpstreamLimiterStatus(),
481
- prewarm: { ...prewarmProgress },
482
- requests: devtools.requests,
483
- errors: devtools.errors,
484
- };
485
- }
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
+ import { getRequestContext } from "../../http/request-context.js";
22
+
23
+ /** Yollar config'ten: framework paket içine taşındığında `../..` sayan her hesap bozulur. */
24
+ const ROOT = getConfig().root;
25
+ const PUBLIC_DIR = getConfig().dirs.public;
26
+ const GENERATED_DIR = getConfig().dirs.generated;
27
+
28
+ /* ------------------------------------------------------------- sayfa ölçümleri */
29
+
30
+ /**
31
+ * @typedef {{
32
+ * url: string,
33
+ * title: string | null,
34
+ * at: number,
35
+ * visits: number,
36
+ * metrics: Record<string, number | null>,
37
+ * resources: { count: number, bytes: number, byType: Record<string, { count: number, bytes: number }> },
38
+ * islands: { total: number, ready: number, names: string[] },
39
+ * api: { url: string, ms: number, status: number, bytes: number, initiator: string }[],
40
+ * html: { bytes: number | null, cache: string | null, ms: number | null },
41
+ * }} PageReport
42
+ */
43
+
44
+ /** @type {Map<string, PageReport>} */
45
+ const pages = new Map();
46
+
47
+ /** Tarayıcıdan gelen ölçüm paketini saklar. En yeni paket öncekini ezer. */
48
+ export function recordPageReport(payload) {
49
+ if (!payload?.url) return;
50
+
51
+ let url;
52
+ try {
53
+ url = new URL(payload.url).pathname + new URL(payload.url).search;
54
+ } catch {
55
+ url = String(payload.url);
56
+ }
57
+
58
+ const previous = pages.get(url);
59
+
60
+ pages.set(url, {
61
+ url,
62
+ title: payload.title ?? previous?.title ?? null,
63
+ at: Date.now(),
64
+ visits: (previous?.visits ?? 0) + 1,
65
+ metrics: payload.metrics ?? {},
66
+ resources: payload.resources ?? { count: 0, bytes: 0, byType: {} },
67
+ islands: payload.islands ?? { total: 0, ready: 0, names: [] },
68
+ api: Array.isArray(payload.api) ? payload.api.slice(0, 100) : [],
69
+ html: previous?.html ?? { bytes: null, cache: null, ms: null },
70
+ });
71
+ }
72
+
73
+ /** Ölçümler tarayıcı sekmesinde değil sunucuda durur; sıfırlama da buradan. */
74
+ export function clearPageReports() {
75
+ pages.clear();
76
+ serverApiCalls.length = 0;
77
+ }
78
+
79
+ /* --------------------------------------------------- sunucu tarafı API çağrıları */
80
+
81
+ /**
82
+ * @typedef {{
83
+ * url: string,
84
+ * host: string,
85
+ * method: string,
86
+ * status: number,
87
+ * ms: number,
88
+ * bytes: number,
89
+ * at: number,
90
+ * error: string | null,
91
+ * page: string | null,
92
+ * details: unknown,
93
+ * }} ServerApiCall
94
+ */
95
+
96
+ /** @type {ServerApiCall[]} */
97
+ const serverApiCalls = [];
98
+ const MAX_API_CALLS = 300;
99
+
100
+ /** Başarısız çağrı gövdesinin overlay'e taşınacak üst sınırı. */
101
+ const DETAILS_MAX = 4_000;
102
+
103
+ /**
104
+ * @typedef {{
105
+ * url: string,
106
+ * method: string,
107
+ * status: number,
108
+ * ms: number,
109
+ * bytes: number,
110
+ * error: string | null,
111
+ * page: string | null,
112
+ * details: unknown,
113
+ * }} ApiFailure
114
+ */
115
+
116
+ /**
117
+ * SSR sırasında yapılan dış çağrıları ölçer. `globalThis.fetch` sarılır;
118
+ * yalnızca dev'de çağrıldığı için üretim yolu dokunulmaz kalır.
119
+ *
120
+ * Başarısız cevaplar (4xx/5xx ya da ağ) isteğe bağlı `onFailure` ile
121
+ * overlay hata günlüğüne de düşer — uygulama kendi logger'ıyla stderr'e
122
+ * yazsa bile panel "hangi sayfa hangi API" bilgisini görsün.
123
+ *
124
+ * @param {{ onFailure?: (call: ApiFailure) => void }} [options]
125
+ */
126
+ export function trackServerFetch(options = {}) {
127
+ const original = globalThis.fetch;
128
+ if (/** @type {any} */ (original).__jskeletWrapped) return;
129
+
130
+ const { onFailure } = options;
131
+
132
+ /** @type {typeof fetch} */
133
+ const wrapped = async (input, init) => {
134
+ const url = typeof input === "string" ? input : (input?.url ?? String(input));
135
+ const method = String(init?.method ?? "GET").toUpperCase();
136
+ const started = Date.now();
137
+ const page = currentPage();
138
+
139
+ // Kendi sunucumuza yapılan istekler (ısıtma, sağlık kontrolü) API sayılmaz.
140
+ const isSelf = /^https?:\/\/(127\.0\.0\.1|\[::1\]|localhost)(:|\/|$)/i.test(url);
141
+
142
+ try {
143
+ const response = await original(input, init);
144
+ if (!isSelf) {
145
+ const details = response.ok
146
+ ? null
147
+ : await readFailureDetails(response);
148
+ const error = response.ok ? null : summarizeFailure(response.status, details);
149
+ const call = {
150
+ url,
151
+ method,
152
+ status: response.status,
153
+ ms: Date.now() - started,
154
+ bytes: Number(response.headers.get("content-length") ?? 0),
155
+ error,
156
+ page,
157
+ details,
158
+ };
159
+ push(call);
160
+ if (error) onFailure?.(call);
161
+ }
162
+ return response;
163
+ } catch (error) {
164
+ if (!isSelf) {
165
+ const message = error instanceof Error ? error.message : String(error);
166
+ const call = {
167
+ url,
168
+ method,
169
+ status: 0,
170
+ ms: Date.now() - started,
171
+ bytes: 0,
172
+ error: message,
173
+ page,
174
+ details: null,
175
+ };
176
+ push(call);
177
+ onFailure?.(call);
178
+ }
179
+ throw error;
180
+ }
181
+ };
182
+
183
+ /** @type {any} */ (wrapped).__jskeletWrapped = true;
184
+ globalThis.fetch = wrapped;
185
+ }
186
+
187
+ /** @returns {string | null} */
188
+ function currentPage() {
189
+ return getRequestContext()?.pathname ?? null;
190
+ }
191
+
192
+ /**
193
+ * @param {Response} response
194
+ * @returns {Promise<unknown>}
195
+ */
196
+ async function readFailureDetails(response) {
197
+ try {
198
+ const text = (await response.clone().text()).slice(0, DETAILS_MAX);
199
+ if (!text) return null;
200
+ try {
201
+ return JSON.parse(text);
202
+ } catch {
203
+ return text;
204
+ }
205
+ } catch {
206
+ return null;
207
+ }
208
+ }
209
+
210
+ /**
211
+ * Overlay başlığı: durum + varsa API'nin kendi doğrulama mesajı.
212
+ *
213
+ * @param {number} status
214
+ * @param {unknown} details
215
+ * @returns {string}
216
+ */
217
+ function summarizeFailure(status, details) {
218
+ const label = `HTTP ${status}`;
219
+ const detail = failureMessage(details);
220
+ return detail ? `${label}: ${detail}` : label;
221
+ }
222
+
223
+ /**
224
+ * Upstream gövdesinden kısa, okunabilir bir cümle çıkarır. `[object Object]`
225
+ * basmamak için nesneleri bilinçli dolaşır.
226
+ *
227
+ * @param {unknown} details
228
+ * @returns {string | null}
229
+ */
230
+ function failureMessage(details) {
231
+ if (details == null) return null;
232
+ if (typeof details === "string") return details.slice(0, 280);
233
+ if (typeof details !== "object") return String(details);
234
+
235
+ const record = /** @type {Record<string, unknown>} */ (details);
236
+ for (const key of ["details", "detail", "message", "error", "title"]) {
237
+ const value = record[key];
238
+ if (typeof value === "string" && value.trim()) return value.slice(0, 280);
239
+ if (value && typeof value === "object") {
240
+ const nested = failureMessage(value);
241
+ if (nested) return nested;
242
+ }
243
+ }
244
+ try {
245
+ return JSON.stringify(details).slice(0, 280);
246
+ } catch {
247
+ return null;
248
+ }
249
+ }
250
+
251
+ /** @param {Omit<ServerApiCall, "host" | "at">} call */
252
+ function push(call) {
253
+ let host = "—";
254
+ try {
255
+ host = new URL(call.url).host;
256
+ } catch {
257
+ // Göreli adres: host bilinmiyor.
258
+ }
259
+
260
+ serverApiCalls.push({ ...call, host, at: Date.now() });
261
+ while (serverApiCalls.length > MAX_API_CALLS) serverApiCalls.shift();
262
+ }
263
+
264
+ /* ------------------------------------------------------------ build çıktısı */
265
+
266
+ /** Boyut hesapları dosya değişmedikçe tekrarlanmaz. */
267
+ const sizeCache = new Map();
268
+
269
+ /**
270
+ * @param {string} file mutlak yol
271
+ * @returns {{ bytes: number, gzip: number, brotli: number | null } | null}
272
+ */
273
+ function measure(file) {
274
+ let stat;
275
+ try {
276
+ stat = fs.statSync(file);
277
+ } catch {
278
+ return null;
279
+ }
280
+
281
+ const key = `${file}:${stat.size}:${stat.mtimeMs}`;
282
+ const hit = sizeCache.get(key);
283
+ if (hit) return hit;
284
+
285
+ let gzip = 0;
286
+ let brotli = null;
287
+
288
+ try {
289
+ const buffer = fs.readFileSync(file);
290
+ // Build önceden sıkıştırılmış eşlerini üretiyorsa onları kullan; yoksa
291
+ // gzip'i burada hesapla (rapor tek seferlik, maliyeti kabul edilebilir).
292
+ brotli = statSize(`${file}.br`);
293
+ gzip = statSize(`${file}.gz`) ?? zlib.gzipSync(buffer, { level: 6 }).length;
294
+ } catch {
295
+ return null;
296
+ }
297
+
298
+ const value = { bytes: stat.size, gzip, brotli };
299
+ sizeCache.set(key, value);
300
+ return value;
301
+ }
302
+
303
+ /** @param {string} file @returns {number | null} */
304
+ function statSize(file) {
305
+ try {
306
+ return fs.statSync(file).size;
307
+ } catch {
308
+ return null;
309
+ }
310
+ }
311
+
312
+ /** @returns {Record<string, string>} */
313
+ function readJson(file, fallback) {
314
+ try {
315
+ return JSON.parse(fs.readFileSync(file, "utf8"));
316
+ } catch {
317
+ return fallback;
318
+ }
319
+ }
320
+
321
+ /**
322
+ * Manifest girdileri + boyutları. Yol public/ altına göre çözülür.
323
+ */
324
+ function assets() {
325
+ const manifest = readJson(path.join(GENERATED_DIR, "manifest.json"), {});
326
+
327
+ return Object.entries(manifest).map(([name, url]) => {
328
+ const size = measure(path.join(PUBLIC_DIR, url.replace(/^\//, "")));
329
+ return {
330
+ name,
331
+ url,
332
+ kind: path.extname(url).slice(1) || "other",
333
+ bytes: size?.bytes ?? null,
334
+ gzip: size?.gzip ?? null,
335
+ brotli: size?.brotli ?? null,
336
+ };
337
+ });
338
+ }
339
+
340
+ /**
341
+ * esbuild metafile'ından chunk analizi: her çıktı için boyut, hangi
342
+ * kaynaklardan oluştuğu ve hangi chunk'ları import ettiği.
343
+ */
344
+ function chunks() {
345
+ const metafile = readJson(path.join(GENERATED_DIR, "metafile.json"), null);
346
+ if (!metafile?.outputs) return { outputs: [], groups: [], available: false };
347
+
348
+ /** @type {Record<string, number>} */
349
+ const groups = {};
350
+
351
+ const outputs = Object.entries(metafile.outputs)
352
+ .filter(([file]) => file.endsWith(".js") || file.endsWith(".css"))
353
+ .map(([file, output]) => {
354
+ const size = measure(path.join(ROOT, file));
355
+
356
+ const inputs = Object.entries(output.inputs ?? {})
357
+ .map(([source, info]) => ({ source, bytes: info.bytesInOutput ?? 0 }))
358
+ .filter((input) => input.bytes > 0)
359
+ .sort((a, b) => b.bytes - a.bytes);
360
+
361
+ for (const input of inputs) {
362
+ const group = groupOf(input.source);
363
+ groups[group] = (groups[group] ?? 0) + input.bytes;
364
+ }
365
+
366
+ return {
367
+ file: `/${file.split(path.sep).join("/").replace(/^public\//, "")}`,
368
+ entry: output.entryPoint ?? null,
369
+ isChunk: file.includes("chunks"),
370
+ bytes: output.bytes,
371
+ gzip: size?.gzip ?? null,
372
+ brotli: size?.brotli ?? null,
373
+ imports: (output.imports ?? [])
374
+ .filter((item) => item.kind !== "file-loader")
375
+ .map((item) => ({
376
+ path: `/${item.path.split(path.sep).join("/").replace(/^public\//, "")}`,
377
+ kind: item.kind,
378
+ })),
379
+ inputs: inputs.slice(0, 40),
380
+ inputCount: inputs.length,
381
+ };
382
+ })
383
+ .sort((a, b) => b.bytes - a.bytes);
384
+
385
+ return {
386
+ available: true,
387
+ outputs,
388
+ groups: Object.entries(groups)
389
+ .map(([name, bytes]) => ({ name, bytes }))
390
+ .sort((a, b) => b.bytes - a.bytes),
391
+ };
392
+ }
393
+
394
+ /**
395
+ * Kaynak dosyayı okunur bir gruba indirger: paket adı ya da üst klasör.
396
+ * @param {string} source
397
+ */
398
+ function groupOf(source) {
399
+ const normalized = source.split(path.sep).join("/");
400
+ const modules = normalized.lastIndexOf("node_modules/");
401
+
402
+ if (modules >= 0) {
403
+ const rest = normalized.slice(modules + "node_modules/".length).split("/");
404
+ return rest[0].startsWith("@") ? `${rest[0]}/${rest[1]}` : rest[0];
405
+ }
406
+
407
+ const parts = normalized.split("/").filter(Boolean);
408
+ return parts.slice(0, 2).join("/") || normalized;
409
+ }
410
+
411
+ /* ------------------------------------------------------------------- rapor */
412
+
413
+ /**
414
+ * Rapor sayfasının tek veri kaynağı.
415
+ * @param {{ requests: object[], errors: object[] }} devtools
416
+ */
417
+ export function buildReport(devtools) {
418
+ const usage = process.memoryUsage();
419
+
420
+ // SSR ölçümleri: ısıtma turu her sayfanın HTML boyutunu ve render süresini
421
+ // biliyor; gezilen sayfalarla eşleştirilir.
422
+ const warmByPath = new Map(
423
+ (prewarmProgress.entries ?? []).map((entry) => [entry.path, entry]),
424
+ );
425
+
426
+ const pageList = [...pages.values()].map((page) => {
427
+ const warm = warmByPath.get(page.url.split("?")[0]);
428
+ return {
429
+ ...page,
430
+ html: warm
431
+ ? { bytes: warm.bytes, cache: warm.cache, ms: warm.ms }
432
+ : page.html,
433
+ };
434
+ });
435
+
436
+ // Hiç gezilmemiş ama ısıtılmış sayfalar da listelenir: SSR tarafı bilinir,
437
+ // istemci ölçümleri boş kalır.
438
+ for (const entry of prewarmProgress.entries ?? []) {
439
+ if (pages.has(entry.path)) continue;
440
+ pageList.push({
441
+ url: entry.path,
442
+ title: null,
443
+ at: prewarmProgress.finishedAt ?? prewarmProgress.startedAt,
444
+ visits: 0,
445
+ metrics: {},
446
+ resources: { count: 0, bytes: 0, byType: {} },
447
+ islands: { total: 0, ready: 0, names: [] },
448
+ api: [],
449
+ html: { bytes: entry.bytes, cache: entry.cache, ms: entry.ms },
450
+ });
451
+ }
452
+
453
+ return {
454
+ generatedAt: Date.now(),
455
+ process: {
456
+ pid: process.pid,
457
+ node: process.version,
458
+ uptime: process.uptime(),
459
+ memory: { rss: usage.rss, heapUsed: usage.heapUsed },
460
+ env: process.env.NODE_ENV ?? "development",
461
+ },
462
+ pages: pageList.sort((a, b) => (b.visits - a.visits) || b.at - a.at),
463
+ serverApi: serverApiCalls.slice().reverse(),
464
+ build: { assets: assets(), ...chunks() },
465
+ cache: {
466
+ size: getHtmlCacheSize(),
467
+ entries: getHtmlCacheEntries(),
468
+ // Veri önbelleğinden yalnızca sayaç: uzun kuyruklu bir sitede on
469
+ // binlerce anahtar oluyor ve dökümü rapora koymak faydasız bir yük.
470
+ data: getDataCacheSize(),
471
+ // Sayaçlar dökümün yerine geçmiyor, onu tamamlıyor: "kaç girdi var"
472
+ // sorusundan çok "kaç okuma upstream'e gitti" sorusu karar veriyor.
473
+ dataStats: getDataCacheStats(),
474
+ // Paylaşımlı kademe kapalıyken de basılır: "Redis'i açtım ama neden
475
+ // çalışmıyor" sorusunun cevabı en çok burada aranıyor.
476
+ redis: getRedisStatus(),
477
+ },
478
+ // Hız freninin o anki durumu. 429 fırtınasında "şu an saniyede kaça
479
+ // indi" bilgisi olmadan ayar yapmak körlemesine oluyor.
480
+ upstream: getUpstreamLimiterStatus(),
481
+ prewarm: { ...prewarmProgress },
482
+ requests: devtools.requests,
483
+ errors: devtools.errors,
484
+ };
485
+ }